Java has several features:
.equals()
checks if their content is the same.Example:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different memory locations)
System.out.println(s1.equals(s2)); // true (same content)
Example:
abstract class Animal {
abstract void sound();
void breathe() {
System.out.println("Breathing...");
}
}
interface Swimmer {
void swim();
}
class Dog extends Animal implements Swimmer {
void sound() {
System.out.println("Bark");
}
public void swim() {
System.out.println("Dog swims");
}
}
Example:
final int x = 10;
// x = 20; // Error: Cannot assign a value to final variable x
A Singleton class ensures that only one instance of the class is created and provides a global point of access to it. It is useful for managing resources like database connections.
Example:
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Example:
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1"); // Allowed
Hashtable<String, String> hashTable = new Hashtable<>();
hashTable.put("key1", "value1"); // Allowed, but no nulls allowed.
The transient
keyword is used to indicate that a field should not be serialized when the object is being serialized.
Example:
class User implements Serializable {
String name;
transient int password; // Will not be serialized
}
Garbage collection is the process of automatically reclaiming memory from objects that are no longer in use. Java provides garbage collectors that remove unreferenced objects.
Example:
class Test {
public void finalize() {
System.out.println("Object is garbage collected");
}
}
Example:
String str = "Hello";
str = str + " World"; // New object created
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing object
Multithreading allows a program to execute multiple tasks concurrently, improving performance on multi-core systems. In Java, threads can be created by extending the Thread
class or implementing the Runnable
interface.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Starts the thread
}
}
try-catch
, regardless of exceptions.Java Reflection is an API that allows you to inspect and manipulate the runtime properties of classes, methods, and fields. It is widely used for creating flexible frameworks.
Example:
Class<?> clazz = Class.forName("java.lang.String");
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
Method overloading occurs when multiple methods in a class have the same name but different parameter lists (number or types of parameters).
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
The super
keyword is used to refer to the immediate parent class of a class. It can be used to access parent class methods, constructors, and fields.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calling parent class method
System.out.println("Bark");
}
}
An exception is an event that disrupts the normal flow of a program's execution. Java provides exception handling mechanisms like try
, catch
, and finally
.
IOException
.NullPointerException
.The try-catch
block is used to handle exceptions. Code that may throw an exception is placed in the try
block, and exceptions are handled in the catch
block.
Example:
try {
int a = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
A constructor is a special method used to initialize objects. It has the same name as the class and no return type.
Example:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
The this
keyword refers to the current object instance. It is often used to differentiate between class members and method parameters with the same name.
==
: Compares references (whether two variables point to the same memory location)..equals()
: Compares the actual contents of two objects.Example:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
A default
method allows you to define a method with a body inside an interface. This was introduced in Java 8 to allow backward compatibility when adding new methods to interfaces.
Example:
interface MyInterface {
default void sayHello() {
System.out.println("Hello");
}
}
Java Collections include classes like ArrayList
, HashMap
, LinkedList
, TreeSet
, HashSet
, etc., used for storing and manipulating groups of objects.
An Iterator
allows you to traverse through a collection and safely remove elements while iterating.
Example:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
compareTo()
).compare()
).The volatile
keyword ensures that a variable's value is always read from and written to the main memory, preventing caching issues in multi-threaded environments.
Example:
private volatile boolean flag = false;
Vector
in single-threaded environments.ArrayList
.An enum in Java is a special class that represents a group of constants (unchangeable variables). Enums provide a type-safe way to handle a fixed set of constants.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Java supports four types of inner classes:
The super()
keyword is used to call the constructor of the parent class. It must be the first statement in the subclass constructor.
Example:
class Parent {
Parent() {
System.out.println("Parent class constructor");
}
}
class Child extends Parent {
Child() {
super(); // Calls the parent class constructor
System.out.println("Child class constructor");
}
}
The instanceof
operator checks whether an object is an instance of a particular class or implements a specific interface.
Example:
String str = "Hello";
System.out.println(str instanceof String); // true
Thread
that makes the thread sleep for a specified amount of time.Example:
Thread.sleep(1000); // Makes the current thread sleep for 1 second
The synchronized
keyword is used to ensure that a method or block of code is accessed by only one thread at a time, which is essential for thread safety.
Example:
public synchronized void increment() {
count++;
}
A deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources. This situation arises when threads hold resources while waiting for others to release their resources.
The clone()
method creates a copy of an object. The object class implements the Cloneable
interface, and it must override the clone()
method.
Example:
class Person implements Cloneable {
String name;
Person(String name) {
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Java 8 introduced the default
keyword in interfaces to provide concrete methods with default implementation, allowing backward compatibility when adding new methods to interfaces.
Example:
interface MyInterface {
default void sayHello() {
System.out.println("Hello from MyInterface");
}
}
The finally
block is always executed after the try-catch
blocks, regardless of whether an exception was thrown or not. It is used for cleanup operations like closing file streams.
String
is created, it cannot be changed.The continue
statement is used to skip the current iteration of a loop and continue with the next iteration.
Example:
for (int i = 0; i < 5; i++) {
if (i == 3) continue; // Skip 3
System.out.println(i);
}
The break
statement is used to exit a loop or a switch case prematurely.
Example:
for (int i = 0; i < 5; i++) {
if (i == 3) break; // Exit the loop when i is 3
System.out.println(i);
}
==
: Compares references (i.e., whether two variables point to the same object in memory).equals()
: Compares the actual content of the objects.ArrayList
).HashSet
).HashMap
).The Object
class is the root class of all Java classes. Every class in Java implicitly inherits from Object
. It provides basic methods like equals()
, hashCode()
, toString()
, and clone()
.
A HashSet
is a collection that does not allow duplicate elements and does not maintain any order of its elements. It is backed by a HashMap
.
Example:
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate element
System.out.println(set); // Output: [Apple, Banana]
The Iterator
interface provides methods for traversing a collection, allowing you to safely access elements and remove them during iteration.
Example:
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
The Thread.sleep()
method pauses the current thread for the specified number of milliseconds, allowing other threads to execute.
Example:
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
throw
: Used to explicitly throw an exception.throws
: Used in a method signature to declare that a method might throw exceptions.Example:
void myMethod() throws IOException { // Throws declaration
throw new IOException("IOException occurred");
}
The try-catch-finally
block is used for exception handling. Code that may throw an exception is placed inside the try
block, exceptions are caught in the catch
block, and the finally
block executes regardless of exception occurrence.
A checked exception is an exception that is checked at compile-time. The program must handle these exceptions explicitly with a try-catch
block or declare them using throws
.
An unchecked exception (also known as a runtime exception) is an exception that is not checked at compile-time. These exceptions are subclasses of RuntimeException
. The program does not have to explicitly handle them with a try-catch
block or declare them using throws
.
Example:
public class Example {
public static void main(String[] args) {
int a = 5 / 0; // ArithmeticException: Division by zero
}
}
equals()
: Compares the content of two objects to check if they are logically equivalent.hashCode()
: Returns an integer value that is used to identify the object. The hashCode()
method is used in hashing-based collections (like HashMap
, HashSet
).Example:
String str1 = "hello";
String str2 = "hello";
System.out.println(str1.equals(str2)); // true
System.out.println(str1.hashCode() == str2.hashCode()); // true
The assert
keyword is used for debugging purposes. It tests a boolean expression, and if the expression evaluates to false
, an AssertionError
is thrown.
Example:
int x = 10;
assert x > 0 : "x must be positive"; // If x is not positive, an AssertionError is thrown
The volatile
keyword is used to indicate that a variable's value will be modified by multiple threads. It ensures that the latest value of the variable is always visible to all threads.
Example:
private volatile boolean flag = false;
A lambda expression is a concise way to represent an anonymous function (i.e., a function with no name) that can be passed around as an argument or assigned to a variable. Introduced in Java 8, it is commonly used with functional interfaces.
Example:
// Syntax: (parameters) -> expression
Runnable r = () -> System.out.println("Hello, Lambda!");
r.run(); // Output: Hello, Lambda!