100 common Java interview questions (with answers and code examples) are continuously updated

  1. What is a Java program?
    A Java program is a set of executable codes compiled by a Java compiler and can run on a Java Virtual Machine (JVM).
public class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("Hello, World!");
    }
}

  1. What are the types of variables in Java?
    There are eight basic types of variables in Java: byte, short, int, long, float, double, char, and boolean.
int age = 25;
String name = "John Doe";
double salary = 5000.50;
boolean isEmployed = true;

  1. What are Java packages?
    Java packages are a mechanism for organizing classes and interfaces. It can group related classes and interfaces together for better code management and maintenance.
package com.example.mypackage;

public class MyClass {
    
    
    // class implementation
}

  1. What is inheritance in Java?
    Inheritance is a mechanism in Java that allows a class (called a subclass) to inherit the properties and methods of another class (called a parent class).
public class Animal {
    
    
    String name;
    int age;
    public void eat() {
    
    
        System.out.println("Animal is eating");
    }
}
public class Dog extends Animal {
    
    
    String breed;
    public void bark() {
    
    
        System.out.println("Dog is barking");
    }
}

  1. What is an interface in Java?
    An interface is a mechanism in Java that defines a set of methods but provides no implementation. A class can implement one or more interfaces and provide implementations for the methods defined in the interfaces.
public interface MyInterface {
    
    
    public void method1();
    public int method2(String str);
}
public class MyClass implements MyInterface {
    
    
    public void method1() {
    
    
        System.out.println("Method 1 implementation");
    }
    public int method2(String str) {
    
    
        return str.length();
    }
}

  1. What is polymorphism in Java?
    Polymorphism is a mechanism in Java that allows different objects to respond differently to the same method. This is achieved through inheritance and interfaces.
public class Animal {
    
    
    public void makeSound() {
    
    
        System.out.println("Animal is making a sound");
    }
}
public class Dog extends Animal {
    
    
    public void makeSound() {
    
    
        System.out.println("Dog is barking");
    }
}
public class Cat extends Animal {
    
    
    public void makeSound() {
    
    
        System.out.println("Cat is meowing");
    }
}
Animal myAnimal = new Dog();
myAnimal.makeSound();

  1. What is exception handling in Java?
    Java's exception handling is a mechanism that allows a program to perform some specific actions when an exception occurs, instead of crashing directly.
try {
    
    
    int result = 10 / 0;
} catch (ArithmeticException e) {
    
    
    System.out.println("Exception caught: " + e.getMessage());
} finally {
    
    
    System.out.println("Finally block executed");
}

  1. What are threads in Java?
    A thread in Java is a mechanism that allows a program to execute multiple tasks simultaneously. Each thread has its own execution path and can run independently, but share the same memory space.
class MyThread extends Thread {
    
    
    public void run() {
    
    
        System.out.println("Thread is running");
    }
}
MyThread t = new MyThread();
t.start();

  1. What are the collections in Java?
    Collections in Java include data structures such as List, Set, Map, and Queue, which allow storing and manipulating multiple values ​​in a single object.
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
System.out.println(list);

Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("orange");
System.out.println(set);

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
System.out.println(map);

Queue<String> queue = new LinkedList<>();
queue.add("apple");
queue.add("banana");
queue.add("orange");
System.out.println(queue);

  1. What is reflection in Java?
    Reflection in Java is a mechanism that allows programs to obtain class information and manipulate class properties and methods at runtime.
Class<?> c = Class.forName("com.example.MyClass");
Object obj = c.newInstance();
Method method = c.getMethod("myMethod");
method.invoke(obj);

  1. What are Java annotations?
    Java annotations are a mechanism that allow programs to add metadata in code. Annotations can be applied to elements such as classes, methods, and variables to provide additional information about these elements.
@MyAnnotation(value = "someValue")
public class MyClass {
    
    
    // class implementation
}

  1. What are Lambda Expressions in Java?
    Lambda expressions are a mechanism in Java 8 that allow programs to define anonymous functions in a more concise manner, making the code more readable and maintainable.
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
list.forEach((String s) -> System.out.println(s));

  1. What are streams in Java?
    A stream in Java is a mechanism that allows a program to process data in a continuous manner. Streams can read data from files, networks, and other sources and convert it to different formats.
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
Stream<String> stream = list.stream();
stream.forEach((String s) -> System.out.println(s));

  1. What are generics in Java?
    Generics in Java are a mechanism that allows a program to specify a generic type parameter at compile time and use that type parameter at run time. This makes the code more flexible and reusable.
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
for (String s : list) {
    
    
    System.out.println(s);
}

  1. What is an enum in Java?
    An enumeration in Java is a mechanism that allows a program to group together a group of related constants for better management and maintenance of the code.
public enum DayOfWeek {
    
    
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
DayOfWeek today = DayOfWeek.MONDAY;
System.out.println(today);

  1. What is file IO in Java?
    File IO in Java is a mechanism that allows programs to read and write files. It allows programs to access files on disk, and to read and write data in files.
try {
    
    
    FileWriter writer = new FileWriter("myfile.txt");
    writer.write("Hello, world!");
    writer.close();
} catch (IOException e) {
    
    
    e.printStackTrace();
}

  1. What is serialization in Java?
    Serialization in Java is a mechanism that allows a program to convert an object into a stream of bytes and write it to a file or send it over a network. Deserialization is the process of converting a stream of bytes back into an object.
public class MyClass implements Serializable {
    
    
    private String name;
    private int age;
    public MyClass(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
    // getters and setters
}
MyClass obj = new MyClass("John Doe", 25);
try {
    
    
    FileOutputStream fileOut = new FileOutputStream("myfile.ser");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(obj);
    out.close();
    fileOut.close();
} catch (IOException e) {
    
    
    e.printStackTrace();
}

  1. What are regular expressions in Java?
    Regular expressions in Java are a mechanism that allow programs to find and replace patterns in text. Regular expressions are strings of special characters that match patterns in text.
String str = "Hello, world!";
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
    
    
    System.out.println("Pattern found");
}

  1. What is network programming in Java?
    Network programming in Java is a mechanism that allows programs to connect to other programs over a network and communicate.
try {
    
    
    Socket socket = new Socket("localhost", 8080);
    OutputStream out = socket.getOutputStream();
    out.write("Hello, world!".getBytes());
    out.flush();
    socket.close();
} catch (IOException e) {
    
    
    e.printStackTrace();
}

  1. What is an injection attack in Java?
    An injection attack in Java is a security hole that allows an attacker to add malicious code to a program. Injection attacks can be prevented through input validation and filtering.
String input = request.getParameter("input");
if (!isValid(input)) {
    
    
    throw new IllegalArgumentException("Invalid input");
}

  1. What is encryption in Java?
    Encryption in Java is a mechanism that allows a program to convert data into an unreadable format to protect the security of the data. Encryption can be used for passwords, credit card numbers, and other sensitive information.
String plainText = "Hello, world!";
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(plainText.getBytes());
byte[] digest = md.digest();

  1. What is JDBC in Java?
    JDBC in Java is a mechanism that allows programs to connect to other programs through a database and interact with data. JDBC is an acronym for Java Database Connectivity.
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
    
    
    // process result set
}
rs.close();
stmt.close();
conn.close();

  1. What is JUnit in Java?
    JUnit in Java is a testing framework that allows programmers to write and run automated tests. JUnit helps programmers find bugs and problems in their code.
import org.junit.Test;
import static org.junit.Assert.*;

public class MyClassTest {
    
    
    @Test
    public void testMyMethod() {
    
    
        MyClass obj = new MyClass();
        int result = obj.myMethod();
        assertEquals(10, result);
    }
}

  1. What is logging in Java?
    Logging in Java is a mechanism that allows the programmer to record the running information of the program and inspect them when needed. Logs can help programmers diagnose and solve problems.
import java.util.logging.*;

public class MyClass {
    
    
    private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName());
    public void myMethod() {
    
    
        LOGGER.info("Method called");
    }
}

  1. What is JPA in Java?
    JPA in Java is a mechanism that allows programmers to access databases in an object-oriented manner. JPA is an acronym for Java Persistence API.
@Entity
@Table(name = "mytable")
public class MyClass {
    
    
    @Id
    private Long id;
    private String name;
    // getters and setters
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("mydatabase");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
MyClass obj = new MyClass();
obj.setName("John Doe");
em.persist(obj);
em.getTransaction().commit();
em.close();
emf.close();

Guess you like

Origin blog.csdn.net/qq_27244301/article/details/130385995