Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd edition of text OR Finish reading Chapter 1 of the International edition of the text Assignment: Check the first assignment requirements Collect materials for the first assignment Creating Constants Many programs have data that does not need to be changed. Littering programs with literal values can make the program hard do read and maintain. Replacing literal values with constants remedies this problem. Constants allow the programmer to use a name rather than a value throughout the program. Constants also give a singular point for changing those values when needed. Creating Constants Constants keep the program organized and easier to maintain. Constants are identifiers that can hold only a single value. Constants are declared using the keyword final. based on T. Gaddis Starting Out with Java: From Control Structures through Data Structures 1
Constants need not be initialized when declared; however, they must be initialized before they are used or a compiler error will be generated. Creating Constants Once initialized with a value, constants cannot be changed programmatically. By convention, constants are all upper case and words are separated by the underscore character. f i n a l double CAL SALES TAX = 0. 7 2 5 ; The String Class As stated in the last lecture, Java types can be divided into groups 1. primitive types and 2. reference types Java Strings are an example of a reference type Java has no primitive data type that holds a series of characters. it does have the primitive type char to hold a single character The String class from the Java standard library is used for this purpose. In order to be useful, the a variable must be created to reference a String object. S t r i n g number ; this can be depicted by the following figure: The above statement only creates a reference of type String (not the actual String object) the String reference number has not been initialised, so it currently references (points to) null Trimester 2 2015 2 The University of New England
Notice the S in String is upper case. By convention, class names should always begin with an upper case character. Primitive vs. Reference Variables Primitive variables actually contain the value that they have been assigned. i n t numvalue = 2 5 ; The value 25 will be stored in the memory location associated with the variable numvalue Objects are not stored in variables, however. Note: Objects are referenced by variables. Primitive vs. Reference Variables When a variable references an object, it contains the memory address of the object s location. Then it is said that the variable references the object. S t r i n g cityname = "Charleston " ; String Objects A variable can be assigned a String literal. S t r i n g value = "Hello" ; Strings are the only objects that can be created in this way. (i.e., without the use of the new keyword) Usually, an instance of an object is created by using the new keyword. S t r i n g value ; value = new S t r i n g ( "Hello" ) ; 1. The first statement creates a reference of type String named value (it currently references (points to) null 2. The second statement creates the actual String object, initialises it with the string Hello and sets the String reference value to point to it. The University of New England 3 Trimester 2 2015
these 2 statements can be combined into 1 statement S t r i n g value = new S t r i n g ( "Hello" ) ; this can be depicted by the following figure: the String reference value, references the String object, which contains the Hello string literal. The use of the new keyword is the method that all other objects must use when they are created. See examples: StringDemo.java and also StringDemo1.java The program StringDemo: / / A s i m p l e program d e m o n s t r a t i n g S t r i n g o b j e c t s. / / n o t e we a r e c r e a t i n g S t r i n g o b j e c t s WITHOUT t h e use o f new keyword public c l a s s StringDemo { public s t a t i c void main ( S t r i n g [ ] args ) { S t r i n g g r e e t i n g = "Good morning " ; S t r i n g name = "Herman" ; } } System. out. p r i n t l n ( g r e e t i n g + name ) ; can be depicted graphically being executed by the following figure: Trimester 2 2015 4 The University of New England
here 2 different String references (greeting and name) point to 2 different String objects (one contains the literal string Good morning and the other Herman ) The String Methods Since String is a class, objects that are instances of it have methods. One of those methods is the length() method. this can be depicted by the following figure: Note: objects in general contain data and methods The University of New England 5 Trimester 2 2015
the data (in this case) being the literal string Hello one of the methods being the length() method. to invoke the length() method of a String object, you specify the variable name followed by a dot followed by the method name, e.g., value. length ( ) ; This statement invokes the length method on the object pointed to by the value variable. See example: StringLength.java String Methods The String class contains many methods that help with the manipulation of String objects. String objects are immutable, meaning that they cannot be changed. Many of the methods of a String object can create new versions of the object. See example: StringMethods.java Scope Scope refers to the part of a program that has access to a variable s contents. Variables declared inside a method (like the main method) are called local variables. Local variables scope begins at the declaration of the variable and ends at the end of the method in which it was declared. See example: Scope.java (This program contains an intentional error.) Commenting Code Java provides three methods for commenting code. Trimester 2 2015 6 The University of New England
Comment Style Description // Single line comment. Anything after the // on the line will be ignored by the compiler. /*... */ Block comment. Everything beginning with /* and ending with the first */ will be ignored by the compiler. This comment type cannot be nested. /**... */ Javadoc comment. This is a special version of the previous block comment that allows comments to be documented by the javadoc utility program. Everything beginning with the /** and ending with the first */ will be ignored by the compiler. This comment type cannot be nested. Commenting Code Javadoc comments can be built into HTML documentation. See example: Comment3.java To create the documentation: Run the javadoc program with the source file as an argument, for example: javadoc Comment3.java The javadoc program will create javadoc/index.html and several other documentation files in the same directory as the input file. Programming Style Although Java has a strict syntax, whitespace characters are ignored by the compiler. The Java whitespace characters are: space tab newline carriage return form feed See example: Compact.java Indentation Programs should use proper indentation. Each block of code should be indented a few spaces from its surrounding block. The University of New England 7 Trimester 2 2015
Two to four spaces are sufficient. Tab characters should be avoided. Tabs can vary in size between applications and devices. Most programming text editors allow the user to replace the tab with spaces. See example: Readable.java The Scanner Class So far we have only seen how to output something to the console using System.out e.g., the Java statement: System. out. p r i n t l n ( "HelloWorld" ) ; We also need to be able to read input into our program. To read input from the keyboard we can use the Scanner class. the Scanner class is a predefined class that is part of the Java API. (Just like the String class is a predefined class that is part of the Java API) Importing Packages All of the standard Java classes in included with Java are stored in a package called java the basic language functions are stored in a package inside of the java package called java.lang normally you would have to import every package or class that you want to use, but since Java is useless without mych of the functionability in java.lang, it is imported implicitly by the compiler for all Java programs. this is equivalent to having the following line placed at the beginning of every Java source code file: import java. lang. ; so instead of having to have this line in every Java program, the designers of the language loading java.lang by default The Scanner class is defined in java.util, so we will to enter the following statement at the top of our programs to be able to use it: import java. u t i l. Scanner ; Trimester 2 2015 8 The University of New England
The Scanner Class Scanner objects work with System.in to enable it to get input from the keyboard. To create such a Scanner object, we can use the following statement: Scanner keyboard = new Scanner ( System. i n ) ; the System.in part connects our Scanner object to standard input i.e., the keyboard Scanner class methods are listed in the text, and in the Java API See Payroll.java as an example of how they are used Converting String Input to Numbers From time to time we may need a way to convert a string that is composed of numbers, into a numeric type (e.g., to be able to use it in a calculation) User entry via graphical dialog boxes is treated as a string in Java it is up to the programmer to convert it to the required type Each of the numeric wrapper classes, (covered later in the next trimester) has a method that converts a string to a number (assuming that the string contains only numbers) The Integer class has a method that converts a string to an int, The Double class has a method that converts a string to a double. These methods are known as parse methods because their names begin with the word parse. The University of New England 9 Trimester 2 2015
The Parse Methods / / S t o r e 1 in bvar. byte bvar = Byte. parsebyte ( "1" ) ; / / S t o r e 2599 in ivar. i n t ivar = I n t e g e r. p a r s e I n t ( "2599" ) ; / / S t o r e 10 in svar. short svar = Short. parseshort ( "10" ) ; / / S t o r e 15908 in lvar. long lvar = Long. parselong ( "15908" ) ; / / S t o r e 1 2. 3 in fvar. f l o a t fvar = F l o a t. p a r s e F loat ( "12.3" ) ; / / S t o r e 7945.6 in dvar. double dvar = Double. parsedouble ( "7945.6" ) ; The System.exit( ) method normally a Java program stops executing when the end of the main method is reached. there are times where this does not happen e.g., with non-consol programs graphical programs there are also times when you would like a Java program to terminate before the end of the main method is reached. the System.exit( exit code ) method can be used in these instances to terminate program execution this method needs to have an argument supplied to it when it is invoked. the argument required for the System.exit method is an integer value that corresponds to an exit code. this exit code is passed back to the operating system when the program terminates: for example, the statement: System. e x i t ( 0 ) ; terminates the program and sends an error code (integer value) of 0 back to the operating system. an exit code value of 0 is traditionally used to indicate that the program ended successfully Trimester 2 2014 10 The University of New England
Things to Do Reading: Finish reading Chapter 2 of the 2nd edition of text OR Finish reading Chapter 1 of the International edition of the text Next Lecture: Software Development The University of New England 11 Trimester 2 2014