Java Questions


1. Consider the following code , what is the output provided a valid file name is given on the command prompt?
import java.io.*;
        class Q032{

               public static void main(String args[]) throws Exception{
                       FileInputStream fin;
                       int c = 0;
                       try
                       {
                               fin = new FileInputStream(args[0]);
                               while ((c = fin.read()) != -1)
                               {
                                      System.out.print((char)c);
                               }
                       }
                       catch (Exception e)
                       {
                               System.out.println(e);
                       }
                       fin.close();
               }
        };
Options :
  1. Compile-time error " Variable fin may not have been initialized."
  2. Run-time exception " java.lang.ArrayIndexOutOfBoundsException: 0"
  3. Run's fine displaying the contents of the file .
  4. Compile-time error " Undefined variable: args"

2. What is the output for the following -
class A{
               static int i;

               A(){
                ++i;
               }

               private int get(){
                       return ++i;
               }
        };

        class B extends A{

               B(){
                       i++;
               }

               int get(){
                       return ( i + 3);
               }
        };

        class Q028 extends B{

               public static void main(String ka[]){
                       Q028 obj = new Q028();
                       A ob_a = new A();
                       ob_a = (A)obj;
                       System.out.println(ob_a.get());
               }
        };
Options :
  1. 2
  2. Compile error " No method matching get() found in class Q026."
  3. 5
  4. NullPointerException thrown at run-time .

3. What is the output ?
class Q006{
              
               public static void main(String args[]){
                       boolean flag = false;
                       if ( flag = true)
                       {
                               System.out.println("true");
                       }
                       if ( flag == false)
                       {
                               System.out.println("false");
                       }
               }
        };
Options :
  1. true
  2. false
  3. Compile-time error " Q006.java:11: Incompatible type for declaration. Can't convert boolean to java.lang.Boolean. "
  4. true
    false

4. What is the output ?
class A{

               A(){
                       System.out.print("1");
               }
        };

        class Q005 extends A{

               Q005(){
                       System.out.print("2");
               }

               public static void main(String args[]){
                       Q005 obj = new Q005();
                       System.out.println("3");
               }
        };
Options :
  1. 123
  2. 23
  3. 3
  4. 1 , 2 , 3 each on a separate line
5. What is the output ?
class Q002{

               public static void main(String args[]){
                       int i = -1;
                       System.out.println(-1 >> 17);
               }
        };
Options :
  1. Compile error
  2. Run-time Exception thrown
  3. -1
  4. Do you expect me to shift the bits
6. Predict the output -
class Q008{
               public static void main(String args[]){
                       int i = -1;
                       System.out.println((i<0)?-i:i);
               }
        };
Options :
  1. 1
  2. -1
  3. Compile error
  4. Run-time error
7. Will the following compile ? If yes what is the output ?
class Q009{
               public static void main(String args[]){
                       System.out.println((Math.abs(Integer.MIN_VALUE)));
                       //FYI Integer.MIN_VALUE = -2147483648
               }
        };
Options :
  1. 2147483648
  2. Compile Error
  3. -2147483648
  4. NegativeArraySizeException thrown at runtime
8. Will the following code compile ? If yes , what is the output ?
class Q012{

               Q012(int i){
                       System.out.println(i);
                       this.i = i;

               }

               public static void main(String ka[]){
                       Q012 obj = new Q012(10);
               }
        }
Options :
  1. 0
  2. 10
  3. null
  4. Compile error " Q012.java:10: No variable i defined in class Q012. "

9. What is the output of this code ?
class Q011{
               int i;
               Q011(int i){
                       System.out.println(i);
                       this.i = i;

               }

               public static void main(String ka[]){
                       Q011 obj = new Q011(10);
                       System.out.println(obj.i);
               }
        }
Options :
  1. 10
    10
  2. Compile error " Q012.java:16: Variable i may not have been initialized. "
  3. 0
    10
  4. 10
    0

10. What is the output for this piece ?
class Test{

               static boolean flag;

               public static void main(String args[]){
                       if ( flag )
                       {
                               System.out.println(flag);
                       }
               }
        };
Options :
  1. Compiler error , boolean flag : variable flag may not have been initialized
  2. Compiler error , System.out.println ( flag ) : can't convert boolean to String
  3. true
  4. false
  5. Compiles & runs fine with no output generated


Answers :
  1. a
  2. b
  3. a
  4. a
  5. c
  6. a
  7. c
  8. d
  9. a
  10. e



























1. What is the output when Test01 class is run ?
class A{

        A(){
               //some initialization
        }

        void do_something(){
               System.out.println("I'm in A");
        }
};

class B extends A{

        B(){
               //some initialization
        }

        void do_something(){
               System.out.println("I'm in B");
        }
};

class Test01{

        public static void main(String args[]){
               A a = new B();
               a.do_something();
        }
};
Options :
  1. I'm in A
  2. I'm in B
  3. Compiler error , A a = new B ( ) : Explicit cast needed to convert A to B
  4. ClassCastException thrown at runtime

2. What is the output for the following code ?
class Q014{
       
        public String get(int i){
               return null;
        }
       
        public static void main(String ka[]){
               System.out.println((new Q014()).get(1));
        }
};
Options :
  1. 0
  2. NullPointerException at run-time
  3. Compile error
  4. null

3.What is the output ?
class Q018{
        static Object obj;
        static String get(){
               return null;
        }

        public static void main(String args[]){
               System.out.println((Q018.get()) == (Q018.obj));
        }
};
Options :
  1. Compile error
  2. Run-time error
  3. true
  4. false

4. What is the output ?
class Q015{
       
        public String get(int i){
               return null;
        }
       
        public static void main(String ka[]){
               Q015 obj = new Q015();
               Object i = obj.get(10);
               System.out.println(i.toString());
        }
};
Options :
  1. null
  2. NullPointerException at run-time
  3. Compile error
  4. 0

5.What is the output ?
class Q013{
        int i;

        Q013(int i){
               System.out.println(i);

        }

        public static void main(String ka[]){
               Q013 obj = new Q013(10);
               System.out.println(obj.i);
        }
}
Options :
  1. 10
    10
  2. Compile error , System.out.println ( obj.i ) : variable i may not have been initialized
  3. 0
    10
  4. 10
    0

6. What is the output ?
class Test02{

        public String fetch(){
               return null;
        }

        public static void main(String args[]){
               Test02 obj = new Test02();
               String str = obj.fetch();
               System.out.println((str+"").toString());
        }
};
Options :
  1. null
  2. Compiler error , can't invoke a method on null
  3. NullPointerException thrown at runtime
  4. ClassCastException thrown at runtime

7. What is the output ?
class Q022{
        public static void main(String ka[]){
               while(false){
                       System.out.println("Great");
               }
        }
};
Options :
  1. Run's with no output
  2. Run-time error " Statement not reached."
  3. Great
  4. Compiler error , System.out.println ( "Great") : statement not reached

8. What is the output ?
class A{
        static int i; 

        private int get(){
               return 1;
        }
};

class B extends A{

        private int get(){
               return 2;
        }
};

class Q027 extends B{

        public static void main(String ka[]){
               Q027 obj = new Q027();
               System.out.println(obj.get());
        }
};
Options :
  1. 2
  2. Compile error , System.out.println ( obj.get ( ) ) : no method matching get ( ) found in class Q027
  3. 1
  4. 2
  5. NullPointerException thrown at run-time .

9. What is the output ?
class Q029{
        public static void main(String args[]){
               boolean b[] = new boolean[2];
               System.out.println(b[1]);
        }
};
Options :
  1. Compile error " Variable b may not have been initialized."
  2. Run-time error " Variable b may not have been initialized."
  3. false
  4. true
10. Consider the following applet . Is there something wrong with it ? Choose the most appropriate option ( only one ) .
public class App_Test extends Applet{

        App_Test(){
               //some initialization
        }

        public void paint(Graphics g){
               g.drawString("Applet started" , 50 , 50);
        }
};Options :
  1. Nothings wrong with it
  2. It should override the init ( ) method of it's superclass ( Applet )
  3. An applet subclass can't override the default constructor
  4. The drawString ( ) method in paint ( ) has wrong number of arguments
  5. The constructor of App_Test must be defined as public





Answers :
  1. b
  2. d
  3. c
  4. b
  5. d
  6. a
  7. d
  8. b
  9. c
  10. e

































1. Will the following code compile ? If yes choose the most correct two options .
class Q011{
        public static void main(String args[]){
               char a = 'a' + 2;
               System.out.println(a);
               int i = 2;
               char c = 'a' + i;//---1
               System.out.println(c);//---2
              
        }
};
Options :
  1. Compile-time error " Explicit cast needed to convert int to char "
  2. The code can be made to compile by commenting out lines marked as 1 & 2
  3. The code can be made to compile by commenting out the line " char a = 'a' + 2; "
  4. The output is
    67
    67

2. What is the output ? FYI ( int ) ' A ' = 65 
class Q1{
        public static void main(String args[]){
               byte b = 65;
               switch (b)
               {
               case 'A':
                       System.out.println("A");
                       break;
               case 65:
                       System.out.println("65");
                       break;
               default:
                       System.out.println("default");
              
               }
        }
};
Options :
  1. A
  2. 65
  3. Compile time error , case 65 : duplicate case label
  4. Runtime error "Duplicate case label: 65"
  5. default

3. Will the output from the following two code snippets be any different ?
Snippet 1 :
               for ( int i = 0 ; i < 5 ; i++ )
               {
                       System.out.println(i);
               }

Snippet 2 :
               for ( int i = 0 ; i < 5 ; ++i )
               {
                       System.out.println(i);
               }
Options :
  1. yes
  2. no

4. What is the output of the following code ? FYI 1 divided by 2 = 0.5
class Q009{
        public static void main(String args[]){
               float f = 1/2;
               System.out.println(f);
        }
};
Options :
  1. Compile-time error float f = 1 / 2 : explicit cast needed to convert int to float
  2. 0.0
  3. 0.5
  4. ClassCastException thrown at run-time

5. What is the output for the following code ?
class Torment{

        int i = 2;

        public static void main(String args[]){
               int i = 12;
               System.out.println(i);
        }
};
Options :
  1. Compiler error , System.out.println ( i ) : can't make a static reference to a non static variable i
  2. Output = 2
  3. Output = 12
  4. Compiler error , i = 12 : variable i is already defined in this class

6. What is the output ?
class FearFactory{
        static{
               System.out.println("Genesis");
        }

        FearFactory(){
               System.out.println("Birth");
        }

        public static void main(String args[]){
               //I'm Lazy
        }
};
Options :
  1. Output = Birth
  2. Output = Genesis
  3. No output generated
  4. Compiler error , System.out.println ( " Genesis " ) : type expected

7. Consider the following class . Which of the marked lines need to be commented out for the class to compile correctly ?
class Evolve{

        static int i = 1;
        static int j = 2;
        int x = 3;
        static int y = 6;

        public static void main(String args[]){
               System.out.println(i + j);//---1
               System.out.println(x + i);//---2
               System.out.println(i + y);//---3
               System.out.println(x + j);//---4
        }
};
Options :
  1. 1 & 2
  2. 1 ,2 & 4
  3. 3 & 4
  4. 2 & 4
  5. 1 , 2 & 3

8. What is the compiler error generated ( if any ) by the following piece of code .
class Jelly{

        public static void main(String args[]){
               float f = 1./2;
               System.out.println(f);
        }
};
Options :
  1. float f = 1. / 2 : invalid numeric type
  2. float f = 1. / 2 : explicit cast needed t convert int to float
  3. System.out.println ( f ) : can't invoke a method on primitive data types
  4. No problem , the code compiles fine .
  5. float f = 1. / 2 : explicit cast needed to convert double to float

9. Will the following class compile ? If yes what is the output ?
class Envy{
        static int i;

        Envy(){
               ++i;
        }

        public static void main(String args[]){
               System.out.println(i);
        }
};
Options :
  1. Yes , it compiles but NullPointerException thrown at runtime
  2. Compiler error , System.out.println ( i ) : variable i may not have been initialized
  3. Yes it compiles & output = 0
  4. Yes it compiles & the output = 1
  5. Compiler error , ++ i : can't make a nonstatic reference to a static variable , i

10. Choose all the valid declarations for the main method from the list below ( any  three )
        a. public void main(String args[])
        b. public static int main(String args[])
        c. public static void main(String [] ka)
        d. public static void main(String [] args)
        e. public static void main(String ka [])

Answer :
  1. a & b
  2. c
  3. b
  4. b
  5. c
  6. b
  7. d
  8. e
  9. c
  10. c , d & e









1. Will the following code compile ? If yes , what is the output & if not what is the compiler error ?
 class Test{

        static String raid(){
               try
               {
                       throw new Exception();
               }
               catch (Exception e)
               {
                       int i = 1 / 0 ;
                       return "Error";
               }
               finally
               {
                       return "Peace";
               }
        }

        public static void main(String args[]){
               System.out.println(raid());
        }
};
Options :
  1. Compiler error , return "Error" : statement not reached
  2. Compiler error ,  i = 1 / 0 : Exception must be caught or declared in the throws clause
  3. Compiles & prints Error when run
  4. Compiles & prints Peace when run

2. What is the compiler error generated by the following piece of code or what is the output if any ?
 class Test01{

        public static void main(String args[]){
               int i = 1;
               if ( i = 2 )
               {
                       System.out.println("In if");
               }
               else System.out.println("In else");
        }
};
Options :
  1. Output = In If
  2. Compiles but no output is generated
  3. Output is = In else
  4. Compiler error , if ( i = 2) : can't convert int to boolean

3. Will the code given below compile ? If run with the following command line - java just - what is the output ?
 class Test02{

        public static void main(String args[]){
               String str = args[0];
               switch ( str.equals("just"))
               {
               case 1:
                       System.out.println("case 1");
                       break;
               case 2:
                       System.out.println("case 2");
                       break;
               default:
                       break;        
               }
        }
};
Options :
  1. Output = case 1
  2. Output = case 2
  3. No output generated
  4. Compiler error , switch ( str.equals("just")) : Can't convert boolean to int.
  5. Compiler error , case 1 : can't convert boolean to int

4. What is the output of the following code fragment when run with the following command line - java 1 ?
 class Test03{

        public static void main(String args[]){
               int i = Integer.parseInt(args[0]);
               switch (i)
               {
               case 1:
                       System.out.println("case 1");
               case 2:
                       System.out.println("case 2");
               default:
                       System.out.println("default");
                       break;        
               }
        }
};
Options :
  1. case 1
    case 2
    default
  2. case 1
  3. Runtime exception thrown -NumberFormatException , Integer.parseInt ( args[0] ) : Can't convert String to int
  4. The code won't compile because there is no method parseInt ( ) defined in the Integer class .

5. Predict the output for the following piece of code .
 class Test04{

        public static void main(String args[]){
               for ( int i = 1 ; i <= 5 ; i++ )
               {
                       if ( i < 5 )
                       {
                               continue;
                       }
                       else System.out.println( i );
               }
        }
};
Options :
  1. 1 to 5 are printed on a new line each
  2. 1 to 4 are printed on a new line each
  3. Only 5 is printed
  4. 2 to 5 are printed on a new line each
  5. 2 to 4 are printed on a new line each
  6. No output is generated because continue terminates the loop

6. Will the following code block compile ? If yes , what is the output ?
 class Test05{

        public static void main(String args[]){
               try
               {
                       throw new Exception();
                       System.out.println("try");
               }
               catch (Exception e)
               {
                       System.out.println("catch");
               }
               finally
               {
                       System.out.println("finally");
               }
        }
};
Options :
  1. try
    catch
    finally
  2. catch
    finally
  3. finally
  4. Exception must be declared in the throws clause
  5. Compiler error , System.out.println("try") : statement not reached

7. What is the output for this ?
 class Test06{

        public static void main(String args[]){
               for (int i = 0 ; i < 5 ; i++)
               {
                       System.out.println(i);
                       break;
               }
        }
};
Options :
  1. 0 to 5 , each on a separate line
  2. 1 to 5 , each on a new line
  3. 1 to 4 each on a new line
  4. 0
  5. 0 to 4 , each on a new line

8. Will the following code generate a compiler error ? If not , what is the output ?
class Test07{

        public static void main(String args[]){
               for (int i = 0 ; i < 5 ; i++)
               {
                       break;
                       System.out.println(i);
               }
        }
};
Options :
  1. 0 to 5 , each on a separate line
  2. 1 to 5 , each on a new line
  3. 1 to 4 each on a new line
  4. 0
  5. Compiler error , System.out.println ( i ) : statement not reached
  6. 0 to 4 , each on a new line

9. Choose the most appropriate option for the following piece of code -
 class Test08{

        public static void main(String args[]){
               char c = 'a';
               switch (c)
               {
               case 1:
                       System.out.println( "case 1" );
                       break;
               case 2:
                       System.out.println( "case 2" );
                       break;
               case 3:
                       System.out.println( "case 3");
                       break;
               default:
                       System.out.println( "default" );
                       break;
               }
        }
};
Options :
  1. Compiler error , switch ( c ) : Can't convert char to int
  2. Compiler error , switch ( c ) : Can't convert char to boolean
  3. Compiles & runs with the output = default
  4. Compile & runs with the output = case 2
  5. Compiler error , switch ( c ) : can't convert String to boolean

10. Does the following piece of code compile ? If yes , what is the output ?
 class Test09{

        static int tomb( char a){
               throw new NumberFormatException();
        }

        public static void main(String args[]){
               try
               {
                       tomb('a');
               }
               catch (Exception e)
               {
                       System.out.println("Done");
               }
        }
};
Options:
  1. NumberFormatException thrown at runtime
  2. Compiler error , throw new NumberFormatException() : Checked Exceptions must be declared in the throws clause or must be caught in the corresponding catch block
  3. Compiler error , System.out.println("Done") : statement not reached
  4. Output = Done
Answers :
  1. d
  2. d
  3. d
  4. a
  5. c
  6. e
  7. d
  8. e
  9. c
  10. d

 I'll assume that you know what binary numbers are & that you are aware of the shift operators ( >> , << , >>>) in Java . If you'd like to know more about how , why , what of binary data mail me , I'll write a tutorial on it only if somebody needs it ! Do read the disclaimer at the end of this page before going further .
OK that said we can start with it .
Why byte is not a byte anymore after a shift operation ?
Lets assume the following block of code -
byte b = 2;
byte c = 1;
byte d = b >> c;
When the above code is compiled you get the following compile-time error -
Incompatible type for declaration. Explicit cast needed to convert int to byte.
The reason for this is that the operands ( b & c ) are implicitly promoted to the int type before any binary operators are applied . Refer JLS 5.6.1 .

What this means -
At the time of declaration/assignment 2 is defined as 00000010 ( byte type) .
But before the shift operand is applied , 2 is converted to 0000000000000000000000000000010 ( int type) .
And since there is no implicit conversion from int to byte , the error is justified .
The same is true for short & char types as well .
Before any binary operator is , applied arithmetic promotion of operands takes place so that the operands are at least of the type int .

What is shifting anyways ?
Shifting is basically taking the binary equivalent of a number & moving the bit pattern left or right . This is analogous to a queue - one bit moves forward & leaves while  the one behind takes it's place . Simple ! This is exactly what the >> & << operators do ( >>> is a bit tricky ) .

Try an example !
Consider 78 whose binary equivalent is
00000000 00000000 00000000 01001110 Try here !
Say you wanna shift it right ( >> ) 2 times , keeping that queue in mind , here's what we get
00000000 00000000 00000000 00010011 ( = 19 )
Similarly now lets shift left ( << ) 3 times & we get
00000000 00000000 00000010 01110000 ( = 624 )
Now for some negative values -
Lets try -65 whose binary equivalent is
11111111 11111111 11111111 10111111
Shift left ( << ) 2 times & the result is
11111111 11111111 11111110 11111100 ( = -260 )
Shift right ( >> ) 2 times & the result is
11111111 11111111 11111111 11101111 ( = -17 )

Did I miss something up there !?
When you shift left ( << ) the void left behind by the shift is filled by zero's but that's not the case when you shift right ( >> ) .

When shifting right ( >> ) the leftmost bits exposed by the right shift are filled in with previous contents of the leftmost bit . That's why when we right shifted 78 we filled it with zero's ( zero is the leftmost bit ) & when we right shifted -65 we filled it with one's ( since one was the leftmost bit ) .
As for the bits in the extreme right ( rightmost bits ) , they're discarded .
Try right shifting ( >> ) these values -
-1 = 11111111 11111111 11111111 11111111 ( result is always -1)
0 = 00000000 00000000 00000000 00000000 ( result is always 0)
Note that right shifting ( >> ) always preserves the sign of the original number i.e. to say that a negative number will stay negative while a positive number will stay positive after a right shift ( >> ) .

So what about the >>> ( unsigned right shift ) operator ?
Sometimes we may require a right shift ( >> ) but we wouldn't like it to fill one's , instead we'd like it to fill zero's & only zero's no matter what . This is where the >>> ( unsigned right shift ) operator fits in .
It fills the void left behind by the leftmost bits with zero's only . So -
78 >>> 2 = 19 &
-78 >>> 2 = 1073741804 Try here .