Java Interview Question Answers

Q1: What do you know about Java?

Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Q2: What is java and why it came into existence?

Java is a programming language provided with application developement and deployment environment.
It came into existence because of following objectives/features:
1) To over come problem in C++ like pointer
2) MultiThreading
3) Platform Independent
4) Automatic garbage collection
5) Improved security and many more.

Q3: What is JVM and is it platform independent?

VM is responsible for converting byte code into machine readable code. JVM is platform dependent, so every different OS has different JVM.

Q4: What is the difference between JVM and JRE?

Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn't contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed.

Q5: What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." message.

Q6: What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Q7: Can static methods be overridden?

The static methods can not be overridden.

Q8: What if I write static public void instead of public static void?

Program compiles and runs properly.

Q9: What gives Java its 'write once and run anywhere' nature?

Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be feed to any platform.

Q10: What is difference between path and classpath variables?

PATH is an environment variable used by operating system to locate the executables. Classpath is specific to java and used by java executables to locate class files.

Q11: Why main method is static?

Because object is not required to call static method if it is non-static method,jvm creats object first then call main() method that will lead to the problem of extra memory allocation.

Q12: How can one prove that the array is not null but empty using one line of code?

Print arr.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print arr.length.

Q13: Can we execute a program without main() method?

Yes, one of the way is static block

Q14: What if I do not provide the String array as the argument to the method?

Program compiles but throws a runtime error "NoSuchMethodError".

Q15: Can an application have multiple classes having main method?

Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Q16: Can I have multiple main methods in the same class?

No the program fails to compile. The compiler says that the main method is already defined in the class.

Q17: Objects are passed by value or by reference?

Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object . Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed. Java passes the references by value just like any other parameter. The pointer to the object is passed as value. Thus, method manipulation will alter the objects, since the references point to the original object but will not intialize the new object.

Q18: What is OOPs concept?

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
Object: Any entity that has state and behavior is known as an object. For example: chair
Class: Collection of objects is called class. It is a logical entity.
Inheritance: When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism: When one task is performed by different ways i.e. known as polymorphism.In java, we use method overloading and method overriding to achieve polymorphism.
Abstraction: Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.In java, we use abstract class and interface to achieve abstraction.
Encapsulation: Binding code and data together into a single unit is known as encapsulation. For example: capsule.A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Q19: What is finally and finalize in java?

finally block is used with try-catch to put the code that you want to get executed always, even if any exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.
finalize() is a special method in Object class that we can override in our classes. This method get’s called by garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when object is garbage collected.

Q20: What kind of variables a class can consist of?

A class consist of Local variable, instance variables and class variables.
Variables defined inside methods, constructors or blocks are called local variables.
Instance variables are variables within a class but outside any method.
Class variables are variables declared with in a class, outside any method, with the static keyword.

Q21: Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the JVM.

Q22: Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q23: What is overriding in java?

When we have more than one method with same name in a single class but the arguments are different, then it is called as method overloading. Overriding concept comes in picture with inheritance when we have two methods with same signature, one in parent class and another in child class. We can use @Override annotation in the child class overridden method to make sure if parent class method is changed, so as child class.

Q24: What is the difference between abstract class and interface?

abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
Abstract classes can have method implementations whereas interfaces can’t.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run abstract class if it has main() method whereas we can’t run an interface.

Q25: What are different types of inner classes?

Nested top-level classes, Member classes, Local classes, Anonymous classes.
Nested top-level classes - If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner.
Top-level inner classes - implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.
Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q26: What is static import?

If we import a class with static then we can directly use all the static variable and method from that imported class without classname.

Q27: Can an abstract class have a static method?

Yes an abstract class have a static method and it can be accessed by any other class(even not a concrete class).

Q28: Can there be an abstract class with no abstract methods in it?

Yes, there can be an abstract class without abstract methods.

Q29: Can an abstract class have a constructor?

Yes an abstract class have a default and parameterized constructors.

Q30: Why static methods cannot access non static variables or methods?

A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.

Q31: What is Marker interface?

A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well known marker interfaces are Serializable and Cloneable.

Q32: Difference between String, StringBuffer and StringBuilder?

String is immutable and final in java, so whenever we do String manipulation, it creates a new String. StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder. StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.

Q33: Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

Q34: Can this keyword be assigned null value?

No

Q35: Can we use String with switch case?

Yes in Java 7 we can have switch case statements with string.

Q36: How does Java allocate stack and heap memory?

Each time an object is created in Java it goes into the part of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack. When a method is invoked and stack pointer is decremented when a method call is completed.
In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.
The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

Q37: Can we use String with switch case?

One of the Java 7 feature was improvement of switch case of allow Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements.

Q38: What are the steps involved in Java Application Execution ?

1. Creating java source file
2. Compiling Java Source Files into *.class file which is actually Byte Code. Use of javac command.
3. Loading class file into Java Run Time (JRE) using class loader
4. Use Bytecode verifier to check for byte code specification
5. Use Just In time Code Generator or Interpreter for byte code execution.

Q39: What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles JAVA byte code to native machine code and execute it directly on the underlying hardware and hence reduces the amount of time needed for compilation.

Q40: What is classloader?

The classloader is a system that is used to load classes and interfaces which are required to run the application. There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader etc.

Q41: What is byte code verifier?

Byte code verifier checks for illegal code like pointers, violated access rights on objects etc. in complied byte code.
1. Check whether classes follow JVM specification for classes
2. Check for stack overflows
3. Check for access restriction violations
4. Illegal data conversions

Q42: What is the default value of the local variables?

Local variables are not initialized to any default value, neither primitives nor object references.

Q43: What will be the initial value of an object?

All object references are initialized to null in Java.

Q44: Is constructor inherited?

No, constructor is not inherited.

Q45: Can you make a constructor final?

No, constructor can't be final.

Q46: Can you override private or static method in Java ?

You can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.

Q47: What is the difference between creating String as new() and literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
It does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly.
Its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.

Q48: How are this() and super() used with constructors?

Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

Q49: How to define a constant variable in Java?

Variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed. static final int MAX_LENGTH = 50; is an example for constant.

Q50: How one can change the heap size of a JVM?

We can use the below command: java -Xms -Xmx program For example: java -Xms64m -Xmx128m program

Q51: What is blank final variable?

final variable, not initalized at the time of declaration, is known as blank final variable.

Q52: What is immutable object?

Immutable classes are Java classes whose objects can not be modified once created.Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.