Java Interview Questions and Answers for fresher

1. Difference between Java and C++? What would you prefer and why?

I would prefer Java over C++ because Java has all the features and it does not support such complex features like structure, templates, operator overloading.

C++

Java

C++ is a platform-dependent language. Java is a platform independent language.
C++ is a compiled language Java is a compiled and interpreted language.
C++ is not portable Java is portable
Memory management is manual here We have a garbage collector here for memory management.
Method and operator can be overloaded. Only method overloading is achieved in java.
C++ does not have thread support.It has o depends on third party lib. Java has built in support with a class thread.

2. What is the use of class loaders in java?

In java dynamic class loading is achieved using Classloader.It loads, links initializes the class file when it is calling the class for the first time at runtime.

3. What is an instanceof keyword?

It is an operator in java which is used to test whether the object is an instance of the class specified.

Example:

Class Demo{  
 public static void main(String args[]){  
 Demo d=new Demo();  
 System.out.println(d instanceof Demo); 
 }  
}

Output: true.

4. What happens when an exception is thrown by the main method?

When an exception is thrown by the main() method, Java Runtime terminates the program and prints the exception message and stack trace in the system console.

5. How to get the database server details in Java program?

You will get the name of all databases.

DatabaseMetaData metadata = connection.getMetaData();
ResultSet result = metadata.getCatalogs();
while (result.next()) {
    String aDBName = result.getString(1);
    System.out.println(aDBName);
}

6. Why is the Java platform independent? Is the JVM platform independent?

The meaning of platform-independent is java compiled code can run at any platform.

when we write a program in java and when you compile it .class file is generated this .class file is known as bytes code of java. This .class file is not in the executable stage. This bytecode generated in one platform can be executed on another platform. We need to execute this bytecode using JVM (Java Virtual machine) Then, JVM translates the Java bytecode to machine understandable code. Thus we can say Java is platform-independent and because of JVM.

JVM is not platform Independent because for every platform we will need the respective JVM.

7.  Difference between interface and abstract in Java? Give one eg?

  1. Methods of Interface are implicitly abstract and cannot have implementation while an abstract class can have implementation methods.
  2. Variables declared in Interface is by default final. An abstract class may contain nonfinal variables.
  3. In Interface, we use the implement keyword and in Abstract class we use the extend keyword.
  4. Interfaces are rules because you must give the implementation to them that you can’t ignore or avoid.

Ex: consider a mobile phone, in that functionality like call(), sendsms() these are mandatorary so we can create an interface for this.but there is some functionality like viewImage() is not mandatory so we can create an abstract class for it.

8. What is Multiple Inheritance? Does java support it.? Why?

When one class extends more than one class then this is called multiple inheritance. eg: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn’t allow multiple inheritance.

Java doesn’t allow multiple inheritance to avoid the ambiguity caused by it. One of the eg.is the diamond problem that occurs in multiple inheritance.

But we can implement using Interface in Program because it will not cause any ambiguity.

9. What is method Overloading and overriding? Is Method Overloading achieved using different return types?

Method overloading means two separate methods in a class with the same name but different arguments, while the method return type may or may not be different, which allows us to reuse the same method name.

Ex.

class Shape{
public  void area(radius r){}
Public void area(length l,width w){}
}

Method overriding means a method in a child class that is already defined in the parent class with the same method the same name, arguments, and return type is Method Overriding. 

Ex.

 class RBI{
public void setInterestRate(rate r){
}
}Class HDFC extend RBI{
public void setInterestRate(rate r){
}
}

10. What are the memory areas allocated by JVM?

In Java Memory Allocation is divided into the following sections :

  • The code section contains your bytecode.
  • The Stack section of memory contains methods, local variables, and reference variables.
  • The Heap section contains Objects (may also contain reference variables).
  • The Static section contains Static data/methods.

11. What is a Singleton Class in Java?

Singleton class is a class whose only one object can be created. We can achieve it using the following:

  • By making the constructor private.
  • Make a method static with the return type of the singleton class.

For the Singleton class, we use the getInstance() method in java.

12. Why do we set Environment variables?

Environment variables are the global variables accessed by processes under OS. The PATH is set so that our OS is able to access exe files from the command line.

When we compile a java code we need javac.exe inside the bin directory where JDK is installed (for ex. C:\Program Files\Java\jdk1.8.0_91\bin). If we don’t set the PATH in Environment variable every time you compile or run you have to provide a complete path of javac:

Once you set the PATH Environment variable we can compile and run the program without giving complete javac path every time.

13. Why Java doesn’t have pointers?

No, because usage of pointer leads to illegal access of data i.e pointers show the exact address of the data and using this address any modifications can be made to info stored leading to lack of security, but java is a secured language and also robust that’s the reason pointers concept was removed from java.

14. What is a reference variable in java?

reference variables in java which act in a similar way like a pointer that is holding the address of an object

Eg.

class A{
}Class B {
A a=new A();
}

here ‘a’ is a reference variable which stores the address of the object A and the address is not revealed to the user or any other because if u try to access the address of ‘a’ it returns a fully qualified address i.e. packagename.classname@some hexadecimal value by doing so the security is preserved and illegal access is avoided.

15. What is Class & Object in Java?

Classes and Objects are basic of Object Oriented Programming language.A class is a blueprint from which objects are created. Class have Properties and attributes that are common to all the objects.

An object is a basic unit of OOPs. Object has State, behaviour, & Identity.

State: It represents properties of an object.

Behavior: It represents the function of the object

Identity: It gives a unique name to the object.

Object State Behavior Identity
Pen Color

Weight

Shape

Size

type

Writing Pen
Fan Color

Size

type

On/off

rotation

Fan

16. What are the ways to create objects?

Using new keywords: It is the most common way to create Objects.

Eg.

Cricketer cricket=new Cricketer();

Using Class.forName(String classname): It is present in the java.lang package. It returns a class object associated with the class. here we have to give a fully qualified name of the class.   

Eg.

Class.forName(“oracle.jdbc.driver.OracleDriver”)

Using clone() method: It is present in the Object class and creates and returns the copy of the object.

Eg.

Cricketer cricket=new Cricketer();
Cricketer2 cricket2=cricket.clone();

Deserialization: It is a technique of reading an object from a save state in a file.

FileInputStream in=new FileInputStream();
ObjectInputSream out=new ObjectInputSream();
Object o=out.readObject();


17. What is Anonymous Object?

Objects that are instantiated but not stored in any reference variable.

Eg.

new Circle(); //Anonymous Object
//Let's call by reference variable
}Circles=new Circle();
s.area(5);
//Let's call using anonymous object
New Circle.area(5);
/Complete Example:
class Circle
{
Void area(radius r)
{
int  pi=3.14;
float area=3.14*r*r;
System.out.println(“area of Circle is ”+area)
}
public static void main()
{
New Circle.area(5) //by calling anonymous Object.
}

18. What is an instance?

The instance is related to classes. As we know classes are used to define the properties and behavior of things. For eg., Fan has properties like a model, size, shape, and behavior on/off. But if you want to be specific about a particular Fan so we create an instance of Fan. It is the instance that will capture the specific information of individual Fan.

19. Difference between JDK, JVM & JRE?

JDK: JDK stands for Java Development Kit. It provides a development environment for Java application. It includes:

  1. JRE
  2. An interpreter/loader
  3. Compiler
  4. Archiver
  5. javadoc.

JRE: JRE stands for Java Runtime Environment. It also provides a requirement for executing a Java application. It includes

  1. Core classes, files
  2. JVM

JVM: It is responsible for executing Java programs. It is an important part of JDK & JRE.

20. What is the access Specifier? 

Java provides an access Specifier that restricts the scope or visibility of a package, class, methods, variable. 

  1. Default: When no access modifier is specified It is said to be having default access. (It is default)
  2. Private: private access is specified using a private keyword. The methods or class declared with private keyword are accessible only within the class in which they are declared.
  3. Protected: The protected access modifier is specified using the keyword protected. The methods or data members declared as protected are accessible within the same package or subclasses in different packages.

public: The public access modifier is specified using the keyword public. classes, methods or data members which are declared as public are accessible from everywhere in the program.

21. Can we write two main() methods?

Java starts the execution of a program by invoking main() method. We can have more than one main() when we are doing method overloading otherwise not.

Example:

class ExampleOfMainMaethod{
public static void main(String a[]){
}
public static void main(int a){
}
}

22. Why do we make the main() method static?

We make the main() method static because as we know main() is the starting point of execution for the compiler, so the compiler calls this method without creating an object of the class.

23. Explain each term public static void main(String a[])?

public: It is an access specifier so that JVM can identify the main() method.

static: We make the main() method static because as we know main() is the starting point of execution for the compiler, so the compiler calls this method without creating an object of the class.

void: the main() method does not return anything.

main() method: It is the entry point of execution for JVM. It is the default signature.

String a[]: The main()  method accepts data from the user. It accepts an array of strings. Here a[] is an array of Strings type.

24. What is a collection in Java? In which package Collection framework is present? 

A group of Objects which are taken as a single unit is known as a collection of Objects. There is a Collection framework in java which is a set of classes and interfaces which implement common data structures.

In java.util package.

25. Difference between Map and list?

List Map
Elements are stored in sequence. Elements are stored in key-value pairs.
It allows duplicate elements. It does not allow duplicate elements.
It allows any number of null values In this key can have at most one null value and value can have as many null values.
List and all its implementation maintains insertion order. In map some of its implementations maintain insertion order and some not.

26. Difference between ArrayList and Vector.?

ArrayList Vector
ArrayList is not synchronised Vector is Synchronised.
If the number of entries exceeds the maximum size of ArrayList. It gets expanded to 50%. If the number of entries exceeds the maximum size of Vector. It gets expanded to 100%.
It is introduced in JDK 1.2 It is a legacy class
It is fast. It is slow.
It uses iterator interface It uses both iterator and Enumerator.

27. Why do we use ArrayList when we have Array?

Array has some limitations over ArrayList because It has contiguous memory location also we cannot change the size of array. On the other hand ArrayList is a class of collection framework it can be resized based on the requirement.

28. Give some methods of Set?

add(element) Add the element to the set.
addAll(collection) Append all the elements from the mentioned collection to existing one.
clear() Remove all elements.
contains(element) Check whether the element is present in the set or not.
containAll(collection) Check whether the set contains all the elements present in the collection or not.
hashCode() Get the hashCode value for the element.
isEmpty() Whether the set is empty or not.
iterator() Used to traverse elements.

29. What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class.

30. What is the JIT compiler in Java?

JIT is a Just-In-Time compiler in Java. It is a program that converts the Java bytecode into instructions that are sent directly to the processor when JVM comes across the method it calls the method directly instead of interpreting it that improves the performance of Java applications at run time.

31. What is a constructor in Java?

A constructor is a block of code that is used to initialize an object. It should have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

Different Type Of Constructor:

  • Default Constructor: default constructors are the no-argument constructors that will be created by default. Its main purpose is to initialize the instance variables with the default values.
  • Parameterized Constructor: The parameterized constructor in Java, is the constructor initializing the instance variables with the provided values. The constructors which take the arguments are called parameterized constructors.

32. Difference between HashMap and HashTable?

HashMap and Hashtable both classes implement java.util.Map interface.

HashMap HashTable
It is non-synchronized It is Synchronised
It allows one null key and any number of null values It doesn’t allow null values.
It has been a part of the collection framework since the beginning. It was added later.

33. What is the difference between a local variable and an instance variable?

In Java, a local variable is inside a method, constructor, or a block and has only local scope.

public void fun()
{
int a,b //local variable
}

Instance variables are declared inside the class whose scope is bound to the object of class.

Class test
{
int a,b //instance variable
}

34. What is the difference between this() and super() in Java?

 

this()

super()

this() points to current object super() points to the base class object.
Used to call the default constructor of the same class Used to call the default constructor of the parent class.
Access method of the same class Access method of the parent class.

35. What is constructor chaining?

When one constructor calls the other constructor with a current object is constructor chaining. It is achieved using this() and super() method.