Monday, October 13, 2008

Revision Quiz

1. A ____ object can store and retrieve “value” objects indexed by “key” object.
Ans: Hashtable

2.Wrapper class objects contain mutable values.
True/False?
Ans: False

3.A Vector can hold object references or primitives types.
Ans: False

4.Hashtable class implements which of the following interfaces?Ans: Map

5.String s1=new String(“MyString”);String s2=new String(“MyString”);s1==s2 will return ___.

Ans: False

6.Float.NaN or Double.NaN refers to ___
Ans: Not a number

7.The java.lang.System is a ___ class.

Ans: final

8.The ___ class is a wrapper around int data type in java.

Ans: Integer

9.java.lang.Double is a concrete subclass of abstract class java.lang.Number.
True/False
Ans:True

10.What happens when you try to compile and run the following code snippet?
public class Wrapper{
public static void main(String []a)
{
String s=”15.25”;
try {
int number=Integer.parseInt(s); //line 1
System.out.println(number); //line 2
}
catch(NumberFormatException nfe)
{
System.out.println(“sorry”);
}
catch(Exception e){ }
}
}
A) It will compile fine and display 15 when run.
B) It will compile fine and display Sorry when run.
C) It will not compile.
D) It will compile fine nothing will be displayed when run
Ans: B

11.The java.lang.Math class has ___ constructor.

A) public
B) private
C) protected
Ans: B

12.A Vector maintains object references in the order they were added.
Ans: True

13.The String class represents a mutable string

Ans: False

14.The parent class of both Integer and Character class is Number class
Ans: False

15.What happens when you try to compile and run the following code snippet?

public class WrapChar
{
public static void main(String []a)
{
Character wrapChar=new Character(“c”);//line1
System.out.println(wrapChar);//line 2
}
}
A) Compile time error at line 1
B) Compile time error at line 2
C) Compile fine and display c when run
D) Compile fine but throws RuntimeException
Ans: A

Tuesday, September 9, 2008

LAST MINUTE REVISION NOTES

The tips to attend the exam SCJP 5

1. Check for any obvious complier errors first like two else statements , accessing ofprivate variable/method , accessing a variable declared in a for loop outside the for loop.

2. If you try to unbox a null Integer value to int , it will result in a NullPointerException.

3. If method having the same name as Class name and having a return type is not a constructor but a ordinary method.

4. Map is the only interface that does not extend Collection. List , Set and Queue extends the Collection interface.

Collection is a interface ,
Collections is Class which extends Object class.

Map: key , value pair
Hashtable , HashMap , LinkedHashMap , TreeMap

Set : unique values
HashSet , TreeSet , LinkedHashSet

List : List of values allows duplicates, accessed by index
ArrayList , Vector , LinkedList

Queue : stack or queue. to-do list. priority queue is sorted based on the natural order or based on the object of Comparator or Comparable.LinkedList , PriorityQueue
The twins clases.

a. The Hashtable and HashMap: Both are atmost same except that Hashtable methods are synchronized and it does not allow null key/value, whereas HashMap allows one null key and many null values and its methods are not synchronized . The Hashtable is oldest class in java. The t in Hashtable is indeed a small letter rather than capital letter.

b. The Vector and ArrayList have same functionalities except that Vector Methods are synchronized , while ArrayList methods are not. Both ArrayList and Vector implementes RandomAccess interface (which is marker interface having no methods) as of java 5

c. The LinkedList can be used to access values in insertion order. The LinkedHashMap can be used access values in insertion or access order. The LinkedList implements Queue(as of java 5) and List. The LinkedList now implements queue methods like offer, poll and peek.

d. The TreeSet , TreeMap and PriorityQueue sorts the values.

e. The HashSet , Hashtable and HashMap are unordered and unsorted. if you add n values in these Collection objects , iteration will not give you a particular ordering ie no insertion or access or natural order. It iterates in a random order.

f. The LinkedHashSet is ordered form of HashSet , The LinkedHashMap is the ordered form of HashMap.

g. the offer() method adds a element in queue. the poll method returns the first method and removes it from queue. the peek just returns the first method from queue. The higgest priority is stored first in PriorityQueue. if you poll each value from PriorityQueue then values returned will be of Higgest proririty to lowest priorirty.

h. The Object of class which need to be added in HashSet , Hashtable , LinkedHashSet or HashMapt must override the below methods
The exception are all Wrapper classes. The class Number , StringBuffer and StringBuilder.

For example object of Student class need to be added in LinkedHashSetA student class contains id , name. As id is a primaray key , we should not have rwo students with the same id. if the Student class does not override the above methods then

Student d = new Student(44); //44 is id
Student d 1= new Student(44); //44 is id
public int hashCode(){}
public boolean equals(Object o){}
public boolean equals(Object o { if (o instanceof Student) {
Student t= (Student) o;
if(o.getId() ==this.id ) {
return true;
} //if
} //ifreturn false;
} //method
public int hashCode() {
//use any of the below
return id*4;
return id;
return 1038; //any constant
//do no use any of the below
Random r =new Random(44);
return r.nextInt();
//here t is transient variable
return t*id;
}
if above method is implemented then d and d1 will be same object.
both d and d1 are different object accoring to the LinkedHashSet , as a result both will be added to the Set

i. The Object of class which need to be added in TreeMap , TreeSet and PriorityQueue must implement Comparable or Comparator interface

j. java.lang.Comparabl e declaresompareTo( ) and accepts one Object as argument.k. java.util.Comparato r declares compare() which accepts 2 Object as argument.

l. in generics if you declare a variable it must be instantiated with the same type or no type at all

//valid

Listlisto1 =new ArrayList ();
List listo2 =new ArrayList();

List listo3 =new ArrayList ();
List list3 =new ArrayList();
m1(list01);/ /error
m2(list01);/ /ok
m1(list02);/ /error
m2(list02);/ /ok
m1(list03);/ /ok
m2(list03);/ /ok
m1(list3);// ok
m2(list3);// error

//invalid

List listo =new ArrayList(); //compiler error


// functions
static void m1( a) {}
static void m2( a) {}


//The argument that Child class can be applied to a parent class i s not at all applicable to generics . if you specified a type in the variable declaration it must be followed while instantiating also.

In the Exam , there will be drag-drop quetion . in which there will be 4 variable instanciated with the genreic and passed as arguemnt to a function. you have drag and drop , if the code compiles or not.

m.
public class {} and
public class {}
are invalid syntax and leads to compiler error

but it can be defined as

public class {} or
public class {}
public class {} public class {}
public T getObject() {} //correct
public T computeArrays( Y y) {}
//correct, the font-size of s is increased to differentiate from the interface Collection
//here Y is the argument and T is the return type.

5. For garbage collection , you must focus on the value and its reference . there may be a question . which is earliest line in which the value referred by object in line 5(some line) is eligible for garbage collection . The reference variable will be given other values in the consecutive steps but focus if the value which was created/defined in line 5 (example) is referenced by any other variable. The variable can be instance or local variable. if it is a local variable , its scope will be till the method ends but except in the situation the value is returned.
For example below :

Object o= new Object//line 5
Object s =o;//line 6
// the value created in line 5 is referred by s

case 1 .

o = new Object(); //7 //o is set to different value
s=null; //8 s is null or
s = new Object(); // s is set to a new value
}
so old value has no reference.

here the value created in line 5 will be eligible for gc after line 5

case 2.

o= new Object();//5
Object s =o;//6
o = new Object();//7
return s;//8 }
The value created in line 5 will not be eligible for garbage collection even after the method has ended as it is returned.

case 3:

private Object o;
public void data() {
Object o = new Object();//1
doSomething( o);//2
o = new Object();//3
o=null;//4
doSomething( null);//5
Object s = new Object();//6
Object nothing = new Object();//7
return s;//8
}//9

In the above example value created in line 1 is eligible for garbage collection after the line 5. The value created in the line 3 is eligible for garbage collection after the line 4.

The value created in line 6 will not be eligible for garbage collection even after the method ends as the value is returned. The value created in line 7 is eligible for garbage collection after the line 9.

public void doSomething( Object obj) {
o= obj;
}

Saturday, August 9, 2008

Serialization and Deserialization Important Tips


**For an object to be serialized, it has to implement either the java.io.Serializable or java.io.Externalizable interfaces, the latter being a subtype of Serializable.

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

**Serializable is a marker interface: it specifies no methods and merely indicates an object that has serializable state.

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

**All subclasses of a Serializable class are also serializable.

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

**If a supertype of a Serializable object is not itself serializable, then the object can assume the responsibility for saving and reconstructing the supertype's state (public, protected, and package fields if they share a package).For this to work, the superclass must have a public no-arg constructor.

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

**Further, if an object at runtime refers to a nonserializable object, the serialization system will throw a NotSerializableException, since it cannot write the complete object graph to the serialized stream.

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

**If an object holds multiple references to another object, this second object is serialized only once, and subsequent references to it will include a handle as a reference instead.

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

**Along with instance data, the object serialization system writes a special object to the stream to represent the serializable object's class.

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

**This object is of the type java.io.ObjectStreamClass, and is essentially a descriptor for the Class object associated with the serializable object. It contains the class's name, its unique version number (serialVersionUID), and the class fields.

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

**In addition, it also has methods to obtain the actual class represented by this object, if, and only if, this class is already present in the local VM:

Class forClass() : If there is no class identified in the local VM that corresponds to this ObjectStreamClass, then a null value is returned.

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

**Not all objects are suitable for serialization:

1.Threads, for instance, do not have state that can later be recreated. (Actually, it is possible, but very difficult, to do so.)

2.There can also be objects that should not be serialized for semantic reasons. Even if an object is serializable, you may not need to write all object fields to the stream during serialization. For instance, a variable that loses its meaning in a different execution context (such as something indicating the current time) should be marked transient, and will instead be initialized to its default value when reading it from the stream.

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

**If instances of a class need a special way to serialize their state, that class can implement the Externalizable interface, which mandates two methods:
void readExternal(ObjectInput inputStream);

void writeExternal(ObjectOutput outputStream);

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

**The main difference between Externalizable and Serializable is that the latter serializes, by default, the entire object graph, including states of an object's superclass. While in the former Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

Externalizable gives you complete control over the serialization process.

Serialization allows you to create a JVM-independent binary representation of an in-memory Java object. This external representation may be used to transfer or store the object and to recreate it in another JVM.

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

**Two streams in java.io--

1. ObjectInputStream

2. ObjectOutputStream

-- are run-of-the-mill byte streams and work like the other input and output streams. However, they are special in that they can read and write objects.

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

**Serializable has no methods but Externalizable has 2 methods: readExternal() and writeExternal()

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

You can use object serialization in the following ways:
· Remote Method Invocation (RMI) --communication between objects via sockets
· Lightweight persistence--the archival of an object for use in a later invocation of the same program.

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

**Technique to protect sensitive data in classes :

Mark fields that contain sensitive data as private transient. transient and static fields are not serialized or deserialized.

Marking the field will prevent the state from appearing in the stream and from being restored during deserialization.

Since writing and reading (of private fields) cannot be superseded outside of the class, the class's transient fields are safe.

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

Accessor Types Public and Private

Question 1

Given :

public class Hello{
private int i = j;
private int j = 10;
public static void main(String args[]) {
System.out.println((new Hello()).i); }
}

Choose

1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing.
3. No error - The output is 0;
4. No error - The output is 10;

Answer is 2. It is because i is a private variable of Hello. Hence it cannot be accessed directly.

Question 2


Given :

public class Hello {
private int i = giveJ();
private int j = 10;
private int giveJ()
{ return j;
}
public static void main(String args[])
{ System.out.println((new Hello()).i);
}
}

Choose :
1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing. .
3. No Compilation error - The output is 0;
4. No Compilation error - The output is 10;


Answer 2 is correct. We cannot assign a value to instance varaible by calling the method.

Sunday, July 6, 2008

Inner Classes

In Object Oriented programming, for reuse and flexibility/extensibility you need to keep your classes specialized.

In other words, a class should have code only for the things an object of that particular type needs to do; any other behavior should be part of another class better suited for that job.

Sometimes, though, you find yourself designing a class where you discover you need behavior that belongs in a separate, specialized class, but also needs to be intimately tied to the class you're designing.

One of the key benefits of an inner class is the "special relationship" an inner class instance shares with an instance of the outer class.

That "special relationship" gives code in the inner class access to members of the enclosing (outer) class, as if the inner class were part of the outer class.

In fact, that's exactly what it means: the inner class is a part of the outer class. Let's look at each of them.

Regular Inner Classes

A normal "regular" inner class is declared inside the curly braces of another class, but outside any method or other code block.

class MyOuter {
class MyInner { }
}

An inner class is a full-fledged member of the enclosing (outer) class, so it can be marked with an access modifier as well as the abstract or final modifiers. (Never both abstract and final together— remember that abstract must be subclassed, whereas final cannot be subclassed).

An inner class instance shares a special relationship with an instance of the enclosing class. This relationship gives the inner class access to all of the outer class's members, including those marked private.

class MyOuter {
private int x = 7;
// inner class definition
class MyInner
{ public void seeOuter()
{ // Yes you can access the private variables of enclosing class
System.out.println("Outer x is " + x);
}
} // close inner class definition
} // close outer class

To instantiate an inner class, you must have a reference to an instance of the outer class to tie to the inner class.

An inner class instance can never stand alone without a direct relationship to an instance of the outer class.

From code within the enclosing class, you can instantiate the inner class using only the name of the inner class, as follows:

MyInner mi = new MyInner();

From code outside the enclosing class's instance methods, you can instantiate the inner class only by using both the inner and outer class names, and a reference to the outer class as follows:

MyOuter mo = new Myouter();
MyOuter.MyInner inner = mo.new MyInner();

or

MyOuter.MyInner inner = new MyOuter().new MyInner();

From code within the inner class, the keyword this holds a reference to the inner class instance.

To reference the outer this (in other words, the instance of the outer class that this inner instance is tied to) precede the keyword this with the outer class name as follows:

MyOuter.this;

Method Local Inner Classes

A method-local inner class is defined within a method of the enclosing class.

class MyOuter2 {
private String x = "Outer2";
void doStuff() {
class MyInner {
public void seeOuter()
{ System.out.println("Outer x is " + x);
} // close inner class method
} // close inner class definition }
// close outer class method doStuff()
} // close outer class

For the inner class(Method - Local Inner Class) to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code.

class MyOuter2 {
private String x = "Outer2";
void doStuff() {
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
} // close inner class method
} // close inner class definition
MyInner mi = new MyInner(); // This line must come
// after the class
mi.seeOuter();
} // close outer class method doStuff()
} // close outer class

In other words, no other code running in any other method—inside or outside the outer class—can ever instantiate the method-local inner class.

Like regular inner class objects, the method-local inner class object shares a special relationship with the enclosing (outer) class object, and can access its private (or any other) members.

However, the inner class object cannot use the local variables of the method the inner class is in unless those variables are marked final.This is bcoz the local variables of the method live on the stack, and exist only for the lifetime of the method.

You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable.

Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the local variables are marked final! The only modifiers you can apply to a method-local inner class are abstract and final. (Never both at the same time, though.)

A local class declared in a static method has access to only static members of the enclosing class, since there is no associated instance of the enclosing class. If you're in a static method there is no this, so an inner class in a static method is subject to the same restrictions as the static method. In other words, no access to instance variables.

Anonymous Inner Classes

Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.

Type - 1 (Subclass of the named type)

class Popcorn {
public void pop() {
System.out.println("popcorn");
}
}class Food {
Popcorn p = new Popcorn()
{
public void pop() {
System.out.println("anonymous popcorn");
}
};
}
Polymorphism is in play when anonymous inner classes are involved. You can only call methods on an anonymous inner class reference that are defined in the reference variable type!

This is no different from any other polymorphic references, for example,

class Horse extends Animal{
void buck() { }
}
class Animal {
void eat() { }
}
class Test {
public static void main (String[] args)
{
Animal h = new Horse();
h.eat(); // Legal, class Animal has an eat() method
h.buck(); // Not legal! Class Animal doesn't have buck()
}
}

Type - 2 (Implementer of the specified interface type)

interface Cookable {
public void cook();
}
class Food {
Cookable c = new Cookable()
{ public void cook()
{ System.out.println("anonymous cookable implementer");
}
};
}
Anonymous interface implementers can implement only one interface.

Type - 3 (Argument defined anonymous inner classes)

class MyWonderfulClass {
void go() {
Bar b = new Bar();
b.doStuff(new Foo() {
public void foof() { System.out.println("foofy");
} // end foof method
}); // end inner class def, arg, and b.doStuff stmt.
} // end go()
} // end class
interface Foo {
void foof();
}
class Bar {
void doStuff(Foo f) {}
}
An argument-local inner class is declared, defined, and automatically instantiated as part of a method invocation.
The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });

An anonymous inner class is always created as part of a statement; don't forget to close the statement after the class definition with a curly brace.

This is a rare case in Java, a curly brace followed by a semicolon.Because of polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.

An anonymous inner class can extend one subclass(type-1) or implement one interface(type-2), Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.

Static Nested Classes

Static nested classes are inner classes marked with the static modifier.

class BigOuter {
static class Nested { }
}

A static nested class is not an inner class, it's a top-level nested class.The class itself isn't really "static"; there's no such thing as a static class. The static modifier in this case says that the nested class is a static member of the outer class.

That means it can be accessed, as with other static members, without having an instance of the outer class. Because the nested class is static, it does not share any special relationship with an instance of the outer class.

In fact, you don't need an instance of the outer class to instantiate a static nested class.Instantiating a static nested class requires using both the outer and nested class names as follows:

BigOuter.Nested n = new BigOuter.Nested();

Example :

class BigOuter {
static class Nest {void go()
( System.out.println("hi");
}
}
}
class Broom {
static class B2 {void goB2() {
System.out.println("hi 2");
}
}
public static void main(String[] args) {
BigOuter.Nest n = new BigOuter.Nest(); // both class names
n.go();
B2 b2 = new B2(); // access the enclosed class
b2.goB2();
}
}

Which produces:
hihi 2

Just as a static method does not have access to the instance variables and non-static methods of the class, a static nested class does not have access to the instance variables and non-static methods of the outer class.

Look for static nested classes with code that behaves like a nonstatic (regular inner) class.

Sunday, June 1, 2008

Latest Dumps SCJP

Q1 Select three correct statements.


(1) A static method may override another static method
(2) A static method cannot override a non-static method
(3) A non-static method cannot override a static method
(4) A non-static method may be overloaded by a static method
(5) A synchronized method cannot be overridden


Answer : 2,3,4

Explanation :
Overriding is for non-static methods and hiding is for static methods. So the following statements are the only true statements about hiding and overriding:

a static method (in a subclass) may hide another static method (in a superclass)
a static method (in a subclass) cannot hide a non-static method (in a superclass)
a non-static method (in a subclass) may override another non-static method (in a superclass)
a non-static method (in a subclass) cannot override a static method (in a superclass)

Tuesday, May 6, 2008

SCJP Questions with Answers

Q 1
What is the output of the following code when compiled and run? Select two correct answers.

public class TechnoSample {
public static void main(String[] args){
for(int i = 0; i <>
System.out.println(getPrimitive(127)); //line 1
}
}
public static int getPrimitive(byte b) { //line 2
return (short)(Math.random()*b); //line 3
}
}


(1) Compilation error on line 1
(2) Compilation error on line 2
(3) Compilation error on line 3
(4) Line 3 compiles fine
(5) Prints 10 random numbers between 0 and 127


Answer : 1,4
Explanation :
Line 1 does not compile because getPrimitive() takes a byte and we pass it an int. In a normal assignment (byte b = 127;) this would work because 127 is in the range for byte values and the compiler implicitely does a norrowing conversion.But this is not the case in method invocations. A quote from JLS 5.3: "The designers of the Java programming language felt that including these implicit narrowing conversions would add additional complexity to the overloaded method matchingresolution process". This speaks for itself. Line 3 compiles fine because we have to do with a widening primitive conversion form short to int which is perfectly straightforward.


Q2 Select three correct statements.


(1) A static method may override another static method
(2) A static method cannot override a non-static method
(3) A non-static method cannot override a static method
(4) A non-static method may be overloaded by a static method
(5) A synchronized method cannot be overridden


Answer : 2,3,4
Explanation :
Overriding is for non-static methods and hiding is for static methods. So the following statements are the only true statements about hiding and overriding:

a static method (in a subclass) may hide another static method (in a superclass)
a static method (in a subclass) cannot hide a non-static method (in a superclass)
a non-static method (in a subclass) may override another non-static method (in a superclass)
a non-static method (in a subclass) cannot override a static method (in a superclass)



Q3 Select three correct statements about the following code.
public class TechnoSample {
public static void main(String[] args) {
TechnoSample myref = new TechnoSampleSub();
try{
myref.test();
}
catch(Exception e){}
}
void test() throws Exception{
System.out.println("In TechnoSample");
throw new Exception();
}
}
class TechnoSample Sub extends TechnoSample {
void test() {
System.out.println("In TechnoSampleSub");
}
}



(1) The try-catch block that encloses myref.test(); is mandatory for the code to compile
(2) Prints: In TechnoSample
(3) Prints: In TechnoSampleSub
(4) Method test() in class TechnoSampleSub has no obligation to declare a throws clause
(5) An exception is thrown at runtime


Answer : 1,3,4
Explanation :
myref is an instance of class TechnoSampleSub referenced by a variable of type TechnoSample. Method test() in class TechnoSample is overridden in class TechnoSampleSub, thus the one to be invoked is the one declared in class TechnoSampleSub(Polymorphism!). Moreover, test() has no obligation to declare a throws clause (see overriding rules!). The try-catch block is mandatory because myref could as well reference an instanceof class TechnoSample and in that case the method test() to be invoked would be the one declared in class TechnoSample which throws an exception.


Q4 Given the following code:
import java.util.Date;
public class Example {
public static void main(String args[]) {
Date d1 = new Date (99, 11, 31);
Date d2 = new Date (99, 11, 31);
method(d1, d2);
System.out.println("d1 is " + d1 + "\nd2 is " + d2);
}
public static void method(Date d1, Date d2) {
d2.setYear (100);
d1 = d2;
}
}

Which one or more of the following correctly describe the behavior when this program is compiled and run?


(1) compilation is successful and the output is:
d1 is Fri December 31 00:00:00 GMT 1999 d2 is Fri December 31 00:00:00 GMT 1999

(2) compilation is successful and the output is:
d1 is Fri December 31 00:00:00 GMT 1999 d2 is Sun December 31 00:00:00 GMT 2000

(3) compilation is successful and the output is:
d1 is Sun December 31 00:00:00 GMT 2000 d2 is Sun December 31 00:00:00 GMT 2000

(4) the assignment 'd1 = d2' is rejected by the compiler because the Date class cannot overload the operator '='
(5) the expression (d1 is " + d1 + "\nd2 is " + d2) is rejected by the compiler because the Date class cannot overload the operator '+'


Answer : 2
Explanation :
1) is false because we know that the data in d2 was changed. 3) is false because we know that the data in d1 was not changed. The names d1 and d2 are used in both main and method to be confusing. They are different and stored on the stack in different place. All the interesting stuff that happen in the Example class is in method. main simply initializes some data and prints the results. In method, the following happens:
1.d2 has its year set to 100 (really 2000, as 2.Object d1 is set to be the same as d2. This is a change of the actual reference, not in the data at d1.
Both of these line are perfectly legal, and do not result in a compilation error, so d) is false. I will also point out here that e) is String context. toString() is defined by the Object class and so it is available on all classes in Java. Most non-trivial classes override toString() to return more explicit information about themselves.



Thursday, April 3, 2008

LAST MINUTE REVISION POINTS

1. Evaluation and execution –remember that evaluation is from left to right but
execution is from right to left.

2. There must be some statement after do keyword in do – while loop for it to
compile without error.
i.e.
do ; while(false); //correct
do {;}while(false); //correct
do {}while(false); //correct
do while(false); //error

3. If “t” is a reference variable then ,
t.equals(null) is
false
(null).equals(t) compiler error
let’s say t2 is some other reference variable then
t.equals(t2)
false and not error
consider,
t = null;
t.equals(t2); //not compiler error but runtime error

4. If a class is declared inside a package with public modifier then that class
becomes invisible to all other classes in other packages unless they import the
package or use extended form of addressing the class.

5. The Iterator method of collection interface when invoked returns an instance of
Iterator class.

6. given,
char c = ‘a’;
int i = 1;
c + =i; //correct
c = c+ i; //illegal

7. when use int numbers in basic arithmetic operation then the output is an integer
number. Hence ,
int i = 4/3;
“i” will have the value 1.

8. Native methods can be set to any access level - public , protected, private, default.

9. The methods in the immediate super class in the inheritance tree may be accessed
through the use of keyword “super” , but classes above the immediate super class
are not visible.

10.
Valid comments
· /* this is a comment */
· /** this is a comment */
· /*this is a comment **/
· // /** this is a comment */ */
Important:-
· /* //this is a comment */
11. invalid comments
· /** this is a comment */ */

12. If a method declares some exception in throws clause and the subclass of the
given class while overriding the method declares some new exception then before
assuming that it causes compiler error first check whether the new exception
thrown in the subclass’ method is unchecked exception or not.

13. After solving the logic inside the problem before jumping to conclusion check
whether some code is unreachable or not. Because if it happens so then it results
in compiler error.

14. The following form of instantiating a static inner class results in compiler error,
new ().new ();

15. long l = Integer.MAX_VALUE;
float f = l;
double d = l;
then “d==f” is false due to rounding of numbers in float literal.
But when we assign l to Long.MAX_VALUE or to Integer.MIN_VALUE then
we get the result of “d==f” as true.

16. We can place label statements around a block of code wherever we wish , unless
the name used is not a keyword and follows all the rules meant for identifier.
For eg.
labelA:
{
…..some complex code….
…..some complex code….
if(someThingIsTrue)
{
break labelA;
}
}
this way we place break statement with label in any labeled block of code
which may break out of the code if something comes true.
Furthur the same labels can be used for other block of code as long as they
don’t overlap.

17. An abstract method cannot be marked as both
· Abstract and strictfp
· Abstract and native
· Abstract and synchronized
· Abstract and final
· Abstract and private
· Abstract and static

18. Shift operators can be used only on integers .

19. Switch statements can evaluate byte , short, char , int.
but not long, float.double.
i.e. long l = 10;
switch(l){}//causes compiler error
before jumping to conclusion about switch statements , verify whether
the case arguments are lying within the range of the switch argument.
For e.g. byte b = 10;
Switch(b)
{
case 10: …….. complexcode………break;
case 1000: …….. complexcode………break;
}
here second case statement causes compiler error since it is out of range of
byte literal.

20. The case argument must be primitive literal type or final variable.

21. For loop declarations,
valid
· for(int i=0,j=0;i<10;i++);invalid
· for(i=0,int j=0;;);
· int k =1;
for(int i=0,k=0;;);

Monday, March 3, 2008

SCJP 1.5 Dump questions

Q1
class test
{
public static void main(String[] args)
{
test inst_test = new test();
String pig[][] = { {"one little piggy"}, {"two little piggies"}, {"three little piggies"} };
for ( Object []oink : pig )
{
for ( Object piggy : oink )
{
System.out.println(piggy);
}
}
}
}

a. one little piggy two little piggies three little piggies
b. Compile Error incompatible types.
c. java.lang.String;@187c6c7 java.lang.String;@187c6c8 java.lang.String;@187c6c9
( or something like that )
d. Runtime Null Pointer Exception
e. Prints nothing

Answer1:
a. oink refers to every object reference in a one dimensional row of pig[][].
piggy refers to every object within that row.

--------------------------------------------------------------------------
Q2
class test
{
public static void main(String[] args)
{
test inst_test = new test();
int i1 = 2000;
int i2 = 2000;
int i3 = 2;
int i4 = 2;
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree == Ifour );
inst_test.method( i3 , i4 );
inst_test.method( i1 , i2 );

}
public void method( Integer i , Integer eye )
{
System.out.println(i == eye );
}
}

a. true false true
b. false true false
c. false false false
d. true true false
e. Compile error

Answer 2:
b: false true false. lthree and lfour are two seperate objects. if the lines 1 and 2 were
lthree = 2 and lfour = 2 the result would have been true. This is when the objects are created in the pool. When the references I and eye in the pool are compared 2==2 results in true and 2000==2000 is false since it exceeds 127.

-------------------------------------------------------------------------
Q3
enum cafe {
BIG ( 10 ) ,
SMALL ( 1 ),
MED ( 5 )
int mySize = 0;
cafe ( int size )
{
mySize = size;

}

}

What happens when this enum is in the code outside a class ?

a. Compiles fine
b. Compiler error
c. Runtime Exception occurs if mySize is accessed.

Answer 3:
a: Compile error: semicolon missing after MED ( 5 ). Watch out for that semicolon when an enum has variables and functions.

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

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.

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

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google