0% found this document useful (0 votes)
47 views10 pages

Java Interview Questions

Uploaded by

kannu12356mbd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
47 views10 pages

Java Interview Questions

Uploaded by

kannu12356mbd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

Features of Java:

 Object-Oriented: Java is based on object-oriented programming which makes it


modular, flexible, and extensible.
 Platform-Independent: Java programs are executed on the JVM, making them platform-
independent.
 Simple and Secure: Java provides a simple syntax and robust security features.
 Robust: Java has strong memory management, exception handling, and type-checking
mechanisms.
 Multithreaded: Java supports multithreading, allowing concurrent execution of two or
more threads.
 Architecture-Neutral: Java code is compiled into bytecode which is architecture-
neutral.
 Portable: Java programs can be easily ported from one platform to another.
 High Performance: Just-In-Time compilers enable high performance.
 Distributed: Java has a rich set of APIs that make it easy to develop distributed
applications.
 Dynamic: Java can dynamically link in new class libraries, methods, and objects.
What is the difference between Java and JavaScript?
 Java is a statically-typed, object-oriented programming language designed for server-
side applications.
 JavaScript is a dynamically-typed scripting language primarily used for client-side web
development.
What is the difference between Java and C++?
 Java is platform-independent thanks to the JVM, while C++ is platform-dependent.
 Java uses automatic garbage collection, whereas C++ requires manual memory
management.
 Java does not support multiple inheritance directly; it uses interfaces.
 Java code is compiled into bytecode by the Java compiler (javac), and the bytecode is executed
by the JVM.C++ code is compiled into machine code by a C++ compiler (like GCC, Clang, or
MSVC).

What is the purpose of the super keyword in Java?
 The super keyword in Java refers to the superclass (parent class) and is used to access
superclass methods and constructors.
// Superclass
class Animal {
String name;
// Superclass constructor
Animal(String name) {
this.name = name;
}

// Superclass method
void display() {
System.out.println("I am an animal. My name is " + name);
}
}

// Subclass
class Dog extends Animal {
String breed;

// Subclass constructor
Dog(String name, String breed) {
super(name); // Call superclass constructor
this.breed = breed;
}

// Subclass method
void display() {
super.display(); // Call superclass method
System.out.println("I am a dog. My breed is " + breed);
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create an object of the subclass
Dog dog = new Dog("Buddy", "Golden Retriever");

// Call the subclass method


dog.display();
}
}
// Output-
I am an animal. My name is Buddy
I am a dog. My breed is Golden Retriever
Explain the difference between public, private, protected, and default access modifiers
in Java.
 public: Accessible from any other class.
 private: Accessible only within the same class.
 protected: Accessible within the same package and subclasses.
 default (no modifier): Accessible within the same package.
What is the purpose of the static keyword in Java?
 The static keyword is used to indicate that a member variable or method belongs to the
class itself rather than instances of the class.
1. Static Variables
Static variables (also known as class variables) are shared among all instances of a class.
They are declared using the static keyword and exist for the lifetime of the class.
Example -

class Counter {
static int count = 0; // static variable
Counter() {
count++;
}

void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter obj3 = new Counter();

obj1.displayCount(); // Count: 3
obj2.displayCount(); // Count: 3
obj3.displayCount(); // Count: 3
}
}

2. Static Methods
Static methods belong to the class rather than any specific instance. They can be called without
creating an instance of the class. Static methods can only access static variables and other static
methods directly.
Example-
class MathUtils {
// static method
static int add(int a, int b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
int sum = MathUtils.add(5, 3); // Call static method without creating an instance
System.out.println("Sum: " + sum); // Sum: 8
}
}

3. Static Blocks
Static blocks are used to initialize static variables. They are executed when the class is loaded.

Example –

class StaticBlockExample {
static int value;

// static block
static {
value = 42;
System.out.println("Static block initialized.");
}
}

public class Main {


public static void main(String[] args) {
System.out.println("Value: " + StaticBlockExample.value); // Static block initialized. Value: 42
}
}
4. Static Nested Classes
A static class nested within another class can be instantiated without an instance of the outer
class.
Example-
class OuterClass {
static class NestedStaticClass {
void display() {
System.out.println("Inside static nested class.");
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.NestedStaticClass nestedObject = new OuterClass.NestedStaticClass();
nestedObject.display(); // Inside static nested class.
}
}
What is a static method in Java?
 A static method belongs to the class rather than instances and can be called without
creating an object of the class.
What is the purpose of the final keyword in Java?
 The final keyword is used to declare constants, prevent method overriding, and
inheritance.

1. Final Variables
A final variable can be assigned only once. Once a final variable has been assigned, it
always contains the same value.
Example -
public class Main {
public static void main(String[] args) {
final int constantValue = 10;
System.out.println("Constant Value: " + constantValue);

// Uncommenting the following line would cause a compile-time error


// constantValue = 20;
}
}

2. Final Methods
A final method cannot be overridden by subclasses. This is useful when you want to prevent
subclasses from changing the implementation of a method.
Example -
class BaseClass {
final void display() {
System.out.println("This is a final method in the base class.");
}
}

class DerivedClass extends BaseClass {


// Uncommenting the following method would cause a compile-time error
// void display() {
// System.out.println("Attempting to override the final method.");
// }
}

public class Main {


public static void main(String[] args) {
DerivedClass obj = new DerivedClass();
obj.display(); // This will call the final method from the base class
}
}
3. Final Classes
A final class cannot be subclassed. This is useful when you want to prevent other classes from
inheriting from your class.
Example -
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}

// Uncommenting the following class would cause a compile-time error


// class DerivedClass extends FinalClass {
// }

public class Main {


public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display();
}
}
Explain the difference between final, finally, and finalize in Java.

 final: Keyword used to declare constants, prevent method overriding, and inheritance.
A modifier that makes variable, methods or class immutable or unchangeable.
 finally: Block used in exception handling to execute code after try-catch blocks, regardless of
an exception.
public class FinallyExample {
public static void main(String[] args) {
try {
int data = 25 / 0; // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("This block always executes.");
}
}
}
 finalize (): Method called by the garbage collector before an object is destroyed.
public class FinalizeExample {
// Overriding finalize method
protected void finalize() throws Throwable {
System.out.println("Finalize method called.");
}

public static void main(String[] args) {


FinalizeExample obj = new FinalizeExample();
obj = null; // Eligible for garbage collection

// Requesting JVM to run Garbage Collector


System.gc();

System.out.println("Main method ends.");


}
}
What is a package in Java?
 A package is a namespace for organizing classes and interfaces in a logical manner.
How do you import packages in Java?
 Packages are imported using the import keyword followed by the package name. For
example: import java.util.*;.
What is the purpose of the import statement in Java?
 The import statement allows the use of classes and interfaces from other packages.
Can you implement multiple interfaces in Java?
 Yes, a class can implement multiple interfaces in Java.
// Interface 1
interface Animal {
void eat();
}

// Interface 2
interface Bird {
void fly();
}

// Class implementing multiple interfaces


class Eagle implements Animal, Bird {
// Implementing method from Animal interface
@Override
public void eat() {
System.out.println("Eagle is eating.");
}

// Implementing method from Bird interface


@Override
public void fly() {
System.out.println("Eagle is flying.");
}
}

public class Main {


public static void main(String[] args) {
Eagle eagle = new Eagle();
// Using methods from multiple interfaces
eagle.eat();
eagle.fly();
}
}
What is the purpose of the instanceof operator in Java?
The instanceof operator in Java is used to check whether an object is an instance of a particular class or
its subclasses. It returns a boolean value, true if the object is an instance of the class, and false otherwise.
class Animal { }

class Dog extends Animal { }

public class Main {


public static void main(String[] args) {
Animal animal = new Dog();

// Checking if animal is an instance of Animal (true, Dog inherits Animal)


System.out.println(animal instanceof Animal); // true

// Checking if animal is an instance of Dog (true)


System.out.println(animal instanceof Dog); // true

// Checking for null (null is not an instance of any class)


Object obj = null;
System.out.println(obj instanceof String); // false
}
}
Output-
true
true
false
What are the different types of variables in Java?
 Local variables: Defined within a method and accessible only within that method.
 Instance variables: Belong to an instance of a class.
class Person {
String name; // Instance variable
int age;
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Bob";
person1.age = 30;
Person person2 = new Person();
person2.name = "Charlie";
person2.age = 25; }
}
 Class variables (static variables): Belong to the class itself and shared among all
instances.
is the difference between local variables, instance variables, and class variables
in Java?
 Local variables are defined within methods and have method scope.
 Instance variables are defined in a class but outside any method and have object scope.
 Class variables are defined with the static keyword in a class and have class scope.
How do you declare and initialize variables in Java?
 Variables are declared with a type followed by a name. For example: int x;.
 They can be initialized at the time of declaration. For example: int x = 10;.
What is the purpose of the final keyword for variables in Java?
 The final keyword makes a variable constant, meaning its value cannot be changed once
assigned.
What is the purpose of the volatile keyword in Java?
 The volatile keyword indicates that a variable's value will be modified by different
threads and ensures visibility of changes to all threads.
What is the purpose of the transient keyword in Java?
 The transient keyword is used in serialization to indicate that a variable should not be
serialized.
What is a Java array?
 An array is a container object that holds a fixed number of values of a single type.
How do you declare and initialize arrays in Java?
 Arrays are declared with the type followed by square brackets. For example: int[] array;.
 They can be initialized using the new keyword. For example: int[] array = new int[10];.
What is the length of an array in Java?
 The length of an array is accessed using the length property. For example: array.length.
What is the difference between arrays and ArrayList in Java?
 Arrays have a fixed size, while ArrayList can dynamically resize.
 Arrays can hold primitive types and objects, while ArrayList can hold only objects.
What is the purpose of the clone() method in Java?
 The clone() method creates a new instance of a class with the same values as the existing
instance.
What is the purpose of the toString() method in Java?
 The toString() method returns a string representation of an object.
What is the purpose of the equals() method in Java?
 The equals() method is used to compare the contents of two objects for equality.
What is the purpose of the hashCode() method in Java?
 The hashCode() method returns an integer value, generated by a hashing algorithm, that
represents the object.
What is the purpose of the getClass() method in Java?
 The getClass() method returns the runtime class of the object.
What is exception handling in Java?
 Exception handling in Java is a mechanism to handle runtime errors, allowing the
program to continue its normal flow.
Explain the try, catch, and finally blocks in Java.
 try: Block of code that might throw an exception.
 catch: Block of code that handles the exception.
 finally: Block of code that executes after try-catch, regardless of an exception.
What is the purpose of the throw keyword in Java?
 The throw keyword is used to explicitly throw an exception from a method or block of
code.
What is the purpose of the throws keyword in Java?
 The throws keyword is used in method signatures to declare the exceptions that a method
can throw.
What is the difference between checked and unchecked exceptions in Java?
 Checked exceptions are checked at compile-time, while unchecked exceptions are
checked at runtime.
What is the purpose of the try-with-resources statement in Java?
 The try-with-resources statement ensures that each resource is closed at the end of the
statement.
What is a Java String?
 A String in Java is an immutable sequence of characters.
How do you create and manipulate strings in Java?
 Strings can be created using string literals or the new keyword. They can be manipulated
using various methods like concat(), substring(), replace(), etc.
What is the difference between String, StringBuilder, and StringBuffer in Java?
 String is immutable.
 StringBuilder is mutable and not synchronized.
 StringBuffer is mutable and synchronized.
What is a Java ArrayList?
 An ArrayList is a resizable array implementation of the List interface.
How do you create and manipulate ArrayLists in Java?
 An ArrayList is created using: ArrayList<Type> list = new ArrayList<>();.
 Elements can be added using add(), accessed using get(), and removed using remove().
What is the purpose of the Iterator interface in Java?
 The Iterator interface provides methods to iterate over a collection.
What is a Java HashMap?
 A HashMap is a collection that stores key-value pairs and allows null values and null
keys.
How do you create and manipulate HashMaps in Java?
 A HashMap is created using: HashMap<KeyType, ValueType> map = new HashMap<>();.
 Entries can be added using put(), accessed using get(), and removed using remove().
What is the purpose of the entrySet() method in Java HashMap?
 The entrySet() method returns a set view of the mappings contained in the map.
What is the purpose of the put() and get() methods in Java HashMap?
 put(): Adds a key-value pair to the map.
 get(): Retrieves the value associated with a key.
What is the purpose of the remove() method in Java HashMap?
 The remove() method removes the key-value pair associated with the specified key.
What is a Java HashSet?
 A HashSet is a collection that does not allow duplicate elements and uses hashing for
storage.
How do you create and manipulate HashSets in Java?
 A HashSet is created using: HashSet<Type> set = new HashSet<>();.
 Elements can be added using add(), checked for existence using contains(), and removed
using remove().
What is the purpose of the add() method in Java HashSet?
 The add() method adds the specified element to the set if it is not already present.
What is the purpose of the remove() method in Java HashSet?
 The remove() method removes the specified element from the set if it is present.
What is a Java LinkedList?
 A LinkedList is a doubly linked list implementation of the List and Deque interfaces.
How do you create and manipulate LinkedLists in Java?
 A LinkedList is created using: LinkedList<Type> list = new LinkedList<>();.
 Elements can be added using add(), accessed using get(), and removed using remove().
What is the purpose of the add() and remove() methods in Java LinkedList?
 add(): Adds an element to the list.
 remove(): Removes an element from the list.
What is a Java TreeSet?
 A TreeSet is a NavigableSet implementation that uses a tree for storage and orders
elements in their natural ordering or by a specified comparator.
How do you create and manipulate TreeSets in Java?
 A TreeSet is created using: TreeSet<Type> set = new TreeSet<>();.
 Elements can be added using add(), checked for existence using contains(), and removed
using remove().
What is the purpose of the add() and remove() methods in Java TreeSet?
 add(): Adds the specified element to the set.
 remove(): Removes the specified element from the set.

What is the purpose of the contains() method in Java collections?


 The contains() method checks if the collection contains a specified element.

What is the purpose of the isEmpty() method in Java collections?


 The isEmpty() method checks if the collection is empty.

What is the purpose of the size() method in Java collections?


 The size() method returns the number of elements in the collection.

What is the purpose of the clear() method in Java collections?


 The `clear() method removes all elements from the collection.

What is the purpose of the toArray() method in Java collections?


 The toArray() method converts the collection to an array.

What is the purpose of the iterator() method in Java collections?


 The iterator() method returns an iterator over the elements in the collection.

Comparable and comparator in java


Singleton classes
Clone method , toString , super class of all objects ,
Custom exception

You might also like