Top 50 Java Interview Questions & Answers

These questions are very important as its frequently asked in interviews. so if you are willing to know then be in this blog as I am going to express all the questions and answers. Let’s begin-

  1. What is Java?
What is Java Programming Language? - JournalDev
java programming

Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.

2. Why is Java a platform independent language?

Java language was developed in such a way that it does not depend on any hardware or software due to the fact that the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

3. Why is Java not a pure object oriented language?

Java supports primitive data types – byte, boolean, char, short, int, float, long, and double and hence it is not a pure object-oriented language.

4. Pointers are used in C/ C++. Why does Java not make use of pointers?

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

5. What do you understand by an instance variable and a local variable?

Local and Instance Variables, Part 2 - Intro to Java Programming - YouTube
local and instance variable

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Example:

____________________________________

class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
____________________________

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

Example:

______________________________
public void athlete() {
String athleteName;
double athleteSpeed;
int athleteAge;
}
______________________________

6. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviors in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

7. Tell us something about JIT compiler?

  • JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
  • The compiler is nothing but a translator of source code to machine-executable code. But what is special about the JIT compiler? Let us see how it works:
  • First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
  • Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
  • JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
  • Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

8. Can you tell the difference between equals() method and equality operator (==) in Java?

equals()==
This is a method defined in the Object class.It is a binary operator in Java.
This method is used for checking the equality of contents between two objects as per the specified business logic.This operator is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.

Note:

In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

9. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:

________________________________

for (;;)
{
   // Business logic
   // Any break logic
}
_________________________

Using while loop:

_____________________________

while(true){
   // Business logic
   // Any break logic
}
_______________________

Using do-while loop:

_____________________________

do{
   // Business logic
   // Any break logic
}while(true);a

_______________________

10. Briefly explain the concept of constructor overloading?

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.ax

_______________________________________________________

class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses) {
 variable1 = doctors;
 variable2 = nurses;
}
public Hospital(int doctors) {
 variable1 = doctors;
}
public Hospital(double salaries) {
 variable3 = salaries
}
}
____________________________________________

11. Comment on method overloading and overriding by citing relevant examples?


In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

_____________________________________________________

class OverloadingHelp {
   public int findarea (int l, int b) {
           int var1;
           var1 = l * b;
           return var1;
   }
   public int findarea (int l, int b, int h) {
           int var2;
           var2 = l * b * h;
           return var2;
   }
}
___________________________________________

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding.
Let’s give a look at this example:

________________________________________________________________

class HumanBeing {
       public int walk (int distance, int time) {
               int speed = distance / time;
               return speed;
       }
}
class Athlete extends HumanBeing {
       public int walk(int distance, int time) {
               int speed = distance / time;
               speed = speed * 2;
               return speed;
       }
}
__________________________________________________

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

12. A single try block and multiple catch blocks can co-exist in a Java Program. Explain?
Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

_______________________________________________________

public class MultipleCatch {
public static void main(String args[]) {
 try {
  int n = 1000, x = 0;
  int arr[] = new int[n];
  for (int i = 0; i <= n; i++) {
   arr[i] = i / x;
  }
 }
 catch (ArrayIndexOutOfBoundsException exception) {
  System.out.println("1st block = ArrayIndexOutOfBoundsException");
 }
 catch (ArithmeticException exception) {
  System.out.println("2nd block = ArithmeticException");
 }
 catch (Exception exception) {
  System.out.println("3rd block = Exception");
 }
}
}
________________________________________________

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

13. Explain the use of final keyword in variable, method and class?


In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

final variable:
When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
final method:
A method declared as final cannot be overridden by its children’s classes.
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn’t make sense. Java throws compilation error saying – modifier final not allowed here
final class:
No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

14. Do final, finally and finalize keywords have the same function?
All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

______________________

final int a=100;
a = 0;  // error
__________________

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

____________________________________________________________

try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
________________________________________________

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

_______________________________________________________

public static void main(String[] args) {
String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}
_____________________________________________

15. When can you use super keyword?

The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.

Following are the cases when this keyword can be used:

  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.

The following example demonstrates all 3 cases when a super keyword is used.

_________________________________________________

public class Parent{
       protected int num = 1;
       
       Parent(){
           System.out.println("Parent class default constructor.");
       }
       
       Parent(String x){
           System.out.println("Parent class parameterised constructor.");
       }
       
       public void foo(){
           System.out.println("Parent class foo!");
       }
   }
   
   public class Child extends Parent{
       private int num = 2;
       
       Child(){
           System.out.println("Child class default Constructor");
           
           super();    // to call default parent constructor
           super("Call Parent");    // to call parameterised constructor.
       }
       
       void printNum(){
           System.out.println(num);
           System.out.println(super.num); //prints the value of num of parent class
       }
       
       @Override
       public void foo(){
           System.out.println("Parent class foo!");
           super.foo();    //Calls foo method of Parent class inside the Overriden foo method of Child class.
       }
   }
______________________________________________

16. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters

17. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

18. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

19. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.
  • Multithreading: The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections: In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

20. How would you differentiate between a String, StringBuffer, and a StringBuilder?

Difference Between String , StringBuilder and StringBuffer Classes with  Example : Java | Programming Pearls
Difference between string, string buffer and string builder
  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads.

Syntax:

__________________________________________________________

// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");
______________________________________________

21. Using relevant properties highlight the differences between interfaces and abstract classes?

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

_____________________________________

public abstract class Athlete {
public abstract void walk();
}
_____________________________

Interface example:

______________________________________

public interface Walkable {
void walk();
}
_____________________________

22. In Java, static as well as private method overriding is possible. Comment on the statement?

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

23. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

24. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

25. What is the importance of reflection in Java?

The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn’t allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.

______________________________________________________________________________

Method methodOfFoo = fooObject.getClass().getMethod("fooBar", null);
methodOfFoo.invoke(fooObject, null);
___________________________________________________________

Using reflection has its own cons:

  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.

Hence, it is advisable to follow solutions that don’t involve reflection and use this method as a last resort.

26. What are the different ways of threads usage?

We can define and implement a thread in java using two ways:
Extending the Thread class

________________________________________________________________

class InterviewBitThreadExample extends Thread{  
   public void run(){  
       System.out.println("Thread runs...");  
   }  
   public static void main(String args[]){  
       InterviewBitThreadExample ib = new InterviewBitThreadExample();  
       ib.start();  
   }  
}
_________________________________________________

Implementing the Runnable interface

______________________________________________________________________

class InterviewBitThreadExample implements Runnable{  
   public void run(){  
       System.out.println("Thread runs...");  
   }  
   public static void main(String args[]){  
       Thread ib = new Thread(new InterviewBitThreadExample()); 
       ib.start();  
   }  
}
______________________________________________________
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

27. What are the differences between constructor and method of a class in Java?

ConstructorMethod
Constructor is used for initializing the object state.Method is used for exposing the object’s behavior.
Constructor has no return typeMethod should have a return type. Even if it does not return anything, return type is void.
Constructor gets invoked implicitlyMethod has to be invoked on the object explicitly.
If the constructor is not defined, then a default constructor is provided by the java compiler.If a method is not defined, then the compiler does not provide it
The constructor name should be equal to the class nameThe name of the method can have any name or have a class name too
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn’t make sense. Java throws compilation error saying – modifier final not allowed hereA method can be defined as final but it cannot be overridden in its subclasses.
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects.A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method

28. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.
For example:

_________________________________________________________________________

class InterviewBitTest{
   int num;
   InterviewBitTest(int x){ 
       num = x; 
   }
   InterviewBitTest(){ 
       num = 0; 
   }
}
class Driver {
   public static void main(String[] args)
   {
       //create a reference
       InterviewBitTest ibTestObj = new InterviewBitTest(20);
       //Pass the reference to updateObject Method
       updateObject(ibTestObj);
       //After the updateObject is executed, check for the value of num in the object.
       System.out.println(ibTestObj.num);
   }
   public static void updateObject(InterviewBitTest ibObj)
   {
       // Point the object to new reference
       ibObj = new InterviewBitTest();
       // Update the value 
       ibObj.num = 50;
   }
}
Output:
_____________________________________________________________________

Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.
For example:

________________________________________________________

class InterviewBitTest{
   int num;
   InterviewBitTest(int x){ 
       num = x; 
   }
   InterviewBitTest(){ 
       num = 0; 
   }
}
class Driver{
   public static void main(String[] args)
   {
       //create a reference
       InterviewBitTest ibTestObj = new InterviewBitTest(20);
       //Pass the reference to updateObject Method
       updateObject(ibTestObj);
       //After the updateObject is executed, check for the value of num in the object.
       System.out.println(ibTestObj.num);
   }
   public static void updateObject(InterviewBitTest ibObj)
   {
       // no changes are made to point the ibObj to new location
       // Update the value of num
       ibObj.num = 50;
   }
}
Output:
___________________________________________________

29. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

30. What happens if the static modifier is not included in the main method signature in Java?

There wouldn’t be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

31. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:

________________________________________________________________

protected Object clone() throws CloneNotSupportedException{
 return (Object)super.clone();
}
_________________________________________________
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

32. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed.

Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

33. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. – A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

34. List the features of Java Programming language?

features of java

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn’t depend upon the operating system to be executed.
  • Secured: Java is secured because it doesn’t use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn’t exist in Java.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is “close” to native code. It is still a little bit slower than a compiled language (e.g., C++).
  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn’t occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

35. What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

36. What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

37. xWhat gives Java its ‘write once and run anywhere’ nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

38. What are the various access specifiers in Java?

What are Access Modifiers in Java? - Use My Notes
various access specifiers in java

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.

39. What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

40. What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object’s data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

41. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain?

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example – to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.
  • Let’s take an example:

___________________________________

package comparison;
public class Top {
public int start() {
  return 0;
}
}
class Bottom extends Top {
 public int stop() {
  return 0;
 }
}
_______________________________

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this

______________________________________

public class Top {
 public int start() {
  return 0;
 }
 public void stop() {
 }
}
______________________________

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

_______________________________

class Bottom {
 Top par = new Top();
 public int stop() {
  par.start();
  par.stop();
  return 0;
 }
} 
_________________________

42. How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

___________________________________________

43. How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

44. Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

_______________________________________________

public class Tester {
 
   private String message;
 
   public Tester(){
      message = "Hello World!";
   }
   public Tester(String message){
      this.message = message;
   }
 
   public String getMessage(){
      return message ;
   }
_____________________________________

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

45. What is the difference between Array list and vector in Java?

Array ListVector
Array List is not synchronized.Vector is synchronized
Array List is fast as it’s non-synchronized.Vector is slow as it is thread safe.
If an element is inserted into the Array List, it increases its Array size by 50%.Vector defaults to doubling size of its array
Vector defaults to doubling size of its arrayVector defaults to doubling size of its array
Array List can only use Iterator for traversing an Array List.Vector can use both Enumeration and Iterator for traversing.

46. What are the differences between HashMap and HashTable in Java?

HashmapHashtable
It is non synchronized. It cannot be shared between many threads without proper synchronization code.It is synchronized. It is thread-safe and can be shared with many threads.
It permits one null key and multiple null values.It does not permit any null key or value.
is a new class introduced in JDK 1.2.It was present in earlier versions of java as well.
It was present in earlier versions of java as wellIt is slower.
It uses fail fast iterator.It uses an enumerator which is not fail fast.
It inherits AbstractMap class.It inherits Dictionary class

47. How to not allow serialization of attributes of a class in Java?

The NonSerialized attribute can be used to prevent member variables from being serialized.
You should also make an object that potentially contains security-sensitive data nonserializable if possible. Apply the NonSerialized attribute to certain fields that store sensitive data if the object must be serialized. If you don’t exclude these fields from serialisation, the data they store will be visible to any programmes with serialization permission.

48. Can you call a constructor of a class inside another constructor?

Yes, we can call a constructor of a class inside another constructor. This is also called as constructor chaining. Constructor chaining can be done in 2 ways-

  • Within the same class: For constructors in the same class, the this() keyword can be used.
  • From the base class: The super() keyword is used to call the constructor from the base class. The constructor chaining follows the process of inheritance. The constructor of the sub class first calls the constructor of the super class. Due to this, the creation of sub class’s object starts with the initialization of the data members of the super class. The constructor chaining works similarly with any number of classes. Every constructor keeps calling the chain till the top of the chain.

49. Explain the term “Double Brace Initialization” in Java?

Double Brace Initialization is a Java term that refers to the combination of two independent processes. There are two braces used in this. The first brace creates an anonymous inner class. The second brace is an initialization block. When these both are used together, it is known as Double Brace Initialization. The inner class has a reference to the enclosing outer class, generally using the ‘this’ pointer. It is used to do both creation and initialization in a single statement. It is generally used to initialize collections. It reduces the code and also makes it more readable.

50. What is a package in Java? List down various advantages of packages?

Packages in Java, are the collection of related classes and interfaces which are bundled together. By using packages, developers can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and reused. Below I have listed down a few of its advantages:

  • Packages help in avoiding name clashes
  • They provide easier access control on the code
  • Packages can also contain hidden classes which are not visible to the outer classes and only used within the package
  • Creates a proper hierarchical structure which makes it easier to locate the related classes.
Rajesh Kumar
Follow me
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x