Download
java quick reference guide n.
Skip this Video
Loading SlideShow in 5 Seconds..
Java Quick Reference Guide PowerPoint Presentation
Download Presentation
Java Quick Reference Guide

Java Quick Reference Guide

155 Views Download Presentation
Download Presentation

Java Quick Reference Guide

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Java Quick Reference Guide prepared by Jack Wilson Cerritos College

  2. Language Description Java is a: • high-level • platform neutral • object-oriented • general purpose programming language used to create graphical and non-graphical applications and applets.

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

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

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

  6. Data Types Note: String is not a primitive data type; it is a class.

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

  8. Control Structures - Selection if/else-if statement nested if if/else if Example if (expression) if (x < y) statement; x++; else else if (expression) if (x < z) statement; x--; else else statement; y++;

  9. 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++; } }

  10. 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 keyboard Note: 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 double z = inFile.nextLong( ); //get next token as a long integer S = inFile.next( ); //get next token as a String S = 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.

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

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

  13. Output in Java Output 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 isconverted 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.

  14. Output in Java Output 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 isconverted into the String value "10". • The variable num2 is of type double. The double value 2.5 isconverterd 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.

  15. Output in Java Output 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 ) isevaluated 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 isconverted 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.

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

  17. Formatting Numeric Outputusing the printf( ) Method Example: System.out.printf(“The sum is %f%n”, sum); • summustbe a variable of type double or float because the format specifier fisused. • sumwill 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

  18. Formatting Numeric Outputusing the printf( ) Method Example: System.out.printf(“The count is %d%n”, count); • countmustbe a variable of type int because the format specifier dis used. • countwill be displayed in a field with as many positions as necessary to display the number. • The %n causes a newline character to be output

  19. 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 • totalmust be a variable of type double or float because the f format specifier is used. • totalwill 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 totalis a big enough number, it will be formatted with commas because the flag ,is used. • If total was 23784.56, it wouldbe displayed as: $ 23,784.56 • If total was 37.05, it would be displayed as:$ 37.05

  20. Formatting Numeric Outputusing the printf( ) Method Examples: Floating dollar sign ( $ ) System.out.printf(“The total is $%,.2f%n”, total); // precision only, no width • totalmustbe a variable of type double or float. • totalwill 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 totalis 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

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

  22. Input in Java • Scanner class (new to JDK 5.0) Classes previously used in some Java textbooks: • Keyboard Class Documentation • TextIO Class Documentation • 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.

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

  24. Class Declarations( Procedural Programming ) [ <import statement(s)> ] class <Class-name> { <static global variables> <static method declarations> public static void main( String[] args ) { … } }

  25. Method Declarations( Procedural Programming ) static <data-type> <method-name> ( [<parameter-list>] ) [ throws <exception> ] { [ <local variable declarations> ] [ <method statements> ] [ <return-statement> ] //a return statement is required if the method returns a value //data-type is void if the method does not return a value }

  26. Compiling a Java Program in jGRASP

  27. Running a Java programin jGRASP

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

  29. 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 integer custName = inFile.next( ); // get next token as a string movieName = inFile.nextLine( ); // get the rest of the line as a string custBalance = 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.

  30. Using an Input File ( old style: pre JDK 5.0 ) Requires the use of the following classes: • FileReader and BufferedReaderTo use these classes import the package java.ioThe 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. static 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();

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

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

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

  34. 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 variable while ( record != null ) { st = new StringTokenizer( record, ",\t\n" ); // delimiters are comma, tab, newline custNumString = st.nextToken( ); // get next token as a string custName = st.nextToken( ); // get next token as a string custBalanceString =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.

  35. 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 int custName = inputfile.next( ); // get next field as a String custBalance = 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

  36. Using an Output File Requires 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 = newPrintWriter("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.

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

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

  39. Using the Justify Class The 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 )