Presentation is loading. Please wait.

Presentation is loading. Please wait.

Using Classes and Objects

Similar presentations


Presentation on theme: "Using Classes and Objects"— Presentation transcript:

1 Using Classes and Objects
Chapter 3 Using Classes and Objects

2 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

3 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.

4 Logic of an if statement
condition evaluated false statement true

5 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.

6 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.

7 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.

8 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.

9 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.

10 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?

11 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

12 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

13 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:

14 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?

15 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)

16 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.

17 The if-else Statement statement1 condition false true statement2

18 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.

19 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

20 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.

21 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.

22 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

23 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

24 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()

25 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

26 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

27 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:

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

29 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

30 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

31 Outline Creating Objects The String Class

32 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

33 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

34 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

35 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)

36 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.

37 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.

38 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

39 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.

40 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;

41 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

42 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.

43 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.

44 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"); }

45 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.

46 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

47 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

48 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.*;

49 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

50 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)

51 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()

52 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.

53 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

54 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

55 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

56 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

57 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

58 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


Download ppt "Using Classes and Objects"

Similar presentations


Ads by Google