OBJECT ORIENTED PROGRAMMING I LECTURE 6 GEORGE KOUTSOGIANNAKIS CS 201 OBJECT ORIENTED PROGRAMMING I LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2016 Illinois Institute of Technology- George Koutsogiannakis
NEW TOPICS Null Objects. Using Java Pre Defined Classes (Library Classes). String Class. Formatting Numbers. Math class.
NEW TOPICS Using the Scanner class to read user input from the keyboard. Wrapper classes. Autoboxing / Unboxing.
Java Predefined Classes (Library Classes) The Java SDK provides more than 2,000 classes that can be used to add functionality to our programs. The Java Documentation provides specific information on each of these library classes. For each class it lists the: Fields of the class Constructors of the class Methods of the class. The documentation is referred to as the “Application Programming Interface” abbreviated as API.
Using Library Classes These Library classes are already coded, ready to be used by a programmer. They offer certain functionality which you don’t have to recreate in your program. When you want to use a library class use the API to find out what methods are available in that class by going online: http://java.sun.com/javase/6/docs/api/
Why Use Library Classes No reason to reinvent the wheel!! They provide certain functionality thus freeing the program from duplicating the code to create himself/herself the functionality. The java runtime system can use the functionality provided by the library class you are using. You need, however, to notify the runtime system (JVM) with an import statement.
Using Library Classes Library classes belong in packages. A package can have many library classes. Some library classes can be used with any of your programs without any special effort i.e. The library classes belonging to the package java.lang are an example. Math class is an example of a class that belongs to the package java.lang.
Using Library Classes Other library classes are not automatically used. They need to be imported. Imported means that the compiler needs to be notified so that it can load these library classes that we want to use. An example of such a class is the classes in package: java.util The Scanner class is a class in that package.
Examples public class MyCalculator { public static void main(String[] args) double a=3.5; double b=6.5; double c=5.2; double z=a*Math.pow(b,c); System.out.println(“The result is:”+z); } The Math library classes calls its method pow that calculates the value of b raised to the c power. No import statement is used because Math class is one of those classes that are imported automatically with every program (also the Math class is like that).
Examples import java.util.Scanner; public class MyCalculator { public static void main(String[] args) //code here Scanner scan=new Scanner(); // other code here } Since we want to use the Scanner library class an import statement is needed. The scanner class will allow us to receive input from the user of the program.
Some Java Library Packages (or Pre Defined Classes as sometimes are called) Classes are grouped in packages according to functionality Package Categories of Classes java.lang Basic functionality common to many programs, such as the String class and Math class java.awt Graphics classes for drawing and using colors javax.swing User-interface components java.text Classes for formatting numeric output java.util The Scanner class, the Random class and other miscellaneous classes java.io Classes for reading from and writing to files
Using a Class From a Package Classes in java.lang are automatically available to use. Classes in other packages need to be "imported" using this syntax: import package.ClassName; or import package.*; (imports all required classed from package) Example import java.text.DecimalFormat; import java.text.*;
Import Statements The package name is java.util An import statement has to be written above the line that names your class. For example: import java.util.*; public class MyClass { } The package name is java.util The .* means that we want to use all the classes in that package. import is a keyword.
The String Class The String class allows creation and manipulation of Strings data types. String is a library class in java.lang package, therefore every java program gets access to this class without the need for an import statement.
The String Class String Constructors allocates an empty String object Represents a sequence of characters Examples: String greeting = new String( "Hello" ); String empty = new String( ); String Constructors String( String str ) allocates a String object with the value of str, which is a String object or a String literal String( ) allocates an empty String object
The String Class Example: Remember that you can also create a String via a declaration and assignment of a value i.e. String lastName=“Jones” + appends a String to another String. At least one operand must be a String. + in this case is called the concatenation operator Example: String s1 = new String( "Hello " ); String s2 = "there. "; String s3 = s1 + s2; // s3 is: Hello there.
The String Class For instance in the statement: int x; System.out.println(“The value of the number is:”+x); The concatenation operator in front of the int data type x converts x from an int type to a String type. The String Library class provides many different methods that can help us for instance: Identify the number of characters in a String (the length of the String.) Isolate a substring from within the String. Identify the position of a specific character within a String Others.
Sample Methods from String Class (from Java API-Documentation) char charAt(int index) Returns the char value at the specified index. Int codePointAt(int index) Returns the character (Unicode code point) at the specified index. int codePointBefore(int index) Returns the character (Unicode code point) before the specified index.. int compareTo(String anotherString) Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The returned integer is zero if the two Strings are equal or a positive number otherwise int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. String concat(String str) Concatenates the specified string to the end of this string.
How to use the methods You need the string object first. i.e. String str=new String(“My name”); (keep in mind that this is the same as String str=“My Name”;) int x=str.length(); x now indicates the number of characters in the String. Another example: String str1=“My Name is John”; String str2=“Your name is Helen”; str1.concat(str2); str1 is now “My Name is John Your name is Helen”
The indexOf Methods Return type Method name and argument list int indexOf( String searchString ) returns the index of the first occurrence of searchString, or -1 if not found indexOf( char searchChar ) returns the index of the first occurrence of searchChar, or -1 if not found The index of the first character of a String is 0. Example: String hello = "Hello"; int index = hello.indexOf( 'e' ); The value of index is 1. NOTICE THAT: The first position (first character) has index 0.
The substring Method Return type Method name and argument list String substring( int startIndex, int endIndex ) returns a substring of the String object beginning at the character at index startIndex and ending at the character at index end Index – 1 Example: String hello = "Hello"; String endOfHello = hello.substring( 3, hello.length( ) ); The value of endOfHello is “lo” because we asking for the part of the String that starts with character at index zero and ends with the last character in the String. H has index 0 e has index 1 l has index 2 l has index 3 0 has index 4 (which is the same as hello.length() index minus 1) See Example 3.6 StringDemo.java
FORMATTING NUMBERS The DecimalFormat LIBRARY class and the NumberFormat LIBRARY class allow you to specify the number of digits for printing and add dollar signs and percent signs to your output Both classes are in the java.text package We will cover the NumberFormat class later.
FORMATTING NUMBERS 0 required digit The DecimalFormat Class : DecimalFormat Constructor: DecimalFormat( String pattern ) instantiates a DecimalFormat object with the format specified by pattern IN THE ARGUMENT LIST OF THE CONSTRUCTOR. Pattern characters: 0 required digit # optional digit, suppress if 0 . decimal point , comma separator % multiply by 100 and display a percent sign
FORMATTING NUMBERS The DecimalFormat format method String format( double number ) returns a formatted String representation of number passed as argument. See example on next slide:
FORMATTING NUMBERS import java.text.NumberFormat; Import java.text.DecimalFormat; public class Formatting { public static void main(String[] args) double d=23.456289; DecimalFormat twodigits=new DecimalFormat("0.00"); NumberFormat moneyFormat=NumberFormat.getCurrencyInstance(); String b=twodigits.format(d); System.out.println(b); String money=moneyFormat.format(d); System.out.println(money); } //The first output is 23.46 //Notice the rounding of the decimal points //second output is $23.46
null Objects An object reference is term used to denote the nam ewe give to an object. We can declare an object without using the new operator to actually give initial values to the instance variables of the class that represents the object. An object reference can point to no object. In that case, the object reference has the value null. Object references have the value null when they have been declared, but have not been used to instantiate an object. i.e Student myself; myself is an object reference of class Student in this case. Attempting to use a null object reference causes a NullPointerException at run time. This kind of a message from the compiler could mean that you forgot to instantiate (create using new operator) the object.
null Objects Thus, the following declaration causes a null reference: Student stud1; stud1 points to nothing until it is instantiated using the new operator. stud1=new Student(); now std1 points to an area in memory where the initialized values of the instance variables of the class Student are stored..
Input Using the Scanner Class We need to be able to capture input from the user. One way of providing input to the program is via the keyboard The Scanner library class provides the functionality to allow us to capture keyboard input (and also read input from a file—we will cover the file reading later) Scanner class is part of the Library package java.util Therefore we have to import the Scanner class
Receiving input from the user. Remember that we have used the argument list of the main method to receive input from the user when the user types the commend to interpret on a DOS pane: i.e. >java Myprogram George 25 (where George and 25 are two inputs provided by the user of the program).
Receiving input from the user. The class MyProgram has a main method. The identifier args in the list of arguments of the main method captures the inputs typed by the user. public static void main(String[] args) { String name=args[0]; //captures the input: George String mynumber=args[1]; //captures the next input : 25 //Notice that even though the number 25 was typed, it has been captured as a String data type. If we need the number in an arithmetic expression we will have to convert it from a String to an int data type. We will learn how to do that later.
Receiving Input from the User Using the Scanner library class. Sometimes we need to prompt the user during the execution of the program so that input is provided after a specific set of instructions has been executed. The previous technique of making the input part of the command to start the execution WILL NOT work then. We can provide this functionality by using the Scanner library class. The user can be prompted to enter data, after the program starts execution, via the keyboard. The Scanner object will read the characters typed on the keyboard.
Input Using the Scanner Class Provides methods for reading byte, short, int, long, float, double, and String data types from the Java console (keyboard) and other sources (like a file). Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.) i.e in the String “My name is Joe” there are 4 tokens. The first token is the substring “My” and so on.
A Scanner Constructor (System.in is the keyboard) Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console (keyboard). (System.in is the keyboard) Example: Scanner scan = new Scanner( System.in ); scan then is the object that we are going to use to read characters from the keyboard if System.in has been passed to the constructor of the Scanner class. The Scanner class has methods that help us capture the user ‘s input (as an example from the keyboard or a file).
Scanner class methods Some of the methods are listed in the next slide. Connect to the link for the java API http://java.sun.com/javase/6/docs/api/ and study the methods of Scanner class.
Scanner next… Methods Return type Method name and argument list dataType nextDataType( ) returns the next token in the input stream as a dataType. dataType can be byte, int, short, long, float, double, or boolean i.e nextDouble() or nextInt() String next( ) returns the next token in the input stream as a String nextLine( ) returns the remainder of the line as a String
Prompting the User Example: The next… methods do not prompt the user for an input value Use System.out.print to print the prompt, then call the next… method Example: Scanner scan = new Scanner( System.in ); System.out.print( "Enter your age > " ); int age = scan.nextInt( ); In this example the user program stops execution after statement 2 is executed. The program waits for the user to type something (a number in this case)
Prompting the User On the DOS window we will see: C:\Users\George>java MyProgram Please enter your age > _ After the user enters a number (let us say that the user typed the number 19) and presses the Enter key, the program resumes execution and line 3 is executed. Line 3 reads what the user typed (19) as a String and at the same time converts it into an int data type. It assigns that data type (stores in memory) to the identifier age in this example. From there on the program continues with the execution of other instructions. It is possible that we may want to stop the program further down again and ask the user to enter another input.
SOFTWARE ENGINEERING TIP Provide the user with clear prompts for input. Prompts should use words the user understands and should describe the data requested and any restrictions on valid input values. Example: Enter your first and last name or Enter an integer between 0 and 10
String Input Use the next method to read a String scan.next(); captures a String typed on the keyboard. (Remember that anything you type on the keyboard is captured as a String first by the Scanner. It can be converted after that). The next method will read only one word of String input because the space is a whitespace character. To read a whole line, including spaces, use the nextLine method. Example: System.out.print( “Enter a sentence > “ ); String sentence = scan.nextLine( );
Capture an entire line of Input as a one String i.e. >java Myprogram Please enter a short story:_ The user could enter (type via the keyboard) for example My name is Peter and I am an Electrical Engineering student What will be stored in the memory location labeled sentence (see previous example code) is the entire phrase as a String data type: “My name is Peter and I am an Electrical Engineering student”
Scanner Example Suppose that we want to read a String that a user of our program enters on the keyboard: import java.util.Scanner; class UsingScanner { public static void main(String[] args) Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); String a=scan.next(); double d=Double.parseDouble(a); System.out.println(d); }
Scanner Example Interpreting this program has the following outcome: C:\CS115\Myexamples\ScannerExamples>java UsingScanner Enter a decimal number 12.34 The number you entered is:12.34 Notice that after the statement “Enter a decimal number” is displayed, the program waits for the user to enter something on the keyboard. Notice that the next action is for the user to type 12.34 on the keyboard. The program then prints the last statement “The number you entered is:12.34”
Scanner Example In the program the line: String a=scan.next(); captures whatever the user typed as a String data type (even if the user typed a number!) Our program converts the data type String represented by the identifier a to a double data type via the line: double d=Double.parseDouble(a);
Wrapper Classes We can always convert a String to a primitive data type using classes called “Wrapper classes”. In this example the class Double is the Wrapper class (notice that it is written with a capital D to differentiate it from the primitive data type double written with a lower case d). Its job is to convert a String to a double data type by invoking the method parseDouble that takes a primitive data type double as argument.
The Wrapper Classes “Wrap” the value of a primitive data type into an object Useful when methods require an object argument Also useful for converting Strings to an int or double
Wrapper Classes Primitive Data Type Wrapper Class double Double float long Long int Integer short Short byte Byte char Character boolean Boolean
Integer and Double Methods static Integer Methods static Double Methods Return value Method Name and argument list int parseInt( String s ) returns the String s as an int Integer valueOf( String s ) returns the String s as an Integer object Return value Method Name and argument list double parseDouble( String s ) returns the String s as a double Double valueOf( String s ) returns the String s as a Double object
Back to Scanner We can capture the input from the keyboard directly as a numeric primitive data type instead of capturing it as a String first and then converting it (parsing it) to the particular numeric data type: i.e. Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); double a=scan.nextDouble();
Using the nextDouble method with Scanner object import java.util.Scanner; class UsingScannerDouble { public static void main(String[] args) Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); double d=scan.nextDouble(); System.out.println("The number you entered is:"+d); } Output: Enter a decimal numbner 13.456 The number you entered is:13.456
Autoboxing and Unboxing Autoboxing (Converting a primitive data type to an equivalent object): Automatic conversion between a primitive type and a wrapper object when a primitive type is used where an object is expected Integer intObject = 42; Unboxing (Converting an Object to a primitive data type) Automatic conversion between a wrapper object and a primitive data type when a wrapper object is used where a primitive data type is expected int fortyTwo = intObject;
To String() method We can add a new method in a template class that will allow us to see the values of the attributes of the class all at once without asking the accessor method for each one to give us its value and then displaying that value. We will call this method toString method public String toString() { code goes here } Notice that it returns a String.
Example of toString in the template class Suppose we have the class Person with attributes : String firstName, String lastName, int age. After all the other methods (i.e. constructors , accessor, mutator methods) we will add the following method at the bottom of the Person template class: public String toString() { String output=“The First Name is:”+ “ “+firstName+” ‘’+”The Last Name is:”+” “+” “+lastName+” “+ “The Age is :”+” “+age ; return output; }
Using the toString in the client class Now assume that we have a class PersonClient that uses the Person class. In the client class’ main method we instantiate an object of Person and use it to set the attributes . i.e. Person p=new Person(); p.setFirstName(“George”); etc. We can now get the attributes’ values and display them by including the following line of code: System.out.println(p.toString());
Study Guide Study Chapter 3 Read chapter 3 Sections 3.6, 3.7, 3.8, 3.9