• Methods *

  •  

    Java Study Guide

    Sources:

    1. Mughal & Rasmussen
    2. Brogden
    3. Flanagan
    4. Jaworski
    5. Grand
    Source Files Package Import Comments // Comment extends to end of line

    /* Comment can be multiline

    and extends to closing */

    /** Multiline

    Javadoc comment */
     
     

    Java Names

    Reserved words

    These words have meaning in the language
     
    abstract boolean break
    byte case catch
    char class continue
    default do double
    else extends final
    finally float for
    if implements import
    instanceof int interface
    long native new
    package private protected
    public return short
    static super switch
    synchronized this throw
    throws transient try
    void volatile while
         

    These are reserved but not used

    const

    goto

    These are reserved literal values

    null

    true

    false

    These are listed in two books(2 & 3) but not two others (1 & 4) as reserved but not used.
     
    byvalue cast future
    generic inner operator
    outer rest var

    Types

    Primitive types
     
    Family Datatype Size Max, Min
    Logic boolean 1 bit or N/A N/A
    Integers  byte 8 bits or 1 byte -27 to 27 - 1 or-128 to 127 
    short 16 bits or 2 bytes -215 to 215 - 1 or -32768 to 32767
    int 32 bits or 4 bytes -231 to 231 - 1 or about +- 2.1 billion
    long 64 bits or 8 bytes -263 to 263 - 1 or +- 9.2 e 18
    Floating Point float 32 bits or 4 bytes Approx. +- 1 e +- 40 
    double 64 bits or 8 bytes Approx. +- 1 e +- 300
    Textual ( Unicode) char 16 bits or 2 bytes 0 to 216-1 or 0x0 to 0xFFFF

    Reference Types

    Special Reference Types

    String

    Array Reference Types Wrapper Classes

    Each primitive type has a wrapper class.
     
    Primitive Type Wrapper Class
    boolean Boolean
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double
    char Character

    Instances of Wrapper classes are immutable, i.e. their value cannot be changed.

    Type Conversions and Casts

    byte -> short -> int -> long -> float -> double, and char -> int -> etc. instanceof operator

    Object classes can be compared using the instanceof operator

    <object> instanceof < Class >

    Any instanceof comparison to a null object will produce false.

    Comparisons of individual objects can be done using getClass

    e.g. obj1.getClass() == obj2.getClass()

    Literals

    Logical ( Boolean )

    Integers Hexadecimal (Base 16) Literals Octal ( Base 8 ) Literals Floating Point Literals

    Floating point literals are assumed when...

    Character Literals

    Can be specified ...

    public class TestChar { static char One = 'Z'; // char literal

    static char Two = 0x5a; // Hex Value

    static char Four = '\u005a'; // Unicode Literal

    static char Five = '\132'; //Octal Value Character Literal

    // static char Three = \u005a;

    // Thinks that you are referring to a variable called Z!

    static {

    System.out.println(One + "," + Two + "," + Four + "," + Five);

    // Output is Z,Z,Z,Z

    }

    public static void main (String ars [] ){ }

    }

    Reference Type Literal

    Class Declarations

    Scope

    Modifiers

    abstract or final

    Subclassing Implementation Initialization

    Initializers - blocks of code or expressions that create the initial state.

    Initializer blocks

    static { } // will be run upon creation of the class

    or

    { } // will be run upon creation of an instance of the class

    Constructors

    Constructors look like methods ...

    e.g.

    class A {

    A ( int n ) { }

    }

    class B extends A { }

    // Should generate the compiler error

    // "No constructor matching A ( ) found in A "

    Initializer Order static initializers ( only the first time the class is loaded )

    superclass initializers

    superclass constructors

    instance initializers

    constructors

    e.g.

    class A {

    public A() { System.out.println("Constructor in A");}

    static { System.out.println("Static Initializer in A");}

    { System.out.println("Instance Initializer in A"); }

    } // End class A

    class B extends A {

    public B() { System.out.println("Constructor in B"); }

    static { System.out.println("Static Initializer in B"); }

    { System.out.println("Instance Initializer in B");}

    } // End class B

    class D {

    static {System.out.println("Static Initializer in D"); }

    }

    public class ConstructionTest {

    static {System.out.println("Static Initializer in ConstructionTest"); }

    public static void main (String [] args) {

    new B(); }

    } // End ConstructionTest

    The output from this program is:

    Static Initializer in ConstructionTest

    Static Initializer in A

    Static Initializer in B

    Instance Initializer in A

    Constructor in A

    Instance Initializer in B

    Constructor in B

    Note that the class D is not loaded, but if the main method is changed to

    public static void main (String [] args) {

    new B( );

    new D ( ); }

    The output becomes:

    Static Initializer in ConstructionTest

    Static Initializer in A

    Static Initializer in B

    Instance Initializer in A

    Constructor in A

    Instance Initializer in B

    Constructor in B

    Static Initializer in D

    e.g.

    class A {

    static int B = 1;

    static int C = B * D; // Compiler Error

    static int D = 1;

    }

    e.g.

    class A {

    static int B = 1;

    static int C = ValueOfC(); // Logic Error

    static int D = 1;

    static int ValueOfC(){

    System.out.println(D);

    return B * D;

    }

    }

    public class ForwardTest {

    public static void main (String [ ] args){

    new A();

    }

    }

    While class A may appear to have a forward reference, this program compiles. The error occurs in the logic. When the call to ValueOfC is made, D is not properly initialized and the value output by program is zero, the default value for D. Thus C acquires the value 1 * 0 = 0, because of the incorrect order of initialization.

    Exceptions in Initializers

    Initialization of Variables

    Default Values

    DataType Default Value
    boolean false
    char '\u0000'
    Integer ( byte, short, int, long ) 0
    Floating-point ( float, double ) +0.0F or +0.0D
    Object Reference Type null
    e.g. int i = 100 ; e.g. String s = new String ( "This is a String") ;

    Initializing Arrays

    e.g. int [ ] i = new int [ 10 ] ; e.g. int [ ] i = { 1, 2, 3, 4 };

    or int [ ] i = new int [ ] {1, 2, 3, 4 };

    e.g. int [ ] i = new int [4] {1, 2, 3, 4 }; // Statement will fail e.g. int [ ] [ ] = new int [ 4 ] [ ] ; // will work

    but int [ ] [ ] new int [ ] [ 4 ] ; // will fail

    e.g. int [ ] [ ] = { {1,2} , {3,4} } e.g.

    int [ ] [ ] = { {1,2} , {3, 4, 5, 6}, null , { } , new int [ 10 ] };

    // all valid assignments

    Finalization

    Finalizer methods

    A object finalizer method ...

    protected void finalize ( ) throws Throwable { } Class Member Declarations

    Species of Members

    A class member can be one of three species, variable, method, or nested class.

    Scope

    static ( Class ) Members Instance Members Variables

    final ( Constants )

    transient and volatile Nested Member Classes ( Inner Classes ) static (top level) classes

    Nested classes declared as static...

    inner interfaces non - static inner class

    Nested classes defined without the static modifier...

    e.g.

    TopLevel.Inner1.Inner2 TII = new TopLevel ( ).new Inner1 ( ).new Inner2 ( );

    Variable Declaration

    int [ ] i , j ; creates two integer arrays.

    int i [ ] , j ; creates one integer array i and one single integer j.

    Methods

    static Methods

    Instance Methods

    final

    abstract native synchronized Method Return Type e.g. These are all valid and equivalent methods:

    int [ ] [ ] [ ] A ( ) { }

    int [ ] [ ] A ( ) [ ] { }

    int [ ] A ( ) [ ] [ ] { }

    int A ( ) [ ] [ ] [ ] { }

    Method Name Method Parameters e.g.

    class B {

    int Bint = 100;

    }

    class C {

    int i = 100;

    B Bobj = new B ( );

    void CallD {

    D (i , Bobj );

    }

    void D (int x, B y ) {

    x=10;

    y.Bint = 10; // Changes the value of the object's member

    y = new B ( );

    }

    public static void main(String [ ] args ) {

    C Ctest = new C ( );

    Ctest.CallD;

    System.out.println ( Ctest.i ) ; // Outputs 100

    System.out.println (Ctest.Bobj.Bint ) ; // Ouputs 10

    }// End Main

    } // End Class C
     
     

    Method Signature

    e.g.

    int A(int B, int C, long D) { } // Reference method

    int A(int D, int B, long C) { } // Same signature

    int A(long B, long C, int D) { } // Different, types

    int A(int B, long D) { } // Different, number

    int A(int B, long D, int C) { } // Different, order

    e.g.

    int A(int B, int C, long D) { } // Reference method

    long A(int D, int B, long C) { } // Same signature

    e.g.

    int A(int B, int C, long D) { } // Reference method

    int A(final int B, final int C, final long D) { } // Same signature

    Overriding methods

    If a class declares a method with the same signature as a method in its superclass, it can override that method, provided...

    e.g.

    class ExceptionA extends Exception { }

    class ExceptionAA extends ExceptionA { }

    In Superclass

    void C ( ) throws ExceptionA { } // Superclass method

    Possible methods In Subclass

    void C ( ) throws ExceptionA { } // Overrides

    int C ( ) throws ExceptionA { } // Error, different return type

    private void C ( ) throws ExceptionA { }

    //Error, narrowed accessibility

    protected void C ( ) throws ExceptionA { } // Overrides

    void C ( ) throws Exception { } // Error, widens exceptions

    void C ( ) throws ExceptionAA { } // Overrides

    void C (int z ) throws ExceptionA { }

    // Does not override, but overloads

    super reference. this reference Overloading Methods e.g.

    void A( ) { } // reference

    int A ( ) { } // Error, return type does not change signature

    long A ( int i ) { } // OK, different signature

    Variable Shadowing e.g.

    class A {

    int B = 10;

    int C ( ) { return 10;}

    }

    class D extends A {

    int B = 100;

    int C ( ) { return 100; }

    }

    public class TestShadow {

    public static void main(String [] args){

    D Dtype = new D ();

    A Atype = Dtype; // Upcast to A class

    System.out.println (Dtype.B);

    System.out.println (Dtype.C( ) );

    System.out.println (Atype.B); // Shadowed Value

    System.out.println (Atype.C( ) ); // Still overridden value

    }

    }

    The output from this program is:

    100

    100

    10

    100

    Local Declarations

    Block Local Scoping

    e.g.

    int i;

    {

    int j;

    {

    int k;

    i=1; // ok

    j=1; // ok

    k=1; // ok

    }

    i=1; // ok

    j=1; // ok

    k=1; //Error, k not defined in this block

    }

    i=1; // ok

    j=1; // Error, j not defined in this block

    k=1; //Error, k not defined in this block

    Initialization of Local Variables Local Classes

    Local Classes ...

    e.g.

    class SuperA {

    String T = "Shadowed SuperA";

    String S ="SuperA";

    }

    class SuperInner {

    String T = "Super Inner";

    void PrintClass ( ){

    System.out.println("Class SuperInner");

    }

    }

    public class OuterA extends SuperA {

    String T = "OuterA";

    public static void main(String [] args){

    OuterA A = new OuterA ( );

    SuperInner SI = A.TestInnerClass("Final Variable");

    SI.PrintClass();

    }

    SuperInner TestInnerClass (final String B){

    class InnerClass extends SuperInner {

    String T = "Innner Class";

    {System.out.println(OuterA.this.T);}

    {System.out.println(OuterA.this.S);}

    {System.out.println(T);}

    {System.out.println(super.T);}

    {System.out.println(B);}

    void PrintClass ( ){

    System.out.println("Class InnerClass");

    }

    }

    return new InnerClass ();

    }

    }

    The output of this program is:

    OuterA

    SuperA

    Inner Class

    Super Inner

    Final Variable

    Class InnerClass

    Notice that the object returned is an instance of the inner class cast to a reference of the superclass, as demonstrated by the last line of output, which is from the overridden version of the method.

    Anonymous Classes

    Anonymous classes ...

    e.g.

    class SuperA {

    String T = "Shadowed SuperA";

    String S ="SuperA";

    }

    class SuperAnonymous {

    String T = "Super Anonymous";

    void PrintClass ( ){

    System.out.println("Class SuperAnonymous");

    }

    }

    public class OuterA extends SuperA {

    String T = "OuterA";

    public static void main(String [] args){

    OuterA A = new OuterA ( );

    SuperAnonymous SI = A.TestAnonymousClass("Final Variable");

    SI.PrintClass();

    }

    SuperAnonymous TestAnonymousClass (final String B){

    return new SuperAnonymous () {

    String T = "Anonymous Class";

    {System.out.println(OuterA.this.T);}

    {System.out.println(OuterA.this.S);}

    {System.out.println(T);}

    {System.out.println(super.T);}

    {System.out.println(B);}

    void PrintClass ( ){

    System.out.println("Class AnonymousClass");

    } // End of Anonymous PrintClass method

    } // End of Anonymous Class

    ; // Actually the end of the return statement

    } // End of TestAnonymousClass

    }

    The output from this program:

    OuterA

    SuperA

    Anonymous Class

    Super Anonymous

    Final Variable

    Class AnonymousClass

    Operators

    Multiplication / Division / Modulus

    Addition / Subtraction

    Shift

    Relational ( < , >= , instanceof, etc.)

    Equality / Not Equal

    AND ( & )

    XOR ( ^ )

    OR ( | )

    Conditional AND ( && )

    Conditional OR ( | | )

    Assignment Operator ( = )

    Flow of Control

    Labeled Statements and Blocks

    e.g.

    public class TestLabel {

    static final int SFV = 100;

    public static void main (String [] args){

    boolean b = true;

    main:

    while (b ) {

    break main;

    }

    System.out.println("Break first loop");

    main:

    while (b ) {

    break main;

    }

    System.out.println("Break second loop");

    main:; // legal but cannot be the target

    // of control transfer since it does not create

    // an enclosing context and there is no goto

    main:{

    if (b) break main;

    System.out.println("In Block");

    }

    System.out.println("End of block");

    main:{

    if (!b) break main;

    main:{

    if (b) break main;

    System.out.println("In Nested Block");

    }

    System.out.println("End Nested Block");

    if (b) break main;

    System.out.println("In block");

    }

    System.out.println("End of block");

    main: SecondLabel: ThirdLabel:{

    if (b) break SecondLabel;

    }

    } // end main

    } // end class

    The output of this program is:

    Break first loop

    Break second loop

    End of block

    End nested block

    End of block

    switch

    e.g.

    public class TestSwitch {

    static final int SFV = 100;

    public static void main (String [] args){

    byte b = 10;

    switch (b){

    default:

    { }

    case 1: case 2: case 3:

    {}

    case SFV:

    { }

    // case 300: causes a compiler error

    { }

    }// end switch

    } // end main

    } // end class

    for loop

    break Statement continue Statement return Statement Exception handling try - catch - finally e.g. illegal syntax

    try something( );

    catch (Exception e ) recover();

    finally whew ( ) ;

    throw Statement; Interfaces This creates an unusual problem. Interface methods are implicitly public, which is why the compiler gives an error for this example code that says you must use a public method to override the method of the interface. interface A {

    void TestMethod ();

    }

    public class B implements A {

    void TestMethod () { }

    }

    Interface variables Interface methods Threads

    Creation

    Running a Thread

    Thread termination

    A Thread dies under one of the following conditions

    Thread synchronization synchronized methods synchronized blocks Thread states

    Threads can be in one of four states

    wait and notify join ( ) and isAlive ( )

    Summary of Thread Methods
     
    Method Class Static or Instance throws InterruptedException Must be Executed in synchronized block-
    start ( )  Thread Instance    
    run ( ) Thread Instance    
    interrupt ( ) Thread Instance    
    join ( ) Thread Instance    
    yield ( ) Thread static    
    sleep ( long ) Thread static yes  
    wait ( ) Object Instance yes yes
    notify ( ) Object Instance   yes
    notifyAll ( ) Object Instance   yes

    Deprecated Methods:

    suspend, resume, and stop have been deprecated in Java 2.