Java Interview Questions
Java Interview Questions

Java Interview Questions -Set 8

Java Interview Questions -Set 8

Q: What is the difference between == and equals() in Java?

Answer:

== and equals() are used for comparison, but they have different purposes:

  1. == Operator:
    • Compares references (memory addresses) of objects.
    • Checks if two references point to the same object.
  2. equals() Method:
    • Compares the values within the objects.
    • Should be overridden in a class to provide meaningful comparison.

Example:

String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2);       // false
System.out.println(s1.equals(s2));  // true

Q: What are the main features of Java 8?

Answer:

Java 8 introduced several important features, including:

  1. Lambda Expressions:
    • Enables functional programming by allowing the creation of anonymous methods.
  2. Stream API:
    • Facilitates functional-style operations on sequences of elements.
  3. Default Methods:
    • Allows methods in interfaces to have implementations.
  4. Optional Class:
    • Helps to avoid NullPointerException by providing a container that may or may not contain a value.
  5. New Date and Time API:
    • Provides a comprehensive and consistent date-time library.

Example:

List<String> names = Arrays.asList("John", "Jane", "Jack", "Doe");

names.stream()
     .filter(name -> name.startsWith("J"))
     .forEach(System.out::println);

Q: What is the use of the final keyword in Java?

Answer:

The final keyword in Java can be used in different contexts:

  1. Final Variable:
    • Value cannot be changed once initialized.
    • Example: final int MAX = 100;
  2. Final Method:
    • Cannot be overridden by subclasses.
    • Example: public final void display() { ... }
  3. Final Class:
    • Cannot be subclassed.
    • Example: public final class Utility { ... }

Example:

public final class Constants {
    public static final int MAX_VALUE = 100;
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Constants.MAX_VALUE);
    }
}

React 🔥 if this resource is helpful!

See also  Money -Hacks :Top 20 way to Generate income as Coders and Programmers ! Don’t Miss Out

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *