Core Java is the fundamental skill to become a Java developer. Many projects can be developed only with core Java skills. Review your understanding with these core Java interview questions and answers. Get started with our Core Java course syllabus.
Core Java Interview Questions for Freshers
Here are 40 Core Java Basic Interview Questions for freshers.
Core Java Interview Questions on Fundamental Concepts
1. What is Java?
Java is a high-level, object-oriented programming language that is renowned for its robustness, security, and platform independence.
2. Define JVM, JRE, and JDK.
JVM, or Java Virtual Machine: Runs Java code.
JRE, or Java Runtime Environment: It consists of the JVM, essential classes, and libraries.
JDK, or Java Development Kit: It contains the JRE as well as debuggers and compilers.
3. Describe OOPs.
The foundation of the object-oriented programming paradigm (OOP) is the idea that objects have behaviors (methods) and properties (attributes).
A computer programming paradigm known as object-oriented programming (OOP) arranges software according to objects rather than logic and functions.
OOP is a well-liked programming style that works well for complicated, large-scale, and often updated software.
4. Explain the features of OOPs.
These are some of OOP’s salient features:
- Objects: Data fields with distinct characteristics and actions are called objects. Data is contained in objects, which are characterized by their behaviors (methods) and qualities (attributes).
- Classes: A class describes the features and behaviors of objects and serves as a blueprint for their creation.
- Code reusability: OOP gives programmers the ability to create modular, manageable, and reusable code.
- Scalability and efficiency: OOP can increase the modularity and flexibility of programs.
- Collaborative development: An object-oriented program’s structure facilitates collaborative development.
5. Explain the core principles of OOP.
The following are the fundamental ideas of object-oriented programming (OOP):
Polymorphism: It enables programmers to create logical programs by using a single interface to access objects of many sorts.
Abstraction: By obscuring extraneous elements and emphasizing only the most crucial ones, abstraction makes a class’s or method’s intricate operation simpler.
Encapsulation: All of an object’s crucial information and features are contained within its encapsulation.
Inheritance: With the ability to modify or add to the properties and methods of preexisting (parent) classes, inheritance enables programmers to construct new classes based on them.
Dynamic binding: Like choosing a method to execute at the last second during runtime.
6. What is the difference between == and .equals()?
- == verifies that two objects belong to the same memory address, or reference equality.
- .equals() determines whether two objects have the same value, or content equality.
Core Java Interview Questions on Data Types and Variables
7. What are the various data types in Java?
There are two primary types, such as primitive and reference data types.
- Byte, short, int, long, float, double, char, and boolean are examples of primitive data types.
- Class, interface, and array are examples of reference data types.
8. What is the difference between int and Integer?
The primary distinction between int and integer in Java is that the integer is a wrapper class that offers greater flexibility for storing, converting, and working with int data, while int is a primitive data type that stores entire numbers:
- Data type: Integer is a wrapper class, whereas int is a primitive data type.
- Flexibility: Because it can only store an integer’s binary value, int is less flexible than integer.
- Memory: compared to integers, int uses less memory.
- Comparison: The.equals() method is used to compare two Integer class objects, while the == sign is used to compare int variables.
- Default value: Int and Integer have default values of 0 and null, respectively.
- Performance: It is more effective and appropriate for tasks requiring high performance.
- Nullability: Null values can be represented in an integer with flexibility.
You can balance functionality and efficiency by taking your project’s unique requirements into account when deciding between integer and int.
9. What is type casting in Java?
The process of changing a variable’s value from one data type to another is known as type casting in Java. The compiler can accomplish it automatically, or the programmer can do it by hand.
10. Explain automatic type conversion and explicit type casting in Java
Variables can be changed from one data type to another using the type casting capability. Type casting comes in two varieties:
- Implicit type casting: The compiler’s automatic conversion of a smaller data type to a larger one is referred to as widening conversion.
- When there is no data loss, this occurs.
- For instance, Java will automatically change an int to a double if you assign it to one.
- Explicit type casting: The process by which a programmer manually transforms a larger data type into a smaller one is called narrowing conversion.
- When data loss is a possibility, this is employed.
- For instance, explicit type casting is required if you wish to change a double to an int.
Explore more with our core Java online course.
Core Java Interview Questions on Operators
11. What are the various types of operators in Java?
Java operators come in the following varieties:
Arithmetic Operators: Basic mathematical operations including addition, subtraction, multiplication, division, and modulus are carried out using arithmetic operators.
- +: Addition
- – Subtraction
- \*: Multiplication
- /: Division
- %: Modulus
Logical Operators: Boolean variables can be combined or inverted using logical operators to carry out logical operations.
- &&: Logical AND operator
- || Logical OR operator
- !: Logical NOT operator
Assignment Operators: Assignment operators are used to set or modify a variable’s value.
- = Basic assignment operator
- += Add and assign
- -= Subtract and assign
- \*: Multiply and assign
- /= Divide and assign
- %= Modulo and assign
Bitwise operators are employed to help execute operations on individual bits.
12. What is operator precedence and associativity in Java?
Operator Precedence: The sequence in which operations are carried out is determined by operator precedence.
Example:
a= 4+5/10;
if we solve the addition in the case above first, the result will be 9/10=0.9.
Now, the answer is 4 + 0.5 = 4.5 if we solve the division first.
Due to the fact that division comes before addition, the second response is a legitimate one.
Consequently, a=4.5
Operator Associativity: The direction in which operations are clustered is determined by operator associativity.
Example:
a = 5 * 5/10
The solution is 25/10=2.5 if we solve the multiplication operation first.
The answer is 5*0.5=2.5 if we first solve the division operation.
The first response is accurate since the two operators provided have the same precedence; so, we should examine the left-to-right associativity.
Consequently, a=2.5.
Core Java Interview Questions on Control Flow Statements
13. What are the various control flow statements in Java?
Control flow statements enable a program to select various execution paths according to specific circumstances; it’s similar to selecting a different road when driving depending on traffic or your destination.
If, else, switch, while, do while, and for are the main control flow statements in Java.
14. Explain the difference between while and do-while loops.
The do-while loop runs the loop body at least once before checking the condition, whereas the while loop checks the condition before running the loop body.
Enhance your core skills with our advanced Java training in Chennai.
Core Java Interview Questions on Arrays
15. Explain array in Java.
A container object that can store a set number of values of a single type is called an array. When an array is constructed, its length is predetermined. Its length is set after creation. An array example has already been shown to you in the “Hello World!” application’s main method.
16. How do you declare and initialize an array?
dataType[] arrayName = new dataType[size]; or dataType[] arrayName = {element1, element2, …}
17. What is the difference between a single-dimensional and a multidimensional array?
- A single list of different elements with the same data type is stored in a one-dimensional array.
- An array of different arrays, a list of different lists, or an array of different one-dimensional arrays can all be stored in a two-dimensional array. It uses a list format to represent several data objects.
Core Java Interview Questions on Strings
18. What is a String in Java?
A String is a sequence of characters. An object that represents a collection of character values is called a string in Java.
- The Java string object is made up of distinct character values for each letter in the string. The char class in Java is used to represent characters.
- An array of character values that have the same meaning as a string can be written by users.
19. Explain the String class and its methods.
Numerous methods for working with strings are available in the String class, including length(), charAt(), indexOf(), substring(), concat(), and others.
20. What is the difference between String and StringBuffer/StringBuilder?
While StringBuffer and StringBuilder are mutable classes, String is immutable. In contrast to StringBuilder, StringBuffer is synchronized and thread-safe. StringBuilder is therefore quicker than StringBuffer.
Core Java Interview Questions for Experienced
Here are the advanced core Java questions asked in interviews for experienced candidates.
Core Java Interview Questions on Classes and Objects
21. What is a class and an object in Java?
An object in Java is an instance of a class, and a class serves as a template for producing objects.
Class: A class specifies an object’s attributes, methods, and other characteristics. Classes cannot be tangible; they are intellectual things. The keyword class is used to construct a class.
Object: An object is a class blueprint that has been concretely realized. Its instance variables serve as a representation of its state.
For the properties specified by their class, objects have values. The term new is used to construct an object.
22. Explain constructors in Java.
A constructor is a unique Java function that produces an instance of a class and initializes an object.
When it’s called: When an object is formed with the new() keyword, a constructor is called.
What it does: A constructor initializes the object’s instance variables and allocates memory for it.
How it got its name: The class and a constructor share the same name.
What it is lacking: A constructor cannot be static, volatile, or final, and it lacks a return type.
What it is comparable to: In contrast to a method, which executes an action, a constructor is used to initialize an object.
When it is not necessary: The Java compiler will automatically generate a default constructor if a class lacks one.
Types of constructors: Default, parameterized, and copied constructors are among the various types.
- Default constructor: Sets an object’s initial values by default.
- Parameterized constructors: Values supplied as arguments are used to initialize objects by parameterized constructors.
- Copy constructor: The copy constructor generates a new object of the same class that has the same characteristics as the original.
23. What distinguishes a parameterized constructor from a default constructor?
The primary distinction between a parameterized constructor and a default constructor is that the latter accepts parameters, whereas the former does not.
Default constructor: Produced automatically by the compiler in cases where a class lacks a constructor that is explicitly defined. It sets the instance variables of the object to their initial values.
Parameterized constructor: initializes the instance variables for a certain object by accepting one or more parameters. With particular values supplied as inputs, you can initialize the object’s properties.
24. What is method overloading and method overriding?
In object-oriented programming, methods with the same name are used in both method overloading and method overriding.
Method Overloading: It entails defining several methods in the same class with the same name but distinct parameters.
- The number, kind, and order of the parameters may vary.
- Depending on the arguments supplied to the method, overloading allows you to implement several actions.
Method Overriding: Creating a method in a child class with the same name, parameters, and return type as a method in the parent class is known as method overriding.
- The method of the parent class is superseded by the method of the child class.
- By overriding, you can modify the method’s behavior to suit the requirements of the subclass.
Discover our advanced Java course syllabus to upgrade yourself.
Core Java Interview Questions on Inheritance
25. What is inheritance in Java?
A key idea in object-oriented programming (OOP) in Java is inheritance, which enables a class to inherit traits and actions from another class. This encourages a hierarchical structure among classes and permits code reuse.
The following are some essential ideas about inheritance in Java:
- Superclass: The class that features are inherited by a subclass. It is sometimes referred to as a parent class or base class.
- Subclass: The inheritance class is derived from another class. It is sometimes referred to as a kid class, extended class, or derived class.
- Inheritance relationship: The parent-child connection is the relationship between a subclass and its superclass.
- Inheritance keyword: To inherit from a class, use the extends keyword.
- Inheritance Hierarchy: A class hierarchy with more specialized classes at the bottom and a more generic class at the top.
- For instance, a Car class is more specialized and inherits from the Vehicle class, but a Vehicle class is the most broad.
26. Explain the types of inheritance.
Different forms of inheritance exist in object-oriented programming, such as:
- Single Inheritance: When a class inherits from a single parent class, it can utilize the parent’s methods and properties. This facilitates code management.
- Multiple Inheritance: A class can combine properties from numerous sources since it inherits from multiple parent classes. Design freedom is increased as a result.
- Multilevel Inheritance: A chain of inheritance is created when a class inherits from a derived class. As a result, every class can expand on the capabilities of its parent class.
- Hierarchical inheritance: One parent class is the source of inheritance for several classes. Making a family of related classes with similar traits is made easier with this.
- Hybrid Inheritance: It integrates several inheritance models—such as hierarchical, multiple, and single—into a single structure.
27. Define super keyword in Java
A subclass can access the constructors and methods of the parent class by using the super keyword.
- As a result, the subclass can inherit and utilize the parent class’s features.
- To access parent class members that have been overridden in the subclass, the super keyword is frequently utilized.
Core Java Interview Questions on Polymorphism
28. What is polymorphism in Java?
A key idea in Java is polymorphism, which enables objects to carry out various operations depending on the object calling them. It is an essential component of OOP, or object-oriented programming.
The Greek terms “poly” and “morphs,” which signify “many” and “forms,” respectively, are the origin of the word polymorphism.
29. Describe Java’s runtime and compile-time polymorphisms.
Java polymorphism can be classified as either compile-time or runtime, depending on when the method to call is decided.
- Compile Time Polymorphism: When several methods in a class have the same name but distinct parameters or return types, this is referred to as method overloading.
- Compilation is when this process takes place.
- Runtime Polymorphism: This happens when the method to call on an object is decided upon while the program is running; it is also referred to as dynamic method dispatch.
- Different classes can use the same method with the same parameters due to method overriding.
- During runtime, the Java virtual machine chooses which method to call.
Core Java Interview Questions on Interfaces and Abstract Classes
30. Explain interface in Java.
An interface is a reference type in Java that specifies the methods a class must have to function.
- Purpose: Interfaces serve the purpose of defining contracts that outline the interactions between software. They are useful for achieving security and abstraction.
- Structure: Related procedures with empty bodies are grouped together by abstract classes called structure interfaces. By default, interface properties are public, static, and final, while interface methods are public and abstract.
- Behavior: Classes can implement behavior interfaces, but they are not able to instantiate them. While inheritance is restricted to a single direct superclass, classes are able to apply multiple interfaces.
- Usage: With the help of usage interfaces, one can concentrate on the task at hand rather than the method of completion. An interface, for instance, can be used to specify information that is consistent across all interface implementations.
- Example: To indicate the methods that can be used to move a robotic automobile, for instance, you can build an interface.
31. What is an abstract class in Java?
In Java, an abstract class is one that can serve as a template for other classes to extend but cannot be instantiated on its own.
- Use: While permitting certain methods to be implemented by subclasses, abstract classes are used to specify common functionality for a collection of subclasses.
- Methods: Concrete methods (methods with implementation) and abstract methods (methods without implementation) can both be found in abstract classes.
- Inheritance: It is possible to subclass abstract classes, and the subclass typically provides implementations for every abstract method in the original class.
- Abstract keyword: To construct an abstract class and method, use the abstract keyword.
- Similarity to Interfaces: Although they can have default method implementations, abstract classes are comparable to interfaces.
32. What distinguishes an abstract class from an interface?
The primary distinctions between an abstract class and an interface in Java are:
- Methods: Whereas abstract classes can have both abstract and non-abstract methods, interfaces only have abstract methods.
- Fields: Every field in an interface is by default final, static, and public. It is possible to declare non-static and final fields in an abstract class.
- Access modifier: Access modifiers such as public, private, protected, and static are available for abstract class methods. Interface methods are abstract and implicitly public.
- Inheritance: Interfaces do not allow multiple inheritance, but abstract classes do.
- Instantiating: Abstract classes that implement interfaces can be instantiated, but interfaces themselves cannot.
- Declaration: While “abstract” is used to declare an abstract class, “interface” is used to declare an interface.
- Extending and implementing: While “implement” is used to implement an interface, “extend” is used to extend an abstract class.
Accelerate your career with our J2EE training in Chennai.
Core Java Interview Questions on Exception Handling
33. What is exception handling in Java?
In Java, exception handling is a way to handle unforeseen circumstances that may arise while a program is operating. Instead of crashing, it enables a program to keep operating while displaying error warnings.
Exceptions may arise for the following reasons:
- A user inputs inaccurate information.
- There is a hardware malfunction.
- A network connection malfunctions
- A database server fails.
- A program tries dividing by zero.
- A user attempts to open a file that isn’t available.
34. Explain the try-catch-finally block in Java
A catch block, which manages the exception that arises in the related try block, always comes after the try block. The method must have a try block, which must be followed by either a finally block, a catch block, or both.
- try: Encloses code that might throw an exception.
- catch: Handles specific exceptions.
- finally: Executes code regardless of whether an exception is thrown.
Syntax
try{
//code that may throw an exception
}catch(Exception) {
//code
}
Core Java Interview Questions on Threads
35. What is thread in Java?
The path a program follows while it is executing is called a thread in Java. Every Java Virtual Machine (JVM) application has at least one thread, which is the smallest unit of execution within a process.
Because they enable numerous activities to occur within a single function, threads are crucial. They are useful for:
- Parallelism: Performing several things concurrently is known as parallelism.
- Responsiveness: Responding to human input while executing laborious operations in a different thread.
- Simplified programming: Coding distinct components of an application separately and then executing them concurrently is known as simplified programming.
- Asynchronous programming: Programming asynchronously involves carrying out non-blocking input/output activities.
36. In Java, how do you start and construct a thread?
Starting a Thread: A freshly formed thread is started using the Thread class’s start() function. It carries out the following tasks:
- With a new callstack, a new thread begins.
- The thread transitions between the New and Runnable states.
- The thread’s target run() procedure will execute when it has an opportunity to do so.
Step 1: Creating Thread by Extending Thread Class
File Name: Multi.java
class Multi extends Thread{
public void run(){
System.out.println(“thread is running…”);
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Step 2: Java Thread Example by implementing Runnable interface
FileName: Multi3.java
class Multi3 implements Runnable{
public void run(){
System.out.println(“thread is running…”);
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}
Core Java Interview Questions on Input/Output Streams
37. In Java, what are input and output streams?
The data sequence that is read from the source and written to the destination is known as a stream in Java.
- Data is read from the source using an input stream.
- Data is written to the destination using an output stream.
class { public static void main(String[] args)
{ HelloWorld Println(System.out.”Hello, World!”)
}
}
Learn more with our hibernate course syllabus.
Core Java Interview Questions on Collection Framework
38. In Java, what is the Collections Framework?
Reusable collection data structures are implemented by a group of classes and interfaces known as the Java collections framework. It functions similarly to a library by offering classes that implement collections and interfaces that specify them.
Among the Java collections framework’s fundamental interfaces are:
- Collection: The base of the hierarchy of collections.
- Set: A collection that cannot contain duplicate elements.
- List: A structured grouping of items that might have duplicates.
- Queue: Before processing, a queue is a collection that holds several elements.
- Map: An item that associates values with keys.
Core Java Interview Questions on Generics
39. Define Generics in Java
Parameterized types are known as generics. Allowing a type (such as an integer, string, etc.) or user-defined types to be a parameter to classes, methods, and interfaces is the idea. Using Generics, it is possible to construct classes that function with diverse data types.
Example
class Test<T> {
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}
class Main {
public static void main(String[] args)
{
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());
Test<String> sObj
= new Test<String>(“GeeksForGeeks”);
System.out.println(sObj.getObject());
}
}
Conclusion
Your Java interview preparation will be greatly simplified by this extensive list of 40 important core Java interview questions and answers. You can confidently answer a variety of technical inquiries if you comprehend these foundational ideas. Get hands-on exposure with our core Java training in Chennai.