KEMBAR78
Java Interview Q and A | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
6 views7 pages

Java Interview Q and A

The document covers various Java programming concepts, including type erasure in generics, the Java Memory Model, immutable objects, and the String Pool. It also explains differences between operators like == and .equals(), method overloading vs. overriding, and the use of the final keyword. Additionally, it discusses resource management with try-with-resources, the distinction between interfaces and abstract classes, and the concepts of autoboxing and unboxing.

Uploaded by

NandaShivani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

Java Interview Q and A

The document covers various Java programming concepts, including type erasure in generics, the Java Memory Model, immutable objects, and the String Pool. It also explains differences between operators like == and .equals(), method overloading vs. overriding, and the use of the final keyword. Additionally, it discusses resource management with try-with-resources, the distinction between interfaces and abstract classes, and the concepts of autoboxing and unboxing.

Uploaded by

NandaShivani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Difficult

Question 1: Generics and Type Erasure

Problem Statement: Explain type erasure in Java generics. How does it affect the runtime type
information of generic types, and how can you overcome limitations it introduces?

Answer: Type erasure is a process by which the Java compiler removes all generic type
information during compilation. This means that all the type parameters are replaced by their
bounds or Object if the type parameters are unbounded. The benefit of this approach is that it
ensures backward compatibility with older versions of Java that do not support generics.
However, it also means that the generic type information is not available at runtime.

To overcome the limitations introduced by type erasure, you can use reflection with
java.lang.reflect.ParameterizedType to inspect generic types at runtime, though this is
rarely necessary. Additionally, you can pass a Class object as a parameter to methods where you
need to know the generic type at runtime.

Question 2: Java Memory Model

Problem Statement: Describe the Java Memory Model (JMM) and its significance in
concurrent programming. Specifically, discuss the concepts of visibility and atomicity, and how
the volatile keyword relates to these concepts.

Answer: The Java Memory Model defines how threads interact through memory and what
behaviors are allowed in concurrent execution. It is crucial for understanding the actions that can
lead to thread interference and memory consistency errors.

Visibility refers to when changes made by one thread to shared variables are visible to other
threads. Atomicity refers to operations or series of operations that are executed as a single unit of
work without interference from other operations.

The volatile keyword in Java is used to ensure visibility. When a field is declared volatile, the
JVM guarantees that any thread that reads the field will see the most recent write by any thread.
However, volatile does not guarantee atomicity for compound operations (e.g., incrementing a
value).

Question 3: Immutable Objects

Problem Statement: Design an immutable class in Java. Explain the principles you need to
follow to create such a class and why immutability is often considered a good practice in multi-
threaded applications.

Answer: To design an immutable class in Java:


1. Declare the class as final so it can’t be extended.
2. Make all fields private and final.
3. Do not provide setters.
4. Ensure the class is properly constructed by initializing all fields via the constructor.
5. If the class holds references to mutable objects, ensure those objects are not changed after
construction. This can involve making defensive copies of objects both on construction
and when returning them.

Immutable objects are thread-safe by definition since their state cannot be modified after
creation, eliminating synchronization concerns in concurrent contexts.
Medium
Question 1: String Pool in Java

Problem Statement: What is the String Pool in Java?

Answer: The String Pool in Java is a special storage area in the Java heap. When a string is
created using string literals (e.g., String s = "Hello";), Java checks the pool to see if an
identical string already exists. If it does, the new variable will reference the existing string. If not,
a new string is created in the pool. This mechanism saves memory and ensures that string literals
are stored efficiently. However, strings created with the new operator (e.g., new
String("Hello")) do not use the string pool unless explicitly interned using the intern()
method.

Question 2: Equals vs. ==

Problem Statement: Explain the difference between == and .equals() in Java.

Answer: In Java, == is a reference comparison operator that checks whether two references point
to the same object in memory. On the other hand, .equals() is a method that checks if two
objects are logically "equal" according to the logic defined within the .equals() method. By
default, the .equals() method in the Object class behaves the same as ==, but it is often
overridden in subclasses to check logical equality. For example, two different String objects
containing the same characters are considered equal when compared using .equals().

Question 3: Overloading vs. Overriding

Problem Statement: What is the difference between method overloading and method overriding
in Java?

Answer: Method overloading occurs when two or more methods in the same class have the same
name but different parameters (different type, number, or both). It is a compile-time
polymorphism example. Method overriding occurs when a subclass provides a specific
implementation of a method already provided by one of its parent classes. Overriding allows a
subclass to implement a parent class method based on its requirement, and it is an example of
runtime polymorphism.

Question 4: Final Keyword

Problem Statement: What is the purpose of the final keyword in Java?

Answer: In Java, the final keyword can be used in several contexts:

 Variable: When applied to a variable, final makes it a constant, meaning its value
cannot be modified once initialized.
 Method: A final method cannot be overridden by subclasses.
 Class: A final class cannot be subclassed. This is useful for creating immutable classes
or ensuring certain classes are not extended for security reasons.

Question 5: Try-with-Resources

Problem Statement: What is try-with-resources in Java, and how does it benefit resource
management?

Answer: Try-with-resources is a feature introduced in Java 7 that simplifies the management of


resources such as files, sockets, and database connections. It automatically handles the closing of
resources used within the try block, reducing the risk of resource leaks and making the code
cleaner and more readable. To use try-with-resources, the resources must implement the
AutoCloseable or Closeable interface. This ensures that the close() method is called
automatically at the end of the try block, even if an exception is thrown.
Easy
Question 2: Default Constructor

Problem Statement: What is a default constructor in Java?

Answer: A default constructor is a no-argument constructor automatically provided by Java if no


constructors are explicitly defined within a class. It initializes the object with default values (null
for objects, 0 for numeric types, false for boolean, '\u0000' for char).

Question 4: Access Modifiers

Problem Statement: What are the access modifiers in Java?

Answer: Java provides four access modifiers to set access levels for classes, variables, methods,
and constructors:

 public: The member is accessible from any other class.


 protected: The member is accessible within its package and by subclasses.
 default (no modifier): The member is accessible only within its own package.
 private: The member is accessible only within its own class.

Question 5: The static Keyword

Problem Statement: What does the static keyword signify in Java?

Answer: The static keyword in Java is used to indicate that a particular member (variable or
method) belongs to the class, rather than instances of that class. This means:

 Static Variables: A single copy of the variable is shared among all instances of the class.
 Static Methods: Can be called without creating an instance of the class. Static methods
can access static variables and other static methods directly.

Question 1: final, finally, and finalize

Problem Statement: Explain the difference between final, finally, and finalize in Java.

Answer:

 final is a keyword that can be applied to variables, methods, and classes. A final
variable cannot change its value once assigned, a final method cannot be overridden by
subclasses, and a final class cannot be subclassed.
 finally is a block that follows a try-catch structure. It is executed after the try block and
any catch blocks have completed, and it executes regardless of whether an exception was
thrown or caught. It's typically used for cleanup code, such as closing resources.
 finalize is a method from the Object class that the garbage collector calls on an object
when it determines that there are no more references to the object. It's used to perform
cleanup operations before the object is garbage collected, but its use is generally
discouraged in favor of the try-with-resources statement and implementing
AutoCloseable.

Question 2: Interface vs. Abstract Class

Problem Statement: Describe the difference between an interface and an abstract class in Java.

Answer:

 Interface: An interface in Java is a reference type that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot
contain instance fields. The methods in interfaces are abstract by default. A class can
implement multiple interfaces.
 Abstract Class: An abstract class can contain abstract methods (without bodies) as well
as implemented methods. Abstract classes can also contain fields. A class can extend
only one abstract class, which means Java supports single inheritance for classes.

Question 3: Wrapper Classes

Problem Statement: What are wrapper classes in Java?

Answer: Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as
objects. The primitive data type is wrapped in an object of its corresponding class. These classes
are part of the java.lang package and include Integer, Boolean, Character, Float, Double,
Short, Byte, and Long. Wrapper classes are used with collections, like ArrayList, which can
store only objects.

Question 4: String vs. StringBuilder vs. StringBuffer

Problem Statement: Compare String, StringBuilder, and StringBuffer in Java.

Answer:

 String: Strings are immutable in Java. Whenever a modification is made to a String, a


new String object is created.
 StringBuilder: StringBuilder is mutable. It provides an API for string manipulation
such as insertion, replacement, and deletion but it is not synchronized, which means it's
not thread-safe but faster in single-threaded environments.
 StringBuffer: Like StringBuilder, StringBuffer is also mutable and provides the same
API for string manipulation. However, it is synchronized, making it thread-safe but
slower than StringBuilder.

Question 5: Autoboxing and Unboxing


Problem Statement: What are autoboxing and unboxing in Java?

Answer:

 Autoboxing is the automatic conversion that the Java compiler makes between the
primitive types and their corresponding object wrapper classes. For example, converting
an int to an Integer, a double to a Double, and so on.
 Unboxing is the reverse process, where the Java compiler converts an object of a
wrapper class back to its corresponding primitive type.

public class NonRepeatingChar


{
public static void main(String[] args)
{
String str = "leetcode";
int[] freq = new int[26];
for (int i = 0; i < str.length(); i++)
{
freq[str.charAt(i) - 'a']++;
}
for (int i = 0; i < str.length(); i++)
{
if (freq[str.charAt(i) - 'a'] == 1)
{
System.out.println("First non-repeating character: " + str.charAt(i));
return;
}
}
System.out.println("There are no non-repeating characters in the string.");
}
}

import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int[] array = {1, 2, 3, -1, -2, 4};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}

You might also like