Showing posts with label SCJP. Show all posts
Showing posts with label SCJP. Show all posts

Wednesday 21 August 2013

Top Most Core Java popular Interview Questions



  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
  1. 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
  1. 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.
Q   What canstop a thread from execution?
A   → Program exiting via call to System.exit(int);
      → Another thread’s priority is increased
      → A call to stop method in Thread class.

Q   What willstop a thread from execution?
A   → Program exiting via call to System.exit(int);
      → A call to stop method in Thread class.
  1. The Iterator method of collection interface when invoked returns an instance of Iterator class.
  2. given,
char c = ‘a’;
int i = 1;
c + =i; //correct
c = c+ i; //illegal
  1. 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.
  1. native methods can be set to any access level -  public , protected, private, default.
  2. 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.
  3. valid comments
·         /* this is a comment */
·         /** this is a comment */
·         /*this is a comment **/
·          // /** this is a comment */ */
Important:-
·         /* //this is a comment */
  1. invalid comments
·         /** this is a comment */ */

  1. 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.
  2. 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.
  3. the following form of instantiating a static inner class results in compiler error,
new <outerClassName>().new <staticInnerClassName>();
  1. 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.
  1. 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.
  1. 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
  1. shift operators can be used only on integers .
  2. 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.
  1. the case argument must be primitive literal type or final variable.<compatible type>
  2. for loop declarations,
valid

·         for(int i=0,j=0;i<10;i++);
i=10

·         for(i=0,j=0;;);

·         for(;;);

invalid

·         for(i=0,int j=0;;);

·         int k =1;
for(int i=0,k=0;;);

  1. equals(),toString(),hashCode() are public in Object class.
  2. If a nested class has static nested variable then it can be used without instatiating the inner class.
  3. Unicode representation of char is hexadecimal form of representation.
  4. If we place a method declaring void as its return type in any assignment or print statements ,it results in compiler error.

  1. If there are any static blocks in a class then when the class is first loaded i.e. calling its static method or instantiating it for the first time ,these blocks of code will be executed in order in which they appear in the declaration of the class.
Further if there are other non – static blocks then they are executed before running the constructors. Summarizing,
First time loading,
              
  next  next

during the subsequent instantiation of the class the non – static block followed by the constructor is executed.
subsequent instantiating of the class,

  next 



  1. when we invoke a static method of a class then , thread will obtain the lock of the instance of the given class in java.lang.Class created at runtime by the JVM.
When we need to call the wait ,notify ,notifyAll method then we need to obtain the reference of that object in the java.lang.Class . to do this we use the form,
<className>.class .wait();

  1. we can apply final modifier along with transcient , static but not volatile but we can apply both transcient and volatile modifiers to field at the same time.
  2. let a method by name m1() calls another method by name m2() which again calls another method called m3(). Let’s say m3() throws a smaller exception ,then method m2 can declare a broader exception than the one passed from m1 or declare the same exception or it can even  put in a try-catch block i.e. to say as we go down the call stack methods can declare  wider exceptions in their throws clause.
  3. given,
class A extends B{} //Line 1
class B extends A{} //Line 2//causes compiler error
here at line 1 compiler error is not caused but instead at line 2 compiler complains of cyclic inheritance.

  1. All the Unicode characters have four numbers (hexadecimal ) placed after ‘\u
i.e. ‘\uXXXX’
here X → can take the values 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
hence the following results in compiler error
‘\u002’,’\u030’
  1. In some questions though it may seem that we are initializing a variable before using it through a conditional block (like having only if – statement and initializing a variable before using it)but instead it will be certain that the variable will be initialized (like having a else statement along with if statement).In some cases even default statement in switch construct carries out similar function.
  2. within a method local inner clss the final variables of the enclosing method can be accessed but cannot be assigned a value even if they aren’t previously assigned a value. → this results in compiler error.
  3. If an exception is thrown again from a catch block then before exiting the finally block will be executed where the exception may be made to be discarded by placing a return statement.for example,


……..main(String [] args)
{
            try{…some complex code….}
            catch(ArithmeticException e){throw new Exception();}
            finally{return;}
}
this prints nothing .

  1. variables declared in a try block are local to that block and aren’t even visible in the catch ,finally or any other block of the same method.
try
{
            int i=2;
            throw new Exception();
}
catch(Exception e)
{
            …print(i); // causes error since ‘i is not visible in the catch block.
}
  1. following statements cause compiler error,
//  char a = ‘\u000a’;
 //  char b = ‘\u00b’;
/* char c =’\u00d’; */
the below statement doesn’t cause error
/* char d = ‘\u000a’; */
  1. the JVM exits only when
·         All non – daemon threads complete
·         Some thread calls System.exit(int) method

  1. A class declared in an interface
·         Is always public
·         Is always static
·         Cannot access i.e. the methods declared in the class cannot call other methods declared in the interface.
·         Can have final, abstract, modifier.
  1. consider,
String str = null;
Here str behaves in all the assignment and print statements in the same way as it would behave if it had contained the string “null”.

  1. Even if the modifier applied to class is public , if the constructor is placed explicitly by the programmer without any modifier then it won’t have the same access  modifier as the class but instead it would possess package access.
·         Hence classes outside the given package can’t instantiate this class.
·         Hence classes outside the package can’t extend this class, since the constructor will not be visible to them.
  1. consider the following conditions,
·         we have an interface containing method which throws some exception in throws clause.
·         Another class implements this interface and doesn’t declare any exception in  it’s throws clause.
·         Now we instantiate the class using the interface reference variable.
·         When we make a call to the method of the interface using the interface reference then we have to declare the exception in throws clause or put it in try – catch block.
For e.g.
interface I{
void m()throws java.io.IOException;
}

class A implements I{
void m(){}
}

class B{
….main(String[] args)
{
      I i = new A();
      i.m(); //causes compiler error → IOException must be placed in try-catch block or declared in throws clause
}
}
  1. Let’s say we have a static final public variable in one class and is accessed by another class. Then after compilation of both the classes ,if the previous class’s final variable’s value is changed and again compiled (but the second class remains unchanged).Now when the second class is executed then it will have the original value and not the revised value .For e.g.
public class A{
            public static final int i = 10;
}

public class B{
……..main(Atring [] args)
{
……..print(A.i);
}
}

when class A and class B files are compiled then we will get two class files named A.class and B.class and when B.class is executed we get the output of “10”.

            Later the value of i in class A is changed to 100 and again compiled.
But class B is maintained as it is i.e. it is not compiled again. Now we will have two class files named A.class(changed one) and B.class(old one). class A now contains variable i with value 100 but when we execute B.class we get the output as 10 again instead of the expected 100.

            If we remove the final modifier for variable i in class A we get the output of 100 during the second compilation of the class B.

  1. If a variable is declared and initialized inside a non – static or static block or inside a constructor it becomes inaccessible to all other methods within the class excluding that block
  2. If we send NaN as one of the arguments for Math.min or Math.max we get the output as NaN.
  3. when we use instanceof operator the left operand must be an instance of Object class or an instance of its subclass The right operand must be a class , Interface type.

If the object is an instance of thegiven class or one of its subclass then it returns true otherwise it returns false.
new String() instanceof Object → true
new Object() instanceof String → false

Here the compiler won’t complain as long as the left operand belongs to the inheritance tree including the right operand otherwise it causes compiler error.

  1. float f = Float.MIN_VALUE /Float.MAX_VALUE;
then the value of “f” is 0.0f
  1. toString method of wrapper clsses can be invoked in the following form,
Integer.toString(Number,radix);
Here
Radix is usually 2,8,10,16 but it can take values ranging from 0 to 36.
  1. Arrays must be indexed with the values of the type byte, short ,char or int but not long ,float or double.
  2. “this” reference is final so any new reference cannot be assigned to it.→ results in compiler error
  3. the exception thrown by finalized method is ignored by JVM
  4. Initializer blocks(both non –static and static blocks) cannot throw exceptions
  5. important points to be noted while using modulus operator –
·         anything nodulus 0.0 or -0.0 is NaN and not ±Infinity.
·         Anything divide by 0.0 is +Infinity
·         Anything divide by -0.0 is –Infinity
·         ±0.0 divide by ±0.0 is NaN.
·         0.0 divide by anything is 0.0
·         -0.0 divide by anything is -0.0

  1. given,
class A{void m(){}}
class B{}
interface I {}
then considedr the followingm
A a = null;
B b = null;
I i = null;
b = (B)a; //compiler error since we can’t cast B into A as they don’t belong to same inheritance tree.

I = (I)a;//No compiler error but runtime error  results due to this.

Now,
i.m();//compiler error because method m() is invisible to reference variable of interface I

but ,
((A)i).m();//normal compilation but run time error(ClassCastException).
  1. Proper instantiation of non – static inner class given,
class Outer
{
            class Inner{}
}

Outer.Inner name = new Outer().new Inner();

OR

Outer o = new Outer();
Outer.Inner name = o.new Inner();

The following instantiation compiles fine but results in runtime error,

Outer o = null;

Outer.Inner name = o.new Inner(); //run time error(NullPointerException) is caused
  1. Look for programs where keywords are used as labels for many blocks and loops.
This causes compiler error.






For e.g.
……..main(String [] args)
{
            int i = 2;
            case:for(i=0;i<10;i++)
            {
                        if(i==5)break case; //causes compiler error
                        System.out.println(i);
            }
}
           
           
  1. If a class implements an interface and doesn't provide all the required implementing methods then compiler error is caused at the first statement of the class where we would have said that the class implements the interface
For e.g.
public class A implements Runnable //compiler error is caused at this line
{
            public void run(int i){}
}
  1. If a thread is blocked in the wait method of an Object and another thread executes notify method on the same object then the thread might never start at all.
  2. static members of static inner classes can be referenced by classname of static inner class like,
<OuterClassName>.<StaticInnerClassName>.VariableName → this variable is declared static. 

Top Most Collection class Interview Questions



·         Given,
Object a = new LinkedHashSet();
Then a instanceof HashSet is true because linkedHashSet extends HashSet.
·         We get similar results with LinkedHashMap and HashMap since LinkedHashMap extends HashMap.
·         Remember these points
Ø  Collection → interface
Ø  Collections and Arrays→ classes providing utility methods for various operations.
·         ListIterator is an interface which extends only Iterator interface not List interface
·         Enumeration interface was introduced in java 1.0
·         Iterator was added in java 1.2
·         Iterator methods : -
Ø  hasNext();
Ø  next();
Ø  remove(Object);
·         Enumeration interface has methods
Ø  hasMoreElements();
Ø  nextElement();
·         the default number of rows visible in a List is ‘4’.
·         When we add the same element again into a Set using add(Object) then the subsequent additions of the element returns a boolean false in its reurn part.  

Top Most Java Operators and assignments Interview Questions



  1. given,
class A{}
class B extends A{}
B b = null;
A a = b;
B b1= (B)a;
The above code fragment doesn’t  cause NullPointerException since we are casting amongst the members of inheritance tree. Hence b1 will have the value “null”.
Similaraly,
given,
int[] i = null;
Cloneable c = i;
i = (int [] ) c;

The above code fragment doesn’t result in runtime error(NullPointerException) since  any array extends Cloneable interface.
  1. All arrays implement Cloneable interface and java.io.Serializable interface
  2. given,
long [] l = {1,2,3,4,5};
int [] i  = {10,20,30};
l[0]= i[0];//legal and correct
l = i; //causes compiler error
l = (long[])i;//causes error
  1. given,
final short s1 = 1;
final char c1 = 2;
short s2 = 3;
char c2 = 4;
byte b1,b2,b3,b4;
remember the following,
b1 = s1;//legal because compiler applies implicit casting since it is final variable.
b2 = c1;//legal because compiler applies implicit casting since it is final variable.
b3 = s2;//illegal because compiler doesn’t apply implicit casting.
b4 = c2;//illegal because compiler doesn’t apply implicit casting.

  1. Important formula,
-x = ~x +1;
and
~x = -x-1;
  1. if ,
int i1;
int i2;
int i3;
i1 = <<someNumber>>;
i2 = <<someComplexMethodName>>();
i3 = i1<<i2;
if i2 is greater than 31 then “i2&0x1f” is used in its place.
  1. The assignment operators are,
   =
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=

Note:
There is no assignment operator like &&=, ||= , ~=.

  1. given,
byte b = 1;
long l = 1000;
b += l;//line 3
the above fragment will not cause compiler error since compiler applies implicit casting before executing the line number 3.the above code fragment will be executed as follows.
·         b += l;
·         b = (byte)(b+l);
·         b = (byte(1+1000);
·         b = someValue;
In general ,
E1 op= E2;
            can be written as E1 = (type)(E1 op E2);
            here type is the datatype of the operand E1 and “op” is the operator applied.

given,
interface inter{}
class B implements inter {}
class sub implements B {}

class Test
{
public static void main(String [] args)
{
            B b = new B();
            I i = b;
            sub s = (sub)b;//line 1
}}

  1. At line one compiler error doesn’t occur because we applying explicit casting on members of the same inheritance tree. Thus at line 1 runtime error and not compiler error is caused. This is be cause B is superclass of sub and an instance of B cannot be converted into a type of sub class.

class Test2
{
            public static void main(String [] args)
            {
                        B[] b = {new B()};
                        sub[] s = new sub[1];
                        Object obj = b;
                        s = (sub[])obj;//line 1
            }
}
  1. At line one a runtime error and not compile time error is caused.
  2. given,
byte a = 1;
byte b = 2;
byte c = (byte)a+b;// Line 1
line 1 causes compiler error since casting is done only to a and not to sum of
a and b.As a result the RHS will be int and LHS will be byte which results in compiler error.

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt