Saturday, December 29, 2007

Threads Some Important Points


1. Methods in object class
· wait : throws interruptedException
· notify
· notifyAll

Remember : they are final and must be called from within a synchronized
context, otherwise illegalmonitorstate exception is thrown at runtime.


*******************************************

2. yield , sleep are static members of Thread class.

********************************************

3. stop , resume , suspend are deprecated members of Thread class.

*********************************************

4. InterruptedException is checked exception.

**********************************************

5. Given
synchronized (expression){…..}
· expression may evaluate to reference to object.
· expression cannot evaluate to primitive type or null.
· If execution block completes ( abruptly or normally )the lock is released.
· synchronized statements can be nested.
· synchronized statements with identical expression can be nested.


*************************************************

6. Thread.yeild method
· may cause the current thread to move from runnable to ready state .
· It isn’t guaranteed i.e. same thread may start executing again.


******************************************************

7. Thread.sleep method
· makes thread to move from running to not – runnable state
· thread takes lock with it if it has got one.


************************************************

8. Thread class inherits Runnable interface.

*************************************************

9. A dead thread can never be restarted.

**************************************************

10. When overriding the ‘run’ method of the Thread class remember the following
points
· the prototype must be public void run(){}
· Access modifier must be public.
· ReturnType must be void.
· No arguments must be specified and if done it doesn’t cause error but it can’t
be used to start a new thread.
. if the class implements Runnable interface then it has to possess run method
with no arguments specified otherwise compiler error is caused.
· it must not declare any new checked exception in its throws clause.
· it must not be declared static
· It can declare unchecked exception in its throws clause.
· If start method is called twice then illegalThreadStateException is thrown.


************************************************

11. the run method in Thread class is empty method which does nothing.

*******************************************************
12. join,sleep,wait methods declare InterruptedException in their throws clause.

*************************************************

13. If we extend thread class or implement runnable interface then the present run()
method must not be marked static ,if it is marked it causes compiler error.


***************************************************

14. The priority of a thread can be altered after the thread has been started using
setPriority method .The code compiles fine.


***************************************************

Saturday, December 22, 2007

Mock Questions for Test Preparation

1) Will this work?

public static void main(String args[])
{
RuntimeException re;
throw re;
}

Ans -> No , compile time exception :: variable re may not have been initialized
-------------------------------------------------------------------------------------------------------------


2) NumberFormatException is a subclass of IOException

-------------------------------------------------------------------------------------------------------------

3) if ("string".toUpperCase() =="STRING")
{
System.out.println("Yes");
}
else System.out.println("No");

Ans -> No // if we use .equals() here , then we get “yes” . This is because , “string” and “STRING” are two separate object references pointing to two separate objects. == is used to compare whether two object references point to same object or not. .equals() compares the objects for their contents.
-------------------------------------------------------------------------------------------------------------------

3) when we extend a class , the static class variables are also passed on to the child class. Final class variables are not passed. Transient class variables are passes( they are implicitly initialized ).

--------------------------------------------------------------------------------------------------------------------

4) We cannot extend a math class ( its final) . all its constants and methods are static.

---------------------------------------------------------------------------------------------------------------------

5) We cannot instantiate a math class .. its constructors are private.

---------------------------------------------------------------------------------------------------------------------


5) class XTC {

public static void main ( String [ ] ka ) {
int s = 64 / 9 ;
float f = 64 / 9 ;
double d = 64 / 9 ;
System . out . println ( s + " & " + f + " & " + d ) ;
}
};

Ans -> 7 , 7.0 , 7.0

---------------------------------------------------------------------------------------------------------------------

6) What is the output of the following ? Will it compile at all ?

class XTC {

public static void main ( String [ ] ka ) {
Integer b = new Integer(3) ;
System . out . println ( b instanceof Integer ) ;

}
};

Ans -> true

-----------------------------------------------------------------------------------------------------------------------

7) What is the output of the following ? Will it compile at all ?

class XTC {

public static void main ( String [ ] ka ) {
Integer b = null;
System . out . println ( b instanceof Integer ) ;

}
};

Ans -> false

--------------------------------------------------------------------------------------------------------------------


8) What is the output of the following ? Will it compile at all ?

class XTC {

public static void main ( String [ ] ka ) {
Integer b = null;
System . out . println ( b instanceof Object ) ;

}
};

Ans -> false

------------------------------------------------------------------------------------------------------------

9) What is the output of the following ? Will it compile at all ?

class XTC {

public static void main ( String [ ] ka ) {
Integer b = new Integer(3);
System . out . println ( b instanceof Object ) ;

}
};

Ans -> true

------------------------------------------------------------------------------------------------------------------------


10) if (Double . POSITIVE_INFINITY == Double . POSITIVE_INFINITY )
{
System . out . println ( “Yes”) ;
}

Ans -> Yes

--------------------------------------------**********************---------------------------------------------

Monday, December 17, 2007

SCJP Tutorial -- Exception Handling

Exception Handling



Defination :-
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

There are 3 main advantages for exceptions:
1. Separates error handling code from "regular" code
2. Propagating errors up the call stack (without tedious programming)
3. Grouping error types and error differentiation


Syntax :-


try {

int y =5;

for(int i =5; i<=0; i++)

{ int z = x/i; }

}catch(Exception e1)

{ system.out.println( "Exception Occured" +e.printstacktrace());

}

finally {

System.out.println("Fional code is always executed");

}


Important tricks to be Noted :-

" An exception causes a jump to
the end of try block. If the exception occurred in a method called from a try
block, the called method is abandoned.


******************************************************************************************************

" If there's a catch block for
the occurred exception or a parent class of the exception, the exception is now
considered handled.

*******************************************************************************************************

" At least one 'catch' block or one 'finally' block
must accompany a 'try' statement. If all 3 blocks are present, the order is
important. (try/catch/finally)

*******************************************************************************************************

" finally and catch can come only with
try, they cannot appear on their own.

****************************************************************************************************

" Regardless of whether or not an
exception occurred or whether or not it was handled, if there is a finally
block, it'll be executed always. (Even if there is a return statement in try
block).

**************************************************************************************************

" System.exit() and error conditions are the only exceptions
where finally block is not executed.

****************************************************************************************************

" If there was no exception or the
exception was handled, execution continues at the statement after the
try/catch/finally blocks.

****************************************************************************************************

" If the exception is not handled, the process
repeats looking for next enclosing try block up the call hierarchy. If this
search reaches the top level of the hierarchy (the point at which the thread was
created), then the thread is killed and message stack trace is dumped to
System.err.

****************************************************************************************************

" Use throw new xxxException() to throw an exception. If the
thrown object is null, a NullPointerException will be thrown at the handler.

****************************************************************************************************

" If an exception handler re-throws an exception (throw in a catch
block), same rules apply. Either you need to have a try/catch within the catch
or specify the entire method as throwing the exception that's being re-thrown in
the catch block. Catch blocks at the same level will not handle the exceptions
thrown in a catch block - it needs its own handlers.

****************************************************************************************************

" The method
fillInStackTrace() in Throwable class throws a Throwable object. It will be
useful when re-throwing an exception or error.

****************************************************************************************************

" The Java language
requires that methods either catch or specify all checked exceptions that can be
thrown within the scope of that method.

****************************************************************************************************

" All objects of type
java.lang.Exception are checked exceptions. (Except the classes under
java.lang.RuntimeException) If any method that contains lines of code that might
throw checked exceptions, compiler checks whether you've handled the exceptions
or you've declared the methods as throwing the exceptions. Hence the name checked exceptions.

****************************************************************************************************

" If there's no
code in try block that may throw exceptions specified in the catch blocks,
compiler will produce an error. (This is not the case for super-class Exception)

****************************************************************************************************

" Java.lang.RuntimeException and java.lang.Error need not be handled or
declared.

****************************************************************************************************



Classification of Exception:


Exception-->ClassNotFoundException, ClassNotSupportedException, IllegalAccessException, InstantiationException, IterruptedException, NoSuchMethodException, RuntimeException, AWTException, IOException

RuntimeException-->EmptyStackException, NoSuchElementException, ArithmeticException, ArrayStoreException, ClassCastException, IllegalArgumentException, IllegalMonitorStateException,
IndexOutOfBoundsException, NegativeArraySizeException, NullPointerException, SecurityException.

IllegalArgumentException-->IllegalThreadStateException, NumberFormatException

IndexOutOfBoundsException-->ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException

IOException-->EOFException, FileNotFoundException, InterruptedIOException, UTFDataFormatException, MalformedURLException, ProtocolException, SockException, UnknownHostException, UnknownServiceException.

Thursday, December 13, 2007

Notes on Java Fundamentals

Basic Lexical elements----
--->keywords & other reserved words

*******************************************************************
1. Access modifiers - private,public,protected
2.other modifiers---abstract,final,static,synchronized,transient, volatile
3 Name space keywords -- import,package

*******************************************************************
byte,short,int,long-- signed two's complement integers
boolean -- 1 bit
char-- 16 bit unicode characters rather than ASCII set used in C

********************************************************************
Formula ------2^(n-1) to 2^(n-1)-1`

********************************************************************

Exceptional Floating point constants---

Float.NAN
(NAN Stands for Not A Number)
Float.NEGATIVE_INFINITY
Float.POSITIVE_INFINITY
Double.NAN
Double.NEGATIVE_INFINITY
Double.POSITIVE_INFINITY

************************************************************************

char represented in single quotes -
'\u0000'--- followed by four hexadecimal

************************************************************************

Integral can be decimal, hexadecimal or octal
Hexadecimal starts with 0x
Octals start with 0

************************************************************************
Floating point e or E stands for exponential value
eg 7e3 =7000

*************************************************************************

note--> double x=77; is valid declaration as doublex =77D;

*************************************************************************

To convert boolean, characters,integers,floating point numbers to String use valueOf() method
String is not null terminated.

**************************************************************************

Once initialized string objects are inmutable i.e cannot change their contents. so use stringBuffer if the contents have to be changed.

****************************************************************************

String bounds checked at run time rather than compile time.

string abc ="sdefg";
is not same as
string abc =new("string");

if we use first one compiler scans current cache to check for another string object with same literal value.
If it is there it reuses same object.

********************************************************************************

Friday, December 7, 2007

Books for SCJP preparation

The following are good books that can be refered for the SCJP 1.5 Exam ;-

1. A Programmer's guide to Java Certification by Khalid A Mughal

2. SCJP Exam for J2SE 5 - A Concise and Comprehensive Study Guide for the Sun Certified Java Programmer Exam by Paul Sanghera

3. Complete Java 2 certification Study Guide by Philip Heller

4. SCJP 5 book by Katherine sierra and Berth Bates

Other Resources Over Internet :-

1. Generics Tutorial from SUN Download

2.Test yourself with Tiger Quiz by SUN

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google