Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Cracking FAANG companies interviews with a few months of preparation

Learn Advanced Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Java Interview Questions
Java Interview Questions for 2023

Java Programming Interview Questions

Understanding of java interview questions is very important for Java development roles. Mostly java Interview rounds in Investment banks like Barclays, Credit Suisse, Citibank, etc, still, many of them don’t have any idea of what kind of questions they can expect there. Object Oriented, JDBC, Collection Framework are the most important pillars that support the fundamental concepts of the Java programming language. If you are an aspiring Java Developer, it is very important for you to have a strong knowledge of these core concepts before you appear for an interview. In this article, We’ll share a couple of frequently asked questions from investment banks to Java developer that will definitely help you in clearing your interview with flying colors.

Go through all the questions to enhance your chances of performing well in the interviews. The questions will revolve around the basic and core fundamentals of Java.

So, let’s dive deep into the surplus of useful interview questions on Java.

Learn More

Java Interview Questions and Answers

What is Java?

Java is a high-level, object-oriented, reliable, secure, high-performance, multithreaded, and portable programming language. It is also platform-independent. In June 1991, James Gosling created it. Because it offers its own JRE and API, it can also be referred to as the platform. discussing the origins of the language, which was originally dubbed Oak after an oak tree that was located outside of Gosling's office. Later, the project was known as Green before being renamed Java after the Indonesian coffee variety Java

What is Java

List the features of Java Interview Questions.

The Java programming language has the following features.

Simple: Learning Java is simple. Because Java's grammar is based on C++, writing programmes in it is simpler.

Java's object-oriented paradigm enables us to maintain our code as a collection of various types of objects that include both data and behaviour.

Java supports the read-once, write-anywhere paradigm. On every machine, the Java programme can be run. Java programmes (.java) are transformed into executable bytecode (.class), which can be used on any machine.

Java Features

Platform Independent: The programming language Java is cross-platform. When compared to other programming languages like C and C++, it does not require a platform to run. Java comes with a platform that is used to run its programmes. Java can be run independently of an operating system.

Secure: Java's lack of explicit references makes it secure. Java is made more secure by the addition of the ByteCode and Exception handling concepts.

Strong memory management makes Java a robust programming language. It is more resilient because of ideas like automatic trash collection and exception handling, among others.

What does Java virtual machine mean to you?

The computer can run Java programmes thanks to the Java Virtual Machine. The main method contained in the Java code is called by JVM, which functions as a run-time engine. The computer system needs to implement the JVM specification. The Java code is converted by the JVM into a Bytecode that is similar to native code and independent of the target machine.

Java virtual amchine

What distinguishes JDK, JRE, and JVM from one another?

JVM
JVM, which stands for Java Virtual Machine, is an abstract machine that offers the runtime environment needed to execute Java bytecode. It is a specification that details how the Java Virtual Machine operates. Oracle and other businesses have given its implementation. JRE is the name of its implementation. For numerous hardware and software systems, JVMs are accessible (so JVM is platform dependent). When we run the Java class, a runtime instance is created. The JVM has three concepts: instance, implementation, and specification.

JRE
The Java Runtime Environment is known as JRE. It is how the JVM is implemented. A collection of software tools called the Java Runtime Environment is used to create Java programmes. To offer the runtime environment, it is employed. It is how the JVM is implemented. It really does exist. It has a collection of libraries and additional files that the JVM uses during runtime.

JDK
The term "Java Development Kit" is an abbreviation. It is a setting for creating software that is used to create Java applets and applications. It really does exist. JRE and development tools are included. JDK is an implementation of any of the Java Platforms listed below, all of which were made available by Oracle Corporation:

What is the platform?

The hardware or software environment in which a piece of software is run is known as a platform. Platforms come in two flavours: hardware- and software-based. The platform is software-based and uses Java.

What distinguishes the Java platform from other platforms in terms of its primary features?

The Java platform differs from other platforms in the ways listed below.
🚀 Java is a software-based platform, as opposed to other platforms that could be either hardware- or software-based.
🚀 While other platforms can only have the hardware components, Java runs on top of other hardware platforms.

How many different kinds of memory spaces does JVM allocate?

🚀 Class(Method) Area: The Class Area is used to hold structures specific to each class, including the runtime constant pool, fields, method data, and method code.

🚀 Heap: The runtime data region is where the objects' memory is allocated.

🚀 Java stack is used to store frames. It participates in method invocation and return and holds local variables and incomplete results. Each thread has a unique, concurrently constructed private JVM stack. Every time a method is called, a fresh frame is made. Once its method has been invoked, a frame is destroyed.

🚀 Program Counter Register: The address of the Java virtual machine instruction presently being executed is stored in the PC (programme counter) register.

🚀 Native Method Stack: It contains all the native methods used in the application.

Why Java consider a platform independent language?

Because the compiler compiles the code and then converts it to platform-independent byte code that can be run on various platforms, the Java language was created in a way that it is independent of all hardware and software. The installation of a runtime environment (JRE) on the machine is the only prerequisite for running that byte code.

Java platform independent

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

Instance variables All methods in the class can access variables known as instance variables. They are stated both inside the class and outside the methods. These variables, which are inextricably linked to an object, characterise its characteristics.
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.

class Person {
public String Name;
public int Age;
public String address;
}

Local variables Each class object will have a copy of the variables available for use. All other instances of the class continue to be untouched if any changes are made to these variables; just that instance will be affected.

public void Person() {
String Name;
int age;
String address;
}

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

code in bytes. Java programmes are translated into class files (Byte Code), which serve as a translation layer between source code and machine code, by the Java compiler. This bytecode can be run on any machine and is not platform-specific.

What are the various access specifiers in Java?

The terms used to specify the access scope of a method, class, or variable in Java are called access specifiers. The four access specifiers in Java are listed below.

🚀 Public Any class or method can access the classes, methods, or variables that are specified as public.

🚀 Protected may be accessible by classes belonging to the same package, by subclasses of this class, or by classes that are members of the same class.

🚀 Default can only be accessed inside the package. All classes, methods, and variables have default scopes by default.

🚀 Private Only other members of the class may access the private class, methods, or variables.

Java access specifiers

Why are static variables and methods used?

The static methods and variables are shared by all of the class's objects. The static is a class component, not an object. We don't need to build the object to access the static variables because they are kept in the class area. Therefore, static is utilised when it's necessary to specify variables or methods that apply to all class objects.

For instance, the name of the college is what all the students have in common in the class that simulates a group of college students. As a result, the term " college name" will be considered static.

What do you mean by object?

The Object is a living thing with a state and behaviour. In Java, an object is an instance of the class with instance variables serving as the object's state and methods serving as the object's activity. The new keyword can be used to construct a class object.

What do you mean by constructor?

The specific kind of method used to initialise an object's state is known as the constructor. When the class is created and the object's memory is allocated, it is called. When an object is created with the new keyword, the class's default constructor is used each time. The constructor's name must resemble the class name. There can be no explicit return type in the constructor.

What variety of constructors does Java support?

Java cnstructor

There are two sorts of constructors in Java, depending on the inputs supplied to them.

Default Constructor: The default Constructor is the one that does not take any arguments. Instance variables are typically initialised with default values using the default constructor. It can also be utilised to carry out various beneficial tasks related to object generation. If no constructor is defined in the class, the compiler implicitly calls the default constructor.

Parameterized Constructor: This constructor is able to initialise instance variables with specified values. In other words, we can say that parameterized constructors are constructors that can receive arguments.

Does constructor return any value?

 No, constructor does not return any value.

 • While declaring a constructor you will not have anything like return type.

 • In general, Constructor is implicitly called at the time of instantiation.

 • And it is not a method, its sole purpose is to initialize the instance variables.

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.

What do you understand by copy constructor in Java?

copy constructor

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

 • By constructor

 • By assigning the values of one object into another

 • By clone() method of Object class

What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behavior of an object.
A constructor must not have a return type.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
The Java compiler provides a default constructor if you don't have any constructor in a class.The method is not provided by the compiler in any case.


What is the static variable?

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Java static variable

What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

The static method can not use non-static data member or call the non-static method directly.

this and super cannot be used in static context as they are non-static.

What is the difference between static (class) method and instance method?

There are many differences between static and instance methods. They are given below.

static or class methodinstance method
A method that is declared as static is known as the static method.A method that is not declared as static is known as the instance method.
A constructor must not have a return type.We don't need to create the objects to call the static methods.The object is required to call the instance methods.
Non-static (instance) members cannot be accessed in the static context (static method, static block, and static nested class) directly.Static and non-static variables both can be accessed in instance methods.
For example: public static int cube(int n){ return n*n*n;}For example: public void msg(){...}.


Can we make constructors static?

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

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.

concept of constructor overloading

three constructors are defined here but they differ on the basis of parameter type and their numbers.

What is the static block?

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

class Foo{  
  static{System.out.println("static block is invoked");}  
  public static void main(String args[]){  
   System.out.println("Hello main");  
  }  
}  

Can we execute a program without main() method?

Yes, we can execute a java program without a main method by using a static block. Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block. Static initialization block is going directly into the stack memory. But it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main method.

class StaticInitializationBlock{
   static{
      System.out.println("class without a main method");
      System.exit(0);
   }
}

Explain 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 Calculate
{
  void sum (int a, int b)
  {
    System.out.println("sum is"+(a+b)) ;
  }
  void sum (float a, float b)
  {
    System.out.println("sum is"+(a+b));
  }
  Public static void main (String[] args)
  {
    Calculate  cal = new Calculate();
    cal.sum (8,5);      //sum(int a, int b) is method is called.
    cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
  }
}
Try it Yourself

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 Animal
{
    public void eat()
    {
        System.out.println("Eat all eatables");
    }
}

class Dog extends Animal
{
    public void eat()   //eat() method overridden by Dog class.
    {
        System.out.println("Dog like to eat meat");
    }
    
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
    }
}
Try it Yourself

Can 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:

class TryWithMultipleCatch {
   public static void main(String args[]) {
      try{
         int a[]=new int[5];
         a[3]=10/0;
         System.out.println("First print statement in try block");
      } catch(ArithmeticException e) {
         System.out.println("Warning: ArithmeticException");
      } catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Warning: ArrayIndexOutOfBoundsException");
      } catch(Exception e) {
         System.out.println("Warning: Some Other exception");
      }
      System.out.println("Out of try-catch block");
   }
}

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

Java final keyword is a non-access specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it.

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

Explain public static void main(String args[]) in Java.

Main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args).
public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class.
In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class.
void: It is the return type of the method. Void defines the method which will not return any value.
main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
String args[]: It is the parameter passed to the main method.

What are wrapper classes in Java?

Wrapper class

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.

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

ArrayListVector
Array List is not synchronized. Vector is synchronized.
If an element is inserted into the Array List, it increases its Array size by 50%.Vector 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.
Array List is fast as it’s non-synchronized.Vector is slow as it is thread safe.


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

In Java, super() and this(), both are special keywords that are used to call the constructor.

this()super()
this() represents the current instance of a class.super() represents the current instance of a parent/base class
Used to call the default constructor of the same classUsed to call the default constructor of the parent/base class
Used for pointing the current class instanceUsed for pointing the superclass instance


Why Java Strings are immutable in nature?

In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be modified. Whenever you try to update the value of that object instead of updating the values of that particular object, Java creates a new string object. Java String objects are immutable as String objects are generally cached in the String pool. Since String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security, caching, synchronization, and performance of the application.

What is singleton class in Java and how can we make a class singleton?

Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

Example: Java Singleton Class Syntax

class SingletonExample {

   // private field that refers to the object
   private static SingletonExample singleObject;
                                              
   private SingletonExample() {
      // constructor of the SingletonExample class
   }

   public static SingletonExample getInstance() {
      // write code that allows us to create only one object
      // access the object as per our need
   }
}

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.

What happens when the main() isn't declared as static?

When the main method is not declared as static, then the program may be compiled correctly but ends up with a severe ambiguity and throws a run time error that reads "NoSuchMethodError."

In Java, how do you decide whether to use a string literal or a string object?

To hard-code a string in Java, we have two options. A string literal and a string object. So, what's different about these two options? When you use a string literal, the string is interned. That means it's stored in the "string pool" or "string intern pool". In the string pool, each string is stored no more than once. So if you have two separate variables holding the same string literals in a Java program. Those two Strings don't just contain the same objects in the same order, they are in fact both pointers to the same single canonical string in the string pool. This means they will pass an '==' check. If our Strings were instantiated as objects, however, they would not be "interned," so they would remain separate objects (stored outside of the string pool).

Can we override private methods in Java?

No, we cannot override private or static methods in Java. Private methods in Java are not visible to any other class which limits their scope to the class in which they are declared. The program gives a compile time error showing that display() has private access in Parent class and hence cannot be overridden in the subclass. If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.

What is the difference between StringBuffer and String?

String is an Immutable class, i.e. you can not modify its content once created. While StringBuffer is a mutable class, means you can change its content later. Whenever we alter content of String object, it creates a new string and refer to that, it does not modify the existing one. This is the reason that the performance with StringBuffer is better than with String.

What is OOPS (Object Oriented Programming) and what are the four pillars of oops?

Object-oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.

four pillars of Object Oriented Programming

What is Inheritance?

Inheritance means one class can extend to another class. So that the codes can be reused from one class to another class. The existing class is known as the Super class whereas the derived class is known as a sub class.

Inheritance
Super class:
public class Manupulation(){
}
Sub class:
public class Addition extends Manipulation(){
}

Inheritance is only applicable to the public and protected members only. Private members can’t be inherited.

What do you mean by data encapsulation?

Data encapsulation is a concept of binding data and code in single unit called object and hiding all the implementation details of a class from the user. It prevents unauthorized access of data and restricts the user to use the necessary data only. Data encapsulation refers to sending data where the data is augmented with successive layers of control information before transmission across a network. The reverse of data encapsulation is de-capsulation, which refers to the successive layers of data being removed (essentially unwrapped) at the receiving end of a network.

What do you mean by data encapsulation

What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
What is Polymorphism
There are two types of polymorphism:
Compile time polymorphism
Run time polymorphism
Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.

What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog {

   public static void main(String args[]) {
   
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Dog(); // Animal reference but Dog object

      a.move(); // runs the method in Animal class
      b.move(); // runs the method in Dog class
   }
}
Try it Yourself

What do you mean by an interface in Java?

An interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Thus, interface basically is a group of related methods with empty bodies. Example:

public interface Animal {
      public void eat();
      public void sleep();
      public void run();
}

What are the different types of inheritance in Java?

Java supports four types of inheritance which are:
Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as well as one child class.
Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.
Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.

What is multiple inheritance? Is it supported by Java?

If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes. The problem with multiple inheritance is that if multiple parent classes have the same method name, then at runtime it becomes difficult for the compiler to decide which method to execute from the child class.
Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as Diamond Problem.

What is an association?

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to many, many to one and many to many.

What do you mean by aggregation?

An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not destroy.

What is the difference between abstract classes and interfaces?

Abstract ClassInterfaces
An abstract class can provide complete, default code and/or just the details that have to be overriddenAn interface cannot provide any code at all, just the signature
In the case of an abstract class, a class may extend only one abstract classA Class may implement several interfaces
An abstract class can have non-abstract methodsAll methods of an Interface are abstract
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properlyIf we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method
An abstract class can contain constructorsAn Interface cannot contain constructors
Abstract classes are fastInterfaces are slow as it requires extra indirection to find the corresponding method in the actual class


Why we can’t create the object of abstract class in java?

Because an abstract class is an incomplete class (incomplete in the sense it contains abstract methods without body and output) we cannot create an instance or object; the same way we say for an interface.

If a child class inherits base class then are the constructor of the base class also inherited by the child class?

Constructors are not properties of a class. Hence they cannot be inherited. If one can inherit constructors then it would also mean that a child class can be created with the constructor of a parent class which can later cause referencing error when the child class is instantiated. Hence in order to avoid such complications, constructors cannot be inherited. The child class can invoke the parent class constructor by using the super keyword.

What happens if we make the constructor final?

If we make the constructors final then the class variables initialized inside the constructor will become unusable. Their state cannot be changed.

Are there any limitations of Inheritance?

Inheritance in Java is a powerful concept to enable reusability. However, it too comes with a few limitations:

 • Firstly, there is an increase in program execution time due to constant to and fro between parent and child classes.

 • Next, Inheritance leads to tight coupling between the superclass and the subclass.

 • Thirdly, in case of modifications in the program, the developer needs to make changes in both the superclass and the subclass.

 • Lastly, it requires careful implementation otherwise, the program would yield incorrect functionality.

What is a superclass?

A superclass or base class is a class that acts as a parent to some other class or classes. For example, the Vehicle class is a superclass of class Car.

What is a subclass?

A class that inherits from another class is called the subclass. For example, the class Car is a subclass or a derived of Vehicle class.

What is enum in java

Enumerations serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.

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.

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.


What are the differences between HashMap and HashTable in Java?


HashMapHashTable
HashMap is not synchronized thereby making it better for non-threaded applications.HashTable is synchronized and hence it is suitable for threaded applications.
Allows only one null key but any number of null in the values.This does not allow null in both keys or values.
Supports order of insertion by making use of its subclass LinkedHashMap.Order of insertion is not guaranteed in HashTable.


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.

Example:

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

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.

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

What is operator overloading?

Operator overloading refers to implementing operators using user-defined types based on the arguments passed along with it.

Differentiate between data abstraction and encapsulation.

Data abstractionEncapsulation
Solves the problem at the design levelSolves the problem at the implementation level
Allows showing important aspects while hiding implementation detailsBinds code and data together into a single unit and hides it from the world


What are virtual functions?

A virtual function or virtual method in an OOP language is a function or method used to override the behavior of the function in an inherited class with the same signature to achieve the polymorphism.

The virtual keyword is not used in Java to define the virtual function; instead, the virtual functions and methods are achieved using the following techniques:

 • We can override the virtual function with the inheriting class function using the same function name. Generally, the virtual function is
 defined in the parent class and override it in the inherited class.

 • A virtual function should have the same name and parameters in the base and derived class.

 • For the virtual function, an IS-A relationship is necessary, which is used to define the class hierarchy in inheritance.

 • The Virtual function cannot be private, as the private functions cannot be overridden.

 • The virtual functions can be used to achieve oops concepts like runtime polymorphism.

In a nutshell, the methods or functions that can be used to achieve the polymorphism are the virtual functions or methods in Java.

What is Garbage Collection(GC)

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

What is a friend function?

A function prototype preceded with the keyword “friend” and defined outside the class's scope allows it to access all private and protected members of the class. Even though the prototype for friend function appears in the class definition, friends are not member functions. Coming to the second half of the question, JAVA doesn't support “friend” keyword but the concept of friend function can be implemented in JAVA by choosing appropriate access specifiers for the class and it's members.

What is an exception?

An exception is a kind of notification that interrupts the normal execution of a program. Exceptions provide a pattern to the error and transfer the error to the exception handler to resolve it. The state of the program is saved as soon as an exception is raised.

What is exception handling?

Exception handling in Object-Oriented Programming is a very important concept that is used to manage errors. An exception handler allows errors to be thrown and caught and implements a centralized mechanism to resolve them.

What is the difference between an error and an exception?


Data abstractionEncapsulation
Errors are usually raised by the environment in which the application is running. For example, an error will occur due to a lack of system resources.Exceptions are caused by the code of the application itself.
Errors occur at run-time and are not known by the compiler; hence, they are classified as “unchecked.”Exceptions can be “checked” or “unchecked,” meaning they may or may not be caught by the compiler.
It is not possible to recover from an error.The use of try-catch blocks can handle exceptions and recover the application from them.


What is a try/catch block?


A try/catch block is used to handle exceptions. The try block defines a set of statements that may lead to an error. The catch block basically catches the exception.

What is a finally block?


A finally block consists of code that is used to execute important code such as closing a connection, etc. This block executes when the try block exits. It also makes sure that finally block executes even in case some unexpected exception is encountered.

What is the difference between throw, throws and throwable in Java?


Throw: The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

throw Instance
 
//Example:
 
throw new ArithmeticException("/ by zero");

throws: throws is also a keyword in java which is used in the method signature to indicate that this method may throw mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using try-catch blocks or using throws keyword. Below is the syntax for using throws keyword.

class ThrowsExample
{
    void methodOne() throws SQLException
    {
        //This method may throw SQLException
    }
 
    void methodTwo() throws IOException
    {
        //This method may throw IOException
    }
 
    void methodThree() throws ClassNotFoundException
    {
        //This method may throw ClassNotFoundException
    }
}

Throwable: Throwable is a super class for all types of errors and exceptions in java. This class is a member of java.lang package. Only instances of this class or it’s sub classes are thrown by the java virtual machine or by the throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want to create your own customized exceptions, then your class must extend this class.

class MyException extends Throwable
{
           //Customized Exception class
}
 
class ThrowAndThrowsExample
{
    void method() throws MyException
    {
        MyException e = new MyException();
 
        throw e;
    }
}

What are the types of Exception in Java


Exceptions can be categorized into two ways:

Built-in Exceptions

Checked Exception

Unchecked Exception

User-Defined Exceptions

Checked Exceptions

These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword.

Unchecked Exceptions

These are the exceptions that are not checked at compile time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Can we override a super class method which is throwing an unchecked exception with checked exception in the sub class?


No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub class with same exception or any other unchecked exceptions but can not be overridden with checked exceptions.

Can we keep the statements after finally block If the control is returning from the finally block itself?


No, it gives unreachable code error. Because, control is returning from the finally block itself. Compiler will not see the statements after it. That’s why it shows unreachable code error.

Why an exception occurs in the program?


There can be many reasons that might generate an exception in a Java program.

1. Opening a non-existing file in your program.

2. Reading a file from a disk but the file does exist there.

3. Writing data to a disk but the disk is full or unformatted.

4. When the program asks for user input and the user enters invalid data.

5. When a user attempts to divide an integer value by zero, an exception occurs.

When a data stream is in an invalid format, etc

What do you mean by Multithreading? Why is it important?


Multithreading means multiple threads and is considered one of the most important features of Java. As the name suggests, it is the ability of a CPU to execute multiple threads independently at the same time but sharing the process resources simultaneously. Its main purpose is to provide simultaneous execution of multiple threads to utilize the CPU time as much as possible. It is a Java feature where one can subdivide the specific program into two or more threads to make the execution of the program fast and easy.

What do you mean by Multithreading

What is a thread?


A Thread is a concurrent unit of execution. We can say that it is part of the process which can easily run concurrently with other parts of the process.

What is the difference between Thread and Process?


Following are the differences between thread and process:

A process can have many threads. Threads can execute any part of process.And same part of Process can be executed by multiple threads.

Processes have their own address while Thread share the address space of the process that created it.

Thread has its own stack while in process all threads share a common system resource like heap memory.

differences between thread and process

What are the ways to implement Thread in java?


There are two ways to implement Thread in java.

1. By implementing Runnable interface in java and then creating Thread object from it.

2. By extending the Thread class.

Difference between Thread and Runnable in Java


There are two ways to create a new thread of execution. One is to declare a class to be a subclass of the Thread class. This subclass should override the run method of the Thread class. An instance of the subclass can then be allocated and started.

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

Example of Runnable

class RunnableExample implements Runnable{
   public void run(){
      System.out.println("Thread is running for Runnable Implementation");
   }
   public static void main(String args[]){
      RunnableExample runnable=new RunnableExample();
      Thread t1 =new Thread(runnable);
      t1.start();
   }
}

Example of Thread

class ThreadExample extends Thread{
   public void run(){
      System.out.println("Thread is running");
   }
   public static void main(String args[]){
      ThreadExample t1=new ThreadExample ();
      t1.start();
   }
}

What are the thread states?


Following are the different thread states:

New: A thread which is just instantiated is in the new state. When a start() method is invoked, the thread becomes the ready state. Then it is moved to the runnable state by the thread scheduler.

Runnable: A thread which is ready to run

Running: A thread which is executing is in running state.

Blocked: A blocked thread is waiting for a monitor lock is in this state. This thing can also happen when a thread performs an I/O operation and moves to the next state.

Waiting: It is a thread that is waiting for another thread to do the specific action.

Timed_waiting: It is a thread that is waiting for another thread to perform.

Terminated: A thread that has exited is in this state.

Thread life cycle in java

What is the difference between sleep and wait method in java?


Wait()Sleep()
The Wait() method is related to the Object class.The Sleep () method is related to the Thread class.
It is not a static method.It is a static method.
At the time of the Synchronization, the Wait() method releases obj.At the time of the Synchronization, the Sleep() method doesn't release the obj, i.e., lock.

What is Daemon thread and how to create a Daemon thread in java?

Daemon thread in Java is a low-priority thread that runs in the background to perform tasks such as garbage collection. Daemon thread in Java is also a service provider thread that provides services to the user thread. Its life depends on the mercy of user threads i.e. when all the user threads die, JVM terminates this thread automatically.

By setting the setDaemon(true) , we can create a daemon thread in java.

What is synchronization?

Synchronization is the capability to control the access of multiple threads to any shared resource.

The main advantage of synchronization is:

a. to avoid consistency problem

b. to avoid thread interference

Which is more preferred - synchronization block or synchronization method?

Synchronized block is the more preferred way because it doesn't lock the object while synchronized methods lock the object. Synchronized method will stop multiple synchronized blocks in the class, even though they are not related, from the execution and put them in the wait state to get the lock on the object.

What is deadlock?

Deadlock is a situation where two threads are waiting for each other to release locks holded by them on resources.For example

Thread 1 : locks resource A, waits for resource B

Thread 2 : locks resource B, waits for resource A

What is deadlock

What is context-switching in multi-threading?

It is the process of storing and restoring of CPU state. This helps to resume thread execution from the same point at a later point in time. It is one of the essential features for multitasking operating system and support for the multi-threaded environment.

What is thread starvation?

Thread starvation is basically a situation or condition where a thread won’t be able to have regular access to shared resources and therefore is unable to proceed or make progress. This is because other threads have high priority and occupy the resources for too long. This usually happens with low-priority threads that do not get CPU for its execution to carry on.

What is thread starvation

What is thread priority

Thread priority simply means that threads with the highest priority will get a chance for execution prior to low-priority threads. One can specify the priority but it's not necessary that the highest priority thread will get executed before the lower-priority thread. Thread scheduler assigns processor to thread on the basis of thread priority. The range of priority changes between 1-10 from lowest priority to highest priority.

What is thread priority

What is race condition in java and how we can solve it?

Race condition in Java is a type of concurrency bug or issue that is introduced in your program because of parallel execution of your program by multiple threads at the same time, Since Java is a multi-threaded programming language hence the risk of Race condition is higher in Java which demands a clear understanding of what causes a race condition and how to avoid that. Anyway, Race conditions are just one of the hazards or risks presented by the use of multi-threading in Java just like deadlock in Java. Race conditions occur when two threads operate on the same object without proper synchronization and their operation interleaves on each other.

In order to fix this race condition in Java, you need to wrap this code inside the synchronized block which makes them atomic together because no thread can go inside the synchronized block if one thread is already there.

Is it possible to call the run() method directly to start a new thread?

No, it's not possible at all. You need to call the start method to create a new thread otherwise run method won't create a new thread. Instead, it will execute in the current thread.

What is the lock interface? Why is it better to use a lock interface rather than a synchronized block?

Lock interface was introduced in Java 1.5 and is generally used as a synchronization mechanism to provide important operations for blocking.

Advantages of using Lock interface over Synchronization block:

Methods of Lock interface i.e., Lock() and Unlock() can be called in different methods. It is the main advantage of a lock interface over a synchronized block because the synchronized block is fully contained in a single method.

Lock interface is more flexible and makes sure that the longest waiting thread gets a fair chance for execution, unlike the synchronization block.

What is Semaphore? Why do we use them?

A Semaphore is an integer variable shared among multiple processes. The main aim of using a semaphore is process synchronization and accesss control for a common resource in a concurrent environment. The intial value of a semaphore depends on the problem at hand but mostly, we use the number of resources available as the intial value. As resources start getting occupied we decrement the value of this variable.

There are two types of semaphore:

Binary Semaphore: It can have only two integer values: 0 & 1. It's simpler to implement and provides mutual exclusion. We can use a binary semaphore to solve the critical section problem.

Counting Semaphore: It is again an integer value which can range over an unrestricted domain. We can use it to resolve synchronization problems like resource allocation.

Why wait and notify method are called from synchronized block?

Wait() is called, so that thread can wait on some condition. When condition is met, then thread has to give up the lock. To give up the lock, thread has to own it first. Thread can acquire lock by enter into synchronized context.

If wait method is called outside of synchronized context, then it will throw IllegalMonitorStateException.

What’s the difference between class lock and object lock?

Class Lock: In java, each and every class has a unique lock usually referred to as a class level lock. These locks are achieved using the keyword ‘static synchronized’ and can be used to make static data thread-safe. It is generally used when one wants to prevent multiple threads from entering a synchronized block.

Example:

public class ClassLevelLockExample {
   public void classLevelLockMethod() {
      synchronized (ClassLevelLockExample.class) {
         //DO your stuff here
      }
   }
}

Object Lock: In java, each and every object has a unique lock usually referred to as an object-level lock. These locks are achieved using the keyword ‘synchronized’ and can be used to protect non-static data. It is generally used when one wants to synchronize a non-static method or block so that only the thread will be able to execute the code block on a given instance of the class.

public class ObjectLevelLockExample {
   public void objectLevelLockMethod() {
      synchronized (this) {
         //DO your stuff here
      }
   }
}

What is ThreadPool?

ThreadPool is a pool of threads that reuses a fixed number of threads to execute the specific task.

What is BlockingQueue?

BlockingQueue basically represents a queue that is thread-safe. Producer thread inserts resource/element into the queue using put() method unless it gets full and consumer thread takes resources from the queue using take() method until it gets empty. But if a thread tries to dequeue from an empty queue, then a particular thread will be blocked until some other thread inserts an item into the queue, or if a thread tries to insert an item into a queue that is already full, then a particular thread will be blocked until some threads take away an item from the queue.

What is BlockingQueue

What do you mean by inter-thread communication?

Inter-thread communication, as the name suggests, is a process or mechanism using which multiple threads can communicate with each other. It is especially used to avoid thread polling in java and can be obtained using wait(), notify(), and notifyAll() methods.

What is Thread Scheduler and Time Slicing?

Thread Scheduler: It is a component of JVM that is used to decide which thread will execute next if multiple threads are waiting to get the chance of execution. By looking at the priority assigned to each thread that is READY, the thread scheduler selects the next run to execute. To schedule the threads, it mainly uses two mechanisms: Preemptive Scheduling and Time slicing scheduling.

Time Slicing: It is especially used to divide CPU time and allocate them to active threads. In this, each thread will get a predefined slice of time to execute. When the time expires, a particular thread has to wait till other threads get their chances to use their time in a round-robin fashion. Every running thread will get executed for a fixed time period.

What will happen if we don’t override the thread class run() method?

Nothing will happen as such if we don’t override the run() method. The compiler will not show any error. It will execute the run() method of thread class and we will just don’t get any output because the run() method is with an empty implementation.

class MyThread extends Thread { 
  //don't override run() method 
} 
public class DontOverrideRun { 
  public static void main(String[] args) { 
         System.out.println("Started Main."); 
         MyThread thread1=new MyThread(); 
      thread1.start(); 
         System.out.println("Ended Main."); 
  } 
} 

Output: Started Main. 
        Ended Main.
Try it Yourself

🚀Conclusion

We have now reached the end of this page. With the knowledge from this page, you should be able to create your own programmes with some research, and it's in fact recommended to hone your programming skills with small projects. There is no way to cover all the information you need to be a successful programmer in one course. In fact, programming is a constant learning process, regardless of whether you are a seasoned professional developer or a newbie.

TEST YOUR KNOWLEDGE!


1. Which component is used to compile, debug and execute the java programs?




2. Which one of the following is not a Java feature?




3. Which environment variable is used to set the java path?




4. What will be the output of the following Java program?
class variable_scope 
        {
            public static void main(String args[]) 
            {
                int x;
                x = 5;
                {
    	        int y = 6;
    	        System.out.print(x + " " + y);
                }
                System.out.println(x + " " + y);
            } 
        }
    




5. Which of the following is not a segment of memory in java?




6. What will be the output of the following Java program?

   class box 
            {
                int width;
                int height;
                int length;
            } 
            class mainclass 
            {
                public static void main(String args[]) 
                {        
                     box obj = new box();
                     obj.width = 10;
                     obj.height = 2;
                     obj.length = 10;
                     int y = obj.width * obj.height * obj.length; 
                     System.out.print(y);
                } 
            }
        



7. Which of these class is a superclass of every class in Java?




8. Which of these keywords can be used to prevent Method overriding in Java?




9. Which of these packages contains the exception Stack Overflow in Java?




10. Java extension used in threads




11. A thread become non runnable when





12. A method used to force one thread to wait for another thread to finish







HAVE A QUESTION? GIVE US A CALL OR CONTACT US - WE'D LOVE TO HEAR FROM YOU

PHONE: +91 80889-75867

WhatsApp : Click Here...