Saturday 22 February 2014

Basic core java Interview Questions And Preparation Guide

1. What are the categories of data types Java supports ? 
     Java supports 2 categories of data types.
         a. Primitive types 
        b. Reference types

2. What are the primitive types ?
     Java language supports 8 primitive types of data.
     Those are:
          byte, short, int, long
          float, double
          boolean
          char

3. If you are using primitive data types as local variables, then you must initialize the variable before using. Other wise compiler will throw error.

4. If you are trying to assign data of one type to the other incompatible type compiler will throw error.
     Example
     class Compatible{
          public static void main(String args[]){
               int intVar = 10;
               boolean a = intVar;
          }
     }

     While compiling you will get the below error

     Compatible.java:6: error: incompatible types

     boolean a = floatVar;

     ^

     required: boolean

     found: float

     1 error

5. Always assign a value to a float variable by appending “f” to it like below
     float floatVar = 10.09f

6. Multiplication, Division and remainder operator has more priority than Addition and Subtraction operators.

7. Remainder operator always returns the sign of numerator

    Ex: 
    5 % 2 = 1 
    -5 % 2 = -1
8. If you try to compare two incompatible type values, compiler will throw error.
     class ConditionalEx{
public static void main(String args[]){
int a = 10;
boolean b = true;
System.out.println("a less than b " + (a<b));
}
     }

     If you try to compile the above program, you will get the below error

     ConditionalEx.java:8: error: bad operand types for binary operator '<'

     System.out.println("a less than b " + (a<b));

     ^

     first type: int

     second type: boolean

     1 error


9. Why Logical AND is called short circuit operator
Since if the first statement in the expression evaluates to false, then java won't evaluates the entire expression. So Logial AND is called short circuit AND

10. Why Logical OR is called short circuit operator
Since if the first statement evaluates to true, then java won't evaluates the entire expression. So Logial OR is called short circuit OR

11. When to use if-else if -else ladder, than switch ?
Switch case won't supports range checks like age>30, year<2000 etc., in those cases better to go for if-else if-else ladder.

12. What is the difference between while and do-while ?
the statements within the do block are always executed at least once even if the expression evaluates to true.

13. If you try to access an array with illegal index, then compiler will throw “ArrayIndexOutOfBoundsException”
     Example
     class ArrayEx{
          public static void main(String args[]){ 
                 int arr[] = new int[10];
                arr[11] = 100;
           }
     } 

     When you try to compile, compiler will throw the below error

     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
     at ArrayEx.main(ArrayEx.java:5)

14. If Program defined with array of negative size, then program compiles fine, but “NegativeArraySizeException” will be thrown at run time.

     Example
class ArrayEx{
               public static void main(String args[]){
String arr[] = new String[-10];
               }
           }
Program compiles fine, but run time error come
     Exception in thread "main" java.lang.NegativeArraySizeException at ArrayEx.main(ArrayEx.java:3)

  1. Array size is always an integer, so it is correct to give array size as byte, short and int. But not long.
     Example 1
     class ArrayEx{
public static void main(String args[]){
     byte b = 10;
     short s = 11;
     int i = 5;

String arr1[] = new String[b];
String arr2[] = new String[s];
String arr3[] = new String[i];

System.out.println(arr1.length +"\t" + arr2.length + "\t" + arr3.length);
          } 
     }

     Output 
     10 11 5

     Example 2 
     class ArrayEx{
public static void main(String args[]){
     long i = 10;
     String arr3[] = new String[i];
          } 
     }
When you try to compile, you will get compiler error like below

ArrayEx.java:6: error: possible loss of precision

String arr3[] = new String[i];

^

    required: int
  1. The problem with Arrays is, they can't grow dynamically, once Array is initialized, you can't change the size of the array.
  1. What is an object ?
    An Object is simply a real world entity. For example, book, cat, box, bus, keyboard, person, screen, cell phone etc., all are objects.
   18. What Is a Class?
     A class is a blueprint or prototype from which objects are created.
  1. What is instance variable ?
    Instance variables are those which are associated with object.
20. If you don't initialize an instance variable, by default it is initialized to default value.
Data Type Default Value
int 0
float 0
String Null
boolean FALSE
Reference type null

22. What is Encapsulation ? 
Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If you make the fields as private, then outside of the class you can't access those variables. So Encapsulation is also called data hiding

22.What are the uses of getter and setter methods ?

     See the below post
     http://selflearningjava.blogspot.in/2014/02/object-oriented-feature-encapsulation.html

23. Calling void methods inside the print causes compile time error
     Example
          class MethodEx{

               void print(){ 
               }
 
               public static void main(String args[]){
                      MethodEx obj = new MethodEx();
System.out.println(obj.print());
               }
          } 

When you try to compile the above program, compiler will throw the below error.

MethodEx.java:7: error: 'void' type not allowed here
System.out.println(obj.print());

^

1 error


24. What is method overloading ? 
Methods within a class can have the same name if they have different parameter lists.

25. The return type is not sufficient to differentiate two overload methods.
When you try to differentiate two methods with the return type, then you will get compile time error like “Method is already defined”.

     class OverloadEx{
String print(int s){
     System.out.println("I am integer " + s);
}

void print(int a){
     System.out.println("I am integer " + a);
}
     }

When you try to compile you will get the below error

     OverloadEx.java:7: error: method print(int) is already defined in class OverloadEx

void print(int a){

^

     1 error

26. By default a number considered to be an integer

     class OverloadEx{
void print(int s){
     System.out.println("I am integer " + s);
}

void print(byte a){
     System.out.println("I am byte " + a);
}

void print(short a){
     System.out.println("I am short " + a);
}

void print(long a){
     System.out.println("I am long " + a);
}

public static void main(String args[]){
     OverloadEx obj = new OverloadEx();
     obj.print(10);
}
     }

     Output
     I am integer 10

Above program overloads method print, with 4 parameters byte, short, int and long. Program calls the print() with value 10. By default numbers consider to be primitive. So print with int argument will be called.

27. By default a real value considers as double

     class OverloadEx{
void print(float s){
     System.out.println("I am float " + s);
}

void print(double a){
     System.out.println("I am double " + a);
}

public static void main(String args[]){
     OverloadEx obj = new OverloadEx();
     obj.print(10.01);
}
     }

     Output
     I am double 10.01

28. What is the output of the below program ?

     class OverloadEx{
void print(float s){
     System.out.println("I am float " + s);
}

public static void main(String args[]){
     OverloadEx obj = new OverloadEx();
     obj.print(10.01);
}
     }

already discussed, a real number considers as double by default. So program gives compile time error like below

OverloadEx.java:9: error: method print in class OverloadEx cannot be applied to given types;

obj.print(10.01);

^

required: float

found: double

reason: actual argument double cannot be converted to float by method invocation conversion

1 error

29. What is the output of the below program ?

       class OverloadEx{
void print(float s){
     System.out.println("I am float " + s);
}

public static void main(String args[]){
     OverloadEx obj = new OverloadEx();
     obj.print(10.01f);
}
     }
     Output
     I am float 10.01

30. Can we make constructor and method with the same name ?
     Yes, it is valid in java
 
31. What is the difference between class and instance variable ?
instance variables are associated with object, where as class variables associated with class, i.e, available for all objects.

32. Static methods can't access instance methods

33. Static methods can't access instance variables

34. Applying static for top level class is wrong in java
Example
     static class Person{

     }
     When you try to compile, compiler throws the below error

Person.java:1: error: modifier static not allowed here

static class Person{

^

1 error


35. Static fields are initialized at the time of class loading, where as instance variables are initialized at the time of object creation 

36. Just like instance methods, we can overload static methods also

37. What is initializer block ?
Initializer blocks are used to initialize instance variables.

Syntax of Initializer Blocks
     {
          //initialization Blocks code goes here
     }

The Java compiler copies initializer blocks into every constructor.

38. A class can has more than one initializer block

39. The data in initializer blocks copied to every constructor

40. Initializer block are called every time, when you created the object

41. Initializing static fields in the initialization block is valid, but don't use it, since the static variable is initialized every time when a new object created.

42. call to this must be first statement in constructor 

43. Calling this from any methods other than constructor causes compiler error

     class Person{
Person(){
}
void setName(){
this();
}
     }

When you try to compile the above program, compiler throws the below error
Person.java:7: error: call to this must be first statement in constructor

this();

^

1 error

44. You must initialize the static final variables, other wise compiler throws the error

45. Static final variables must be initialized at the time of creation or in the static block, Otherwise compiler throws the error
 
46. Trying to initialize the static final variable other than at the time of creation or in static block cause the compile time error.

47. You must initialize the final variables whether those are static or non-static, otherwise compiler throws error

48. Final variables for objects must be initialized in the constructor or in the instance blocks

49. Trying to initialize final variables for objects other than in constructor causes compile time error.

50. How to declare global constants in java ? 
Make a variable as public static final.

51. What are the uses of nested classes ?
     Uses Of Nested classes
          Increase Encapsulation : We can make the nested classes as private, so outside world these nested classes are not visible. 

     More readable code : Making small nested classes and enclosing thse with outer classes, makes the code readable

52. You can't access non static fields from static nested class directly

53. You can't access non static methods from static nested class directly

54. To access non static fields from static nested class, object for the outer class must created

55. Local class access the local variables only if those are declared as final

56. Local class access the parameters of a method only if those are declared as final

57. Local classes are a kind of inner classes, so defining static and non final variables causes the compile time error

58 . Local classes in static methods can only refer to static members of the enclosing class

59. Local classes are non-static because they have access to instance members of the enclosing block.

60. Local class can't contain static methods, Doing so causes the compile time error

61. Can I declare an interface inside Class ?
     Yes

62.  Can I declare abstract class inside class ? 
     Yes

63. Can I create an object for an Interface ?
     Yes, Using Anonymous classes

64. Can I create an object for abstract class ?
     Yes, Using Anonymous classes

65. An anonymous class cannot access local variables in its enclosing scope that are not declared as final

66. You cannot declare static initializers or member interfaces in an anonymous class.

67. An anonymous class can have static members provided that they are constant variables

68. Can I declare extra methods in Anonymous classes ?

Yes. It is valid

     Example
class AnonymousEx{

     interface Uniform{
         void setColor(String color);
          String getColor();
     }

     Uniform zpschool = new Uniform(){
                                   String color;
                                   public void setColor(String color){
                                        this.color = color;
                                   }
                                   public String getColor(){
                                        return color;
                                   }
                                   void print(){
                                        System.out.println("I am Extra method");
                                   }
                              };
          }

As you see in the above program, interface Uniform has 2 abstract methods, setColor, getColor. But the Anonymous class has extra method print().


69. Can below program compile ?
class AnonymousEx{

abstract class Uniform{
void setColor(String color);
String getColor();
}

}

No, Compiler throws the below error.

AnonymousEx.java:4: error: missing method body, or declare abstract
void setColor(String color);
^
AnonymousEx.java:5: error: missing method body, or declare abstract
String getColor();
^
2 errors

To solve the above error, make the methods in the abstract class as abstract

class AnonymousEx{

abstract class Uniform{
abstract void setColor(String color);
abstract String getColor();
}

}

70. In java, you can never put an object on stack, only object reference can be stored on stack.

71. is calling to System.gc() runs the garbage collector immediately ?
No, Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

72. What is the difference between gc() in System class and Runtime class?
No difference. System.gc() calls the gc() of Runtime class internally.

73. Is overloading of main method valid ?
      Yes
74. You can call main method in any way like 
          public static void main(String args[])
               (OR)
         static public void main(String args[])

75. . Why is the Java main method static?
Before the main method is called, no objects are created. Having the static keyword means the method can be called without creating any objects first.

76. Why main method is public static in Java
main method should be called by JVM, which is not part of the project, so to make it available for the JVM, main method declaed as public.

Before the main method is called, no objects are created. Having the static keyword means the method can be called without creating any objects first.

77. Why main() in java void ?
In Programming languages, return codes tells the status of particular program/process/function execution. Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

Java supports multi threading, so the main thread may finishes first, before other threads completes execution, So what status code the main thread returns, even it don't know about the executions of other threads started in main method. So in Java there is void return type for main method.

78. Is the below program runs ?

     class MainEx{
          public static void main(){
          }
     }

Above program compiles fine, but Runtime, JVM tries to find the main method with signature
public static void main(String args[])
there is no main method with the above signature in the program, so below run time error thrown
Error: Main method not found in class MainEx, please define the main method as:
public static void main(String[] args)

79. Can constructors throw exceptions ?
     Yes, Constructors are like special methods in java.

80. If a class implements an interface, then it must implement all the methods in the interface, other wise, the class must declared as a abstract.

81. By default all the methods in the interface are public, while implementing the interface, class must provide the public access specifier for the method it implementing, otherwise “weaker access privileges” error thrown at compile time.

 82. All the variables in the interface are final by default, so updating the variable in a class causes the compile time error

83. If a class implementing multiple interfaces, and more than one interface has same variable definition, then using the variable causes ambiguity to the compiler

84. Can interface be final? 
No, Interfaces can't be final. A final class is not extendable. If you make interface as final, there is no use of it. So it is illegal in java.

85. Can an Interface abstract ?
Yes, but no point in putting abstract modifier for the interface, since all the method in interface are abstract by default

86. Can an interface extend more than one interface ?
A single interface can extend any number of other interfaces.

87. Is empty interface like below are valid ?
    Interface Interface1{
    }
    Yes, It is Perfectly valid.
88. Can I use super and this in one constructor ?
No, call to super or this must be first statement in constructor. So you can use either super or this but not both.

89. Object class is the super class for all the classes

90. Sub classes can access the all the data of super classes, other than private fields and private methods

91.  Is run time polymorphism applicable to static methods also ? 
No, static methods can't be overridden, they just hide the static method of the super class.

92. Is the instance variables overridden ?
     No

93. Can I apply static modifier to the subclass overriding method?
      No, compiler throws an error.

94. What is wrong with the below program ?

     class Animal{
          String str = "Animal";
          void print(){
               System.out.println("I am animal");
          }
     }

     class Tiger extends Animal{
          String str = "Tiger";
          private void print(){
               System.out.println("I am Tiger");
          }
     }

When you tries to compile the above program, compiler throws the “Weaker access specifier error”
Tiger.java:3: error: print() in Tiger cannot override print() in Animal
private void print(){
^
attempting to assign weaker access privileges; was package
1 error

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

95. What is the difference between static binding and Dynamic binding ?
Static binding occurs at compile time, where as Dynamic binding at run time. Dynamic method dispatch is an example for Dynamic binding.

96. What is wrong with the below program ?

     class Animal{
          String str = "Animal";
               void print(){
                    System.out.println("I am animal");
               }
     }

     class Tiger extends Animal{
          String str = "Tiger";
          void print()throws Exception{
               System.out.println("I am Tiger");
          }
     }

The overriding method cannot throw any exceptions that are not thrown by the overridden method.

When you tries to compile the above program compiler throws the below error.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
void print()throws Exception{
^
overridden method does not throw Exception
1 error

97. Is the constructors inherited ?
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses.

98. When a subclass object assigned to super class reference variable, then the reference variable can call the methods which are defined in the super class, trying to call the methods which are not defined in super class cause the compile time error.
     Example
     class Animal{
          void print()throws Exception{
               System.out.println("I am animal");
          }
     }

     class Tiger extends Animal{
          void print(){
               System.out.println("I am Tiger");
          }
          void show(){
               System.out.println("I am show method");
          }
     }

     class DynamicMethodDispatchEx{

     public static void main(String args[]){
          Animal anim1 = new Tiger();
          anim1.show();
     }
}

When you are trying to compile the program, below error thrown, since the reference variable of class Animal, “anim1” trying to call the method “show: which is not defined in the class “Animal”.

DynamicMethodDispatchEx.java:5: error: cannot find symbol
anim1.show();
^
symbol: method show()
location: variable anim1 of type Animal
1 error

99.Can I specify weaker access specifier to the overriding method in the sub class ?
     No

100. Covariant types are applicable for reference types, not for primitives
     class Animal{
          int getAnimal(){
               return 0;
          }
     }

     class Tiger extends Animal{
          byte getAnimal(){
               return 0;
          }
     }

     When you tries to compile the class “Tiger”, compiler throws below error

     Tiger.java:2: error: getAnimal() in Tiger cannot override getAnimal() in Animal
     byte getAnimal(){
     ^
     return type byte is not compatible with int
     1 error

101. Can a sub class instance method hides the super class static method ?

    No, Compiler error thrown.
    Example 
    class Animal{
     static void printMsg(){
          System.out.println("I am the super class static method");
     }
}

class Tiger extends Animal{
     void printMsg(){
          System.out.println("I am the sub class static method");
     }
}

When you try to compile the class Tiger, compiler throws the below error. You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.

Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
void printMsg(){
^
overridden method is static
1 error

102. What is wrong with the below program ?

          class Animal{
     public static void printMsg(){
          System.out.println("I am the super class static method");
     }
}

class Tiger extends Animal{
     static void printMsg(){
          System.out.println("I am the sub class static method");
     }
}

The access specifier for an hiding method can allow more, but not less, access than the hidden method. For example, a public static method in the superclass can be made public, but not private, protected and default.

When you tries to compile the class Tiger, compiler throws the below error.

Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
static void printMsg(){
^
attempting to assign weaker access privileges; was public
1 error

103. What is wrong with the below program ?

          class Animal{
  static void printMsg(){
     System.out.println("I am the super class static method");
}
        }

class Tiger extends Animal{
     static void printMsg()throws Exception{
          System.out.println("I am the sub class static method");
     }
}

The hiding method cannot throw any exceptions that are not thrown by the overridden method.

When you tries to compile the above program compiler throws the below error.

Tiger.java:2: error: printMsg() in Tiger cannot override printMsg() in Animal
static void printMsg()throws Exception{
^
overridden method does not throw Exception
1 error

104. Can I specify weaker access specifier to the overriding method in the sub class ?
          No

105. Can interface has static methods ?

No

106. Can a sub class instance method hides the super class static method ?
    No, Compiler error thrown.
107. Super can't be used in static context, whether it is inside static method or block.

108. Call to super must be first statement in constructor

109. Calling super class constructors in any methods other than constructors, cause compiler error.

110. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

111. What is blank final variable in Java ?
Blank final variable in Java is a final variable which is not initialized while declaration, instead they are initialized on constructor or initializer blocks or static initialization blocks.
Refer below link for detailed explanation

112. Both the private and final methods can't be overridden.

117. Can I make private method as final ? 
Since private already implies that a subclass may not override a method, declaring a private method to be final is redundant. It won't cause any problem to your program, Program compiles fine 
118. Can I create constructor inside the abstract class ?
 Yes, but you can't initialize an object for the abstract class.

    abstract class Animal{
      String name;
      Animal(String name){
         this.name = name;
      }
}

119. Can I make abstract class as final ? 
No, If you make abstract class as final, then no other class can able to extend it. So, compiler throws error. Abstract and final can't be used together.

120. Can I make abstract method as final ?
No, If you make abstract method as final, then no other class can able to override it. So, compiler throws error. Abstract and final can't be used together.

121. Can I define main method in abstract class ?
Yes, it is valid, but creation of object to the abstract is not possible.

122. An abstract class allowed to have static methods, where as interfaces have instance methods only.

123. The methods declared in interface are abstract by default.

124. Can an interface has constructor ? 
   No 

125. Can an abstract class have a final method?
Yes, it can. But the final method cannot be abstract itself

126. If I can simulate Abstract class as Interface, why java provides Interface?
because you can implement multiple interfaces, but can't extend multiple abstract classes. To support multiple inheritance, interfaces are necessary.

127.   What are the differnces between abstract class and interface ?
  1. Interfaces support multiple inheritance, where as abstract classes are not.
  1. All the fields declared in interface are static final, where as you can declare static, non static, final, non-final variables in abstract class. There is no restriction in abstract classes.
  1. All the methods declared in interface are abstract by default. It is not necessary for an abstract class to have abstract methods.
  1. Abstract class can have concrete methods, where as interface don't
  1. Abstract class can have constructor, where as interface not.
  1. Abstract classes are used to share the common behavior. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
  1. An abstract class can implement the interface, it doesn't mean that it provides implementation for all the methods in the interface.


                                                   Interview Questions

No comments:

Post a Comment