Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 3 Using Classes and Objects

2 2 We can create more interesting programs using predefined classes and related objects Chapter 3 focuses on: If statements object creation and object references the String class and its methods the Java standard class library the Random and Math classes formatting output enumerated types wrapper classes graphical components and containers labels and images

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

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

5 5 Logic of an if statement condition evaluated false statement true

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

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

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

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

10 10 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. See Age.java (page 112)Age.java

11 11 Block Statements 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?

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

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

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

15 15 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 what is printed? If the value 60 is printed. (FREEZING_POINT set to 32). What data type is FREEZING_POINT? What is the output?

16 16 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 See MinOfThree.java (page 118)MinOfThree.java An else clause is matched to the last unmatched if (no matter what the indentation implies)

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

18 18 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 what is printed? If the value 60 is printed. (FREEZING_POINT set to 32). What data type is FREEZING_POINT? What is the output?

19 19 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 toss and will kickoff.”); else 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.

20 20 The if-else Statement statement1 condition false true statement2

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

22 22 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. Car My first car John's car Dad's car Class Objects

23 23 Objects and Classes In a game that races cars, each car component will accept variations in steering and pedal use as input and produce a new position and speed as output. It may contain methods to draw the car, move the car, check for collisions, etc. A particular car is an object, while the class car embodies the concept of all cars. It is the idea of a car.

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

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

26 26 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

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

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

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

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

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

32 32 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 38 After:

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

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

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

36 36 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

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

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

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

40 40 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)StringMutation.java

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

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

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

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

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

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

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

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

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

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

51 51 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

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

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

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

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

56 56 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)RandomNumbers.java

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

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

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

60 60 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)Quadratic.java We discuss static methods further in Chapter 6

61 61 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

62 62 Formatting Output It is often necessary to format values in certain ways so that they can be presented properly The Java standard class library contains classes that provide formatting capabilities The NumberFormat class allows you to format values as currency or percentages The DecimalFormat class allows you to format values based on a pattern Both are part of the java.text package

63 63 Formatting Output The NumberFormat class has static methods that return a formatter object getCurrencyInstance() getPercentInstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format See Purchase.java (page 131)Purchase.java

64 64 Formatting Output The DecimalFormat class can be used to format a floating point value in various ways For example, you can specify that the number should be truncated to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number See CircleStats.java (page 134)CircleStats.java

65 65 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

66 66 Enumerated Types Java allows you to define an enumerated type, which can then be used to declare variables An enumerated type establishes all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed

67 67 Enumerated Types Once a type is defined, a variable of that type can be declared Season time; and it can be assigned a value time = Season.fall; The values are specified through the name of the type and only those values specified can be used Enumerated types are type-safe – you cannot assign any value other than those listed

68 68 Ordinal Values Internally, each value of an enumerated type is stored as an integer, called its ordinal value The first value in an enumerated type has an ordinal value of zero, the second one, and so on However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value

69 69 Enumerated Types The declaration of an enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The name method returns the name of the identifier corresponding to the object's value See IceCream.java (page 137)IceCream.java

70 70 Enumerated Type public class IceCream { enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough} //----------------------------------------------------------------- // Creates and uses variables of the Flavor type. //----------------------------------------------------------------- public static void main (String[] args) { Flavor cone1, cone2, cone3; cone1 = Flavor.rockyRoad; cone2 = Flavor.chocolate; System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name());

71 71 cone3 = cone1; System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name()); } }

72 72 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

73 73 Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

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

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

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

77 77 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

78 78 Graphical Applications Except for the applets seen in Chapter 2, the example programs we've explored thus far have been text-based They are called command-line applications, which interact with the user using simple text prompts Let's examine some Java applications that have graphical components These components will serve as a foundation to programs that have true graphical user interfaces (GUIs)

79 79 GUI Components A GUI component is an object that represents a screen element such as a button or a text field GUI-related classes are defined primarily in the java.awt and the javax.swing packages The Abstract Windowing Toolkit (AWT) was the original Java GUI package The Swing package provides additional and more versatile components Both packages are needed to create a Java GUI- based program

80 80 GUI Containers A GUI container is a component that is used to hold and organize other components A frame is a container that is used to display a GUI- based Java application A frame is displayed as a separate window with a title bar – it can be repositioned and resized on the screen as needed A panel is a container that cannot be displayed on its own but is used to organize other components A panel must be added to another container to be displayed

81 81 GUI Containers A GUI container can be classified as either heavyweight or lightweight A heavyweight container is one that is managed by the underlying operating system A lightweight container is managed by the Java program itself Occasionally this distinction is important A frame is a heavyweight container and a panel is a lightweight container

82 82 Labels A label is a GUI component that displays a line of text Labels are usually used to display information or identify other components in the interface Let's look at a program that organizes two labels in a panel and displays that panel in a frame See Authority.java (page 144)Authority.java This program is not interactive, but the frame can be repositioned and resized

83 83 Nested Panels Containers that contain other components make up the containment hierarchy of an interface This hierarchy can be as intricate as needed to create the visual effect desired The following example nests two panels inside a third panel – note the effect this has as the frame is resized See NestedPanels.java (page 146)NestedPanels.java

84 84 Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images

85 85 Images Images are often used in a programs with a graphical interface Java can manage images in both JPEG and GIF formats As we've seen, a JLabel object can be used to display a line of text It can also be used to display an image That is, a label can be composed of text, and image, or both at the same time

86 86 Images The ImageIcon class is used to represent an image that is stored in a label The position of the text relative to the image can be set explicitly The alignment of the text and image within the label can be set as well See LabelDemo.java (page 149)LabelDemo.java

87 87 Summary Chapter 3 focused on: object creation and object references the String class and its methods the Java standard class library the Random and Math classes formatting output enumerated types wrapper classes graphical components and containers labels and images

88 88 Programming Languages A program must be translated into machine language before it can be executed on a particular type of CPU The compiler is a software tool which translates source code into a specific target language Often, that target language is the machine language for a particular CPU type. The Java approach is somewhat different.

89 89 Java Translation and Execution The Java compiler translates Java source code into a special representation called bytecode - similar to machine language. Java bytecode is not the machine language for any traditional CPU Another software tool, called an interpreter, translates bytecode into machine language and executes it on a specific machine.

90 90 Java Translation and Execution Java source code Machine code Java bytecode Java interpreter Bytecode compiler Java compiler

91 91 Compiled Languages Therefore the Java compiler is not tied to any particular machine. You have to have a Java interpreter for each processor type. Since the interpreter is working on low-level bytecode, it is faster that interpreting the high-level language directly. Executing bytecode does take longer than executing machine language, but is allows Java to be architecture-neutral and portable. It is also possible to compile the bytecode into a specific machine language so that the program will run faster on that machine.


Download ppt "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."

Similar presentations


Ads by Google