In this post we will see some of the random core Java interview questions and answers.
Q: What is a variable?
Variable is a named memory location that can be easily referred in the program. A variable is just a container for holding data and is accessible through a reference.
Q: What is the Java API?
The Java API(Application Programming Interface) is the set of classes included with the Java Development Environment. These classes are written using the Java language and run on the JVM. The Java API includes everything from collection classes to GUI classes
Q: What is JVM, JRE and JDK?
The Java Virtual Machine(JVM) is the software that can be ported onto various hardware-based platforms.The JVM executes instructions that a Java compiler generates.
The JRE is the Java Runtime Environment consisting of the JVM, the Java libraries, and all other components necessary to run Java applications and applets, but does not contain any development tools such as a compiler or a debugger
JDK contains software development tools which are used to compile and run the Java program. Both JDK and JRE contains the JVM.
Q: Answer following questions relates to java main()
method. What happens when, ?
- Main method is declared as private?
- Static modifier is removed from the signature of the main method?
- I do not provide the String array as the argument to the method?
Answer:
1. The program compiles properly but at runtime it will give “Main method not public” error message.
2. Program compiles.But at runtime throws an error NoSuchMethodError
3. The program works fine.
Q: Can an application have multiple classes having main method?
Yes. 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 no conflict amongst the multiple classes having main method.
Q: Can I have multiple main methods in the same class?
We can have multiple overloaded main methods but there can be only one main method with the following signature : public static void main(String[] args) {} No the program fails to compile. The compiler says that the main method is already defined in the class.
Q: What is the difference between an Interface and an Abstract class?
- An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
- An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: Explain the reason for each keyword of public static void main(String args[])?
- public: main() is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
- static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
- void: main does not return anything so the return type must be void
- arguments: String args[] The argument String indicates the argument type which is given at the command line and args is an array for string given during command line.
Q: What is pass by reference and pass by value in Java?
Pass by reference means, passing the address itself (like pointers) rather than passing the value. Pass by value means passing a copy of the value. Java uses pass by value.
Q: If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
Q: What are the differences between == and .equals()
?
The == operator two object based on their address. i.e. it compares two objects to determine if they are present in the same memory location. It is possible for two String objects to have the same value, but located in different address. == compares references while .equals compares contents.
The method public boolean equals(Object obj) is present in Object class and can be overridden. The default implementation uses the equality operator == to compare the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence.
Example,
public static void main(String[] args) { String string1 = "MYSTRING1"; String string2 = string1; String string5 = "MYSTRING1"; String string3 = new String("abc"); String string4 = new String("abc"); System.out.println("== comparison : " + (string1 == string5)); System.out.println("== comparison : " + (string1 == string2)); System.out.println("Using equals method : " + string1.equals(string2)); System.out.println("== comparison : " + string3 == string4); System.out.println("Using equals method : " + string3.equals(string4)); }
Output
== comparison : true
== comparison : true
Using equals method : true
== comparison : false
Using equals method : true
Q: What is final, finalize() and finally? What does it mean that a class or member is final?
- final – Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant)
- finally – a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.
- finalize – helps in garbage collection. finalize() method is used just before an object is destroyed and garbage collected
Q: How to convert String to Number in java program?
The valueOf()
function of Integer class is is used to convert string to Number. Here is the code
String numString = "1000"; int id = Integer.valueOf(numString).intValue();
Q: What is the difference between a while and a do loop?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop. The do statement will always execute the loop body at least once.
Q: Describe the principles of OOPS.
There are three main principles
- Polymorphism
- Inheritance
- Encapsulation
Q: Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties and behaviour of another object. Inheritance allows well-tested methods to be reused and enables changes to be made once and have effect in all relevant places.
Q: What do you understand by casting in java? What are the types of casting?
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.
Q: What is implicit and explicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios. Explicit casting in the process in which the complier are specifically informed about transforming the object. Example
int i = 1000, k =100.20; long j = i; //Implicit int j = (int) i; //Explicit
Q: What do you understand by down casting?
The process of down casting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy.
Q: Is sizeof a keyword in java?
The sizeof method is not a keyword.
Q: What is a native method?
A native method is a method that is implemented in a language other than Java.
Q: In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.
Q: Explain Polymorphism? Explain the different forms of Polymorphism.
Polymorphism simply means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
In java there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding). Polymorphism exists in three distinct forms in Java. They are
- Method overloading
- Method overriding through inheritance
- Method overriding through the Java interface
Q: Explain Encapsulation.
Encapsulation is a process of binding or wrapping the variables and the method that operates on them into a single entity. This keeps the data safe from outside interface and misuse. Objects allow methods to be encapsulated with their data to reduce potential interference. Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation provides data security by data hiding.
Q: What are different Java access modifiers?
Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing privileges to parts of a program such as methods and variables. These are:
- Public : accessible to all classes
- Protected : accessible to the classes within the same package and any subclasses.
- Private : accessible only to the class to which they belong
- Default : accessible to the class to which they belong and to subclasses within the same package
Q: What are the primitive types available in Java
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
Q: What is the purpose of static variable and method?
- A static variable is associated with the class context, rather than with specific instances of a class. Each object has only one copy per class, no matter how many objects are created from it.
- A static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.
- Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.
- A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.
Q: What is the difference between & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short circuit operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Q: What is the difference between variable declaration and variable definition?
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. For example String s; is just a declaration while String s = new String (“hello!”); is a definition.
Q: What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed 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.
Q: What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Eg: Using Java Reflection API we can get the class name, by using the getName method.
Q: Does JVM maintain a cache by itself?
Yes, the JVM maintains a cache by itself. It creates the Objects on the heap, but references to those objects are on the STACK.
Q: Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.Class instance associated with the object. It is similar to saying: synchronized(XYZ.class) { }
Q: Does java support multiple inheritance? Why?
Java does not support multiple inheritance but it provide a way through which it can enact it. Consider the scenario is C++
Class A{ public void add(){ // some code } } Class B{ public void add(){ // some code } } Class C extends A, B{ public static void main(String arg[]){ C objC = new C(); objC.add(); //problem, compiler gets confused //and cant decide to call Class A or B method. }
This problem is called Diamond problem. This problem in java is taken care with the use of interfaces In Java similar problem would look like:
public interface A{ add(); } public interface B{ add(); } class C implements A,B{ add(){ // doesnt matter which interface it belong to } }
Q: What is difference between instanceof and isInstance(Object obj)?
1. instanceof is a java keyword, but isInstance(Object obj) is a method of java.lang.Class.
2. instanceof keyword is used to check the type of an object which are known at compile time and isInstance() could only be called on class, say instance of java.lang.Class.
if (obj instanceof MyClassType) { // your code here }else if (MyClassType.class.isInstance(obj)) { //your code here }
3) instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.
Q: What is memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn’t get garbage collected.
Q: What restrictions are placed on method overloading?
Two methods may not have the same name and argument list.
Q: What is the difference between String and StringBuffer?
String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support growable and modifiable strings.
Q: Can a private method of a superclass be declared within a subclass?
Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.
Q: What are differences between a constructor and a method? How can a subclass call a method or a constructor defined in a superclass?
- A constructor has the same name as the class and has no return type and is called using new operator to create an instance of class. They are only called once. Methods can be called many times and has its own name, a return type and is invoked using the dot operator.
- Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
- super.method(); is used to call a superclass method from a sub class. To call a constructor of the superclass, we use the super(); statement as the first line of the subclass’s constructor.
Q: Where and how can you use a private constructor?
Private constructor can be used if you do not want any other class to instantiate the class. This concept is generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public method.
Q: How are this()
and super()
used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
Q: What is Method Overriding? What restrictions are placed on method overriding?
When a class defines a method using the same name, return type, and argument list as that of a method in its superclass, the method in the subclass is said to override the method present in the Superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Restrictions placed on method overriding
- Overridden methods must have the same name, argument list, and return type.
- The overriding method may not limit the access of the method it overrides. Methods may be overridden to be more public, not more private.
- The overriding method may not throw any exceptions that may not be thrown by the overridden method.
Q: Differentiate between a Class and an Object?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. The Class class is used to obtain information about an object’s design. A Class is only a definition or prototype of real life object. Whereas an object is an instance or living representation of real life object. Every object belongs to a class and every class contains one or more related objects.
Q: What is difference between overloading and overriding?
Method overloading: When 2 or more methods in a class have the same method names with different arguments, it is said to be method overloading. Overloading does not block inheritance from the superclass. Overloaded methods must have different method signatures but does not consider the return types.
Method overriding : When a method in a class has the same method name with same arguments as that of the superclass, it is said to be method overriding. Overriding blocks inheritance from the superclass. Overridden methods must have same signature.
- Overloading and overriding are different aspects of polymorphism.
- Overloading – static/early binding polymorphism(compile time):
- Overriding – dynamic/late binding polymorphism(runtime)
- Q: If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package or default access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
Q: Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes. However constructor chaining invokes the constructor in super class.
Q: Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing
Q: Can an object’s finalize()
method be invoked while it is reachable?
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
Q: What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system. It returns the runtime information like memory availability.
- Runtime.freeMemory() – Returns JVM Free Memory
- Runtime.maxMemory() – Returns the maximum amount of memory that the JVM will attempt to use. It also helps to run the garbage collector
- Runtime.gc() – Invokes garbage collector
Q: What is the purpose of the System
class?
The purpose of the System class is to provide access to system resources.
Q: Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable object.
Q: What is the functionality of instanceOf()
?
instanceOf operator is used to check whether an object can be cast to a specific type without throwing ClassCastException
.
Q: What is heap in Java?
It is a memory area which stores all the objects created by an executing program.
Q: Why default constructor of base class will be called first in java?
A subclass inherits all the methods and fields (eligible one) from the base class, so base class is constructed in the process of creation of subclass object (subclass is also an object of superclass). Hence before initializing the default value of sub class the super class should be initialized using the default constructor.
Q: What is an abstract class? Can you make an instance of an abstract class?
Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an abstract class by using Class.forName().newInstance()
(Here we get java.lang.InstantiationException). However, if we create an instance of a class that extends an Abstract class, compiler will initialize both the classes. Here compiler will implicitly call the constructor of the Abstract class. Abstract class is a template class that provides some general functionality but leaves specific implementation to its inheriting classes. Example
abstract class AbstractClassExample{ protected String name; public String getname() { return name; } public abstract void function(); }
In real world example, vehicle is an abstract class and bus, truck, car etc are specific implementations
Q: How to define an Interface?
In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. Example
public interface MyInterface { public void functionOne(); public long CONSTANT_ONE = 1000; }