JAVA INTERVIEW QUESTIONS

Java

CORE JAVA INTERVIEW QUESTIONS

95% guaranteed Interview Questions

The collection of JAVA interview questions and their respective answers is provided below. We assure you that these are the most frequent queries.

All of the responses to the questions are precise and to the point.

Basic Java Interview Questions

1. What Exactly is JAVA ?

The most well-known high-level object-oriented programming language is Java, which has a variety of distinctive qualities including robustness, simplicity, security, and portability. James Gosling created Java in 1991 at Sun MicroSystems. Java was formerly known as OAK before being renamed JAVA in 1995.

 

2. What is the background of Java?

James Gosling and the "Green Team" of researchers at Sun MicroSystems initially developed Java in an effort to develop a new language that would enable interoperability across consumer electronics. 

In 1991, they began working on the language. It was initially created for tiny embedded systems found in electronic devices like set-top boxes. The file's name was "Greentalk" by James Gosling, and its extension was.gt. Following that, it was given the name Oak and was created as a component of the Green project.

 

3. What standout characteristics distinguish the Java programming language?

1.Simple:

Java was created to be simple to understand and utilise efficiently for skilled programmers. If you have some prior programming knowledge, learning Java won't be difficult.

2.Secure

The manner that Java is built ensures that user data is secure at every stage of execution.

3.Portable

The term "portability" describes a program's capacity to run on many devices. A given program may require varying amounts of work to execute on various machines, whereas Java programs can run in any environment without requiring source code changes.

"Write once, run anywhere" is another name for it."

4.Object-oriented

Because Java adheres to the object-oriented paradigm, we may maintain our code as a collection of various objects that includes both data and behaviour. 

Java's object model is highly straightforward and flexible, and basic types like integers are maintained as high-performance non-objects.

5.Robust

A computer system's robustness is its capacity to deal with input errors as well as execution faults. Numerous aspects of computer science can be considered robust, including robust machine learning, robust security networks, and robust programming. 

Java uses strong memory management, making it a powerful programming language. It is more resilient because of ideas like automatic trash collection and exception handling, among others.

6.Multithreaded

In Java, multithreading refers to the process of running two or more threads at the same time to maximise CPU usage. In Java, a thread is a lightweight process that uses fewer resources to produce and share process resources.

7.Architecture-neutral

The Java system uses a "binary code format" that is independent of hardware architectures, operating system interfaces, and window systems to address the binary distribution issue. This system-independent binary code has an architecture-neutral format.

8.Interpreted

Java executes programmes using a Just-in-time (JIT) interpreter and a compiler.

9.High performance

Because Java bytecode is "close" to native code, it runs more quickly than other conventionally interpreted programming languages.

10.Distributed

Due to its ability to help users construct distributed applications, Java is distributed.

11.Dynamic

Another name for dynamic binding is run-time polymorphism. The functionality of the method call is not chosen at compile time in this type of binding. To put it another way, it is not feasible to determine at compile time which piece of code will be executed as a result of a method call.

 

4. What is JVM, please?

The entity that controls application memory and offers a mobile execution environment for Java-based programs is known as a Java virtual machine. JVM performs two main tasks: managing and optimizing program memory, and running Java programs on various devices.

 

5. What do JDK and JRE mean?

A software development kit known as Java Development Kit, or JDK, is frequently referred to as a superset of JRE. 

Development of Java applications and Java applets is made possible by the JDK, which is a fundamental component. 

Since this is platform-specific, separate installers are required for Mac, Unix, and each Windows-based operating system.

 

6. What distinguishes JVM, JDK, and JRE?

The main distinctions between JVM, JDK, and JRE

While JRE is used for execution, JDK is the platform for development.

The JVM, or "heart," of the Java programming language, ensures that the program's Java source code is platform-independent.

Both JDK and JRE include JVM since Java programmes cannot be run without it.

 

7. What is a JAVA Class?

In Java, an object with shared properties and methods is created using a class, which serves as a logical template. Each class has the ability to have its own set of objects, all of which share the same attributes.

 

8. How does Java define an object?

An object is a thing with state and behaviour that correspond to the class's properties. 

 

9. Create a simple Java program that prints "Hi, How are you?"

 

Class MaakEduTech

{

Public static void main(String args[])

{

System.out.println(“Hi, How are you?”);

}

}

 

10. What are the various Java memory management Subtypes?

In Java, there are two different ways to manage memory: 

  1. Stack memory
  2. Heap memory

Stack memory: During runtime, different Java objects are given access to physical memory, also known as RAM. It is made to allocate static memory prior to thread execution. 

Heap memory: The location where all Java objects are stored is called heap memory. JVM is the source of this heap space. This heap space is utilised by Java programmes over the duration of the application.

 

11. What is the function of the class loader in Java?

The class loaders are in charge of dynamically loading Java classes into the Java Virtual Machine (JVM) during runtime.A component of the JRE (Java Runtime Environment) is class loaders. Class loaders enable Java programmes to run without the JVM having to be aware of the underlying files or file systems.

 

12. Describe the Java execution process.

Programs are not created in Java as executable files, but rather as bytecode, which is then run at runtime by the JVM (Java Virtual Machine). 

When we utilise the javac compiler, Java source code is converted into bytecode. The file extension.class is used to save this bytecode on the hard drive. This bytecode is transformed by the just-in-time (JIT) compiler before the programme is executed. The outcome is machine code, which is subsequently read from memory and run.

It takes two compilations of Java code to run it:

  1. Java programmes must be translated into bytecode.
  2. Bytecode is transformed into machine code when it is executed.

 

13. What can you tell me about the JIT compiler?

The Just-In-Time (JIT) compiler is a part of the runtime environment that boosts Java application performance by converting bytecode into native machine code at runtime.

Classes make up Java programmes; these classes include platform-neutral bytecodes that a JVM can decipher on a variety of computer architectures. The semantics of each individual bytecode are determined by the JVM at run time, and the necessary calculation is then carried out. 

By converting bytecode into native machine code at run time, the JIT compiler helps Java programmes execute faster.

 

14. What makes Java a platform-neutral language?

Java is known as a platform independent language because programmes created in it can operate on several platforms without the need for source code modifications, or Write Once, operate Anywhere (WORA).

 

15. What are variables, and what kinds of variables are there?

Variables are used to hold data values in programming and serve as containers for the data. There are three different sorts of variables in Java:

 

1.Local Variable

2.Instance Variable

3.Static Variable

 

1)Local Variable

A local variable is one that is declared inside the method body. Only that method can make use of this variable; the other methods in the class are completely unaware of its existence.

The "static" keyword cannot be used to declare a local variable.

 

2)Instance Variable

An instance variable is a variable that is declared inside a class but outside the actual method body. It's not necessary to specify instance variables as static.

Because their value is instance-specific and not shared across instances, these are referred to as instance variables.

 

3)Static Variable

Static variables are those that have been explicitly designated as static. It can't be regional. The static variable can be created once, shared across all of the class instances. When the class is loaded into memory, static variables' memory is only allocated once.

 

16. What forms of data are there in Java?

The varying sizes and values that can be kept in a variable are determined by its data types. In Java, there are two distinct type of of data types:

1.Primitive Data Types

2.Non-Primitive Data Types

 

17.Briefly describe primitive data types.

The size and type of variable values are specified by primitive data types. They serve as the foundation for data processing and cannot be broken down into more basic data kinds.

 

18. What non-primitive data types are there?

Instances or objects are referred to either non-primitive data types or reference data types. These can't save a variable's value directly in memory, but they can store the variable's memory address. Non-primitive data types, on the other hand, are user-defined. They are made by programmers and can be given the value null. Non-primitive data types have standardised sizes.

 

19. Can you explain operators and list the various Java operators' types?

The symbols known as Java operators are used to change the values of the operands and perform operations on variables. Each operator carries out particular tasks. 

Here's an illustration: 5 + 1 = 6, where 5 and 1 are the operands and + (plus) is referred to as the operator. 

Various Java operators

1.Unary Operators

2.Arithmetic Operators

3.Assignment Operators

4.Logical Operators

5.Shift Operators

6.Bitwise Operators

7.Ternary Operators

8.Relational Operators

 

20. Establish an object for the Maak class?

public class Maak

{

int NumberOfCourses;

public int setNumberOfCourses(int number) 

{

           NumberOfCourses=number;

           return 0;

}

public int getNumberOfCourses( ) 

{

           System.out.println("The number of Maak’s courses are:" + NumberOfCourses );

           return NumberOfCourses;

}

public static void main(String []args) 

{

/* Object creation */

Maak my Courses = new Maak();

/* Call class method to set Maak's courses */

 myCourses.setNumberOfCourses( 10 );

 /* Call another class method to get Maak's courses */

myCourses.getNumberOfCourses( );

/* You can access instance variable as follows as well */

System.out.println("My Courses :" + myCourses.getNumberOfCourses());

}

}

 

21.What does a java wrapper class do?

A class that contains primitive data types (such as int, char, short, byte, etc.) is known as a wrapper class. The use of primitive data types as objects is also made possible by these wrapper classes. The java.util package contains these wrapper classes.

 

22.What does the term "object cloning" mean?

The process of making an exact duplicate of an object is known as object cloning. To duplicate an object, use the clone() function of the object class. A class that wants to be able to make object clones must implement the Cloneable interface.

 

23.What does "keywords" in JAVA mean?

A keyword in the Java programming language is a term with a predefined meaning. As JAVA's reserved terms, keywords are not permitted to be used in the names of variables, classes, methods, or other entities.

 

24. What is the final keyword?

The final keyword is a non-access modifier used in Java to make classes, attributes, and methods non-changeable and difficult to inherit or override.

This last keyword is useful when you want a variable to store a constant value that does not vary over time.

Ex: PI (3.14159...).

A "modifier" is another term for the final keyword. 

 

25.What do super keywords in Java mean?

Superclass (parent) objects are referred to by the super keyword.

It is used to access the superclass constructor as well as call methods from superclasses.

The super keyword is most frequently used to clarify the differences between superclasses and subclasses that share methods with the same name.

 

26. What kinds of access specifiers does Java support?

Java classes, constructors, methods, and other members' accessibility can be set with access modifiers in object-oriented programming. We can define the scope for them using the access modifiers.

Access modifiers and non-access modifiers are the two categories of modifiers in Java.

 

Access Modifiers

Access modifiers are keywords that let you manage a class's fields, methods, and constructor visibility. Public, protected, default, and private are the four types of access modifiers in Java.

 

Four Different Access Modifier Types

 

Private: Only within the same class and not from outside the class can we access the private modifier.

 

Default:The default modifier can only be accessed from within the same package; it cannot be accessed from another package. In addition, if we don't supply an access modifier, it will take the default value into account.

 

Protected: Using the child class, we may access the protected modifier both inside and outside of the same package. We cannot access the kid class from outside the package if we do not create it. Therefore, accessing it from outside the package requires inheritance.

 

Public: The public modifier is available from any location. Public modifiers are accessible from both inside and outside of the class, as well as from both inside and outside of the package.

 

27. Describe Java packages and their benefits?

In Java, a collection of related classes and interfaces is referred to as a package. The name itself identifies the collection (group) of related types that provides name-space management, including classes, subpackages, enumerations, annotations, and interfaces. Each class belongs to a specific package. The package must be added to the Java program when you need to utilise an existing class.

  • The following are some advantages of utilising Java packages:
  • The group of classes is organised by the packages into a single API unit
  • They will manage naming disputes
  • Access control will be simpler. The package's access level control is protected and set to default
  • It was simple to find the relevant classes
  • Use the current classes in your packages.

There are two categories for packages:

1.Built-in-Packages

2.User-defined-Packages

 

28. Describe a Java method and provide a java method example.

In Java, a method is a block of code that, when called, executes the specified tasks listed in it. For instance, if the method has written instructions to draw a square, it will do so. Methods that include values or parameters will only ever be invoked to execute them. They are additionally known as functions. 

The primary applications of Java methods are:

 

  1. To enable the "define once, use many times" functionality of code
  2. A complicated programm can be divided up into simpler sections of code.
  3. These techniques improve the readability of code

 

29. What does Java's method overloading mean?

Method overloading is the practice of having many methods in a class with the same name but distinct parameters.

Method overloading is used when there is only one operation to complete, the methods' names are the same, and it improves the readability of the code.

For instance, if you need to multiply some supplied values but the number of arguments can vary, writing the method as multiply(int,int) for two parameters and multiply(int,int,int) for three parameters will be more beneficial and improve the readability of the code. 

The practice of writing these kinds of methods under the same name is known as method overloading.

 

30. What does Java's method overriding mean?

Java refers to method overriding when a method with the same name exists in both the super class and the subclass.

In other words, method overriding is when a subclass (child class) provides a specific implementation of a method that was declared by one of its parent classes.

 

Java Method Overriding use

1)The specific implementation of a method that is already supplied by its Superclass is provided through method overriding.

2)Method overriding allows for runtime polymorphism.

 

Java Method Overriding Guidelines

1)The method's name must match that of the super class.

2)The method's parameters must match those of the super class.

3)Between such classes, there must be an IS-A relationship (inheritance).

 

31.What distinguishes Java's main method from other methods? 

The primary distinction between a main method and any other method is that the main method is where the programme is executed first.

A class is the collection of a set of methods and variables that define an entity, whereas each method represents a functionality or a set of instructions that have been collected together.

 

32.Can we develop a Java programme without using the main method?

Yes, it is possible to run a Java programme without a main method; however, a static block is required. 

A static initialization block is a sequence of statements that are only ever executed once in Java, when the class is loaded into memory by Java ClassLoader. The initialization block that enters the stack memory first is the static initialization block.

Sample Code

class Maak Static Initialization Block

{

Static

{

       System.out.println("Maak’s class without a main method");

       System.exit(0);

}

}

 

33. How are pointers implemented in Java?

Java refers to pointers as references. When using Java, a variable is a specific kind of object that stores the object's reference. And all that this reference is is a pointer that gives the location of the item in memory.

 

34.What various Java selection statement kinds are there?

In Java, there are three types of selection statements: if, if..else, and nested if-else. 

1.The if Statement, first

There is only one selection statement in this.

We must choose the "if" statement when we wish to execute a certain sentence. Any expression that returns a boolean value, such as true or false (1 or 0), is referred to as a condition.  

Here, the condition must be written; if it is met, the condition returns 1, and the statements inside the loop are carried out; if not, the condition returns 0 (false), and the execution is skipped.

 

Syntax:

if (condition)

      statement

Sample code:

if (maaks_age >18)

       System.out.println("Maak is a major");

 

2. The if..else Statement

The second conditional statement

A double selection statement is what this is known as. It selects between two possible actions, hence its name.

Selecting the if..else statement is necessary when you wish to execute statements while checking various criteria. 

When a condition is met in this case, the if block is executed. If not, it performs a command in the else block. 

 

Syntax:

if (condition)

   statement1

else

   statement2

 

Sample code:

if (maak_age < 18)

       System.out.println("Maak is a minor.");

else

       System.out.println("Maak is a major.");

3. Nested if..else

Nesting is the practice of putting if..else statements inside other if..else statements.

Sample Code

if (temperatures > 6000)

{

   System.out.println("Object's colour likely blue");

}

else if (temperatures > 5000)

{

   System.out.println("Object's colour likely white");

}

else if (temperatures > 3000)

{

   System.out.println("Object's colour likely yellow");

}

else

{

   System.out.println("Object's colour likely orange");

}

Blocks

The if and if..else expressions typically anticipate performing a single action. Use braces to group these operations if you want to perform several statements at once.

 

if (condition) {

// statements

} else {

// statements

}

 

35. What does the switch statement mean?

A multiple-selection statement is a switch statement. It determines whether a statement fits one of the provided cases before carrying out the appropriate action.

Syntax:

switch(expression) 

{

       case a:

       // statement

       break;

       case b:

       // statement

       break;

       case n:

       // statement

       break;

       default:

       // statement

}

 

When a match is discovered, the switch statement is stopped using the break statement. If a case has been located, there is no need to waste time during execution.

 

The switch statement's expression must be an integral constant of type byte, short (but not long), int, or char. The String data type is another option.

Code example

String Direction= "E";

switch (position) 

{

       case "N":

              System.out.println("You are in the North");

              break;

       case "W":

              System.out.println("You are in the West");

              break;

       case "S":

              System.out.println("You are in the South");

              break;

       case "E":

              System.out.println("You are in the East");

              break;

       default:

              System.out.println("Non-cardinal position");

}

 

36.What various Java iterative statement kinds are there?

There are many situations in real-world software programming where we must repeatedly do a given activity. There are two methods we can use to complete these duties. First, we can repeatedly code the same thing. This approach goes against the DRY (Don't Repeat Yourself) concept and is incredibly ineffective. The alternative is to employ a Java mechanism called a loop. Loops are iteration statements that are used to carry out a specific activity repeatedly without having to write new lines of code each time. It is quite effective.

 

Java has three different iteration statement types:

  • for statements
  • while statements
  • do-while statements

These iteration statements are referred to as loops in general.

 

37.What does a for loop in Java mean?

An iterative control structure called a "for loop" enables you to create loops that must be run a predetermined number of times. 

When you know how often a task needs to be repeated, you use a for loop.

 

38.What various Java control statement types are there?

Three categories of control statements exist:

  1. Conditional Control Statements
  2. Iterative Control Statements
  3. Unconditional Control Statements / Jump Statements

 

39.What do Java's Jump statements mean?

The unconditional control statements known as jumping statements are what move program execution from one place to another. Jump statements are used to unconditionally move programme control from one place in the programme to another. Jump statements are frequently used to end a loop or switch-case abruptly. 

 

Java Jump Statements

In Java, there are three jump statements.

1.Break Statement

2.Continue Statement

3.Return Statement

 

40. How Do I Write Java Comments?

We can use two different types of comments in Java programs: 

  1. Implementation comments 
  2. Documentation comments

Implementation comments are those that can be found in C++ and are separated by the characters // and *... *. 

Documentation comments (often referred to as "doc comments") are only supported in Java and are separated by /**.

 

41.How is Java's trash collection handled?

A garbage collector exists in Java that looks over live objects to see whether any still-reachable objects are present before marking all unreachable objects for garbage collection using a mark-and-sweep mechanism. You have no control over whether or not the objects are destroyed using automatic garbage collection.

 

42.Why is Java referred to as an object-oriented language?

Because it adheres to the object-oriented paradigm and is built on the idea of objects and classes, the Java programming language is regarded as an object-oriented programming language. Without the creation of objects and classes, Java does not allow us to write any code. The OOPS principles of inheritance, data abstraction, polymorphism, and data encapsulation are supported by Java.

 

43.What distinguishes object-oriented language from object-based language? 

The main distinction between object-based and object-oriented languages is that object-based languages do not necessarily enable inheritance or subtyping, though those that do are also referred to as object-oriented. True object-oriented languages are typically not thought of as object-based languages that do not provide subtyping or inheritance.

 

44.What are the procedures for declaring a class?

1.One of the rules for defining a class is that we must utilise modifiers like "public," "private," and a number of others that you may come across later. (However, take note that only Nested Classes may use the private modifier.)

  1. The name of the class, with the first letter capitalised per tradition.
  2. The word extends followed by the name of the class's parent (Superclass), if any. Only one parent can be extended (subclassed) by a class.

4.A list of all interfaces that the class, if any, implements, separated by commas, should be included. A class may support several interfaces.

  1. The class as a whole, enclosed in braces.

 

45. Could you explain Java's constructors to me?

Constructors are a type of code block that are analogous to methods in Java. When an instance (object) of the class is created, these constructors are invoked. When you call the constructor, memory is allocated for the objects.

       Constructors are a special category of methods used to initialise an object.

       The new() keyword calls at least one constructor each time an object is created. When constructors are not explicitly written in the code, the Java compiler automatically creates a default constructor.

 

46. What does copy constructor mean?

It is possible to initialise an object using another object of the same class by using a copy constructor, which is a member function. A copy constructor is, to put it simply, a constructor that produces an object by initialising it with a different object of the same class that has already been constructed.  

By copying the members of an existing object, the copy constructor initialises the members of a newly generated object.

 

47. What are the various Java constructor types?

In Java, there are two different types of constructors.

 

1.Parameterized Constructor

2.Non-parameterized Constructor

 

48. What does Java Abstraction mean in Java?

Java abstraction is the technique of merely displaying the functionality to the user and hiding the implementation specifics from the user. Use of abstract classes, methods, and interfaces can accomplish this. A class that cannot be created on its own and is intended to be inherited by concrete classes is known as an abstract class.

 

49. How does Java define data encapsulation?

In Java, encapsulation refers to the process of uniting the data (variables) and the code that manipulates them (methods). 

The variables of a class are protected so that only the methods of the class may access them and that no other classes can access them.

 

50. What is inheritance and what are its many types?

The process of passing on a class's behaviour to another class is known as inheritance. The methods and attributes of one class are inherited by another class. The parent class or superclass is the class from which the inherited properties and methods are derived. The child class, derived class, or subclass is the one that inherits the parent class's properties.

 

51. What are some benefits of inheritance?

The Benefits of Inheritance

       Code reduction is the key benefit of employing inheritance. We create the code for the base class, and it has already undergone testing and debugging. Reusing old code reduces development and maintenance expenses. The derived classes must adhere to a standard interface because of inheritance. Code extensibility and code redundancy are both supported by inheritance.

 

52. Give an illustration of polymorphism?

The term "polymorphism" refers to the "many forms" that can exist when there are numerous classes that are related to one another through inheritance.

A class's attributes and methods can be inherited using inheritance. These techniques are used by polymorphism to carry out various tasks.

 

class Maak

{

       public void MaakCourses()

       {

              System.out.println("Maak has courses");

       }

}

class Java extends Maak 

{

       public void MaakCourses() 

       {

              System.out.println("This is Maak’s Java Course");

       }

}

class Python extends Maak

{

       public void MaakCourses() 

       {

              System.out.println("This is Maak’s Python Course");

       }

}

 

53. What exactly is a static variable?

When a variable is marked as static, it indicates that there is only one instance of the class-wide copy of the variable rather than several copies. The class's static methods are those that can be called without first constructing an object (instance) of the class.

Java's static variables and methods have a number of benefits, such as global access, object independence, performance, and code organisation.

 

54. What does the Java singleton class mean?

Java's singleton class design pattern ensures that a class can contain just one object.

A class must implement the following characteristics in order to be a singleton class:

  1. To prevent objects from being created outside of the class, provide a private constructor for the class.
  2. Develop a private class type attribute that points to the solitary item.
  3. Develop a public static method that lets us construct and use the produced object. We will include a condition that prevents us from producing multiple objects inside the procedure.

 

55. What is typecasting, exactly?

The process of changing one data type into another is known as type casting. When you assign a value from one primitive data type to another type, this occurs. 

There are two methods of casting in Java:

1.Widening Casting(Automatic ) Casting, which increases the size of a smaller type. 

Ex: byte -> short -> char -> int -> long -> float -> double.

       

  2.Narrowing casting - a larger data type being converted to a smaller data type.

Ex: float → int

Data loss is a risk when narrowing casting.

Ex: 

float a=10.8;

int b = (int) a;

System.out.println(b);

// In this case, the value of b will be printed as 10, and the decimal digit will be lost.

 

56. What are the various types of type conversion and how are they used?

Type conversion or type casting in computer science refers to the transformation of an entity from one data type into another. 

There are two different forms of type casting:

  1. Implicit type conversion

Coercion is the technical name for implicit type conversion. 

  1. Explicit type conversion.

Casting is the explicit type conversion of a certain kind.

 

57. What is an abstract class, exactly?

In Java, an abstract class is one that has the abstract keyword stated in its declaration. Both abstract and non-abstract methods can be found in abstract classes. These classes can't be instantiated; they need to have their methods implemented and extended.

  1. An abstract keyword must be used when defining an abstract class.
  2. Both abstract and non-abstract methods are possible for these types.
  3. One cannot instantiate these classes.
  4. It may also have static methods and constructors.
  5. It may have final methods that compel the subclass not to alter the method body.

abstract class car

{  

        abstract void run();  

}  

class BmwX5 extends car

{  

       void run()

       {

              System.out.println("running safely");

       }  

       public static void main(String args[])

       {  

              Car obj = new BmwX5();  

              obj.run();  

       }  

}