Java Quick Reference Guide prepared by Jack Wilson Cerritos College
Feb 26, 2016
Language DescriptionJava is a:
– high-level– platform neutral– object-oriented– general purpose
programming language used to creategraphical and non-graphical applications
andapplets.
Java Language Tutorials
• A practical guide for programmers with hundreds of complete, working examples and dozens of trails--groups of lessons on a particular subject.
• These are HTML based tutorials made available by Sun Microsystems.
• Here is the link: http://java.sun.com/docs/books/tutorial
Language Keywords• Here's a list of Java's keywords. These words are reserved--you cannot use any of these words
as names in your Java programs. true, false, and null are not keywords but they are reserved words, so you cannot use them as names in your programs either.
* indicates a keyword that is not currently used ** indicates a keyword that was added for Java 2
abstract double int strictfp**
boolean else interface super
break extends long switch
byte final native synchronized
case finally new this
catch float package throw
char for private throws
class goto* protected transient
const* if public try
continue implements return void
default imports short volatile
do instanceof static while
Java Identifiers• Identifier is the generic term for any programmer-created name.
• Programmers create names for– classes– methods– fields ( global variables )– variables– named constants
• The valid characters which can be used in an identifier are:– upper/lowercase letters– digits 0-9– 2 special characters $ and _ (underscore)
• Identifiers can not begin with a digit
• Identifiers can not contain spaces
• Identifiers are case sensitive
• Camel casing should be used for identifiers in Java– Title case: classes– sentence case: fields, variables, method
• An identifier can not be a keyword in the language
Data TypesJava Primitive Data Types
Type Description Range ( Values )
boolean logical true, false
char 16-bit unsigned integer Unicode Character Set
byte 8-bit integer 1 byte -128 ... 127
short 16-bit integer 2 bytes -32,768 ... 32,767
int 32-bit integer 4 bytes -2,147,483,648 ... 2,147,483,647
long 64-bit integer 8 bytes -9,223,372,036,854,775,808 ... 9,223,372,036,854,775,807
float 32-bit IEEE 754 single-precision number 4 bytes -3.4 * 1038 ... 3.4 * 1038
double 64-bit IEEE 754 double-precision number 8 bytes -1.7 * 10308 ... 1.7 * 10308
The default integer literal type is int.The default floating-point literal type is double.
Note: String is not a primitive data type; it is a class.
Control Structures - Selection if/else statement
Simple if Example
if (expression) if (x < y) statement; x++;
if/else Example
if (expression) if (x < y) statement; x++;else else statement; x--;
Control Structures - Selection if/else-if statement
nested ifif/else if Example
if (expression) if (x < y) statement; x++;else else if (expression) if (x < z) statement; x--; else else statement; y++;
Control Structures- Selection block if - statement
To conditionally-execute more than one statement, enclose the statements in braces ( create a block of statements ).
Form Example
if (expression) if (x < y){ { statement; System.out.println( x ); statement; x++;} }
Input in Java Using the Scanner class
Input from the keyboard is easily done using the Scanner class and the System.in object.
To use the Scanner class you must import the package java.util
Scanner inFile = new Scanner( System.in ); //Get input from the keyboardNote: inFile is a variable name. Any valid identifier can be used.
int x; double y; long z;String s;
x = inFile.nextInt( ); //get next token as an integer Y = inFile.nextDouble( ); //get next token as a doublez = inFile.nextLong( ); //get next token as a long integer
S = inFile.next( ); //get next token as a StringS = inFile.nextLine( ); //get the rest of the line as a String
The Scanner class also has the methods: hasNext( ), hasNextInt( ), and hasNextDouble( ) which return true if a String, int or double can be read from the input buffer. These allow you to “look ahead” and see if a value exists which can be converted to a specific data type is in the input buffer.
Output in Java• Output is done in Java using the System.out object.
– System is the name of a class– out is the name of an object that is part of the System class. The out object
is used to send output to the standard output device ( the screen ).
• The System.out object uses two methods, print( ) and println( ) that work almost identically.
– When you use the print( ) method, a newline character is not automatically output. Use this method when you do not want the cursor to move to the beginning of the next line. This works well for a prompt.
– When you use the println( ) method, a newline character is automatically output. Use this method to position the cursor at the beginning of the next line when it finishes printing the current line of output.
– JDK 5.0 also now supports the use of the printf( ) method to format output.
Output in Java• The print( ) and println( ) methods display a string which
may be composed of multiple expressions that are concatenated together using the concatenation operator +.
• The print( ) and println( ) methods convert any expressions that are not of type String into a String literal.
• Once all of the expressions to be displayed have been converted into strings (if necessary), they are concatenated together to create a single string that is then output to the screen (or written to a file).
Output in JavaOutput Examples
String name = "Jack";System.out.println("Hello " + name + ", nice to meet you!");
• This would display the String "Hello Jack, nice to meet you!".• All of the expressions to be used are of type String so no
conversions are necessary. There are 3 pieces of information to display: (1) a String literal, (2) the value of a variable of type String, and (3) another String literal.
int num1 = 10;System.out.println("The value of num1 is: " + num1);
• This would display the String "The value of num1 is: 10".• The variable num1 is of type int. The integer value 10 is
converted into the String value "10". The two Strings "The value of num1 is: " and "10" are concatenated together and displayed as a single String on the screen.
Output in JavaOutput Examples
int num1 = 10;double num2 = 2.5;System.out.println("num1 is: " + num1 + ", num2 is: " + num2);
• This would display the String "num1 is: 10, num2 is: 2.5".• The variable num1 is of type int. The integer value 10 is
converted into the String value "10". • The variable num2 is of type double. The double value 2.5 is
converterd to the String value "2.5".• The Strings "num1 is: ", "10", ", num2 is: ", and "2.5" are
concatenated together to create the String "num1 is: 10, num2 is: 2.5" and displayed as a single String on the screen.
Output in JavaOutput Examples
int num1 = 10;double num2 = 2.5;System.out.println("num1 + num2 is: " + (num1 + num2));
• This will display the String "num1 + num2 is: 12.5“.
• The expression in the parentheses ( num1 + num2 ) is evaluated and determined to be the double value 12.5. Here the meaning of the plus sign was addition, not concatentation because of the use of parentheses.
• The double value 12.5 is converted into the String literal "12.5"
• The Strings "num1 + num2 is: " and "12.5" are concatenated together to create the String "num1 + num2 is: 12.5" and displayed as a single String on the screen.
The example above shows that an expression can be evaluated and the result of the expression displayed using the print( ) and println( ) methods. You should enclose a numeric expression in parentheses to force the expression to be evaluated before being converted into a String.
System.out.println("num1 + num2 is: " + num1 + num2);
• This would display the String "num1 + num2 is: 102.5".• It will convert the value in num1 into the String literal "10" and the value in num2 into the String literal "2.5". Then
all the Strings: "num1 + num2 is: ", "10" and "2.5" will be concatenated together into the String "num1 + num2 is: 102.5". Without the parentheses around num1 + num2, the meaning of the plus sign is concatenation, not addition.
Formatting Numeric Outputusing the printf( ) Method
• JDK 5.0 introduced the printf( ) method to Java. This method allows you to print expressions in “fields” that are formatted according to a format string.
• Format specifications must begin with a percent (%) sign.
%<width>.<precision>s //output a string
%<width>d //output an integer number //width specifies the size of a field to use
%<width>.<precision>f //output a floating-point number //precision specifies the number of decimal digits used //decimal portion is rounded to number of digits
%n //output a platform specific newline
Note: printf( ) does not print a newline character by default – it is similar to the print( ) method in this regard. Include %n in the format string to do this.
Formatting Numeric Outputusing the printf( ) Method
Example:
System.out.printf(“The sum is %f%n”, sum);
• sum must be a variable of type double or float because the format specifier f is used.
• sum will be displayed with a decimal point in a field with an many positions as necessary to display the number because no width or precision was specified.
• The %n causes a newline character to be output
Formatting Numeric Outputusing the printf( ) Method
Example:
System.out.printf(“The count is %d%n”, count);
• count must be a variable of type int because the format specifier d is used.
• count will be displayed in a field with as many positions as necessary to display the number.
• The %n causes a newline character to be output
Formatting Numeric Outputusing the printf( ) Method
Examples: Fixed dollar sign ( $ )
System.out.printf(“The total is $%,10.2f%n”, total); //This example includes values for for a flag, a width, and a precision
• total must be a variable of type double or float because the f format specifier is used.
• total will be displayed in a field 10 positions wide with 2 positions for decimal digits. [ 10.2 ] Note: the width must include space for commas and the decimal point. If you do not make the width large enough, Java will automatically expand it to be as large as necessary.
• Also, if total is a big enough number, it will be formatted with commas because the flag , is used.
• If total was 23784.56, it would be displayed as: $ 23,784.56• If total was 37.05, it would be displayed as: $ 37.05
Formatting Numeric Outputusing the printf( ) Method
Examples: Floating dollar sign ( $ )
System.out.printf(“The total is $%,.2f%n”, total); // precision only, no width
• total must be a variable of type double or float.
• total will be displayed in a field with 2 positions for decimal digits. Because the precision is specified but not the width, Java will use a field size as large as necessary and
• if total is a big enough number, it will be formatted with commas.• If total was 23784.56, it would be displayed as: $23,784.56• If total was 37.05, it would be displayed as: $37.05
Formatting Numeric Outputusing the String.format Method
If you want to build a formatted string that can be output using System.out.print(), System.out.println( ) or the JOptionPane.showMessageDialog( ) methods you can use the format method of the String class.
String formattedOutput;
formattedOutput = String.format(“The average is %,.2f”, average);
what goes inside the parentheses for the format method is the same information you would use with the printf( ) method!
System.out.println(formattedOutput);
JOptionPane.showMessageDialog(null, formattedOutput);
Input in Java•Scanner class (new to JDK 5.0)
Classes previously used in some Java textbooks:
– Keyboard class – TextIO class
These classes contain methods that can be used to read in values and store them in variables of the primitive data types and also read in a stream of characters and store them in a String object.
Frequently Used Classes
• java.lang.System ( in / out objects, exit() method )• java.lang.String ( declare String object reference variables )• Keyboard ( used to input a field into a variable )• TextIO ( used to input a field into a variable )• java.util.Scanner ( Scan strings/files using data-type specific methods )• java.util.StringTokenizer ( used to parse a String into tokens )• java.util.Random ( used to generate random numbers )• java.lang.Math ( variables: PI, E and methods: pow( ), sqrt( ) )
Note: Information in blue is a package name. All classes in the package java.lang are automatically imported for your use. Other classes must be explicitly imported using an import statement.
Working from the Command Line
To compile a Java source file, enter the command javac <Java source file>– javac Exercise13a.java ( the ".java" is required ) – You must remember to capitalize letters in the file name!– Use the same capitalization as you used for the class name
To run a Java program, enter the command java <program name>– java Exercise13a
Using a Scanner Object to extract fields from an Input File ( JDK 5.0 )
( record with Delimited Fields )
The Scanner class makes processing a delimited file very easy. Data can be read directly into the variables it will be stored in using type-specific methods. This avoids having to do conversion from String to numeric data types.
Example:
Scanner inFile = new Scanner(new File(“Furniture.txt”));
If the delimiter separating the tokens is NOT a whitespace character, use the useDelimiter( ) method to specify the delimiter being used.
For example:
inFile.useDelimiter(","); // every token is separated from the next token by a comma. This includes a "," at the end of each record.
while ( inFile.hasNext() ) // while there is another “record” in the input file{
custNum = inFile.nextInt( ); // get next token as an integercustName = inFile.next( ); // get next token as a stringmovieName = inFile.nextLine( ); // get the rest of the line as a stringcustBalance = inFile.nextDouble( ); // get next token as a double
}Note:
The fields in the record must be delimited by one or more of the delimiter characters ( in the example above: commas are the only allowable delimiter ). Any character may be designated as a delimiter. The default delimiter is a whitespace character.
Using an Input File ( old style: pre JDK 5.0 )
Requires the use of the following classes:
• FileReader and BufferedReader
To use these classes import the package java.io
The import statement would be: import java.io.*;
• A reference to FileReader or BufferedReader objects in any method requires the method to include the throws clause "throws IOException" in the method header.
• To read a record from a file, let us assume that a global object reference variable named inFile will be used.
• put the following declarations with your other GLOBAL variable declarations.
BufferedReader inFile; //used to read a record ( line ) from a file
• In the method where the file stream objects will be declared ( houseKeeping for instance ) put the following statements to create the objects.
inFile = new BufferedReader( new FileReader( "Furniture.txt" ) );
• Replace "Furniture.txt" with whatever the name is for your actual data file.
• The input “file” can be input from the keyboard. Use the following declaration to do this.
• All input will be in the form of a String ( you read in an entire record )
• The method used to read in the String is called readln( ).
Example: record = inFile.readln();
Using an Input File( fixed length records )
• Requires reading in a record and parsing it into fields using the substring method of the String class.
• Sample Input File record format:
continues on next slide
Field start end data type implieddecimals
customer number 1 4 Integer 0
customer name 5 24 String
customer balance 25 30 Floating-point 2
Using the substring method to extract fields from an Input File
( Fixed Length Records ) String custNumString, custName, custBalanceString; // String variables to hold input fields
int custNum; double custBalance; // Numeric fields to hold String data converted to a numeric type
record = inputFile.nextLine(); // record stored in a String
while ( record != null ) {
custNumString = record.substring(0, 4); custName = record.substring(4, 24); custBalanceString = record.substring(24, 30);
...
// use Java wrapper classes to do numeric conversions
custNum = Integer.parseInt( custNumString ); custBalance = Double.parseDouble( custBalanceString );
}
For each field in the data file:
• subtract one from the start position
• use the end position
as the arguments for the substring method.
Using an Input File( record with delimited fields )
• Requires reading in a record and parsing it into fields using the StringTokenizer class ( you must import the package java.util )
OR reading one field at a time using a Scanner object
• Sample Input File record format:
continues on next slide
Field maximum field length
data type includeddecimals
customer number 4 Integer 0
customer name 25 String
customer balance 6 Floating-point
2
Using a StringTokenizer Object to extract fields from an Input File
( record with Delimited Fields )String custNumString, custName, custBalanceString;// String variables to hold input fields
int custNum; double custBalance;// Numeric fields to hold String data converted to a numeric type
StringTokenizer st;
record = inputFile.readln(); // line is a String variablewhile ( record != null ){
st = new StringTokenizer( record, ",\t\n" ); // delimiters are comma, tab, newline
custNumString = st.nextToken( ); // get next token as a stringcustName = st.nextToken( ); // get next token as a stringcustBalanceString =st.nextToken( ); // get next token as a string
// use Java wrapper classes to do numeric conversions
custNum = Integer.parseInt( custNumString );custBalance = Double.parseDouble( custBalanceString );
// division by 100.0 was not necessary here because a decimal point was included in the data} Note:
The fields in the record must be delimited by one or more of the delimiter characters ( in the example above: commas, tabs, and newline characters are allowable delimiters ). Any character may be designated as a delimiter.
Using a Scanner Object to extract fields from an Input File( record with Delimited Fields )
// variables to hold input fields
String custName; int custNum; double custBalance;…
//Scanner object is named inputFile
while ( inputFile.hasNext( ) ){
custNum = inputFile.nextInt( ); // get next field as an intcustName = inputfile.next( ); // get next field as a StringcustBalance = inputFile.nextDouble( ); // get next field as a double
...} Note:
The fields in the record must be delimited by one or more of the delimiter characters ( in the example above: commas were used as the delijmiter character.). Any character may be designated as a delimite
Using an Output FileRequires the use of the following classes:
• FileWriter and PrintWriter• To use these classes import the package java.io• A reference to FileWriter, BufferedWriter or PrintWriter objects in any method requires the method to include
the throws clause "throws IOException"
• To write a record to a file, let us assume that a global object reference variable named outFile will be used.
• put the following declarations with your other GLOBAL variable declarations.
static PrintWriter outFile; //used to write to a file
• In the method where the file stream objects will be declared - houseKeeping for instance put the following statement to create the object.
outFile = new PrintWriter("Furniture Report.txt");
• Replace "Furniture Report.txt" with whatever the name is for your actual report file.
• Use the methods print( ), println( ), and printf( ) to write output to your file.
Formatting Numeric OutputNumberFormat class
• Format as currency or as a rate.
• Requires importing the package java.text
• Declaring a NumberFormat object:
– NumberFormat cf, rf; //cf – currency, rf – rate
– cf = NumberFormat.getCurrencyInstance( );//display number with dollar sign ($), commas ( , ), and a decimal point ( . )
– rf = NumberFormat.getRateInstance( );//display number as a percentage with a percent sign ( % )
– Use the format method to format a floating-point number as a string with formatting specified in the pattern.
System.out.println( "The selling price of the house is: " + cf.format( sellingPrice ) );
System.out.println( "The interest rate for your mortgage is: " + rf.format( intRate ) );
– A NumberFormat CurrencyInstance rounds a floating-point value to 2 decimal digits
Formatting Numeric OutputDecimalFormat class
• Rounds a number to a specific number of decimal digits.
• Requires importing the package java.text
• Declaring a DecimalFormat object:
– DecimalFormat df;
– df = new DecimalFormat("#.###"); // 5.2504 would display as $5.25 //round to 3 decimal digits//does not display non-significant zeros in the decimal positions
– df = new DecimalFormat("0.000"); // 5.2504 would display as 5.250 //a minimum of one integer digit and exactly 2 decimal digits is displayed
Using the Justify ClassThe Justify class has methods which can be used to align a string or a number ( variable or literal ). The alignment can be left, center, or right. All methods of the class return a String .Justify Class Methods:
For the following: • Object is a string, an integer, or a floating-point variable or
literal. Field size, start pos, end pos and number-of-spaces are integer values.
• Justify.left( object, field size )• Justify. center( object, field size )• Justify.right( object, field size )
• Justify.left( object, start pos, end pos )• Justify.center( object, start pos, end pos )• Justify.right( object, start pos, end pos )
• Justify.spaces( number-of-spaces )