Lovin Varghese

SCJP 1.4 Study Guide

Home | Professional Experience | Technical Presentations | SCJP 1.4 Study Guide | Photo Gallery | More Photos

Sun Certified Java Professional (1.4)

Exam Notes

 

  • Primitive Data Types
    • The four singed integrals data types are
      • Byte, short, int, long
    • Representation Size
      • Boolean, byte    ==        8 bits
      • Char, short        ==        16 bits
      • Int,float              ==        32 bits
      • Long, double      ==        64 bits
    • Ranges of integral data type
      • Byte = -27 to  27 1        è -128 to 128
      • Short = -215 to  215 1   è -32768 to 32768
      • int = -231 to  231 1        è  -2147483648 to 2147483648
      • long = -263 to 263 1      è -9223372036854775808  to 9223372036854775808`
    • The char type is integral but unsigned. The range of a variable of type char is from 0 through 216 1.
    • Literals in java are
      • true and false for Boolean.
      • \u232 like things for char.
      • 0x24, 0X24,0x1C like things for integer.
      • 4.23E+21, 1.828f,1234d for floating point variable.
    • In any of the loop, when accessing the array, the safest way to access the array length is by array.length.
    • Initial value of long is 0L, float is 0.0f and double is 0.0d.
    • None of the local variables are initialized by the system; every local variable must be explicitly initialized before used.
    • When an object is created like Button b=new Button(Good).  b contains the reference of the Button object like pointer. When this b is passed to a method the reference is passed not the object.

ChangeButton(Button b)

{          

b=new Button(Evil);  // New button reference will be assigned to b           

                        }

    • If you pass a array of primitive datatype to the method, datatype will not be copied, instead the reference will be given to the method.
    • Array must be in the order of Declaration, Allocation and Initialization.

 

 

  • Operators and Assignments
    • The four singed integrals data types are
    • All operands are evaluated left to right b=1 and a[b]=b=0;
    • For the operators left of an expression (--x) gets evaluated before the rest of calculation.  Operators right of an expression (x++) get evaluated after the expression has been calculated.
    • The bit operator (~) changes all the 1 bits to 0 and 0 bits to 1.
    • The casting of a data type can be done by only, Highest to lowest like (int) double.
    • In the case of casting of Objects, which down casting explicit cast is required but for the up casting explicit cast is not required.
    • In the case of / and * operator, it is better to multiply first and then divide.
    • + operator is overloaded in Java.  For addition and for concatenation.
    • If a binary number is shifted left one position the effect of the shift is to double the original number.  X<<1  => x * 2   : X<<4 => x* 2*2*2*2

Formula:  X<<N => X * 2N   

    • If a binary number is shifted right one position the effect of the shift is to halve the original number. X>>1  => x / 2   : X>>4 => x/ 2*2*2*2

Formula:  X>>N => X / 2N   

    • Using Not(~) operator : ~n = -(n+1)  ie -10 = -(-10+1)=9 

v1 = 41

v2 = ~v1 

i.e.Not(v1) = opp sign(v1+1) therefore v2 = -42

    • Illegal Statement : if( x instanceof [])
    • The "instanceof" operator tests the class of an object at runtime. It returns true if the class of the left-hand argument is the same as, or is some subclass of, the class specified by the right-hand operand. The right-hand operand may equally well be an interface. In such a case, the test determines if the object at left-hand argument implements the specified interface.
    • For AND operation, 1 AND 1 produces 1.  Any other combination produces 0.
    • For XOR operation, 1 XOR  0 produces 1 and 0 XOR produces 1.  Any other combinations produce 0.
    • For OR operation, 0 OR 0 produces 0 and other combinations produces 1.
    • Ternary operator a = x ? b :c;    ==>    if(x){ a=b;}else{a=c;}
    • ! (NOT operator) can be used with only boolean.
    • The result of System.out.println("1"+2+3); is 123.
    • In the case of switch case the default block can be anywhere.
    • The type of the switch expression must be byte, char, short or int.

 

 

  • The Access Modifiers
    • All the modifiers are public, protected, private, final, abstract, static, native, transient, synchronized and volatile.
    • A method with some particular access type may be overridden by a method with a different access type; provided there is path in the figure from the original type to the new type.

Private è Friendly è Protected è Public

    • Final Class cannot be sub classed.  Final variable may not be modified once it has been assigned a value.
    • You may not change a final object reference variable.  You may change data owned by object that is refereed to by a final object reference variable.
    • The abstract modifier can be applied to classes and methods only. A class that is abstract may not be instantiated.  If a class contains one or more abstract methods, the complier insists that the class must be declared abstract.
    • All members of the superclass are inherited by the subclass (inheritance is different from accessibility)
    • An overriding method can't throw more or broader checked exceptions - this is not true for overloading methods
    • private methods cannot be overridden final methods cannot be overridden. overridden static method must also be static
    • Constructors cannot be final , static or abstract.
    • Normally you cannot put any code inside an interface, but a static inner class can be part of an interface
    • Literal null is not an instance of any reference type
      • boolean t2 = "String" instanceof Object //is true as always creates a string object for it ie extends Obj
      • boolean t1 = null instanceof Pizza                       //Always false null not an instance
    • In fact, the compiler insists that a class must be declared abstract if any of the following conditions is true:
      • The class has one or more abstract methods.
      • The class inherits one or more abstract methods (from an abstract parent) for which it does not provide implementations.
      • The class declares that it implements an interface but does not provide implementations for every method of the interface.
    • An instance of superclass is not an instance of subclass
    • An instance of a class is not an instance of an unrelated (or Peer class) class.
    • An instance of a class is not an instance of an interface that it does not implement (unrelated)
    • An instance of a array of non-primitive type is an instance of both Object & Object[] types
    • In a way, abstract is the opposite of final.  A final class, for example, may not be subclassed; an abstract class must be subclassed.
    • The static modifier can be used for the variable and methods.  There are two ways to reference a static variable.
      • Via a reference to any instance of the class.
      • Via a class name.
    • The static methods are not allowed to use the non-static features of their class (although they are free to access the class static data and call its other static method).  Thus static methods are not concerned with individual instances of a class.  They may be invoked before even a single instance of the class is constructed. 
    • A static method may not be overridden to be non-static.
    • At class-load time, all static initialization and all free-floating static code are executed in order of appearance within the class definition.
    • The native  modifier can refer only to methods.  Like the abstract keyword, native indicates that the body of a method is to be found elsewhere.

Class NativeExample

{

native void doSimethingLocal(int i);

static{

`System.loadLibrary(MyNativeLib);

}

                                }

    • The transient  modifier applies only to variables.  A transient variable is not stored as part of its object persistent state.
    • The synchronized modifier is used to control access to critical code in multithreaded programs.
    • Making a variable volatile indicates that such variables might be modified asynchronously, so the compiler takes special precautions.
    • Inheritance defines the relationship is-a between a superclass and subclasses.
    • The has-a relationship is between an instance of a class and its constituents.
    • Constructors cannot be overridden but they can be overloaded in the same class.
    • this() call must occur as the first statement in a constructor and it can only be used in a constructor definition.
    • The super() construct is used in a subclass constructor to invoke constructors in the immediate superclass.  The super can also be used in subclass constructor to access inherited instance members via its superclass.
    • super() call must occur as the first statement in a constructor and hence super() and this() both cannot be inserted together in constructor.
    • If the superclass doesnt have a default constructor then the subclass should explicitly call the other constructors of the superclass with the help of super().
    • super.super.x() is not allowed as super is a keyword not an attribute.

Static Initializer Block

    • Executed just once when the class is initialized
    • usually used to initialize static variable, load external libraries for native methods
    • static{;} is valid block
    • a class can have more than one static block
    • Static Initializer Block cannot pass on checked exceptions - it must be caught & handled as no constructor is involved in the class init

 

Instance Initializer blocks

    • Similar to static blocks but act as constructors during object creation used to factor out code common to all the constructors of the class e.g. final instance variables, in anonymous class which does not have constructors initialize any final blank variables a class can have more than one instance instance init block exception handling is similar as above except that.
    • If an instance initializer block does not catch a checked exception that can occur during its execution then the exception must be declared in the throws clause of every constructor in the class
    • Instance initializer in anonymous class can throw any exception

Order of initialization For a class

1.       Final

2.       Static expr & blocks in order they r specified in class

3.       Object creation -> Super class initialization (static variable , constructors)

4.       Instance variable & expr in order they r specified in class

5.       Local chaining of Constructors of object

 

                                                 Garbage Collection

    • If an object obj1 can access an object obj2 that is eligible for garbage collection, then obj1 is also eligible for garbage collection.
    • Object class contains finalize() method therefore all objects have finalize method protected void finalize() throws Throwable{}
    •  

Modifier

Class

Variable

Method/Ctor

Free Floating Block

Public

Yes

Yes

Yes

No

protected

No

Yes

Yes

No

(default)

Yes

Yes

Yes

No

Private

No

Yes

Yes

No

Final

Yes

Yes

Yes

No

abstract

Yes

No

Yes

No

Static

No

Yes

Yes

Yes

Native

No

No

Yes

No

Transient

No

Yes

No

No

Synchronized

No

No

Yes

No

    • More tips
      • public final static native int method(); is Legal
      • Important Rule: abstract & final cannot be applied together.  Like

abstract final double testing();

      • A final class may not have any abstract methods, but an abstract class may have final methods.
      • Static methods may not be overridden to be non-static.

 

 

 

  • Primitives and Convertion

 

byte

short

char

int

long

float

double

 

 

 

 

 


    • Char goes in the only place it could go: a 16-bit char fits inside a 32 bit in.
    • You cannot convert byte to char or char to a short.

 

 

 

Unary Operators:

"+"

"-"

"++"

"--"

 

~

 

 

Binary Operators

"+"

"-"

*

/

%

>>

>>>

<<

 

 

&

^

|

 

 

 

 

 

                        Eg :      short s=9;

                                    Int i=10;

                                    Float f = 11.1f;

                                    Double d=12.2;

                                    If( ++s * I >= f/d)

                                   

 

    • Rules for a Unary operators
        • If the operand is a byte, a short or a char, it is converted to an int.
        • Else if the operand is of any other type, it is not converted.
    • Rules for a Binary operators
        • If one of the operands is a double, the other operand is converted to a double.
        • If one of the operands is a float, the other operand is converted to a float.
        • If one of the operands is a long, the other operand is converted to a long.
        • Else both operand are converted to ints.

 

    • Only casting of object references potentially requires a runtime check.
    • Two bytes variable cannot be multiplied and assigned to byte variable.
    • Object references can be converted in both method class and assignments, and the rules governing these conversions are identical.

 

  • Exceptions
    • Exception Class Hierarchy

 

 

    • The circumstances that can prevent execution of the code in a finally block are
      • The death of the thread
      • The use of System.exit()
      • Turning off the power of the CPU.
      • An exception arising in the finally block itself.

java.lang.Exception

java.lang.Error

java.lang.Throwable

 

 

 

 

 

 

 

 

 


java.lang.RuntimeException

                                 Checked Exceptions                                                             Errors

 

 

 

                                                                        Runtime Exceptions

 

    • When you extend a class and override a method, Java insists that the new method cannot be declared as throwing check exceptions of classes other than those that were declared by the original method. 
    • One can override a function with the new Exception only if the Exception is a subclass of the original method exception.

    • In a switch case you cannot give case 2+1:  it will go to default: block.

 

  • Inner Classes
    • OuterOne.InnerOne i=o.new InnerOne();  i.innerMethod();
    • If you attempt to use the new operation to construct an instance of an inner class without a prefixing reference to an instance of the outer class, ten the implied prefix this. is assumed.
    • Outter.Inner in= new Inner();

      in.method();                   This code will work fine, except in a static block.

    • Static inner class does not have any reference to an enclosing instance, because of this inner class cannot access instance variables of the enclosing class.
    • You can create an instance of a static inner class without the need for a current instance of the enclosing class.
    • Inner classes inside methods:  Any variable, either a local variable or a formal parameter, can be accessed by methods within an inner class, provided that variable is marked final.
    • If the subclass has a default constructor, then the base class should also have a default constructor implementation.
    • Top-Level Nested Class (DEFINES BOTH static & non-static members)
    • Top-level class can have only default or public modifier but its nested class can have any modifier
    • The static nested class is tied only to the outer class, not an instance of the outer class. e.g. Outer.Inner i = new Outer.Inner(); // i instanceof Outer = false
    • A static nested top-level class can be instantiated without  any reference to any instance of the enclosing context / nesting. Inner n = new Inner(); // outer instance is not a must for static class
    • Inner class cant contain non-static members and therefore cannot contain top-level nested classes and static methods.
    • Only top level nested classes can be declared static.  Declaring a class static only means that instances of the class are created without having an outer instance.  It doesnt put any limits on whether the members of the class can be static or not.

Types of inner class

 

 

Modifier

for class & local variables

Outer Instance exist

Access to Enclosing context  members

Non-Static Inner Class

 

All

Yes

All members

Local Class (as member variables - in blocks class within a method, constructor)

Non-Static

 

None

 

Yes

All members  - enclosing class

Local final variables - enclosing method

implicitly Static if context is static

No

§         static members (encl class)

§         local final variables (encl method)

Anonymous Inner class (as expressions)

Non-Static

 

None

Yes

all members

local final variables

implicitly Static if context is static

No

§         static members

§         local final variables

 

    • The non-final parameter is not accessible from within the inner class.
      • Public method(final int i) {

class myclass implement myInterface{

            public int getInt() { return I;}

}

return new myclass();

                                    }

    • You cannot declare static members within a non-static inner class.
    • Anonymous classes cannot have constructors.

 

Nested Top-Level class

[not an inner class]

·         Nested Top-Level class is a nested class that is declared "static"

·         Nested top-level classes are used as a convenient way to group related classes.

·         This is, but a new kind of top-level class

·         Since static doesn't have a "this" pointer to an instance of the enclosing class, a nested class has no access to the instance data of objects for its enclosing class.

·         Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package.(eg, If class "top" has nested top-level class called "myNested", this would be referred to as top.myNested)

·         Top-level inner classes implicitly have access only to static variables.

class outer {
int a, b;
static class myInner {
int c, d;
void innerMethod() {.....}
}
void outerMethod() {
myInner mi = new myInner();
}
}

class other {
outer.myInner outInner = new outer.myInner();
}

 

Member class

·         A nested class cannot define any "static" variables

·         Scope of the inner class is the entire parent in which it is directly nested. ie, the inner class can reference any members in its parent.

·         The parent must declare an instance of an inner class before it can invoke the inner class methods, assign to data fields and so on (including private ones)

·         Unlike nested top-level classes, inner classes are not directly part of a package and are not visible outside the class in which they are nested.

class outer {
int a=5;
class myInner {
int c=a;          //access to all members of encls.
void innerMethod(){...}
}
void outerMethod() {
myInner mi1 = new myInner();
myInner mi1 = new myInner();
mi1.c = mi2.c + 30;
}
}

Local class

 

·         This is an inner class declared within a block, typically within a method

·         It is not a member of the enclosing class.

·         Their visibility is only within the block of their declaration.

·         In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.

·         Because local classes are not members, the modifiers public, protected, private, and static are not usable.

·         Local classes can access only final variables or parameters.

class MyClass {

public static void main(String[] args) {

  final String s = some local   results;

  class Local {

    Local()      

      {System.out.println(s);}

  }

  new Local();

}

}

 

Anonymous class

 

·         A variation on a local class. The class is declared and instantiated within a single expression

·         These classes are simply inner classes that are not given a specific name.

·         When you don't even need a name because you really just want to pass a method that does something, then you can get away with creating an anonymous inner class.

·         Typically, a class is not named when it is used only once.

·         We are declaring an object of an anonymous class type that either implements the interface or extends the class. If it extends the class, then any methods we define may override the corresponding methods of the base class.

public class A extends JApplet {
JButton b = new JButton("click");
public void init() {
b.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e)

  {System.out.println("Action Performed"); }
} );
}

Extending a class :

 new SuperClassName(arguments) {

      // Class body

     }

Implementing an interface

     new InterfaceName() {

      // Implement interface methods

     }

 

 

 

 

 

 

  • Threads
    • Only the methods of a class or a block of a class can be declared synchronized.
    • When start() method of the Thread is called, this registers the thread with a piece of system code called the thread scheduler.  Calling start () method doesnt immediately cause the thread to run; it just makes it eligible to run.
    • The thread can execute its own run() method or run() method of some other object.
    • Two types of thread implementations are
      • Type 1

public class CounterThread extends Thread{

            public void run(){

                        /// some code

            }

}

      • Type 2

public class CounterThread implements Runnable{

            public void run(){

/// some code

            }

}

CounterThread ct=new CounterThread()l

Thread t=new Thread(ct);

t.start();

 

 

    • A call to the yield() method causes the currently executing thread to move to the Ready state and starts if the scheduler is willing to run any other thread in place of the yielding thread.
    • Yielding allows the time consuming thread, to permit other thread to execute.

Running

Ready

Running

 


sleep()

Sleeping

 


scheduled         yield    

                        scheduled

Ready

 


                                                            time expires

                                                            or interrupted

    • Here are the main points to remember about wait()
      • The calling thread gives up the CPU.
      • The calling thread gives up the lock.
      • The calling thread goes into the monitors waiting pool.
    • Here are the main points to remember about notify()
      • One thread gets moved out of the monitors waiting pool and into the Ready state.
      • The thread was notified must re-acquire the monitors lock before it can proceed.
    • When you call notify() on a monitor, you have no control over which waiting thread gets notified.
    • wait() and notify() should always be called from a synchronized block.
    • Always check the monitors state in the while loop rather than an if statement.
    • A suspended thread can never resume itself,  since to do so it has to be running; a suspended thread can only be resume by a different thread.
    • A monitor is an instance of any class that has synchronized code.
    • After changing the monitors state, call notifyAll() rather than notify().
    • To synchronize an entire method, using the lock of the object that owes the method.  To do this, put the synchronized keyword in the methods declaration.
    • To synchronize part of a method, using the lock of a arbitrary object.  To do this, put curly brackets around the code to be synchronized, preceded by synchronized(theArbitraryObject).
    •  
  • The java.lang and java.util Packages

o         All instance of a wrapper classes (Integer, Character, Boolean, Short, Byte) are immutable objects.

o         d1==d2:  This statement will be true only if the reference of d1 is equals to reference of d2.  Of course this is only the case when both variables refer to the same object.

    • Math.ceil (10.1)  => 11.0 and Math.ceil(-10.1) è -10.0
    • Math.floor(10.1)  => 10.0 and Math.floor(-10.1) è -11.0
    • All wrapper types can be constructed from primitives; all except Character can also be constructed from Strings.
    • All the string value assigned is kept in a pool of literal.  Hence in the case of s1=Hello and s2=Hello  both s1 and s2 points to the same memory. You can make a object allocated outside the pool by using new operator like

s1=new String(Hello);

                       

 

o       LIST

    • The List interface extends the Collection interface to define an ordered collection, permitting duplicates.  The interface adds position-oriented operations, as well as the ability to work with just a part of the List.
    • The List interface also allows working with the sublist of a List with the help of List subList(int,int) function.
    • The ListIterator Interface extends the Iterator Interface to support bi-directional access, as well as adding or changing elements in the underlying collection.  It implement bi-directional iteration through next() and previous() function.  The add() operation results in the new element being added immediately prior to the implicit cursor.
    • ArrayList: If you need to support random access, without inserting or removing elements from any place other than the end of the List.
    • LinkedList:  If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially.

 

 

 

To Implement

AbstractList (need to implement)

AbstractSequentialList (need to implement)

Unmodifiable

Object get(int index)

ListIterator listIterator(int index)

 

int size()

boolean hasNext()

 

 

Object next()

 

 

int nextIndex()

 

 

boolean hasPrevious()

 

 

Object previous()

 

 

int previousIndex()

 

 

int size()

 

 

 

Modifiable

Object get(int index)

ListIterator listIterator(int index)

 

int size()

boolean hasNext()

 

Object set(int index,Object element)

Object next()

 

 

int nextIndex()

 

 

boolean hasPrevious()

 

 

Object previous()

 

 

int previousIndex()

 

 

int size()

 

 

set (Object element)

Variable-size and modifiable

Object get(int index)

ListIterator listIterator(int index)

 

int size()

boolean hasNext()

 

Object set(int index,Object element)

Object next()

 

add(int index,Object element)

int nextIndex()

 

object remove(int index)

boolean hasPrevious()

 

 

Object previous()

 

 

int previousIndex()

 

 

int size()

 

 

set (Object element)

 

 

add(Object element)

 

 

remove()

 

           

o       MAP

    • The Map interface is not a extension of collection interface.  Instead, the interface starts off its own interface hierarchy for maintaining key-value pair.
    • The interface method can be broken down into three sets of operation: alerting, querying and providing alternative views.
    • The alteration operations allow you to add and remove key-value pairs. Key-value pair can be null.  You should not add a Map itself as a key or value.
    • Public Set keySet() : returns a sets of keys in the Map. Since Map has unique key values.
    • Public Collection values() : returns a collection of values in the Map. Since Map may not have unique values.
    • AbstractMap: This class overrides the equals() and hashcode() methods to ensure two equal maps return the same hash code.
    • HashMap:  Should be used if you need to insert, delete and locate elements in Map.  Depending of the size of the collection, it may be faster to add elements to a HashMap, and then convert the map to a TreeMap for sorted key traversal.
    • TreeMap:  Should be used if you need to traverse the keys in a sorted order.
    • WeakHashMap:  A WeakHashMap is a special-purpose implementation of Map for storing only weak references to the keys.  This allow for the key-value pairs of the map to be garbage collected when the key is no longer referenced outside of the WeakHashMap.
    • SORTING
    • Comparable Interface: The compareTo() method of this interface compares the current instance with an element passed in as an argument.  If the current instance comes before the argument in the ordering, a negative value is retuned.  If the current instance comes after, then a positive value is returned.  Otherwise, zero is returned.  It is not a requirement that a zero return value signifies equality of elements.  A zero return value just signifies that two objects are ordered at the same position.
    • COLLECTIONS
    • The collections class provides six factory methods, one of each Collection, List, Map, Set, SortedMap and SortedSet.
      • Collection unmodifiableCollection(Collection c)
      • List unmodifiableList(List list)
      • Map unmodifiableMap(Map map)
      • Set unmodifiableSet(Set set)
      • SortedMap unmodifiableSortedMap(SortedMap map)
      • SortedSet unmodifiableSortedSet(SortedSet set)

 

Eg :  set.add(A); set.add(B); . set=Collections.unmodifiableSet(set);

set.add(C).    This code will throw UnsupportedOperationException

 

    • The key difference between the historical collection classes and the new implementations within the Collections Framework is the new classes are not thread safe.
    • The Collections class provides for the ability to wrap existing collections into synchronized ones with another set of six methods
      • Collection synchronizedCollection(Collection collection)
      • List synchronizedList(List list)
      • Map synchronizedMap(Map map)
      • Set synchronizedSet(Set set)
      • SortedMap synchronizedSortedMap(SortedMap map)
      • SortedSet synchronizedSortedSet(SortedSet set)
    • The simplest way to make sure you don't retain a reference is never to create one:
      • Set set = Collection.synchronizedSet(new HashSet());

 

o       SINGLETON COLLECTIONS

    • The Collections class provides for the ability to create single element sets fairly easily. Instead of having to create the Set and fill it in in separate steps, you can do it all at once.The resulting Set is immutable.
      • Set set = Collection.singleton("Hello");

 

 

 

 

 

 

 

 

  • Assertion APIs
    • Assertion can be used to catch conditions that we dont expect to happen.
    • Since assertions are easy and quick to, getting into the habit of using those means you will catch more errors before them because you trouble.
    • A good rule of thumb is that you should use an assertion for exceptional cases that you would lie to forget about.
    • Think of an assertion as the smallest (and easiest) way to handle an exceptional case.
    • Preconditions are contractual guarantees that must be true at the start of a method, and post conditions are the same, except they are in effect at the end of a method.
    • Assertions can be good for ensuring preconditions if and only if the method is not a public method.
    • Assertions are always good for post conditions.
    • An assertion is conditional error; operationally, assertions are very simple.  Their are two distinct flavors of assertion: simple and complex.
      • Flavor 1

assert expression;

 

public class aClass{

            public void aMethod(int argument){

                        Foo foo=null;

                        /// somehow get foo object

                        /// Now check to make sure weve managed to get one.

                        assert foo!==null

           

            }

}

      • Flavor 2

assert expression_1 : expression_2;

                                    This should be read as, if expression_1 isnt true, throw an error containing the value of expression_2.s

                                    Like:    assert foo!=null : Cant get a Foo object

    • An AssertionError has constructor that take any of the following types:
      • object
      • boolean
      • char
      • int
      • long
      • float
      • double
    • Since assert is a keyword, it can no longer be a variable or method name.
    •  If you suse assertions in your code, it will be incompatible with versions of the JRE prior to 1.4 because assertions need methods and fields from the Class and ClassLoader classes.
    • The public boolean desiredAssertionStatus(); method has been java.lang.Class.
    • Following method and variables are added in java.lang.ClassLoader
      •     java.util.Map classAssertionStatus;
      •     public synchronized void setDefaultAssertionStatus(boolean);
      •     public synchronized void setPackageAssertionStatus(java.lang.String, boolean);
      •     public synchronized void setClassAssertionStatus(java.lang.String, boolean);
      •     public synchronized void clearAssertionStatus();
      •     synchronized boolean desiredAssertionStatus(java.lang.String);
    • Assertions are enabled on the command line via the ea switch.  Assertions are similarly disabled with either the da or disabledassertions commands.
    • Finally, you can enable or disable assertions in the unnamed root package ( the one in the current directory) using the following commands.
      • java ea: mypackage.myprogram
      • java da: mypackage.myprogram

 

Switch

Example

Meaning

"-ea"

java ea

Enable assertions by default

"-da"

java da

Disable assertions by default

"-ea:<classname>"

java -ea:AssertPackageTest

Enable assertions in class AssertPackageTest

"-da:<classname>"

java -da:AssertPackageTest

Disable assertions in class AssertPackageTest

"-ea:<packagename>"

java -ea:pkg0

Enable assertions in package pkg0

"-da:<packagename>"

java -da:pkg0

Disable assertions in package pkg0

"-esa"

java esa

Enable assertions in system classes

"-dsa"

java dsa

Disable assertions in system classes

 

Enter supporting content here