Sunday, February 3, 2008

Some Suggestions for SCJP takers


1] Try to give SCJP from Java 5 (SCJP 310-055)

2] If you are feeling that Generics/ Collection is tough then please read Java Complete Reference Book

3] I faced some difficulty while taking the exam bcz of drag and drop questions. Actually the problem is in Exam software. It was not working properly. I was like playing game . So be careful about those questions.

4] For Garbage collection question you must do paper work. Then and only then you will get 100% in these questions.

e.g. MyClass obj1 = new MyClass();
then drow like this...
new Myclass1 ---------obj1
and if I say obj1=null then do this....
new Myclass1 -------------obj1
Then you can guess that one object has been garbage collected. (new Class()) And it will take hardly 10 to 15 sec to draw isn't it?

5] One more thing that many of you doesn't know we can return array from method like this also........keep in mind ..
public int getArr() []
{
return new int[]{1,2};
}

6] I got lots questions on generics and I got 100% in it ..so be prepared.

7] Be a detective ....go through each and every line...you can do this by moving mouse pointer on each line....

8] Go through each and every objectives....because you may feel that this is the right answer but there may be another answer which is better than this....
e.g a] Compiles fine
b] does not compile
c] throws exception
d] error at line number...
e] Compiles with warnings . -------right answer

9] K&B book is enough but for Generics first read Complete Reference and then read K&B.
10 ] Be confident about program flow specially with Exception Handling programs. And don't worry if you are newcomer it doesn't matter.

And I will be always there to help you .

Do write to me in case of any more tips :
wise(dot)mohit(at)gmail(dot)com

Wednesday, January 23, 2008

Some Questions on Objects for SCJP 5

Q1 What is the result of executing the following fragment of code:
boolean b1 = false;
boolean b2 = false;
if (b2 != b1 = !b2)
{ System.out.println("true");
}
else { System.out.println("false");
}
Select 1 correct option
(1)Compile time error
(2)It will print true
(3)It will print false
(4)Runtime error
(5)It will print nothing
Answer : 1
Explanation : Note that, boolean operators have more precedence than =. (In fact, = has least precedenace) so, in (b2 != b1 = !b2) first b2 != b1 is evaluated which returns a value 'false'. So the expression becomes false = !b2. And this is illegalbecause false is a value and not a variable!Had it been something like (b2 = b1 != b2) then its valid because it will boil down to : b2 = false. Because all an if() needs is a boolean, now b1 != b2 returns false which is a boolean andas b2 = false is an expression and every expression has a return value (which is actually the LHS of the erpression). Here it returns true which is again a boolean.Note, return value of expression (i is int) : i = 10 , is 10 (int).


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

Q2
Given two collection objects referenced by c1 and c2, which of these statements are true?Select 2 correct options
(1)c1.retainAll(c2) will not modify c1
(2)c1.removeAll(c2) will not modify c1
(3)c1.addAll(c2) will return a new collection object, containing elements from both c1 and c2
(4)For: c2.retainAll(c1); c1.containsAll(c2); 2nd statement will return true
(5)For: c2.addAll(c1); c1.retainAll(c2); 2nd statement will have no practical effect on c1


Answer : 4,5
Explanation : public boolean retainAll(Collection c) retains only the elts in this collection that are contained in the specified collection. In other words, removes from this collection all of its elts that are not contained in the specified collectionpublic boolean removeAll(Collection c) removes all this collection's elts that are also contained in the specified collection. After this call returns, this collection will contain no elts in common with the specifiedcollectionpublic boolean containsAll(Collection c) returns true if this collection contains all of the elts in the specified collectionpublic boolean addAll(Collection c) adds all the elts in the specified collectionto this collection. The behavior of this opern is undefined if the specified collection is modified while the opern is in progress(ie., the behavior of this call is undefined if the specified collection is this collection, and is nonempty)

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

Q 3
What happens when the following code gets executed:

class Sample {
public static void main(String[] args)
{ double d1 = 1.0;
double d2 = 0.0;
byte b =1;
d1 = d1/d2;
b = (byte) d1;
System.out.print(b);
}
}
(1)It results in the throwing of an ArithmeticExcepiton
(2)It results in the throwing of a DivedeByZeroException
(3)It displays the value 1.5
(4)It displays the value –1
Answer : 4
Explanation : 1.0/0.0 results in Double.POSITIVE_INFINITY. Double.POSITIVE_INFINITY is converted to Integer.MAX_VALUE ('0' followed by 31 '1's). Integer.MAX_VALUE is then cast to byte value, which simply takes the last 8 bits(11111111) and is -1.


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

Q4
Class finalization can be done by implementing the following method:static void classFinalize() throws Throwable;True Or False?
(1)True
(2)False
Answer : 2
Explanation : PREVIOUSLY: If a class declares a class method classFinalize that takes no arguments and returns no result: static void classFinalize() throws Throwable { . . . } then this method will be invoked before the class is unloaded . Like thefinalize method for objects, this method will be automatically invoked only once. This method may optionally be declared private, protected, or public. NOW: Class finalization has been removed from the Java language. Thefunctionality of JLS 12.7 is subsumed by instance finalization (JLS 12.6).Here is a rationale for this decision. http://java.sun.com/docs/books/jls/class-finalization-rationale.htmlSimilar thing has happend toclass unloading: A class or interface may be unloaded if and only if its class loader is unreachable (the definition of unreachable is given in JLS 12.6.1). Classes loaded by the bootstrap loader may not be unloaded.

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

Q5
Consider the following method:

public void getLocks(Object a, Object b)
{ synchronized(a)
{ synchronized(b) { //do something } } }
and the following instantiations:
Object obj1 = new Object();
Object obj2 = new Object();
obj1 and obj2 are accesible to two different threads and the threads are about to call the getLocks() method.Assume the first thread calls the method getLocks(obj1, obj2).
Which of the following is true? Options Select 1 correct option
(1)The second thread should call getLocks(obj2, obj1)
(2)The second thread should call getLocks(obj1, obj2)
(3)The second thread should call getLocks() only after first thread exits out of it
(4)The second thread may call getLocks() any time and passing parameters in any order
(5)None of the above


Answer : 2
Explanation : (1) This may result in a deadlock (3) The is not necessary. Option 2 works just fine.


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

Sunday, January 13, 2008

SCJP Mock Questions and Answers

Ques1
Given:
1. public class MyThread implements Runnable {
2. private String holdA = "This is ";
3. private int[] holdB = {1,2,3,4,5,6,7,8,9,10};
4.
5. public static void main(String args[]) {
6. MyThread z = new MyThread();
7. (new Thread(z)).start();
8. (new Thread(z)).start();
9. }
10.
11. public synchronized void run() {
12. for(int w = 0;w <>
13. System.out.println(holdA + holdB[w] + ".");
14. }
15. }
16. }

What is the result?


(1) Compilation fails because of an error on line 6
(2) Compilation fails because of an error on line 11
(3) Compilation fails because of errors on lines 7 and 8
(4) Compilation succeeds and the program prints each value in the holdB array at the end of the "This is " line. Each value is printed two times before the program ends, and the values are not printed in sequential order
(5) Compilation succeeds & the prog. prints each val in the holdB array at the end of the "This is " line. Each val is printed in order from 1-10 & after the val 10 prints, it starts printing the vals 1-10 in order again


Answer : 5
Explanation :
Option 5 is correct because the Runnable interface is implemented by declaring a synchronized run() method. The method is declared as synchronized to signify that the object lock must be obtained

Options 1, 2, and 3 are incorrect because compilation succeeds. Option 4 is incorrect, but would be correct if the run() method were not declared as synchronized.
----------------------------------------------------------------------------------------------------------------------------

Ques 2 :Which statement about the Map interface is true?


(1) Entries are placed in a Map using the values() method
(2) Entries are placed in a Map using the entrySet() method
(3) A key/value association is added to a Map using the put() method
(4) A key/value association is added to a Map using the putAll() method


Answer : 3
Explanation :
Option 3 is correct because the put() method is used to add a key/value association to a Map.

Option 1 is incorrect because the values() method returns a Collection of all values in a Map.Option 2 is incorrect because the entrySet() method returns a Set of all mappings in a Map. Option 4 is incorrect because the pubAll() method copies all mappings from one Map to another.
---------------------------------------------------------------------------------------------------------------------------

Ques 3 :
Consider the following class definition:
1. public class Test extends Base {
2. public Test(int j) {
3. }
4. public Test(int j, int k) {
5. super(j, k);
6. }
7. }

Which of the following forms of constructor must exist explicitly in the definition of the Base class?


(1) Base() { }
(2) Base(int j) { }
(3) Base(int j, int k) { }
(4) Base(int j, int k, int l) { }


Answer : 1,3
Explanation :
1 and 3 are correct. In the constructor at lines 2 and 3, there is no explicit call to either this() or super(), which means that the compiler will generate a call to the zero argument superclass constructor, as in 1. The explicit call to super() at line 5 requires that the Base class must have a 7.constructor as in 3. This has two consequences. First, 3 must be one of the required constructors and therefore one of the answers.Second, the Base class must have at least that constructor defined explicitly, so the default constructor is not generated, but must be added explicitly. Therefore the constructor of 1 is also required and must be a correct answer.At no point in the Test class is there a call to either a superclass constructor with one or three arguments, so 2 and 4 need not explicitly exist.

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

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.

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

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google