Java Quick Reference Guide by ygq15756

VIEWS: 49 PAGES: 39

									        Java
Quick Reference Guide
   prepared by Jack Wilson
       Cerritos College
   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.
  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.


                 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
                 * indicates a keyword that is not currently used
                ** indicates a keyword that was added for Java 2
         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 Types
                                          Java 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
                                                                                      -9,223,372,036,854,775,808 ...
long      64-bit integer         8 bytes
                                                                                       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 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++;
 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++;
}                       }
              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 has 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 of the
  System.out object can display a single expression
  or multiple expressions.

• 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 String literals, they are
  concatenated together as one string that is then
  output to the screen.

• If you need to specify multiple expressions,
  separate the expressions using a "+"
  (concatenation operator).
           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 displayed are of type   String so no
    conversions were necessary. There were 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 was
    converted into the String value "10". The two Strings "The
    value of num1 is: " and "10" were concatenated together and
    displayed as a single String on the screen.
           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 was
    converted into the String value "10".
•   The variable num2 is of type double. The double value 2.5 was
    converterd to the String value "2.5".
•   The Strings "num1 is: ", "10", ", num2 is: ", and "2.5" were
    concatenated together to create the String "num1 is: 10, num2
    is: 2.5" and displayed as a single String on the screen.
             Output in Java
Output Examples
int num1 = 10;
double num2 = 2.5;
System.out.println("num1 + num2 is: " + (num1 + num2));

This would display the String "num1 + num2 is: 12.5".
•   The expression in the parentheses ( num1 + num2 ) was evaluated and
    determined to be the double value 12.5. Here the meaning of the plus
    sign was addition, not concatentation.
•   The double value 12.5 was converted into the String literal "12.5"
•   The Strings "num1 + num2 is: " and "12.5" were 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 would 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" would 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.
                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.
              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 stdIn = new Scanner( System.in ); //Get input from the keyboard

int x; double y; long z;
String s;

x = stdIn.nextInt( );                      //get next token as an integer
Y = stdIn.nextDouble( );                   //get next token as a double
z = stdIn.nextLong( );                     //get next token as a long integer

S = stdIn.next( );                         //get next token as a String
S = stdIn.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.


           If the Scanner class methods are being used in a loop, it is best to use a do…while loop.
    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.
        Class Declarations
      ( Procedural Programming )
[ <import statement(s)> ]

class <Class-name>
{
   <static global variables>

    <static method declarations>

    public static void main( String[] args )
    { … }
}
         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
}
Compiling a Java Program in
          jGRASP
Running a Java program
      in jGRASP
     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.

Instead of using the FileReader and BufferedReader classes to access the input file, a File object is used.

Example:

Scanner sc = 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:

sc.useDelimiter(","); // every token is separated from the next token by a
comma. This includes a "," at the end of each record.

while ( sc.hasNext() )   // while there is                              another “record” in the input file
{
    custNum     = sc.nextInt( );    // get                              next token as an integer
    custName    = sc.next( );       // get                              next token as a string
    movieName   = sc.nextLine( );   // get                              the rest of the line as a string
    custBalance = sc.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.

     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();
              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:
   Field                  start     end         data type        implied
                                                                 decimals
   customer number        1         4           Integer          0

   customer name          5         24          String

   customer balance       25        30          Floating-point   2




                      continues on next slide
 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        For each field in the data
                                                                    file:
 while ( record != null )                                              • subtract one from
 {                                                                       the start position
      custNumString = record.substring(0, 4);                          • use the end position
      custName = record.substring(4, 24);
      custBalanceString = record.substring(24, 30);                 as the arguments for the
                                                                    substring method.
       ...

      // use Java wrapper classes to do numeric conversions

        custNum     = Integer.parseInt( custNumString );
        custBalance = Double.parseDouble( custBalanceString );

  }
         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:
      Field                       maximum field    data type   included
                                  length                       decimals

      customer number             4                Integer     0

      customer name               25               String

      customer balance            6                Floating-   2
                                                   point


                         continues on next slide
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.
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
                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 a record ( line ) 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(new FileWriter("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 Output
using the System.out.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 parameters and flags in a format string.
• Parameters are shown using a percent (%) sign.

         %<width>.<precision>s            //output a string

         %<width>d                        //output an integer number

          %<width>.<precision>f           //output a floating-point number

         %n                               //output a platform specific newline
   Note: System.out.printf( ) does not print a newline character by default – it is
   similar to System.out.print( ). Include %n in the format string to do this.
     Formatting Numeric Output
using the System.out.printf( ) Method

 Example:

 System.out.printf(“The sum is %f%n”, sum);

 • sum would be a variable of type double or float.

 • sum would be displayed with a decimal point in a
   field with an many positions as necessary to display
   the number.

 • The %n causes a newline character to be output
     Formatting Numeric Output
using the System.out.printf( ) Method

  Example:

  System.out.printf(“The count is %d%n”, count);

  • count would be a variable of type int.

  • count would be displayed in a field with an many
    positions as necessary to display the number.
     Formatting Numeric Output
using the System.out.printf( ) Method
   Examples:         Fixed dollar sign ( $ )

   System.out.printf(“The total is $%,10.2f%n”, total); //width and precision

   • total would be a variable of type double or float.

   • total would be displayed in a field 10 positions wide with 2
     positions for decimal digits.

   • Also, if total was a big enough number, it would 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 Output
using the System.out.printf( ) Method
   Examples:          Floating dollar sign ( $ )

   System.out.printf(“The total is $%,.2f%n”, total); // precision only, no width

   • total would be a variable of type double or float.

   • total would be displayed in a field with 2 positions for decimal
     digits.

   • if total was a big enough number, it would 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 Output
using the String.format Method

If you want to build a formatted string 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 System.out.printf( ) method!

System.out.println(formattedOutput);
JOptionPane.showMessageDialog(null, formattedOutput);
         Formatting Numeric Output
            NumberFormat 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 Output
           DecimalFormat 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 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 )

								
To top