CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to Objects and Input/Output
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
CMT Programming Software Applications
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 28, 2005.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough September 5, 2007.
Java An introduction. Example 1 public class Example1 { public static void main (String [] args) { System.out.println (“This is the first example”); int.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
***** SWTJC STEM ***** Chapter 3-1 cg 36 Java Class Libraries & API’s A class library is a set of classes that supports the development of programs. Java.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
The Java Programming Language
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
1 The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks,
Chapter 2: Java Fundamentals
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Objectives ► Become familiar with the class String ► ► Learn how to use input and output dialog boxes in a program ► ► Learn how to tokenize the input.
Lecture 2 Objectives Learn about objects and reference variables.
Chapter 3 Introduction To Java. OBJECTIVES Packages & Libraries Statements Comments Bytecode, compiler, interpreter Outputting print() & println() Formatting.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
CSE 1201 Object Oriented Programming Using Classes and Objects.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
CSCI 51 Introduction to Computer Science Dr. Joshua Stough January 29, 2009.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CS 106 Introduction to Computer Science I 01 / 24 / 2007 Instructor: Michael Eckmann.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
1 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used as a type to declare an object reference.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Variables in Java A variable holds either
Chapter Topics The Basics of a C++ Program Data Types
Introduction to Computer Science / Procedural – 67130
Yanal Alahmad Java Workshop Yanal Alahmad
Java Programming: From Problem Analysis to Program Design, 4e
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to C++ Programming
Chapter 2: Basic Elements of Java
MSIS 655 Advanced Business Applications Programming
Introduction to Java Applications
Unit 3: Variables in Java
Presentation transcript:

CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009

Announcements Tutoring Schedule online –Sunday 8-10PM (Spiller) –Monday 4-6PM (Stough), 8-10PM (Siegel) –Tuesday 8-10PM (Siegel) –Wednesday 4-6PM (Stough) –Thursday 4-6PM (Spiller) –Friday 3-5PM (Stough) Card Access – one more step – See Kace Kush in Story House for card activation for Adams Hall after-hours access

Today Increment/decrement operators Escape sequences in string output. Strings More on using pre-defined methods. Reference objects

More Operators Increment and Decrement Increment (++) –adds 1 to any integer or floating point count++; count = count + 1; Decrement (--) –subtracts 1 from any integer or floating point count--; count = count - 1;

Increment and Decrement Prefix( ++count or --count ) –value used in a larger expression is the new value of count (after the increment/decrement) Postfix( count++ or count-- ) –value used in a larger expression is the original value of count (before the increment/decrement) –increment/decrement is the last operation performed (even after assignment)

Increment and Decrement If count currently contains 45, then the statement total = count++; assigns 45 to total and then 46 to count If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count

Questions What is stored in total and count in the following statements? double total = 15.5; total++; int total = 10, count = 5; total = total + count++; int total = 20, count = 3; total = total / --count; total 16.5 total count 15 6 total count 10 2

Escape Sequences in output Escape character \ Used to represent special characters inside Strings Escape sequences –\n - newline –\t - tab –\b - backspace –\r - return –\\ - backslash –\' - single quote –\" - double quote

Examples System.out.println ("I said, \"Hi There!\""); I said, "Hi There!" System.out.print ("Hello\n"); System.out.println ("World"); Hello World System.out.println ("Hello\rWorld"); Hello World System.out.println ("Hi\b\bHello"); Hello System.out.println ("Hello\tWorld"); HelloWorld

Questions What is output by the following statements? System.out.println ("Helen says " + "\"What\'s up?\""); System.out.print ("Enter a number "); System.out.println ("between 1-10"); System.out.print ("\n\tplease!"); Helen says "What's up?" Enter a number between 1-10 please!

The class String String variables are reference variables Given String name; –Equivalent Statements: name = new String("Lisa Simpson"); name = "Lisa Simpson";

Lisa Simpson

The class String The String object is an instance of class string The value “Lisa Simpson” is instantiated The address of the value is stored in name The new operator is unnecessary when instantiating Java strings String methods are called using the dot operator

Common String Methods String(String str) –constructor –creates and initializes the object char charAt(int index) –returns char at the position specified by index (starts at 0) int indexOf(char ch) –returns the index of the first occurrence of ch int compareTo(String str) –returns negative if this string is less than str –returns 0 if this string is the same as str –returns positive if this string is greater than str

Common String Methods boolean equals(String str) –returns true if this string equals str int length() –returns the length of the string String replace(char toBeReplaced, char replacedWith) –returns the string in which every occurrence of toBeReplaced is replaced with replacedWith String toLowerCase() –returns the string that is the the same as this string, but all lower case String toUpperCase() –returns the string that is the same as this string, but all upper case

String Examples String str = "Go Trojans!"; System.out.println (str.length()); System.out.println (str.charAt(3)); System.out.println (str.indexOf('!'); System.out.println (str.toLowerCase()); T go trojans!

Glossary Terms Class - used to group a set of related operations (methods), allows users to create their own data types Method - set of instructions designed to accomplish a specific task Package - collection of related classes Library - collection of packages

Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities XML document processing Packages The classes of Java library are organized into packages. Some of the packages in the standard class library are:

Using Packages We need to import some of the packages we want to use –java.util for Scanner –not java.lang because it's automatically imported for us import packageName; –import java.util.*; imports all of the classes in the java.io package –import java.util.Scanner; imports only the Scanner class from the java.util package

Using Predefined Classes and Methods long Math::round (double); To use a method you must know: –Name of class containing method (Math) –Name of package containing class (java.lang) –Name of method (round), its parameters (double a), what it returns (long), and function (rounds a to the nearest integer)

Using Predefined Classes and Methods Example method call: int num = (int) Math.round (4.6); –why don't we have to import the Math class? (Dot). Operator: used to access the method in the class

Java Program Skeleton import statements if any public class ClassName { declare named constants and/or stream objects public static void main (String[] args) throws IOException { variable declarations executable statements }

Import Statements Tell the compiler which packages are used in the program Import statements and program statements constitute the source code Source code saved in a file with the extension.java Source code file must have the same name as the class with the main method

The main method Heading Body –statements enclosed by { } –declaration statements used to declare things such as variables –executable statements perform calculations, manipulate data, create output, accept input, etc. public static void main (String[] args)

static Heading of the main method has the reserved word static Statements to declare named constants and input stream objects are outside the main method These must also be declared with the static reserved word

Syntax –beware! a syntax error in one place might lead to syntax errors in several other places Use of semicolons, braces, commas –all Java statements end with semicolon –braces {} enclose the body of a method and cut it off from other parts of the program (also have other uses) –commas separate list items

Style Semantics –set of rules that gives meaning to a language –beware! the compiler will not be able to tell you about semantic errors (example: missing parentheses in mathematical expression) Documentation –comments - shown in green in Eclipse –naming rules use meaningful identifiers –prompt lines let the user know what type of input is expected

Style and White Space White space –blanks, tabs, blank lines –used to separate words and symbols –extra space is ignored by computer –blank line between variable declaration and rest of code Programs should be formatted to enhance readability, using consistent indentation

Comments Not used by the computer –only for human consumption Used to help others understand code –explain and show steps in algorithm –comments are essential! Should be well-written and clear Comment while coding Also called inline documentation

/**************************************************************** * Program 0: Hello World * * Programmer: Joshua Stough * * Due Date: September 2, 2008 * * Class: COMP 14 Instructor: Dr. Joshua Stough * * Description: This program prints out a greeting to the world. * * Input: None * * Output: A friendly greeting ***************************************************************/ public class HelloWorld { public static void main(String[] args) { System.out.println ("Hello World!"); } comment class declaration main method method call

Review In the Java programming language: –a program is made up of one or more classes –a class contains one or more methods –a method contains program statements A Java application always contains a method called main Source code saved in a file with the extension.java File must have the same name as the class with the main method Use the dot (.) operator to call methods: Math.round

Review-Skeleton import statements if any public class ClassName { declare named constants and/or stream objects public static void main (String[] args) throws IOException { variable declarations executable statements }

Review Questions What is stored in num? int num = (int) Math.round (12.7); What is printed to the screen? Assume the user enters 10 and that scan is already defined. System.out.print ("Enter a number: "); int num = scan.nextInt(); System.out.println (num * num); 13 Enter a number:

Questions What is stored in total and count in the following statements? int total = 10, count = 5; total += count++; int total = 20, count = 3; total /= --count; String str = "CSCI"; str += 51; total count 15 6 total count 10 2 str CSCI51

Java Variables Primitive Variables –primitive data types (int, double,...) –stores the data in the memory location Reference Variables –stores an address in the memory location –"points to" another memory location

Objects More complex data type than a primitive data type Stored in the "other" memory location –is "pointed to" by a reference variable Is operated on by special operators called methods

Objects and Classes An object's data type is a class The class contains the data types that make up the object and what methods can operate on the object Examples: –String –Integer –Double

Primitive Variables int x = 45; When the computer sees x, it knows which memory location to look up the value in

Reference Variables Integer num; When the computer sees num, it knows which memory location to look for the address in It will read the address in num and look up a value in that memory location

Creating Objects We use the new operator to create objects, called instantiation Integer num; num = new Integer(78); parameter

Review the Terms We declare a reference variable of a class type. We use the new operator to instantiate an object of that class type. We store the address of that object in the reference variable.

Changing the Reference Var num = new Integer (50); The address of the newly-created object is stored in the already-created reference variable num

Garbage Collection What happened to the memory space that held the value 78? If no other reference variable points to that object, Java will "throw it away"

System.out.println (”Hello World!”); object method information provided to the method (parameters) Using Objects System.out object –represents a destination to which we can send output Example: –println method dot operator

Questions 1.True or False. A primitive variable is a variable that stores the address of a memory space. 2.The operator is used to create a class object. 3.In Java, the operator is used to access members of a class. It separates the class (or object) name from the method name. 4.True or False. Class objects are instances of that class. new dot (.) False True

Example Program MathStats.java Ask the user for 3 integers. Output the following: –the 3 numbers –the sum –the average –the sum squared –the square root of the sum

Force Errors Try the following in MathStats.java to see what error message is displayed: –comment out import statement –comment out throws clause –make sumSquare an int –don't initialize sum –don't cast average to double (semantic error)

Summary Increment/decrement primitive variables vs. reference variables objects dot (.) operator String class

Next Time in CSCI 51 Using dialog boxes for I/O Tokenizing Strings Formatting output Reading from and writing to text files If, if/else statements