Using Classes and Objects

Slides:



Advertisements
Similar presentations
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
Advertisements

ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
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.
Chapter Day 6. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 DUE Problem set 2 posted 
Chapter 3 Using Classes and Objects. © 2004 Pearson Addison-Wesley. All rights reserved3-2 Using Classes and Objects We can create more interesting programs.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
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.
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Class Library, Formatting, Wrapper Classes, and JUnit Testing
Chapter 2: Objects and Primitive Data Classes and Objects String, Random, Math, NumberFormat, DecimalFormat and Wrapper Classes.
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
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,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2012 Pearson Education, Inc. Chapter 3 Using Classes and Objects Java Software Solutions Foundations of Program Design Seventh Edition John.
1 Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Flow of Control / Conditional Statements The.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Using Classes and Objects. We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: Object creation.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section 3.2 The Scanner Class – Section 2.6 Instructor: Scott Kristjanson.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making.
CSE 1201 Object Oriented Programming Using Classes and Objects.
1 Chap. 3 Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L, 3.1 – 3.6.
Chapter 3 Using Classes and Objects 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
1 Wrapper Classes  Sometimes we want to use a primitive type as an object, so there are wrapper classes that will help us.  In particular, we need to.
Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Collaboration Policy Programming Tests are individual work. You may not work with others in the class.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
3-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.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Programming in Java (COP 2250) Lecture 7 Chengyong Yang Fall, 2005.
Chapter 3 Using Classes and Objects. 2 We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: If statements.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Using Classes and Objects We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: object creation and.
© 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.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Variables in Java A variable holds either
Formatting Output & Enumerated Types & Wrapper Classes
Using Classes and Objects
Operator Precedence Operators Precedence Parentheses () unary
Creating Objects & String Class
Classes, Libraries & Packages
Boolean Expressions & the ‘if’ Statement
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Chapter 3: Using Classes and Objects
Chapter 3, cont Sept 20, 2004.
Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short.
Objects and Primitive Data
Outline Boolean Expressions The if Statement Comparing Data
Creating Objects A variable holds either a primitive value or a reference to an object A class name can be used as a type to declare an object reference.
CS139 October 11, 2004.
Packages & Random and Math Classes
Outline Creating Objects The String Class The Random and Math Classes
CprE 185: Intro to Problem Solving (using C)
Conditionals and Loops
Presentation transcript:

Using Classes and Objects Chapter 3 Using Classes and Objects

Conditional Statements A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions Java's conditional statements are the if statement, the if-else statement, and the switch statement

The if Statement The condition must be a boolean expression that evaluates to T or F. The boolean expression: If( grade > 60) System.out.println (“Passed”); If the grade is greater than 60, then Passed is printed on the screen. The boolean condition must be within parenthesis.

Logic of an if statement condition evaluated false statement true

The if Statement The if statement has the following syntax: The condition must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.

greater than or equal to Boolean Expressions The condition of an if statement must evaluate to a true or false result Java has several equality and relational operators: Operator == != < <= > >= Meaning equal to not equal to less than less than or equal to greater than greater than or equal to Relational operators always evaluate to a Boolean.

Boolean Expressions The boolean expression: boolean result = (total = = sum) compares two integer variable, total and sum, for equality. If they contain the same value the result is true. Notice that this equality operator is not the same as the = operator.

Booleans Relational and equality operators have precedence relationships similar to and less than arithmetic operators. Be careful when programming to allow for this. The use of booleans provide basic decision-making capabilities.

The if Statement An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); First, the condition is evaluated. The value of sum is either greater than the value of MAX, or it is not. If the condition is true, the assignment statement is executed. If it is not, the assignment statement is skipped. Either way, the call to println is executed next.

Block Statements if (temperature < Threshold) { Several statements can be grouped together into a block statement. Blocks are delimited by braces. A block statement can be used wherever a statement is called for in the Java syntax. In Temperature2.java if (temperature < Threshold) { System.out.println (“It is cold”); System.out.println (“But we will live”); } // what is the output?

Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand Although it makes no difference to the compiler, proper indentation is crucial "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding

The if Statement What do the following statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators

The if-else Statement An else clause can be added to an if statement to make it an if-else statement: if (condition) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed. In Temperature3.java, the following statement:

If-else Statements If (temperature <= FREEZING_POINT) System.out.print (“Its freezing in here”); else System.out.print (“Above Freezing”); If the value 90 is entered for temperature what is printed? (FREEZING_POINT set to 32). What data type is FREEZING_POINT? What is the output?

Nested if Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements An else clause is matched to the last unmatched if (no matter what the indentation implies)

Nested if Statements The body of an if statement or else clause can be another if statement if ( coin == HEADS) if (choice == receive) System.out.println(“You won and will receive”) else System.out println (“You won the coin toss and will not receive.”); System.out.println (“You lost the coin toss”) An else is matched with the closest unmatched if. In this case, the second else matches to the first if. Note that no braces were needed. The whole program is one statement.

The if-else Statement statement1 condition false true statement2

Object-Oriented Programming Java is an object-oriented language. Programs are made from software components called objects which represent objects in the real world. A student is represented in a program by a class Student An object contains data and methods - it groups related methods and the data those methods use. The student class contains data about a student. An object is defined by its class. We create student objects based on the student class. Multiple objects can be created from the same class Objects are meant to be re-usable in other programs.

Object-Oriented Programming A class represents a real world concept and an object represents the realization of that concept. It is description or a blueprint of a category. Objects are specific examples within the category and are described by their class. Objects Class My first car John's car Dad's car Car

Objects and Classes Classes can be used to define other classes. If we had a class vehicle, it may include the definition of other subcategories , such as planes, trains, and automobiles. It would contain all the generic characteristics of a vehicle with each sub- category defining specific individual characteristics within its own class.

Variable types We have discussed primitive types. Variables can also be reference types. Reference types are so-called because the value of a reference variable is a reference to (a pointer to the location in memory) of the actual value. When used in a statement or expression, a reference variable is equal to the address of the memory location where the value you are trying to access is located.

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 variable String title; No object is created with this declaration An object reference variable holds the address of an object The object itself must be created separately

Creating Objects Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class

title = "Java Software Solutions"; Creating Objects Because strings are so common, we don't have to use the new operator to create a String object. title = "Java Software Solutions"; This is special syntax that only works for strings. Once an object has been instantiated, we can use the dot operator to invoke its methods. title.length()

int count = title.length() Invoking Methods We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods int count = title.length() A method may return a value, which can be used in an assignment or expression A method invocation can be thought of as asking an object to perform a service

References Note that a primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically "Steve Jobs" name1 num1 38

Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 After:

Reference Assignment For object references, assignment copies the address: name1 name2 Before: "Steve Jobs" "Steve Wozniak" name2 = name1; name1 name2 After: "Steve Jobs"

Aliases Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really only one object

Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection

Outline Creating Objects The String Class

The String Class Recall that because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that works only for strings Each string literal (enclosed in double quotes) represents a String object

String Methods Once a String object has been created, neither its value nor its length can be changed Thus we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original See the list of String methods on page 119 and in Appendix M

String Indexes It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4

The String Class The String class is defined in the java.lang package (and is therefore automatically imported). Many helpful methods are defined in the String class. They mostly are used to manipulate strings that input as data to a program. See StringMutation.java (page 120)

String Methods: Some example string methods using String name: name.charAt (int index) - returns the character at location index name. startsWith (String prefix) - True if name begins with prefix. name.toLowercase () - returns name converted to lowercase.

String Methods: name.length() - returns the length of the string name.(# of characters) name.equals (Object obj) - return true if the string name and the parameter obj contain the same characters. name.toUppercase - returns the string name in uppercase.

Strings public static void main(String[] args) { String str1 = “Seize the day”; String str2 = “Day of the seize” String str3 = new string(str1); System.out.println (“Length of str1: “ + str1.length()); //output: Length of str1 : 13 System.out.println(“Str1 starts with \”Seize\”: “ + str1.startsWith(“Seize”) ); //output: str1 starts with “Seize”: true

System. out. println(“The character at position3 in str1: “ + str1 System.out.println(“The character at position3 in str1: “ + str1.charAt(3)); //output : The character at position 3 in str1: z if(str1.equals(str3)) System.out.println(“str1 and str3 contain the same characters”); //output : str1 and str3 contain the same characters.

String methods String str1 , str2; int i, n = 1; boolean t; char c; str2 = “ok”; Method Result str1 = str2.toUppercase(); str1= “OK”; str1 = str1.toLowerCase() str1 = “ok”; str1 = str2.replace(‘k’,’h’); str1 = “Oh”; // k replaces h t = str2.equalsIgnoreCase(“ok”); t = true;

String Methods String str1 , str2 = “ ok”; int i ; boolean t; char c; Result t = str2.endsWith(“K”); t = false; t = str2.startsWith(“o”) t = true; c = str.charAt(1); c = ‘k’; i = str2.indexOf(‘j’); i = -1; i = str2.length(); i = 2; str1 = str1.toString(i); str1 = “2”; i =str2.compareTo(“Oh”); i = 1; // 0 if the strings are equal, -1 if str1 is less than, 1 if str1 is greater than str2

String Comparison When we compare primitive data types, such as two ints, two chars, two doubles, etc., we can use the = = operator. We can also use the = = operator to compare two objects. However, when used with an object, the = = operator will only check to see if they are the same objects, not if they hold the same contents. Two strings could contain the same data and not be the same object.

String Comparison This means that code like the following will compare the strings address but not content: if ( string1 = = string2 ) { System.out.println ("Match found"); } This code will only evaluate to true if string1 and string2 are the same object. It does not check their contents. If string1 and string2 have the same content but are different objects, (I.e. different locations in memory), the above comparison will not evaluate to true.

Comparing Strings To compare two strings to determine if they contain the same data, we must use the .equals method(). This method is inherited from java.lang.Object. Here's an example of how to correctly check a String's contents : if ( string1.equals("abcdef") ) { System.out.println (“String contains “abcdef"); }

Strings - Initialization You can initialize a string with: String Quote = “ ‘‘; or String Quote ; In the first case, the string is initialized to the “empty string” , and in the second it is uninitialized and contains a null value.

Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment Its classes are not part of the Java language per se, but we rely on them heavily Various classes we've already used (System , Scanner, String) are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself

Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: 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 Network communication Utilities XML document processing

The import Declaration When you want to use a class from a package, you could use its fully qualified name java.util.Scanner Or you can import the class, and then use just the class name import java.util.Scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*;

The import Declaration All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line: import java.lang.*; That's why we didn't have to import the System or String classes explicitly in earlier programs The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported

The Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values See RandomNumbers.java (page 126)

Random Numbers The Random class provides methods to simulate a random number generator. You can give the generator a seed value as in: Random randomizer1 = new Random(123) Which will produce the same sequence of numbers each time Or you can give it no seed and the values are based on the system time. Because the start value is unpredictable, this produces a different sequence each time it is run: Random randomizer1 = new Random()

Random class The nextInt method of the random class returns a number from the whole spectrum of Integer values. The nextFloat returns a numer greater than 0 and less than or equal to 1. Usually, we scale and shift the numbers to get a particular range.

The Math Class The Math class is part of the java.lang package The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions

value = Math.cos(90) + Math.sqrt(delta); The Math Class The methods of the Math class are static methods (also called class methods) Static methods can be invoked through the class name – no object of the Math class is needed. value = Math.cos(90) + Math.sqrt(delta); See Quadratic.java (page 129) We discuss static methods further in Chapter 6

Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean void Void

Integer age = new Integer(40); Wrapper Classes The following declaration creates an Integer object which represents the integer 40 as an object Integer age = new Integer(40); An object of a wrapper class can be used in any situation where a primitive value will not suffice For example, some objects serve as containers of other objects Primitive values could not be stored in such containers, but wrapper objects could be

num = Integer.parseInt(str); Wrapper Classes Wrapper classes also contain static methods that help manage the associated type For example, the Integer class contains a method to convert an integer stored in a String to an int value: num = Integer.parseInt(str); The wrapper classes often contain useful constants as well For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values

Autoboxing Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: int num = 42; Integer obj = num; The assignment creates the appropriate Integer object The reverse conversion (called unboxing) also occurs automatically as needed: int num = obj