Core Java - Interview Questions
Core Java - Interview Questions
1 Java Introduction Java History, Java Features, Java Editions, Difference between C, C++ and Java
Types of Applications, JDK ,JRE, JVM, JIT,
JVM & First Java
2 Program JVM Architecture,Writing, Saving, Compilation and Execution of a Java Program
Understanding Object
3 Class Methods in Object Class
Methods in Object Class
Naming Conventions,
4 Java Method Rules followed for a Java Identifier,Understanding Seperators
Returning a value from a Java Method Syntax, Zero Parameters Method, Methods with Parameters, Method
5 method Returns Void, Method Returns Value
6 Java main() Understanding syntax of java main(),Command Line Arguments, Varargs
Understanding syntax of java main()
7 Data Types Primitive Data Types, Reference Types, Java Language Keywords.
Single Line Comments, Multiple Line Comments, Instance Variable, Static Variable,
Comments, Variables
8 Local Variable.
9 Constructor What is a Constructor, Types of Constructors
Rules for a Constructor, Constructor Vs Method
Coding programs on Constructors
10 Operators Increment & Decrement Operators
Arithmetic Operators, Relational Operators, Logical Operators, Negation Operator ,
Assignment Operator, Bitwise Operators
Understanding Instance
11 Members Instance Variable Vs Static Variables, Instance Method, Instance Block Vs Static Block
Understanding static A) Static Variable, Static Method, Static Method Vs Instance Method, Static Block
12 Keyword B) Logical Programs
What is Type Casting, Types of Type Casting, Implicit Type Casting, Explicit Type
Type Casting
13 Casting,Upcasting, Downcasting
What is the use of Wrapper Classes, List of Wrapper Classes, Wrapper Class Methods,
Wrapper Classes
14 Auto-Boxing, Auto-Unboxing
15 Control Statements Selection Statements (if, if-else, if-else-if, switch)
Logical programs on (if, if-else, if-else-if)
Understanding switch case
Iteration Statements (while, do-while, for, for-each)
Understanding for loop
Logical programs on for loop
Understanding for-each loop & Jump Statements (break, continue, return)
16 Scanner Class Understanding Scanner Class and its methods
Need of Packages, Structure of a package, Built-in Packages, Package naming rules,
Packages in Java
17 How to access package from another package
18 Access Modifiers Class Level Access Modifiers, Member Level Access Modifiers
Understanding 'this'
19 Keyword Uses of this keyword
20 Arrays How to declare an Array, How to Instantiate an array, Rules for Array Instantiation,
How to access an array element, length Vs length(), Multidimensional Array
Logical Programming on Arrays
21 Strings Why Strings are Immutable, SCP
String Class Methods
String Vs StringBuffer, StringBuffer Vs StringBuilder, String Vs StringBuffer Vs
StringBuilder, String Buffer and String Builder Class Methods
NARESHIT pg. 1
Core Java Interview Questions
NARESHIT pg. 2
Core Java Interview Questions
Nested Inner Class, Static Inner Class, Method Local Inner Class, Anonymous Inner
34 Inner Classes Class
35 Enum Enum inside a Class, Enum in a Switch, Iteration Through an Enum,
NARESHIT pg. 3
Core Java Interview Questions
1. JAVA INTRODUCTION
1. History of Java
1) Who developed Java, and in which year?
2) What was Java originally called, and why was it renamed?
3) Why was Java developed?
4) Which company currently owns Java?
5) In which year was Java first released publicly?
6) What is the significance of the Java 1.0 release?
7) How has Java evolved from JDK 1.0 to the latest version?
8) What is the difference between Java SE, EE, and ME in terms of release history?
9) Why is Java called a platform-independent language?
10) What made Java more popular than other languages during its early release?
2. Features of Java
1) List and explain the main features of Java.
2) What does “Platform Independent” mean in Java?
3) What is meant by “Object-Oriented” in Java?
4) What is the importance of “Robustness” in Java?
5) What makes Java “Secure”?
6) Explain the feature “Portable” in Java.
7) How does Java achieve “Multithreading”?
8) What is “Dynamic” in Java?
9) Explain “Distributed” and how Java supports distributed systems.
10) How does Java achieve “Architecture Neutrality”?
11) What does “Compiled and Interpreted” mean in Java?
12) How does automatic garbage collection contribute to reliability?
13) What is bytecode, and why is it important?
14) Why is Java often called “Write Once, Run Anywhere”?
15) How do features like JIT improve Java’s performance?
3. Java Editions
1) What are the different editions of Java?
2) What is Java SE used for?
NARESHIT pg. 4
Core Java Interview Questions
NARESHIT pg. 5
Core Java Interview Questions
NARESHIT pg. 6
Core Java Interview Questions
which Loads and executes the class file. Below is a diagram of the Architecture of the JVM.
NARESHIT pg. 7
Core Java Interview Questions
------------------------------------------------------------------------------
NARESHIT pg. 8
Core Java Interview Questions
{
public static void main(String [] args)
{
[Link]("Welcome to Java!");
}
}
Step 3: Compilation
Compile the program using the javac command.
javac [Link]
Step 4: Execution
Run the program using the java command.
java HelloWorld
Output: Welcome to Java!
NARESHIT pg. 9
Core Java Interview Questions
------------------------------------------------------------------------------
3. OBJECT CLASS
Interview Questions
1) What is Object Class in Java?
2) What is the superclass of all Java classes?
3) Is it necessary to extend Object class explicitly?
4) How many methods does the Object class have?
5) Can we override methods of the Object class?
6) Which methods are declared as final in the Object class?
7) What is the difference between == and equals()?
8) Why should we override hashCode() when we override equals()?
NARESHIT pg. 10
Core Java Interview Questions
------------------------------------------------------------------------------
4. IDENTIFIERS
Interview Questions
1) What is an identifier in Java? Why do we use identifiers in Java?
2) What are the rules for creating identifiers in Java?
NARESHIT pg. 11
Core Java Interview Questions
keywords
Interview Questions
1) What is a keyword in Java?
2) How many keywords are available in Java?
3) Are Java keywords case-sensitive?
4) Why are keywords reserved in Java?
5) Can keywords be used as identifiers? Why not?
6) What is the use of static keyword?
7) What is the use of final keyword? What happen when we declare a variable, method, class as final?
8) What does the super keyword do in Java?
9) What is the role of this keyword?
10) What is the difference between this and super?
11) What is the purpose of the new keyword?
12) Why do we use the return keyword?
13) What are break and continue keywords?
14) What is the use of void keyword?
15) Explain public, private, protected keywords.
16) What is the difference between abstract and final keywords?
17) What is the role of the extends keyword?
18) What is the use of implements keyword?
19) What is the use of package keyword?
20) What is the difference between import and package?
21) What is the purpose of instanceof keyword?
22) Explain the use of interface keyword.
NARESHIT pg. 12
Core Java Interview Questions
------------------------------------------------------------------------------
Non-Parameterized Methods
NARESHIT pg. 13
Core Java Interview Questions
Interview Questions
1) Explain the purpose of non-parameterized methods in Java. When would you prefer using them?
2) Can a non-parameterized method return different data types? Demonstrate with examples.
3) Can a non-parameterized method access instance variables and static variables? Explain.
4) Can a non-parameterized method call another method that has parameters? Explain with an example.
5) What happens if you call a non-parameterized instance method before creating an object?
Programs
1) Write a non-parameterized method that returns your name.
2) Write a non-parameterized method that returns the current year.
3) Write a non-parameterized method that calculates and returns the square of 5.
4) Write a non-parameterized method that prints a welcome message.
5) Write a non-parameterized method that returns a greeting message based on a predefined variable.
NARESHIT pg. 14
Core Java Interview Questions
3) When should you use a void method instead of a method that returns a value?
4) Can a void method call another method that returns a value? Explain how.
5) What are the advantages and limitations of using void methods in Java?
Programs
1) Write a void method that prints “Hello, World!” to the console.
2) Write a void method that accepts a name as a parameter and prints a personalized greeting message.
3) Write a void method that prints numbers from 1 to 10 using a loop.
4) Write a void method that accepts an array of integers and prints all its elements.
5) Write a void method that performs a calculation but does not return the result.
2) How is the return type of a method declared, and why must it match the returned value?
3) Can a method return different types of values based on conditions? Explain with example.
4) What happens if the return statement in a method is missing or mismatched with the declared return type?
5) What are covariant return types in Java, and how are they used in method overriding?
Programs
1) Write a method that returns the factorial of a given number.
2) Write a method that checks if a number is prime and returns a boolean value.
3) Write a method that takes a string and returns it in reverse order.
4) Write a method that returns the area of a circle given its radius.
5) Write a method that returns the average of two numbers.
2) What types of values can a method return in Java, and how are they used in factory methods?
3) What happens if a non-void method does not return a value? Explain with an example.
4) What is the difference between returning a primitive type and returning an object in Java?
5) What are covariant return types in Java, and how are they applied in factory method implementations?
6) How do return types enable polymorphism in Java, particularly in the context of factory methods?
Programs
NARESHIT pg. 15
Core Java Interview Questions
1) Write a factory method that returns an object based on the input type (e.g., Car, Bike).
2) Write a factory method that creates and returns different shapes (Circle, Rectangle) based on user input.
3) Write a factory method that returns an instance of a subclass depending on a condition.
4) Write a program demonstrating covariant return types using a base class and a subclass.
5) Write a factory method that returns null when no matching object type is found.
NARESHIT pg. 16
Core Java Interview Questions
}
Q: What will happen if you remove () from displayMessage while calling it?
Q: Can you overload the displayMessage() method?
NARESHIT pg. 17
Core Java Interview Questions
}
}
Q: What happens if you try to store the result like int s = printSum(10, 5);?
NARESHIT pg. 18
Core Java Interview Questions
}
public static double add(double a, double b)
{
return a + b;
}
}
Q: What will be the output?
Q: How does Java determine which add() method to call?
8. Return vs Print
Question:
public class Difference
{
public static void main(String[] args)
{
[Link](printMessage());
}
public static String printMessage()
{
[Link]("Inside Method");
return "Returned Value";
}
}
NARESHIT pg. 19
Core Java Interview Questions
NARESHIT pg. 20
Core Java Interview Questions
NARESHIT pg. 21
Core Java Interview Questions
@Override
Child show()
{
[Link]("Child show()");
return this;
}
}
------------------------------------------------------------------------------
6. Java main()
Interview Questions
1. What is the signature of the main() method in Java?
2. Why is main() declared as public static void ?
3. Can we overload the main() method? If yes, how does Java determine which main() to call?
4. Can the main() method be private or protected?
5. Explain what happens when a Java program does not contain a main() method?
6. Explain why main() must be static?Can we change the order of keywords like static, public?
7. Can we have multiple main() methods in different classes?
8. Can main() throw exceptions? If yes, which types?
NARESHIT pg. 22
Core Java Interview Questions
Varargs in java
Interview Questions
1. What are varargs in Java?
2. How do varargs differ from arrays?
3. Can a method have multiple varargs parameters?
NARESHIT pg. 23
Core Java Interview Questions
------------------------------------------------------------------------------
7. DATATYPES
Interview Questions
1. What is a datatype in Java, and why do we need it for every variable?
2. What are the main types of datatypes in Java? Give examples.
3. What is a primitive datatype? Why do we use primitive datatypes?
4. List all primitive datatypes in Java. What kind of values do they store?
5. What is the size, default value, and range of each primitive datatype?
6. What is a reference datatype? Give examples.
7. Can primitive datatypes hold null? Can reference datatypes hold null?
8. What is the difference between primitive and reference datatypes?
9. Can a variable be declared without assigning a value? What happens if you try to use it?
10. Can primitive datatypes be declared inside constructors, static blocks, instance blocks, or non-static
methods? Explain.
11. If you declare all primitive datatypes inside a method and try to print them without initialization, what
happens?
12. What happens if you declare a primitive variable with a value larger than its range? Give an example.
13. If you declare a variable with a primitive types, what does JVM do internally? How much memory is
allocated?
14. Where are primitive variables stored in memory?
NARESHIT pg. 24
Core Java Interview Questions
Code Snippets :
public class Test1
{
public static void main(String[] args)
{
byte b = 10;
short s = 100;
int i = 1000;
long l = 10000L;
float f = 10.5f;
double d = 20.5;
char c = 'A';
boolean bool = true;
[Link](b + " " + s + " " + i + " " + l + " " + f + " " + d + " " + c + " " + bool);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test2
{
public static void main(String[] args)
{
String s = null;
[Link](s);
}
NARESHIT pg. 25
Core Java Interview Questions
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test3
{
static int x;
public static void main(String[] args)
{
[Link](x);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test4
{
static String str;
public static void main(String[] args)
{
[Link](str);
}
}
----------------------------------------------------------------------------------------------------------------------------------
NARESHIT pg. 26
Core Java Interview Questions
static int x;
static
{
x = 100;
[Link](x);
}
public static void main(String[] args) {}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test7
{
int a;
{
a = 10;
[Link](a);
}
Test7()
{
[Link](a);
}
public static void main(String[] args)
{
new Test7();
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test8
{
static int i=10;
public static void main(String[] args)
{
int i;
[Link](i);
NARESHIT pg. 27
Core Java Interview Questions
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test9
{
public static void main(String[] args)
{
byte b = 127;
b += 1;
[Link](b);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test10
{
public static void main(String[] args)
{
int i = 130;
byte b = (byte)i;
[Link](b);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test11
{
public static void main(String[] args)
{
byte b1 = 10;
byte b2 = 20;
int result = b1 + b2;
[Link](result);
}
}
NARESHIT pg. 28
Core Java Interview Questions
----------------------------------------------------------------------------------------------------------------------------------
public class Test12
{
public static void main(String[] args)
{
int i = 10;
double d = 5.5;
[Link](i + d);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test14
{
public static void main(String[] args)
{
String a = "Hello";
String b = a;
b = "World";
[Link](b);
}
}
----------------------------------------------------------------------------------------------------------------------------------
class Person {
String name;
}
public class Test16
{
public static void main(String[] args)
{
Person p1 = new Person();
[Link] = "NIT";
Person p2 = p1;
[Link] = "TECH";
NARESHIT pg. 29
Core Java Interview Questions
[Link]([Link]);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test17 {
public static void main(String[] args) {
Integer a = 10;
int b = 5;
[Link](a + b);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test18
{
public static void main(String[] args)
{
char c = 'Z';
int i = c;
[Link](i);
}
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test19
{
public static void main(String[] args)
{
Integer a = 100;
Integer b = 100;
Integer x = 200;
Integer y = 200;
[Link](a == b);
[Link](x == y);
}
NARESHIT pg. 30
Core Java Interview Questions
}
----------------------------------------------------------------------------------------------------------------------------------
public class Test20
{
public static void main(String[] args)
{
Integer a = null;
int b=a;
[Link](b);
}
}
------------------------------------------------------------------------------
8. COMMENTS IN JAVA
Interview Questions
1. What are the types of comments in Java?
2. Difference between single-line and multi-line comments.
3. Can comments be nested?
4. Are comments compiled into bytecode?
5. What is the purpose of comments in coding standards or documentation?
Variables in Java (Instance, Static, Local)
Interview Questions
1. What are the types of variables in Java?
2. Difference between instance, static, and local variables.
3. Can we declare variables inside a method as static?
4. Scope and lifetime of instance variables, static variable, local variables?
5. How are static variables shared among objects?
6. Default values of instance, static, and local variables.?
7. Can a variable shadow another variable?
8. How do instance, static variables, differ from local variables in memory allocation?
9. What is the difference between class-level and object-level variables?
NARESHIT pg. 31
Core Java Interview Questions
10. What happens if we try to access a local variable in Java without initializing it?
Programs:
1. Write a program to demonstrate the difference between instance and static variables.
2. Show how modifying a static variable affects all objects of a class.
3. Write a method to demonstrate local variable scope.
4. Create a program where variable shadowing occurs and explain the output.
5. Write a program to count the number of objects created using a static variable?
6. Predict the output: program using local variables inside loops and methods.
7. write a program demonstrating instance variable initialization and default values.
8. Create a program to show that local variables must be initialized before use.
------------------------------------------------------------------------------
9. CONSTRUCTOR
Interview Questions
1) What is constructor in java? What is the use of constructors?
2) What are the different types of constructors?
3) When a constructor is executed?
4) What happens when we did not provide any constructor? How object is created?
5) What is the use of the this() keyword in a constructor?
6) What is the use of the super() keyword in a constructor?
7) What is constructor overloading? can we overload a constructor?
8) Is it possible to override a constructor? What happens when we override a constructor?
9) What is constructor chaining?
10) Can a constructor be private? If yes, why do we use it?
11) Can an abstract class have a constructor?
12) Can an interface have a constructor?
13) Can a constructor be static or abstract? Why or why not?
14) Can a constructor be final?
15) What is a copy constructor in Java?
16) What is the difference between a method and a constructor?
17) Can we use final variables in constructors?
NARESHIT pg. 32
Core Java Interview Questions
Programs:
Parameterized Constructor Example
class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}
void display()
{
[Link](id + " " + name);
}
public static void main(String[] args)
{
Student s1 = new Student(1, "Ram");
Student s2 = new Student(2, "Krishna");
[Link]();
[Link]();
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
Constructor Overloading
class Demo {
Demo() {
[Link]("No-Arg Constructor");
}
Demo(int x)
{
[Link]("Parameterized Constructor: " + x);
}
NARESHIT pg. 33
Core Java Interview Questions
Demo(int x, String y)
{
[Link]("Two-Arg Constructor: " + x + ", " + y);
}
public static void main(String[] args)
{
new Demo();
new Demo(10);
new Demo(20, "Hello");
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
Copy Constructor Example
class Employee
{
String name;
int salary;
Employee(String n, int s)
{
name = n;
salary = s;
}
Employee(Employee e) { // Copy constructor
name = [Link];
salary = [Link];
}
void show() {
[Link](name + " " + salary);
}
public static void main(String[] args) {
Employee e1 = new Employee("Raju", 25000);
Employee e2 = new Employee(e1);
[Link]();
[Link]();
}
}
NARESHIT pg. 34
Core Java Interview Questions
----------------------------------------------------------------------------------------------------------------------------------------------
Constructor Chaining using this()
class Car {
Car() {
this("BMW"); // calling parameterized constructor
[Link]("Default constructor");
}
Car(String model) {
[Link]("Car model: " + model);
}
public static void main(String[] args) {
new Car();
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
Inheritance Constructor Chaining using super()
class A {
A() {
[Link]("Parent Constructor");
}
}
class B extends A {
B() {
super(); // calls Parent constructor
[Link]("Child Constructor");
}
public static void main(String[] args)
{
new B();
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
Private Constructor (Singleton Pattern)
class Singleton
{
private static Singleton instance = new Singleton();
NARESHIT pg. 35
Core Java Interview Questions
private Singleton() {
[Link]("Private Constructor");
}
public static Singleton getInstance() {
return instance;
}
public static void main(String[] args) {
Singleton s = [Link]();
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
Constructor in Abstract Class
abstract class Animal {
Animal() {
[Link]("Animal Constructor");
}
}
class Dog extends Animal {
Dog() {
[Link]("Dog Constructor");
}
public static void main(String[] args) {
new Dog();
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
Constructor +Non- Static Block Order Program
class Order {
{
[Link]("Non-Static Block")
}
Order() {
[Link]("Constructor");
}
public static void main(String[] args) {
new Order();
NARESHIT pg. 36
Core Java Interview Questions
new Order();
}
}
------------------------------------------------------------------------------
10. OPERATORS
++ (increment), -- (decrement)
Interview Questions
[Link](b);
NARESHIT pg. 37
Core Java Interview Questions
2. ARITHMETIC OPERATORS
Interview Questions
2)What happens when we divide numbers of different types in Java (int and float)?
For example:
int / int
float / int
int / float
float / float
3)What happens when you divide by zero using integer division?
Programs
[Link](a / b);
[Link](a % b);
NARESHIT pg. 38
Core Java Interview Questions
[Link](a / b);
[Link](a % b);
[Link](a * b - a / b + b);
x = x * (x + 2) / (x - 3);
[Link](x);
3. RELATIONAL OPERATORS
Interview Questions
1. Write a program to compare two numbers and print the larger one.
2. Predict the output:
[Link]('A' < 'a');
3. What values will be printed?
int a = 10, b = 20, c = 10;
[Link](a == b);
NARESHIT pg. 39
Core Java Interview Questions
[Link](a != c);
[Link](5 == 5.0);
4. LOGICAL OPERATORS
Interview Questions
[Link](x);
NARESHIT pg. 40
Core Java Interview Questions
5. NEGATION OPERATOR
Interview Questions:
[Link](!flag);
[Link](!!flag);
6. ASSIGNMENT OPERATOR
Interview Questions
NARESHIT pg. 41
Core Java Interview Questions
int x = 5;
x += 3 * 2;
[Link](x);
a = b = c = 10;
[Link](a + b + c);
7. BITWISE OPERATORS
Interview Questions
[Link](a | b);
[Link](a ^ b);
NARESHIT pg. 42
Core Java Interview Questions
8. BOOLEAN OPERATOR
Interview Questions
[Link](result);
a = !a || false;
[Link](a);
9. TERNARY OPERATOR
Interview Questions
1. Write a program to find the maximum of two numbers using a ternary operator.
2. Write a program to check if a number is even or odd using ternary operator.
NARESHIT pg. 43
Core Java Interview Questions
[Link](max);
[Link](result);
Interview Questions
1. Write a simple class and use the dot operator to access its members.
2. Which members are accessed using the dot operator?
Class Student {
int id = 1;
void show() {
[Link](“ID: “ + id);
NARESHIT pg. 44
Core Java Interview Questions
[Link]();
[Link]([Link]);
Interview Questions
Demo() {
[Link]("Object Created");
NARESHIT pg. 45
Core Java Interview Questions
Interview Questions
1. Write a program to check whether an object belongs to a given class using instanceof.
2. What will be printed? Why is instanceof used?
class Animal {}
------------------------------------------------------------------------------
NARESHIT pg. 46
Core Java Interview Questions
1) non-static variable
Interview Questions
1) What is a non-static variable in Java?
2) Where are non-static variables stored in memory?
3) When are non-static variables created and destroyed?
4) Can non-static variables be accessed without creating an object? Why or why not?
5) Can we use ‘this’ keyword with static variables? Why or why not?
6) What is the default value of a non-static variable if not initialized?
7) If we modify a non-static variable using one object, will that affect another object?
8) What is [Link], and how can we handle it?
9) Can we print an object directly? Explain toString() method.
10) Difference between memory locations of static and non-static variables.
Programs :
1) Can a static method directly access a non-static variable? Explain with an example.
2) Create a class with one static and one non-static variable. Print their values after creating multiple objects
to show the difference in behavior.
3) Demonstrate the use of the this keyword to initialize non-static variables through a constructor.
4) What happens if you try to use the this keyword inside a static method? Explain with code.
5) Create a program where both static and non-static variables are incremented in a method, and analyze the
final values.
2) non-static Method
Interview Questions
1) What is a non-static method in Java, and how is it different from a static method?
2) When and how can a non-static method be invoked?
3) Can a non-static method access static variables and methods? Why or why not?
4) Can a static method call a non-static method directly? Explain with reason.
5) How does memory allocation differ for static and non-static methods in the JVM?
6) Can we use the this keyword inside a non-static method? Why?
NARESHIT pg. 47
Core Java Interview Questions
Programs :
1) Write a program to show that a static method cannot call a non-static method directly (and how to fix it).
2) Create a class with both static and non-static methods. Access both using an object reference and observe
the behavior.
3) Write a program to demonstrate the use of the this keyword inside a non-static method.
4) Create a parent and child class where the child overrides a non-static method from the parent. Show
method overriding in action.
5) Write a program that tries to call a non-static method using a null reference and observe what happens.
3) non-static Block
Interview Questions
1) What is a non-static (instance) block in Java, and when is it executed?
2) How is a non-static block different from a static block?
3) When is a non-static block executed in relation to the constructor?
4) Can we have multiple non-static blocks in the same class? If yes, in what order do they execute?
5) Can a non-static block access static and non-static variables? Explain.
6) Can a non-static block call methods (both static and non-static)?
7) What happens if both a parent and child class have non-static blocks? In which order are they executed
during object creation?
8) Can we use the this keyword inside a non-static block? Why or why not?
9) Can a non-static block throw exceptions or use try–catch?
10) What is the real purpose of using non-static blocks in Java programs (practical use cases)?
Programs
1) Write a simple program with one non-static block and a constructor to show the order of execution.
2) Write a program that shows the difference between static and non-static blocks during class loading and
object creation.
3) Create a non-static block that initializes instance variables before the constructor executes.
NARESHIT pg. 48
Core Java Interview Questions
4) Demonstrate how non-static blocks are executed in an inheritance hierarchy (both parent and child having
blocks).
5) Write a program combining static blocks, non-static blocks, constructors, and methods to show their
complete execution flow.
------------------------------------------------------------------------------
Interview Questions
2. Static Method
Interview Questions
NARESHIT pg. 49
Core Java Interview Questions
Interview Questions
4. Static Block
Interview Questions
NARESHIT pg. 50
Core Java Interview Questions
Interview Questions:
NARESHIT pg. 51
Core Java Interview Questions
1. Program to show the execution sequence of static block, main method, and constructor
2. Create a utility class using only static methods and variables.
3. Static method returning object of its class.
4. Count total login attempts using static variable and method.
5. Program to show static variable shared across objects but instance variable not.
6. Program to demonstrate static block execution order in inheritance.
------------------------------------------------------------------------------
NARESHIT pg. 52
Core Java Interview Questions
int x = 20;
static
int x=10;
Static
NARESHIT pg. 53
Core Java Interview Questions
int a ;
[Link](x);
5. Define a class having one static variable say static int x=10 and invoke x variable in m1() and main(-)
what is the output?
public class Test5
void m1()
[Link]("m1 X :"+x);
NARESHIT pg. 54
Core Java Interview Questions
[Link]("main X :"+x);
6. Is it possible to access non-static variable in static method directly if not what is the error?
public class Test6
int a = 10;
7. What are the different ways are there to call static variables?
public class Test7
//static variable a
8. What are the different ways to call/invoke static methods from main method.
public class Test8
NARESHIT pg. 55
Core Java Interview Questions
[Link]("Test9 : m1()");
[Link]("Test9 : m2()");
m1();
m2();
NARESHIT pg. 56
Core Java Interview Questions
static {
[Link]("SB1");
[Link]("m1()");
Test10.m1();
static {
[Link]("X: "+x);
[Link]("Y: "+y);
[Link]("X: "+x);
[Link]("Y: "+y);
NARESHIT pg. 57
Core Java Interview Questions
m1();
static {
[Link]("X: "+x);
[Link]("Y: "+y);
12. Can we call static method inside static block if yes, what is the output?
public class Test12 {
static {
m1();
//no operation
13. Is main method mandatory to execute java program if yes, what is the error?
public class Test13 {
static {
NARESHIT pg. 58
Core Java Interview Questions
static {
[Link]("X :"+x);
[Link](0);
int x = 10;
[Link]("Test15Super : m1()");
static {
NARESHIT pg. 59
Core Java Interview Questions
static {
m1();
[Link]("Test15Sub : m2()");
m2();
int x = 10;
//non-static block
[Link]("X: "+x);
[Link]("A: "+a);
//static block
static {
NARESHIT pg. 60
Core Java Interview Questions
[Link]("X: "+x);
[Link]("A: "+a);
//main method
//no operation
[Link]("Test17Super : m2()");
[Link]("Test17Sub : m1()");
[Link]("Test17Sub : m2()");
Test17Sub.m1();
NARESHIT pg. 61
Core Java Interview Questions
[Link]("A: "+a);
[Link]("t1.A: "+t1.a);
[Link]("t2.A: "+t2.a);
t1.a=30;
[Link]("t1.A: "+t1.a);
[Link]("t2.A: "+t2.a);
t2.a=40;
[Link]("t1.A: "+t1.a);
[Link]("t2.A: "+t2.a);
int x = 10;
[Link]("Test19:NSB1");
void m1() {
NARESHIT pg. 62
Core Java Interview Questions
[Link]("Test19:m1()");
//no operation
static {
x = 200;
[Link]("SB X: "+x);
x = 300;
[Link]("m1 X:"+x);
[Link]("mian X: "+x);
NARESHIT pg. 63
Core Java Interview Questions
[Link]("Test21:m2() called");
return 10;
[Link]("Test21:m1() called");
return 20;
[Link]("X: "+x);
[Link]("Test22:m2() called");
return 10;
static int x;
[Link]("Test22:m1() called");
return 20;
NARESHIT pg. 64
Core Java Interview Questions
[Link]("X: "+x);
static {
[Link]("SB1 X: "+x);
static {
x=20;
[Link]("SB2 X:"+x);
// no-operation
static {
[Link]("SB1: "+Test24.a);
[Link]("SB1: "+a);
NARESHIT pg. 65
Core Java Interview Questions
static {
[Link]("SB2: "+Test24.b);
[Link]("A: "+a);
[Link]("B: "+b);
[Link]("Welcome To Java");
//empty….
//empty…
NARESHIT pg. 66
Core Java Interview Questions
static {
[Link]("Static Block....");
[Link]("Main Method....");
[Link]("Main Method....");
static {
[Link]("Static Block...");
static {
[Link]("Static Block1...");
NARESHIT pg. 67
Core Java Interview Questions
[Link]("Main Method....");
static {
[Link]("Static Block2...");
[Link]("Main Method...");
[Link]();
NARESHIT pg. 68
Core Java Interview Questions
Example9.m1();
static {
Example9.m1();
[Link]("Control in m1 method");
[Link]("Callig m2 method");
NARESHIT pg. 69
Core Java Interview Questions
Example10.m2();
[Link]("Control in m2 method");
[Link]("Calling m1 method");
Example10.m1();
static {
[Link]("Calling m1 method");
Example10.m1();
int a;
[Link](a);
NARESHIT pg. 70
Core Java Interview Questions
a=10;
[Link](a);
static {
int x=10;
[Link](x);
[Link](x);
static {
[Link]("Static Block");
[Link](Example13.a);
[Link]("Main Method");
NARESHIT pg. 71
Core Java Interview Questions
[Link](a);
[Link](Example14.x);
[Link](x);
int x=200;
[Link](Example15.x);
[Link](x);
NARESHIT pg. 72
Core Java Interview Questions
int x = 60;
Example16.x = Example16.x + x;
[Link](Example16.x);
[Link](x);
static {
int a = 10;
Example17.a = Example17.a + a;
static {
int a = 50;
Example18.a = Example18.a+a;
NARESHIT pg. 73
Core Java Interview Questions
a = a+Example18.a;
Example18.a=a+a;
static {
int x=10;
Example19.x = x + x;
static int x;
static {
x = x + Example19.x;
static int a;
NARESHIT pg. 74
Core Java Interview Questions
[Link](Example20.a);
Example20.a = [Link]();
[Link](Example20.a);
Example20.a = 50;
return 60;
[Link](Example21.x);
Example21.x=10;
return Example21.m2();
[Link](Example21.x);
return 20;
NARESHIT pg. 75
Core Java Interview Questions
[Link](Example22.m1() + Example22.x);
return Example22.x;
[Link](Example23.x);
static {
[Link](x);
Example23.x = x+20;
Example23.x = 50;
return m2();
NARESHIT pg. 76
Core Java Interview Questions
[Link](Example23.x);
return 100;
static {
Example24.a = m1();
[Link](a);
static {
Example24.a = 30;
return m2();
NARESHIT pg. 77
Core Java Interview Questions
[Link](a);
int a = 60;
a = a;
[Link](a);
[Link](Example25.a);
int x=20;
[Link](x);
static {
int x=10;
[Link](x+" ");
NARESHIT pg. 78
Core Java Interview Questions
int x = 10;
[Link](x);
static {
[Link](x+” “);
int x = 10;
[Link](t1.x);
static {
int x=20;
[Link](x+" ");
NARESHIT pg. 79
Core Java Interview Questions
int x = 10;
[Link](Test53.x);
static {
int x = 20;
[Link](x+" ");
t1.x = 20;
[Link](t1.x+" ");
[Link](t2.x);
NARESHIT pg. 80
Core Java Interview Questions
static int i = 1;
i=i+2;
[Link](i+" ");
static int i = 1;
int i = 1;
i=i+2;
[Link](i+" ");
NARESHIT pg. 81
Core Java Interview Questions
static int i = 1;
static int i = 1;
i=i+2;
[Link](i+" ");
int ptr[];
ptr=arr1;
arr1=arr2;
arr2=ptr;
[Link]([Link]+" ");
[Link]([Link]);
NARESHIT pg. 82
Core Java Interview Questions
static int x;
public MyClass() {
method();
method2();
x+=3;
MyClass.x = MyClass.x-2;
x+=5;
this.x = x*x+2;
[Link](mc2.x+"-"+mc3.x);
NARESHIT pg. 83
Core Java Interview Questions
s1.a=20;
welcome();
void welcome() {
[Link]("Welcome to java");
[Link]("Welcome to java");
NARESHIT pg. 84
Core Java Interview Questions
------------------------------------------------------------------------------
Interview Questions
1. What is typecasting in Java, and why is it used?
2. Explain the difference between widening (implicit) and narrowing (explicit) typecasting, with examples.
3. Can a double be stored in an int variable? How? What happens if the value exceeds the int range?
4. What is type promotion in Java, and how does it work when different data types are used together?
5. Can an int be cast to a byte? What happens if the value is too large?
6. What is upcasting in Java? Provide an example with parent and child classes.
7. What is downcasting in Java? Why is it considered risky? How can it be done safely?
8. What is a ClassCastException? Give an example scenario.
9. Can Object references be cast to their actual object type? Show an example.
10. Can interface references be upcast to their implementation class? Explain.
11. How does upcasting affect overridden methods in Java?
12. What happens when you cast a double to a float?
13. Can null references be safely downcast? Explain.
14. Can boolean be cast to int? Why or why not?
15. Can you assign a child class object to a parent class reference? What are the rules?
16. How does typecasting affect memory allocation and storage for primitives vs reference types?
Code Snippets
1)
public class Test1 {
public static void main(String[] args) {
int i = 100;
double d = i;
[Link](d);
}
NARESHIT pg. 85
Core Java Interview Questions
2)
public class Test2 {
public static void main(String[] args) {
double d = 99.99;
int i = (int)d;
[Link](i);
}
}
3)
public class Test3 {
public static void main(String[] args) {
char c = 'A';
int i = c;
[Link](i);
}
}
4)
public class Test4 {
public static void main(String[] args) {
int i = 130;
byte b = (byte)i;
[Link](b);
}
}
5)
class Parent {}
class Child extends Parent {}
public class Test5 {
NARESHIT pg. 86
Core Java Interview Questions
6)
class Parent1 {}
class Child1 extends Parent1 {}
public class Test6 {
public static void main(String[] args) {
Parent1 p = new Child1();
Child1 c = (Child1)p;
}
}
7)
class Parent2 {}
class Child2 extends Parent2 {}
class Unrelated {}
public class Test7 {
public static void main(String[] args) {
Parent2 p = new Parent2();
// Child2 c = (Child2)p; // ClassCastException
}
}
8)
public class Test8 {
public static void main(String[] args) {
int a = 10;
Integer b = 20;
[Link](a + b);
NARESHIT pg. 87
Core Java Interview Questions
}
}
9)
public class Test10 {
public static void main(String[] args) {
byte b1 = 10;
byte b2 = 20;
byte sum = (byte)(b1 + b2);
[Link](sum)
}
}
10)
public class Test15 {
public static void main(String[] args) {
Object obj = "Hello";
String s = (String)obj;
[Link](s);
}
}
11)
public class Test16 {
public static void main(String[] args) {
Object[] objArr = new String[2];
objArr[0] = "Java";
// objArr[1] = 10; // ArrayStoreException
}
}
12)
class A {}
NARESHIT pg. 88
Core Java Interview Questions
class B extends A {}
public class Test19 {
public static void main(String[] args) {
A a = new A();
// B b = (B)a; // ClassCastException
}
}
------------------------------------------------------------------------------
Interview Questions
1) What is a wrapper class in Java, and why do we need it?
2) List all wrapper classes in Java for each primitive type.
3) How is a wrapper class different from a primitive type? Give examples.
4) Can a wrapper object store null? Give an example.
5) What is autoboxing / unboxing in Java? Diff b/w autoboxing and unboxing?
6) Can we perform arithmetic operations directly on wrapper objects? How does it work?
7) What is the difference between == and .equals() when comparing wrapper objects?
8) How does the caching mechanism work for Integer and Boolean?
9) What happens if you try to unbox a null wrapper object?
10) How does autoboxing affect performance in Java programs?
11) Can we declare wrapper objects as final? What happens if we try to change their value?
12) Can autoboxing occur when passing arguments to a method? Give an example.
13) What is the difference between [Link]() and [Link]()?
14) What is the behavior of null in wrapper comparisons?
15) Can wrapper objects be synchronized for thread safety?
16) Are wrapper objects immutable? How does Java handle immutability for wrappers?
Programs
NARESHIT pg. 89
Core Java Interview Questions
NARESHIT pg. 90
Core Java Interview Questions
import [Link];
public class Test8 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10);
[Link](20);
[Link](list);
}
}
NARESHIT pg. 91
Core Java Interview Questions
------------------------------------------------------------------------------
NARESHIT pg. 92
Core Java Interview Questions
NARESHIT pg. 93
Core Java Interview Questions
Programming Questions
1) Write a program to check Armstrong number (e.g., 153 → 1³+5³+3³=153).
2) How do you check if a number is a Strong Number using loops in Java?
3) How do you check if a number is a Perfect Number using loops in Java?
4) Write a program to find the factorial of a given number using a loop.?
NARESHIT pg. 94
Core Java Interview Questions
------------------------------------------------------------------------------
Interview Questions:
1. What is the Scanner class in Java and Which package contains the Scanner class?
2. How do you create a Scanner object for keyboard input?
3. How do you read a string using Scanner?
NARESHIT pg. 95
Core Java Interview Questions
Programming Questions
1. Sum of N numbers – Read N integers and print their sum.
2. Maximum and Minimum number – Read 5 integers and print the max and min.
3. Average of floating-point numbers – Read N doubles in one line and calculate the average.
4. Reverse a string – Read a line of text and print it reversed.
5. Count words in a sentence – Read a line and count the number of words.
------------------------------------------------------------------------------
Interview Questions
NARESHIT pg. 96
Core Java Interview Questions
Structure of a Package
Interview Questions
1) What is the structure of a Java package?
2) Explain the difference between top-level and sub-packages.
3) What are naming conventions for packages?
4) How does the JVM locate classes inside a package?
5) Explain the difference between .class files in default and user-defined packages.
Built-in Packages
Interview Questions
1) What are built-in packages in Java? Give examples.
2) Explain the difference between [Link] and [Link] packages.
3) Which built-in package is automatically imported in every Java program?
4) Can you use a class from a built-in package without import? Explain.
NARESHIT pg. 97
Core Java Interview Questions
------------------------------------------------------------------------------
NARESHIT pg. 98
Core Java Interview Questions
4. Can a protected method be accessed or overridden in another package? How does inheritance affect this?
5. Can you reduce or increase the visibility of an overridden method (e.g., public → protected)? What
happens if you try to?
6. Can a default/package-private, final, or static method be overridden or hidden in another package?
Explain the difference.
7. Do access modifiers affect method overloading? Can you overload methods with different access levels?
8. Can a private static method be overloaded in the same class? How is it different from overriding?
9. Can an abstract class have a private abstract method? Why or why not? Can you declare a private
synchronized method?
10. Can an interface’s default method be private or protected?
Programming Questions:
1. Write code to prove that a default class cannot be accessed outside its package.
2. Demonstrate that a private constructor restricts object creation outside its class.
3. Write code to show that final methods cannot be overridden.
4. Create a program to show visibility changes in method overriding (protected → public).
5. Demonstrate method hiding using a static method.
6. Create a Singleton class and test multiple instance creation.
NARESHIT pg. 99
Core Java Interview Questions
------------------------------------------------------------------------------
------------------------------------------------------------------------------
20. ARRAYS
------------------------------------------------------------------------------
21. STRINGS
1. Strings
Interview Questions
1. What is a String in Java?
2. How do you create a String object & how many way to create the Strings in java?
3. Difference between: String s1 = "Hello"; & String s2 = new String("Hello");
4. Why are String objects immutable in Java?
5. What is String Constant Pool (SCP)?
6. How does SCP help in memory optimization?
7. What happens when you create two String literals with the same value?
8. How does Java store Strings created using new keyword?
9. How does intern() method work in Strings?
10. Why did Java designers make String immutable? (Security, Caching, Thread-safety, Performance)?
11. What is the advantage of storing Strings in SCP?
12. What happens internally when you modify a String?
13. What is the difference between mutable and immutable objects?
14. What happens if you concatenate Strings using + operator?
15. What is the difference between == and equals() in Strings?
16. What is the difference between compareTo() and equals()?
17. Can String be extended (inheritance)? Why or why not?
18. Difference between substring() and subSequence()?
19. What is StringBuffer class in Java?
20. Is StringBuffer mutable or immutable? Is StringBuffer thread-safe? Why?
21. Difference between append() and insert() methods?
22. What is the default capacity of StringBuffer?
23. How does the capacity of StringBuffer increase dynamically?
24. What is StringBuilder in Java?
25. Difference between StringBuffer and Stringbuilder?
26. Is Stringbuilder thread-safe? Why or why not?
27. When should you use Stringbuilder over StringBuffer?
28. What are common methods in Stringbuilder and StringBuffer?
29. Which one is best for frequent string modification?
30. Which one is best for multithreaded environment and singlethread environment?
31. Difference between length() method and length property of arrays.
32. Difference between isEmpty() and isBlank().
33. Difference between trim() and strip() (introduced in Java 11).
34. Difference between strip(), stripLeading(), and stripTrailing().
35. Difference between indexOf() and lastIndexOf().
36. Difference between split() and join() (breaking vs combining).
37. Difference between valueOf() and toString().
42. Write a function to find the longest common prefix string amongst an array of strings. If there is no
common prefix, return an empty string ""?
43. Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the
characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of
characters. No two characters may map to the same character, but a character may map to itself?
44. Write a program to check if one string can become another by shifting its characters to the right in Java?"
45. You are given a string s. Return the array of unique characters, sorted by highest to lowest occurring
characters?
46. Write a program to Count Number of Substrings in a given String?
47. Given a string s, return the longest palindromic substring in s?
48. Find The beauty of a string is defined as the difference between the frequency of the most
frequent character and the least frequent character (excluding characters that do not appear) in that
string?
49. Validate email format using regex.
50. Validate mobile number using regex.
51. Write a Java program to check whether a given string containing parentheses (), curly braces {}, and
square brackets [] is valid or not?
({[]})valid ([)]invalid
------------------------------------------------------------------------------
Interview Questions
------------------------------------------------------------------------------
23. ENCAPSULATION
Interview Questions
1. What is encapsulation in Java?
2. How is encapsulation different from abstraction?
1) Create a Student class with private fields name, rollNumber, and age.
Provide public getters and setters for all fields.
Write a program to create a Student object, set its details, and print all information using getters
3) Create a Product class with private fields productId, productName, and price.
Ensure price cannot be negative using the setter.
Write a program to create multiple products and display their details.
4) Create an Employee class with private fields name, baseSalary, and bonus.
Write a method calculateTotalSalary() that returns baseSalary + bonus.
Ensure bonus is non-negative using setter validation.
Print total salary of the employee using getter methods.
------------------------------------------------------------------------------
24. INHERITANCE
Interview Questions
1) What is inheritance in Java? Why do we use inheritance?
2) Explain the concept of parent (super) class and child (sub) class in Java. How does inheritance establish
a relationship between them?
Programs
1) Write Java programs to demonstrate single,multilevel,hierarchical and hybrid inheritance.
2)Write a program to access parent class members using super?
3)Write a program to show constructor execution order in inheritance?
4) Write a program showing why multiple inheritance is not supported with classes?
5) Write a program using final class in inheritance?
6) Write a program demonstrating diamond problem using interfaces and show how Java resolves it?
7)Write a program demonstrating composition vs inheritance with a real-life example (e.g., Car HAS-A
Engine vs Car IS-A Vehicle).
8)Write a program to show that final methods cannot be overridden by a subclass. Try to override and show
compiler behavior.
9) Create an abstract class with both abstract and non-abstract methods. Extend it and implement the abstract
methods in the subclass.
------------------------------------------------------------------------------
25. POLYMORPHISM
Interview Questions
1) What is polymorphism in Java?
2) What is the difference between compile-time/early binding/static polymorphism and runtime/late
binding/dynamic polymorphism?
3) How does method overloading achieve compile-time polymorphism?
4) How does method overriding achieve runtime polymorphism?
5) What is dynamic method dispatch in Java, and how does the JVM resolve method calls at runtime?
6) What is method hiding in Java? Why static methods cannot participate in runtime polymorphism?
7) What is the role of @Override annotation?
8) What are the rules to override a method?
9) What is covariant return type?
10) Rules for method overloading in Java?
11) What is upcasting and downcasting? Why is downcasting risky?
Programs
1) Create a class to calculate the area of different shapes using
method overloading:
area(double radius) → Circle
area(double length, double width) → Rectangle
area(double side) → Square
Explain how overloading allows using the same method name for
different shapes.
3) Create classes Animal and Dog. Override sound() in Dog to print “Bark”.
Use Animal a = new Dog() and call sound().
Explain how runtime polymorphism works here.
Subclasses: SBI, HDFC, ICICI → override the method with different rates.
Use a parent reference to call the method for each bank.
Explain runtime polymorphism in real-world context.
------------------------------------------------------------------------------
26. ABSTRACTION
Interview Questions
1) What is abstraction in Java? Explain with a real-world example.
2) How is abstraction different from encapsulation?
3) How can you achieve abstraction in java?
4) What is the difference between an interface and an abstract class (before Java 8 vs after Java 8)?
Programs
1) Build an ATM abstraction:
Abstract class ATM with method process()
Withdraw and Deposit must override process()
Call using parent reference.
6) Write a Java program to demonstrate how interfaces help achieve loose coupling.
------------------------------------------------------------------------------
27. MULTITHREADING
8. What is the difference between extending Thread class and implementing Runnable interface?
------------------------------------------------------------------------------
Interview Questions
1. What is an exception in Java? How is it different from an error?
2. Explain the difference between checked and unchecked (runtime) exceptions with examples. How do
they affect program flow?
3. What is the difference between throw and throws in Java?
4. What happens if a checked exception is not handled or declared? Explain exception propagation in Java?
5. Can a method override another method that throws exceptions? What are the rules regarding checked
exceptions?
6. What is the role of a try block, catch block, and finally block? Does a finally block always execute?
7. When will the finally block not execute?
8. Can a try block exist without a catch block? If yes, under what conditions?
9. What are the rules for catching exceptions in hierarchical order in Java, and how does the multi-catch
feature introduced in Java 7 help simplify exception handling?
10. What happens if an exception occurs inside a catch block?
11. Can constructors throw exceptions? How should be handled ?
12. A single try block can throw multiple exceptions like ArithmeticException and
ArrayIndexOutOfBoundsException. How should be handle with single-catch block?
13. Explain best practices for writing exception-safe code, including the impact of over using try-catch
blocks on performance and maintainability.
14. Consider a situation where a try block executes a return statement, but a finally block is also present that
modifies a variable. Which value is returned? Explain how the finally block affects execution.
15. What is the use of printStackTrace(), getMessage(), and toString()?
16. What is the main advantage of using try-with-resources over a normal try-catch-finally block?
17. What is a custom exception in Java? When should we create a custom exception in real time application?
18. If both the catch block and the finally block throw exceptions, which one will be propagated to the
caller, and why?
19. What is the difference between ClassNotFoundException and NoClassDefFoundError in Java? When
does each of them occur? Explain with suitable examples.
20. What is a ClassCastException in Java? Write a program that demonstrates how this exception occurs
and explain how to prevent it.
Programming Questions
1. Write a program that throws a custom exception if a user enters a negative number for age?.
2. write a program to demonstrate multiple exceptions in a single try block, such as arithmetic exception
and array index out of bounds exception. handle them using separate catch blocks.
3. write a program to demonstrate nested try-catch blocks. include at least one inner try that throws an
exception and show how it is handled.
4. write a program using a finally block. include a return statement in the try block and show what value is
returned when the finally block modifies a variable.
5. write a program to demonstrate the difference between throw and throws. include a method that throws
an exception and another method that declares it using throws.
6. write a program to demonstrate try-with-resources using a file or scanner. show how resources are
automatically closed.
7. write a program to demonstrate exception chaining. create one exception that is caused by another and
show how the original exception can be retrieved using getCause().
------------------------------------------------------------------------------
[Link] Keyword
Interview Questions
1) What is the difference between final, finally, and finalize() in Java?
2) Can we declare a class as final? What does it mean, and what happens if we try to inherit it?
3) Can a final variable be reinitialized? Explain with an example.
4) What is a blank final variable? How can we initialize it (including static ones)?
5) Can we declare a method as final? What does it prevent, and can it be overloaded or overridden?
6) Can you have a final reference variable pointing to a mutable object? What happens if you modify the
contents of that object?
7) How can you make a class immutable using the final keyword?
8) Can a final local variable be used inside an anonymous inner class? Why?
Programs
1) Write a Java program to demonstrate that a final variable cannot be reassigned after initialization.
2) Create a program showing how a blank final variable can be initialized inside a constructor.
3) Write a Java program that defines a static final variable and initializes it using a static block.
4) Write a Java program where a final method is declared in a parent class and show that it cannot be overridden
in the subclass.
5) Write a Java program where a final reference variable refers to a mutable object (like an ArrayList). Modify
the contents and observe the behavior.
6) Create a Java program that defines a final variable in a parent class and accesses it through inheritance.
Show that it cannot be changed by the subclass.
2. Garbage Collector
Interview Questions
1) What is a Garbage Collector in Java?
------------------------------------------------------------------------------
Interview Questions
Serialization
Interview Questions
1) What is serialization in Java?
2) How can you make a class serializable in Java?
3) How can you prevent serialization in a subclass when the parent class implements the Serializable
interface?
4) Can a serialized object be transferred over a network?
5) What is deserialization in Java?
6) What is the purpose of the transient keyword in serialization?
7) What is the difference between the Serializable and Externalizable interfaces?
Coding Questions
1) Write a Java program to serialize an object of a class and save it to a file.
2) Write a Java program to deserialize an object from a file and print its field values.
3) Write a Java program to demonstrate the effect of the transient keyword — serialize and deserialize an
object, showing that transient fields are not saved.
4) Write a Java program where a parent class is serializable but the subclass is prevented from being
serialized.
------------------------------------------------------------------------------
Collection
Interview Questions:
1. What is Collection Framework? advantages of the Collection Framework in Java
2. Describe the Collection hierarchy in Java.
3. List down the primary interfaces provided by Java Collections Framework?
4. Why Collection doesn’t extend the Cloneable and Serializable interfaces?
5. what is Generic Collection?
6. what is the difference between Collection and Array?
List Interface
Interview Questions:
[Link] is the use of the List interface What are the key characteristics of a List in Java?
[Link] a List contain duplicate elements?
[Link] are the main classes that implement the List interface?
4. How does List maintain insertion order?
ArrayList
Interview Questions:
1. What is ArrayList in Java? what are the various methods provided by it?
2. How would you convert an ArrayList to Array and an Array to ArrayList?
3. How does ArrayList work internally in Java, and how does it grow dynamically when elements are
added?
4. what is The Intial capacity of the ArrayList and default capacity of the ArrayList?
5. Can you store null values in an ArrayList?
6. How can you make an ArrayList immutable?
7. Is ArrayList synchronized in Java? If not, how can you make an ArrayList synchronized?
8. What are the real-time use cases of ArrayList in Java, and when should it be used?
9. What are the advantages and disadvantages of Arraylist?
10. How many constructors are present in ArrayList?
LinkedList
Interview Questions:
1. What is a LinkedList in Java, and how many types of linked lists does Java support? Explain with
examples.
[Link] does LinkedList work internally?
3. What data structure is used to implement LinkedList?
[Link] are the advantages and disadvantages of using LinkedList?
[Link] example the when use in real time LinkedList examples?
6. Is LinkedList synchronized in Java? If not, how can you make an LinkedList synchronized?
7. How many constructors are present in LinkedList?
Vectors
Interview Questions:
1. what is a Vector in Java?
2. How does vector work internally ?
3. Why is Vector considered legacy?
4. Vector is a synchronized are not?
5. what is The Intial capacity of the Vector and default capacity of the Vector?
6. Can you store null values in an Vector?
7. How many constructors are present in Vector?
Stack
Interview Questions:
1. What is the Stack class in Java?
2. How is Stack implemented internally?
3. What are the methods of the Stack class (push, pop, peek, etc.)?
4. How many constructors are present in Vector?
Set Interface
Interview Questions:
[Link] is the Set interface in Java Collections Framework?
[Link] does Set not allow duplicate elements?
HashSet
Interview Questions:
1. What is HashSet in Java?
2. How does HashSet ensure uniqueness of elements?
3. Does HashSet maintain insertion order?
4. What is the internal data structure used by HashSet?
5. Can HashSet store null values? If yes, how many?
6. Can HashSet store duplicate values? If not, what happens if we try?
7. Why does HashSet use hashCode() and equals() methods?
LinkedHashset
Interview Questions:
1. What is LinkedHashSet in Java?
2. How does LinkedHashSet differ from HashSet?
3. What internal data structure does LinkedHashSet use?
4. Does LinkedHashSet maintain insertion order?
5. Can LinkedHashSet store null values?
SortedSet
Interview Questions:
1. What is SortedSet in Java?
2. Which class commonly implements SortedSet?
3. Can SortedSet store null values? Why or why not?
4. What methods are introduced in SortedSet that are not in Set?
Treeset
Interview Questions:
1. What is TreeSet in Java?
2. Does TreeSet maintain any specific order? Which order?
Queue Interface
Interview Questions:
1. What is the Queue interface in Java?
2. Does Queue allow null elements? Explain.
3. What are the common Queue implementations?
4. On which principle does a Queue work in Java?
PriorityQueue
Interview Questions:
1. What is PriorityQueue in Java?
2. Which data structure is used internally by PriorityQueue?
3. Does PriorityQueue maintain insertion order?
4. What is the default order used in PriorityQueue?
5. Does PriorityQueue allow null,duplicate elements?
6. How does PriorityQueue differ from Queue?
Deque
Interview Questions:
1. What is a Deque in Java and what does it stand for?
2. How is Deque different from a Queue?
3. What type of data structure behavior does Deque support?
4. Can Deque be used as both a stack and a queue?
5. Does Deque allow duplicate elements?
6. Does Deque allow null values? If not, why?
ArrayDeque
Interview Questions:
1. What is ArrayDeque in Java?
Map Interface
Interview Questions:
1. What is the Map interface in Java?
2. How is Map different from List,Set and Queue ?
3. What are the main implementations of Map?
4. Can Map store duplicate keys or values?
5. What are the commonly used Map methods (put, get, remove, containsKey, containsValue)?
6. Can a Map store null keys and null values? Which implementations allow it?
7. What is the difference between keySet(), values(), and entrySet() methods?
HashMap
Interview Questions:
1. What is HashMap in Java?
2. Which interfaces does HashMap implement?
3. Can HashMap store null keys and null values? How many?
4. Does HashMap allow duplicate keys or duplicate values?
6. Does HashMap maintain insertion order?
7. How do you iterate over a HashMap?
8. How does HashMap store key-value pairs internally?
9. How does HashMap handle collisions?
10. What is the role of hashCode() and equals() in HashMap?
LinkedHashmap
Interview Questions:
1. What is LinkedHashMap in Java?
2. Which interfaces does LinkedHashMap implement?
3. Can LinkedHashMap store null keys and null values? How many?
4. Does LinkedHashMap maintain insertion order or sorted order?
SortedMapInterface
Interview Questions:
1. What is the SortedMap interface in Java?
2. How is SortedMap different from Map?
3. Which class commonly implements SortedMap?
4. Does SortedMap allow null keys or null values?
5. Does SortedMap maintain keys in natural order or insertion order?
6. Can SortedMap store duplicate keys or values?
7. What are the key methods of SortedMap?
8. How does SortedMap maintain keys in sorted order?
9.
TreeMap
Interview Questions:
1. What is TreeMap in Java?
2. Which interfaces does TreeMap implement?
3. Does TreeMap allow null keys or null values?
4. Does TreeMap allow duplicate keys or values?
5. What is the natural ordering used by TreeMap?
6. How do you iterate through a TreeMap?
7. How does TreeMap maintain keys in sorted order internally?
Concurrent Collections
Interview Questions:
1. What are Concurrent Collections in Java?
2. Why do we need concurrent collections when we already have synchronized collections?
3. What is the difference between HashMap and ConcurrentHashMap?
4. What is the difference between [Link]() and ConcurrentHashMap?
5. What is the use of CopyOnWriteArrayList in Java?
6. When should we prefer CopyOnWriteArrayList over ArrayList?
7. How does CopyOnWriteArrayList achieve thread-safety internally?
Differences
Interview Questions:
1. Differentiate between Collection and Collections?
2. Differentiate between Iterable and Iterator?
3. Differentiate between an Array and an ArrayList?
4. Differentiate between ArrayList and LinkedList?
5. Differentiate between Comparable and Comparator?
6. Differentiate between Set and Map?
[Link] between List and Set?
8. Differentiate between List and Map?
9. Differentiate between Queue and Stack?
[Link] between PriorityQueue and TreeSet?
[Link] between the Singly Linked List and Doubly Linked List?
[Link] between Iterator and Enumeration?
[Link] between HashMap and HashTable?
[Link] between HashSet and HashMap?
[Link] between Iterator and ListIterator?
[Link] between HashSet and TreeSet?
[Link] between Queue and Deque?
18. Differentiate between HashMap and TreeMap?
19. Differentiate between ArrayList and Vector?
20. Differentiate between Fail-Fast Iterator and Fail-safe iterator?
21. Differentiate between Iterator and Spliterator?
22. Difference between WeakHashMap and IdentityHashMap?
Programs :
1) Write a Java program to remove duplicate elements from a List.
2) Write a program to iterate a List using for loop, Iterator, and forEach.
3) Write a program to find the maximum and minimum elements in a list of integers.
4) Write a program to sort a list in ascending and descending order.
5) Write a program to reverse a list using [Link]() and manually without using it.
6) Write a program to add, remove, and retrieve elements from both ends of a LinkedList.
7) Write a program to compare insertion and retrieval performance between ArrayList and LinkedList.
8) Write a program to demonstrate synchronization in a Vector.
9) Write a program to iterate through a Vector using Enumeration.
10) Write a program to check if a string has balanced parentheses using a Stack.
11) Write a program to reverse a string using a Stack.
12) Write a program to evaluate a postfix expression using a Stack.
13) Implement a Queue using LinkedList and perform enqueue and dequeue operations.
14) Write a program to find the first non-repeating character in a string using a Queue.
15) Write a program to print elements of a PriorityQueue in natural order.
16) Write a program to use a PriorityQueue with a custom comparator for descending order.
17) Write a program to find the k largest elements in an array using a PriorityQueue.
18) Demonstrate addFirst(), addLast(), removeFirst(), and removeLast() operations in a Deque.
19) Implement a palindrome checker using a Deque.
20) Write a program to remove duplicate elements from a list using a HashSet.
21) Write a program to find union and intersection of two sets.
22) Write a program to maintain insertion order while removing duplicates using a LinkedHashSet.
23) Write a program to store and retrieve elements in sorted order using a TreeSet.
24) Write a program to count the frequency of characters in a string using a HashMap.
25) Write a program to find duplicate elements in an array using a HashMap.
26) Write a program to iterate through a HashMap using entrySet(), keySet(), and values().
27) Write a program to sort a HashMap by keys.
28) Write a program to sort a HashMap by values.
29) Write a program to store elements in sorted key order using a TreeMap.
30) Write a program to use a custom comparator in a TreeMap for descending key order.
31) Write a program to demonstrate thread-safe operations using a Hashtable.
32) Write a program to check how null key and value behave in a Hashtable.
33) Write a program to perform thread-safe operations using a ConcurrentHashMap.
34) Write a program to sort a list of custom objects (like Employee) by name or salary using Comparator.
35) Write a program to find the most frequently occurring element in a list using a Map.
36) Write a program to convert one type of collection to another (e.g., List → Set, Set → Map, etc.).
------------------------------------------------------------------------------
Arrays Class
1. What is the Arrays class in Java?
2. What are the key methods of the Arrays class?
3. What is the difference between [Link]() and == operator and [Link]()?
4. How do you copy an array in Java using Arrays ([Link]())?
5. What does [Link]() do?
6. How do you convert an array to a list using Arrays?
7. What is [Link]() used for?
8. How to convert an array to Stream using [Link]()?
9. How does [Link]() work internally? Can we sort in descending order using [Link]()?What is its
time complexity?
10. What’s the difference between [Link]() and [Link]()?
11. How does [Link]() work? What does [Link]() return if the element is not
found?
12. What happens if I pass a primitive int[] array to [Link]()?
13. What is a [Link]() in Java? How to use it and where to use it ?
Collections Class
1. What is the Collections class in Java?
2. What is the difference between Collection and Collections?
3. What are some important methods of the Collections class?
4. What does [Link]() do? How is [Link]() different from [Link]()?
5. How does [Link]() work?
6. How to find min() and max() using Collections?
7. What does [Link]() do?
8. What does [Link]() do?
9. What is the purpose of [Link]()?
10. How do you make a collection thread-safe? By use [Link]() Collections.
synchronizedSet(),[Link]() ?
11. How do you make a collection read-only (unmodifiable)?
12. What does [Link]() do?
Collectors Class
1. What is Collectors in Java? Is Collectors part of the Collections framework?
2. What are the most commonly used methods of Collectors?
3. Difference between Collections and Collectors?
4. What does [Link](), [Link](), [Link]() do?
5. What happens if duplicate keys occur in [Link]()?
6. What is the difference between toMap() and toConcurrentMap()?
7. What is the purpose of [Link]()?Can [Link]() be replaced with [Link]()?
Which one is preferred?
8. What are summingInt, summingDouble, and summingLong used for?
9. What is averagingInt(), and how is it different from summingInt()?
10. What is [Link]() used for?
11. What is groupingBy() in Java Streams?
12. What is the difference between groupingBy() and partitioningBy()?
13. What is nested grouping, and how can you achieve it using Collectors?
14. Where we can use Collectors. reducing() method?
Random Class
1. What is Random class in Java?
2. How to generate random numbers using Random? Difference between [Link]() and Random
class?
3. How does the Random class generate pseudo-random numbers internally?
Date Class
1. What is [Link]?
2. How to get the current date and time?
3. Difference between Date and Calendar.
4. How to convert Date to LocalDate or LocalDateTime?
5. How do you format a Date using SimpleDateFormat with a custom pattern?
6. Why Date class is considered legacy?
Calender Class
1. What is Calendar class in Java? Important Methods of Calendar?
2. How to convert Calendar to LocalDateTime (Java 8+)?
3. How to get the current year, month, and day using Calendar?
4. How do you roll a date forward or backward using Calendar?
Locale Class
1. What is Locale class in Java ?why is it important in internationalization? Important Methods of Locale
class?
2. What are the predefined Locale constants in Java? ([Link], [Link], etc.)
3. How to get all available locales?
StringTokenizer Class
1. What is StringTokenizer in Java? How do you create a StringTokenizer object?
2. Important Methods of StringTokenizer ?
3. Difference Between StringTokenizer, split(), and Scanner?
Formatter Class
1. What is Formatter class in Java? Important Methods of Formatter?
2. Name some common format specifiers (%d, %f, %s, %c) ?
3. Difference Between Formatter and [Link]() ?
4. What is IllegalFormatException and when is it thrown?
------------------------------------------------------------------------------
Lambda Expressions
Interview Questions
Functional Interfaces
Interview Questions
Interview Questions
Interview Questions
1. Create an interface with a static method and call it from the main method.
2. Show what happens if a class defines the same static method name.
Interview Questions
1. Write an interface with one private static method and one default method calling it.
2. Demonstrate how private methods reduce code duplication in interfaces.
Method References
Interview Questions
STREAM API
Interview Questions
INTERMEDIATE OPERATIONS
1. filter()
Concept: Filters elements based on a condition.
Logical Questions:
2. map()
Concept: Transforms elements into another form.
Logical Questions:
3. flatMap()
Concept: Flattens nested structures like lists of lists.
Logical Questions:
4. distinct()
Concept: Removes duplicate elements.
Logical Questions:
5. sorted()
Concept: Sorts elements in natural or custom order.
Logical Questions:
7. peek()
Concept: Used for debugging, performs an action without altering stream.
Logical Questions:
TERMINAL OPERATIONS
1. forEach()
Concept: Iterates through stream elements.
Logical Questions:
2. collect()
Concept: Collects results into a collection or map.
Logical Questions:
3. count()
Concept: Counts elements in the stream.
Logical Questions:
4. reduce()
Concept: Reduces stream to a single value.
Logical Questions:
5. findFirst() / findAny()
Concept: Returns first or any matching element.
Logical Questions:
7. min(), max()
Concept: Find minimum or maximum element based on comparator.
Logical Questions:
8. toArray()
Concept: Convert stream to array.
Logical Questions:
1. Given a sentence, find the word that has the hight length.
input: String s = "I am learning streams API in Java";
output: learning
2. Remove duplicates from the string and return in the same order.
input: String s = "dabcadefg";
output: dabcdefg
3. Given a sentence, find the word that has the 2nd(nth) highest length.
input: String s = "I am learning streams API in Java";
output: streams
output: 7
output: streams
API
Java
7. Given a list of Integers, divide it into lists on having an even number and the other having an odd
number.
input: int[] arr = {1,2,3,4,5,6,7,8};
9. Given an int[] array, re-arrange the elements to form the highest/lowest possible.
input: int []arr = {1, 2, 3, 5, 4};
output: 12345
54321
output: 22
output: H
output: l
13. Given an array of Integers, group the numbers by the range in which they belong.
input: int []arr= {2, 3, 10, 14, 20, 24, 30, 34, 40, 44, 50, 54};
output: {0=[2, 3], 10=[10, 14], 20=[20, 24], 30=[30, 34], 40=[40, 44], 50=[50, 54]}
14. Given a list of Strings, create a list that contains only integers.
input: String [] s = {"abc", "123", "456", "xyz"};
15. Find the product of the first two elements from an array.
String [] s = {"pat", "tap", "pan", "nap", "Team", "tree", "meat"};
COLLECTORS CLASS
Interview Questions
forEach() Method
Interview Questions
Optional Class
Interview Questions
Interview Questions
1. What is [Link]()?
2. How is parallelSort() different from [Link]()?
3. When should we use parallelSort()?
4. Is parallelSort() thread-safe?
5. What algorithm does parallelSort() use?
Programs
Interview Questions
------------------------------------------------------------------------------
Nested Interface
Interview Questions
1) What is a Nested Interface?
7) Implement a Thread using anonymous inner class inside a method of an outer class.
------------------------------------------------------------------------------
35. ENUM
Questions
1) What is an enum in Java, and why is it used?
2) Can an enum implement an interface or extend a class?
3) Can an enum declared inside a class have constructors and methods?
4) Is an enum inside a class implicitly static? Explain.
5) How can we access a nested enum from another class?
6) From which Java version can we use enum in a switch statement?
7) What happens if the enum variable in a switch is null?
8) What method is used to iterate through enum constants?
9) What does the ordinal() method return for enum constants?
10) What is EnumSet and EnumMap? Why are they preferred for enum iteration?
Programs
1) Write a Java program that defines an enum inside a class and prints its constants.
2) Write a program that defines an enum inside a class with a constructor and a custom method.
3) Write code to print enum constants along with their ordinal values.
4) Write code where each enum constant has a custom method, and you call it during iteration.
5) Write a code example where enum iteration triggers specific logic (method calls) for each constant.