ParthaKuchana.com   Stocks & Technology
Top 25 Intermediate Java Interview Questions and Answers | Ace Your Java Interview! Part 2
Top 25 Intermediate Java Interview Questions and Answers | Ace Your Java Interview! Part 2




26. What is a Java annotation and how is it used?

Answer: A Java annotation is a form of metadata that provides data about a program but is not part of the program itself. Annotations can be used to provide information to the compiler, generate code, or provide runtime instructions. For example:
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value();
}

public class AnnotationExample {
@MyAnnotation(value = "Hello")
public void myMethod() {
// Method implementation
}
}
```

27. Explain the difference between `throw` and `throws` in Java.

Answer: The `throw` keyword is used to explicitly throw an exception in a method, while `throws` is used in a method signature to declare that a method might throw one or more exceptions. For example:
```java
public void method() throws IOException {
throw new IOException("This is an IOException.");
}
```

28. Write a Java program to demonstrate the usage of a try-catch block.

Answer:
```java
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
}
}
```

29. What is the `super` keyword in Java?

Answer: The `super` keyword in Java refers to the superclass (parent class) of the current object. It can be used to access superclass methods, constructors, and variables. For example:
```java
class Parent {
void display() {
System.out.println("Parent display method.");
}
}

class Child extends Parent {
void display() {
super.display();
System.out.println("Child display method.");
}
}

public class SuperExample {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
```

30. Explain what an abstract class is in Java. How is it different from an interface?

Answer: An abstract class in Java is a class that cannot be instantiated and can contain abstract methods (methods without implementation) and concrete methods (methods with implementation). An interface is a reference type that can only contain abstract methods (prior to Java 8) and static and default methods (from Java 8 onward). Abstract classes can have member variables, constructors, and method implementations, while interfaces cannot (prior to Java 8).

31. Write a Java program to implement a simple linked list.

Answer:
```java
class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}

class LinkedList {
Node head;

public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}

public class LinkedListExample {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(1);
list.insert(2);
list.insert(3);
list.display();
}
}
```

32. What is the difference between `ArrayList` and `LinkedList`?

Answer: `ArrayList` is a resizable array implementation of the `List` interface, which provides fast random access but slow insertion and deletion of elements. `LinkedList` is a doubly linked list implementation of the `List` and `Deque` interfaces, which provides faster insertion and deletion of elements but slower random access compared to `ArrayList`.

33. How does the `final` keyword work in Java?

Answer: The `final` keyword in Java can be used with variables, methods, and classes. A `final` variable's value cannot be changed once assigned. A `final` method cannot be overridden by subclasses. A `final` class cannot be subclassed.

34. Write a Java program to count the number of vowels in a given string.

Answer:
```java
public class VowelCount {
public static int countVowels(String str) {
int count = 0;
for (char ch : str.toCharArray()) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}
return count;
}

public static void main(String[] args) {
String input = "Hello, World!";
int vowels = countVowels(input);
System.out.println("Number of vowels: " + vowels);
}
}
```

35. Explain the concept of an enumeration in Java.

Answer: An enumeration (enum) in Java is a special data type that defines a set of named constants. Enums can be used to represent a fixed set of related constants and can have methods and fields. For example:
```java
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}

public class EnumExample {
public static void main(String[] args) {
Day day = Day.MONDAY;
System.out.println("The day is: " + day);
}
}
```

36. Write a Java program to convert a binary number to a decimal number.

Answer:
```java
public class BinaryToDecimal {
public static int binaryToDecimal(String binary) {
int decimal = 0;
int base = 1;
for (int i = binary.length() - 1; i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += base;
}
base *= 2;
}
return decimal;
}

public static void main(String[] args) {
String binary = "1101";
int decimal = binaryToDecimal(binary);
System.out.println("Decimal equivalent: " + decimal);
}
}
```

37. Explain the concept of inheritance in Java with an example.

Answer: Inheritance in Java is a mechanism where one class acquires the properties (fields and methods) of another class. It promotes code reuse and establishes an IS-A relationship. For example:
```java
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {
void bark() {
System.out.println("This dog barks.");
}
}

public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
```

38. What is the difference between `Array` and `ArrayList` in Java?

Answer: An `Array` is a fixed-size data structure that holds elements of the same type. Its size cannot be changed once initialized. `ArrayList` is a resizable array implementation of the `List` interface, which can dynamically grow or shrink in size, providing more flexibility compared to arrays.

39. Write a Java program to sort an array of integers using the bubble sort algorithm.

Answer:
```java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```

40. What is a `static` block in Java and when is it executed?

Answer: A `static` block in Java is a block of code that is executed when the class is first loaded into memory. It is used to initialize static variables and is executed before the main method and constructor. For example:
```java
public class StaticBlockExample {
static int num;
static {
num = 100;
System.out.println("Static block executed.");
}

public static void main(String[] args) {
System.out.println("Value of num: " + num);
}
}
```

41. Explain the difference between `==` and `equals()` method in Java.

Answer: The `==` operator checks if two references point to the same object in memory, while the `equals()` method checks if two objects are logically equivalent based on their state. For example:
```java
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2); // false
System.out.println(str1.equals(str2)); // true
```

42. Write a Java program to demonstrate the use of the `Comparator` interface.

Answer:
```java
import java.util.*;

class Student {
int id;
String name;
int age;

Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}

class AgeComparator implements Comparator {
public int compare(Student s1, Student s2) {
return s1.age - s2.age;
}
}

public class ComparatorExample {
public static void main(String[] args) {
List students = new ArrayList<>();
students.add(new Student(1, "John", 25));
students.add(new Student(2, "Jane", 22));
students.add(new Student(3, "Tom", 24));

Collections.sort(students, new AgeComparator());

for (Student s : students) {
System.out.println(s.name + " " + s.age);
}
}
}
```

43. Explain the concept of garbage collection in Java.

Answer: Garbage collection in Java is the process of automatically freeing memory by deleting objects that are no longer reachable in the program. It helps to manage memory and prevent memory leaks. The Java Virtual Machine (JVM) performs garbage collection.

44. Write a Java program to reverse a string.

Answer:
```java
public class ReverseString {
public static String reverse(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}

public static void main(String[] args) {
String input = "Hello, World!";
String reversed = reverse(input);
System.out.println("Reversed string: " + reversed);
}
}
```

45. What is a lambda expression in Java?

Answer: A lambda expression in Java is a concise way to represent an anonymous function (a function without a name). It is used to implement functional interfaces and provides a clear and concise way to write code. For example:
```java
interface MyFunction {
int add(int a, int b);
}

public class LambdaExample {
public static void main(String[] args) {
MyFunction sum = (a, b) -> a + b;
System.out.println("Sum: " + sum.add(5, 3));
}
}
```

46. Explain the concept of polymorphism in Java with an example.

Answer: Polymorphism in Java allows objects to be treated as instances of their parent class rather than their actual class. It can be achieved through method overriding (runtime polymorphism) and method overloading (compile-time polymorphism). For example:
```java
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {
void sound() {
System.out.println("Dog barks.");
}
}

public class PolymorphismExample {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Dog barks.
}
}
```

47. Write a Java program to check if a given string is a palindrome.

Answer:
```java
public class Palindrome {
public static boolean isPalindrome(String str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

public static void main(String[] args) {
String input = "madam";
System.out.println("Is palindrome: " + isPalindrome(input));
}
}
```

48. Explain the purpose of the `transient` keyword in Java.

Answer: The `transient` keyword in Java is used to indicate that a field should not be serialized. When an object is serialized, fields marked as `transient` are skipped and not included in the serialized representation of the object. For example:
```java
import java.io.*;

class Person implements Serializable {
String name;
transient int age;

Person(String name, int age) {
this.name = name;
this.age = age;
}
}

public class TransientExample {
public static void main(String[] args) {
Person person = new Person("John", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

49. Write a Java program to find the factorial of a number using recursion.

Answer:
```java
public class Factorial {
public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}

public static void main(String[] args) {
int num = 5;
System.out.println("Factorial of " + num + " is: " + factorial(num));
}
}
```

50. What is the difference between `StringBuilder` and `StringBuffer` in Java?

Answer: Both `StringBuilder` and `StringBuffer` are used to create mutable sequences of characters. The main difference is that `StringBuffer` is synchronized and thread-safe, while `StringBuilder` is not synchronized and therefore faster for single-threaded operations.
© 2024 parthakuchana.com