Core Java - Interview Questions
Compile-Time vs. Runtime Polymorphism
Question 101: Compile-Time vs. Runtime Polymorphism
Polymorphism ("many forms") allows objects of different classes to be treated as objects of a common type. The method called depends on whether the decision is made at compile time or runtime.
Feature | Compile-Time Polymorphism (Static Binding) | Runtime Polymorphism (Dynamic Binding) |
---|---|---|
Method Resolution | Compile time | Runtime |
Mechanism | Method overloading | Method overriding |
Binding | Static binding (early binding) | Dynamic binding (late binding) |
Flexibility | Less flexible | More flexible |
Speed | Faster execution | Slower execution |
Runtime Polymorphism
Question 102: Runtime Polymorphism
Runtime polymorphism (dynamic method dispatch) occurs when a call to an overridden method is resolved at runtime. The actual method called depends on the object's type, not the reference variable's type.
Java Code
class Bike {
void run() {
System.out.println("running");
}
}
class Splendor extends Bike {
void run() {
System.out.println("running safely with 60km");
}
public static void main(String args[]) {
Bike b = new Splendor();
b.run();
}
}
Output
running safely with 60km
Runtime Polymorphism with Data Members
Question 103: Runtime Polymorphism with Data Members
Runtime polymorphism cannot be achieved using data members because data members are not overridden. Only methods can be overridden.
Java Code
class Bike {
int speedlimit = 90;
}
class Honda3 extends Bike {
int speedlimit = 150;
public static void main(String args[]) {
Bike obj = new Honda3();
System.out.println(obj.speedlimit); // Output: 90
}
}
Static vs. Dynamic Binding
Question 104: Static vs. Dynamic Binding
Method binding (determining which method to call) can occur at compile time or runtime:
- Static Binding (Compile-Time): The method to be called is resolved at compile time. This happens when you call a non-overridden method.
- Dynamic Binding (Runtime): The method to be called is determined at runtime based on the object's type. This happens with overridden methods.
Dynamic Method Dispatch Example
Question 105: Dynamic Method Dispatch Example
Java Code
class BaseTest {
void print() {
System.out.println("BaseTest:print() called");
}
}
public class Test extends BaseTest {
void print() {
System.out.println("Test:print() called");
}
public static void main(String args[]) {
BaseTest b = new Test();
b.print();
}
}
Output
Test:print() called
Java `instanceof` Operator
Question 106: Java `instanceof` Operator
The Java instanceof
operator checks if an object is an instance of a particular class or interface. It returns true
if the object is an instance of the specified type or a subclass of that type; otherwise, it returns false
.
Java Code
class Simple1 {
public static void main(String args[]) {
Simple1 s = new Simple1();
System.out.println(s instanceof Simple1); // Output: true
}
}
Abstraction in Java
Question 107: Abstraction in Java
Abstraction in Java hides complex implementation details and shows only essential information to the user. It's achieved using abstract classes and interfaces.
Learn More About Abstraction in Java
Abstraction vs. Encapsulation
Question 108: Abstraction vs. Encapsulation
Abstraction focuses on what an object does; encapsulation focuses on how an object's data is protected and accessed.
Learn More About Abstraction and Encapsulation
Abstract Classes
Question 109: Abstract Classes
An abstract class in Java cannot be instantiated directly. It serves as a blueprint for subclasses, which provide implementations for the abstract methods.
Java Code
abstract class Bike {
abstract void run();
}
class Honda4 extends Bike {
void run() {
System.out.println("running safely");
}
public static void main(String args[]) {
Bike obj = new Honda4();
obj.run(); // Output: running safely
}
}
Learn More About Abstract Classes
Abstract Methods
Question 110: Abstract Methods
An abstract method is declared without an implementation (body). The subclasses must provide the implementation.
Abstract Methods and Classes
Question 111: Abstract Methods and Classes
Java Code
abstract class Calculate {
abstract int multiply(int a, int b);
}
public class Main {
public static void main(String[] args) {
int result = new Calculate() {
@Override
int multiply(int a, int b) {
return a * b;
}
}.multiply(12, 32);
System.out.println("result = " + result); // Output: 384
}
}
Abstract and Final Methods
Question 112: Abstract and Final Methods
You cannot declare a method as both abstract and final because an abstract method requires implementation in subclasses, whereas a final method cannot be overridden.
Instantiating Abstract Classes
Question 113: Instantiating Abstract Classes
Abstract classes cannot be instantiated directly. You must create a subclass that provides implementations for all the abstract methods.
Interfaces
Question 114: Interfaces in Java
An interface in Java is a reference type that can contain constants, method signatures, default methods, static methods, and nested types. It's used to achieve abstraction and multiple inheritance.
Learn More About Interfaces in Java
Question 115: Static Methods in Interfaces
Yes, you can declare methods as static within a Java interface. Static methods are associated with the interface itself, not with any specific instance of a class that implements the interface.
Polymorphism: Compile-Time vs. Runtime
Question 101: Compile-Time vs. Runtime Polymorphism
Polymorphism lets you treat objects of different classes in a uniform way. The type of the object determines which method to call. This decision can happen during compilation (compile-time polymorphism) or during execution (runtime polymorphism).
Feature | Compile-Time Polymorphism | Runtime Polymorphism |
---|---|---|
Method Resolution | At compile time | At runtime |
Mechanism | Method overloading | Method overriding |
Flexibility | Less flexible | More flexible |
Performance | Faster execution | Slower execution |
Runtime Polymorphism
Question 102: Runtime Polymorphism
Runtime polymorphism (dynamic method dispatch) occurs when a call to an overridden method is resolved during program execution. The specific method invoked depends on the object's type.
Java Code
class Bike {
void run() {
System.out.println("running");
}
}
class Splendor extends Bike {
void run() {
System.out.println("running safely with 60km");
}
public static void main(String args[]) {
Bike b = new Splendor();
b.run(); // Output: running safely with 60km
}
}
Runtime Polymorphism and Data Members
Question 103: Runtime Polymorphism with Data Members
Runtime polymorphism cannot be achieved with data members because data members are not overridden. Only methods can be overridden.
Java Code
class Bike {
int speedlimit = 90;
}
class Honda3 extends Bike {
int speedlimit = 150;
public static void main(String args[]) {
Bike obj = new Honda3();
System.out.println(obj.speedlimit); // Output: 90
}
}
Static vs. Dynamic Binding
Question 104: Static vs. Dynamic Binding
Method binding (determining which method to call) happens at either compile time or runtime:
- Static Binding (Compile-Time): The method is determined at compile time.
- Dynamic Binding (Runtime): The method is determined at runtime based on the object type.
Static Binding Example
class Dog {
private void eat() {
System.out.println("dog is eating...");
}
public static void main(String args[]) {
Dog d1 = new Dog();
d1.eat(); //dog is eating...
}
}
Dynamic Binding Example
class Animal {
void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog is eating...");
}
public static void main(String args[]) {
Animal a = new Dog();
a.eat(); //dog is eating...
}
}
Abstraction in Java
Question 107: Abstraction in Java
Abstraction in Java hides implementation details and exposes only essential information to the user. This simplifies interaction with objects. Abstract classes and interfaces are used to achieve abstraction.
Abstraction vs. Encapsulation
Question 108: Abstraction vs. Encapsulation
Abstraction focuses on *what* an object does; encapsulation focuses on *how* an object's data is protected and managed.
Learn More About Abstraction and Encapsulation
Abstract Classes
Question 109: Abstract Classes
An abstract class in Java cannot be instantiated directly. It serves as a blueprint for subclasses, which provide implementations for abstract methods. Abstract classes can have both abstract and non-abstract methods.
Java Code
abstract class Bike {
abstract void run();
}
class Honda4 extends Bike {
void run() {
System.out.println("running safely");
}
public static void main(String args[]) {
Bike obj = new Honda4();
obj.run(); // Output: running safely
}
}
Abstract Methods
Question 110: Abstract Methods
Abstract methods are declared without a body (implementation). Subclasses *must* provide an implementation.
Abstract Methods and Classes
Question 111: Abstract Methods and Classes
Java Code
abstract class Calculate {
abstract int multiply(int a, int b);
}
public class Main {
public static void main(String[] args) {
int result = new Calculate() {
@Override
int multiply(int a, int b) {
return a * b;
}
}.multiply(12, 32);
System.out.println("result = " + result); // Output: 384
}
}
Abstract and Final Methods
Question 112: Abstract and Final Methods
A method cannot be both abstract and final because abstract methods require implementation by subclasses, while final methods prevent overriding.
Instantiating Abstract Classes
Question 113: Instantiating Abstract Classes
No, you cannot directly create instances (objects) of abstract classes. You must create a concrete subclass that provides implementations for all abstract methods.
Interfaces
Question 114: Interfaces
An interface is a completely abstract class. It defines a contract that implementing classes must adhere to, specifying method signatures (but not implementations). Interfaces support multiple inheritance (a class can implement multiple interfaces).
Static Methods in Interfaces
Question 115: Static Methods in Interfaces
Since Java 8, you can have static methods in interfaces. These methods belong to the interface itself, not to any specific implementing class.
Final Interfaces
Question 116: Final Interfaces
An interface cannot be declared as `final` because it needs to be implemented by classes.
Marker Interfaces
Question 117: Marker Interfaces
A marker interface is an interface with no methods or fields. It serves as a tag to indicate that a class has a certain characteristic (e.g., `Serializable`, `Cloneable`).
Abstract Class vs. Interface
Question 118: Abstract Class vs. Interface
Key differences:
Feature | Abstract Class | Interface |
---|---|---|
Methods | Can have abstract and concrete methods | Only abstract methods (before Java 8); can have default and static methods (since Java 8) |
Variables | Can have instance variables | Cannot have instance variables (only static final) |
Inheritance | Single inheritance | Multiple inheritance |
Constructors | Can have constructors | Cannot have constructors |
Private and Protected Members in Interfaces
Question 119: Private and Protected Members in Interfaces
Interface members are implicitly public. You cannot use `private` or `protected` access modifiers.
Casting to Interface References
Question 120: Casting to Interface References
You can cast an object reference to an interface reference only if the object's class implements that interface.
Read-Only Classes
Question 121: Read-Only Classes
Make a class read-only by making all fields private and providing only getter methods.
Java Code
public class Student {
private String college = "AKG";
public String getCollege() {
return college;
}
}
Write-Only Classes
Question 122: Write-Only Classes
Make a class write-only by making all fields private and providing only setter methods.
Java Code
public class Student {
private String college;
public void setCollege(String college) {
this.college = college;
}
}
Advantages of Encapsulation
Question 123: Advantages of Encapsulation
Benefits of encapsulation:
- Data hiding and protection.
- Improved code modularity and maintainability.
- Read-only and write-only access control.
- Data validation.
- Easier testing.
Packages in Java
Question 124: Packages in Java
Packages group related classes and interfaces. They provide a namespace and control access.
Java Code
package mypack;
public class Simple {
public static void main(String args[]) {
System.out.println("Welcome to package"); // Output: Welcome to package
}
}
Advantages of Packages
Question 125: Advantages of Packages
Advantages of using packages:
- Avoid naming conflicts.
- Improved code organization.
- Namespace management.
Creating Packages
Question 126: Creating Packages
Create packages using the `package` keyword in your Java code and compile using `javac -d . YourClassName.java`.
Accessing Classes
Question 127: Accessing Classes in Different Packages
You can access classes in other packages using their fully qualified names or by importing the package.
`java.lang` Package
Question 128: `java.lang` Package
The java.lang
package is implicitly imported in all Java programs; you don't need to import it explicitly.
Multiple Imports
Question 129: Multiple Imports of Same Package/Class
Multiple imports of the same package or class are allowed. The JVM will load the class only once.
Static Imports
Question 130: Static Imports
Static imports let you directly access static members of a class without using the class name.
Learn More About Static Imports
Exception Handling in Java
Question 131: Types of Exceptions in Java
Java has:
- Checked Exceptions: Must be handled (using `try-catch` or `throws`) at compile time.
- Unchecked Exceptions: Don't need to be explicitly handled at compile time; they're runtime exceptions.
- Errors: Serious problems that usually cause program termination.
Question 132: Exception Handling
Exception handling in Java is a mechanism to gracefully manage runtime errors. It helps prevent program crashes by allowing you to handle unexpected events. It involves using `try`, `catch`, and `finally` blocks to deal with exceptions that may arise during program execution.
Java Exception Hierarchy
Question 133: Java Exception Hierarchy
The Java exception hierarchy starts with the `Throwable` class. `Throwable` has two main branches: `Exception` and `Error`. Exceptions are recoverable; Errors generally indicate severe problems and cause program termination.
(A diagram illustrating the Java Exception hierarchy would be beneficial here but is not directly representable in HTML.)
Checked vs. Unchecked Exceptions
Question 134: Checked vs. Unchecked Exceptions
Key differences:
Feature | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Handling | Must be handled (using `try-catch` or `throws`) at compile time. | Don't need to be explicitly handled at compile time; handled at runtime. |
Types | Extend `Throwable` except `RuntimeException` and `Error`. | Extend `RuntimeException`. |
Examples | IOException , SQLException |
NullPointerException , ArithmeticException |
Base Class for Error and Exception
Question 135: Base Class for Error and Exception
The `Throwable` class is the base class for both `Error` and `Exception` classes in Java.
`try` Blocks and `catch` Blocks
Question 136: `try` Blocks and `catch` Blocks
Each `try` block can be followed by zero or more `catch` blocks to handle specific exceptions or a single `finally` block for cleanup code. The `finally` block always executes, regardless of whether an exception is thrown.
Java Code
public class Main {
public static void main(String[] args) {
try {
int a = 1;
System.out.println(a / 0);
}
finally {
System.out.println("rest of the code..."); //Always executed
}
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
rest of the code...
Multiple `catch` Blocks
Question 137: Multiple `catch` Blocks
When using multiple `catch` blocks, the order is important. Subclasses must come *before* their superclasses because a subclass exception would be caught by the parent class.
`finally` Block
Question 138: `finally` Block
The `finally` block executes after the `try` and `catch` blocks. It's used for cleanup actions (e.g., closing resources) that must happen regardless of whether an exception occurred. A `finally` block is not executed if the program terminates abruptly (e.g., using `System.exit()`).
Learn More About finally Blocks
`finally` Without `catch`
Question 139: `finally` Block Without `catch`
Yes, a `try` block can be followed by a `finally` block without any `catch` blocks. In this case, the `finally` block will execute regardless of whether an exception is thrown in the `try` block.
Learn More About finally Blocks
When `finally` Doesn't Execute
Question 140: When `finally` Is Not Executed
The `finally` block is not executed if the Java Virtual Machine (JVM) exits abruptly due to a fatal error or a call to System.exit()
.
Learn More About finally Blocks
`throw` vs. `throws`
Question 141: `throw` vs. `throws`
Key differences:
Keyword | Purpose |
---|---|
throw |
Throws an exception explicitly. |
throws |
Declares that a method might throw an exception (used in method signatures). |
Learn More About throw and throws
Throwing Non-Throwable Objects
Question 142: Throwing Non-Throwable Objects
Java Code
public class Main {
public static void main(String[] args) {
try {
throw 90; // Compile-time error: incompatible types
} catch (int e) { // Compile-time error: int is not Throwable
System.out.println("Caught the exception " + e);
}
}
}
Output
Compile-time error
Throwing Custom Exceptions
Question 143: Throwing Custom Exceptions
Java Code
class Calculation extends Exception {
public Calculation() {
System.out.println("Calculation class is instantiated"); // Output: Calculation class is instantiated
}
public void add(int a, int b) {
System.out.println("The sum is " + (a + b)); // Output: The sum is 30
}
}
public class Main {
public static void main(String[] args) {
try {
throw new Calculation();
} catch (Calculation c) {
c.add(10, 20);
}
}
}
Rethrowing Exceptions
Question 144: Rethrowing Exceptions
Yes, you can rethrow an exception in a `catch` block using `throw;` or `throw new ExceptionType(...)`.
Overriding Methods and Exceptions
Question 145: Subclass Exception Declaration
A subclass method that overrides a superclass method can declare a narrower set of checked exceptions. It cannot declare additional checked exceptions, but unchecked exceptions are allowed.
Exception Propagation
Question 146: Exception Propagation
Exception propagation is when an uncaught exception moves up the call stack from the method where it's thrown until it's caught or reaches the top of the call stack.
Java Code
class TestExceptionPropagation1 {
void m() {
int data = 50 / 0; // Throws ArithmeticException
}
void n() {
m();
}
void p() {
try {
n();
} catch (Exception e) {
System.out.println("exception handled"); // Output: exception handled
}
}
public static void main(String args[]) {
TestExceptionPropagation1 obj = new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow..."); // Output: normal flow...
}
}
Nested `try-catch-finally` Blocks
Question 147: Nested try-catch-finally Blocks
Java Code
public class Main {
void a() {
try {
System.out.println("a(): Main called"); // Output: a(): Main called
b();
} catch (Exception e) {
System.out.println("Exception is caught"); // Output: Exception is caught
}
}
void b() throws Exception {
try {
System.out.println("b(): Main called"); // Output: b(): Main called
c();
} catch (Exception e) {
throw new Exception();
} finally {
System.out.println("finally block is called"); // Output: finally block is called
}
}
void c() throws Exception {
throw new Exception();
}
public static void main(String args[]) {
Main m = new Main();
m.a();
}
}
Question 148: Exception Handling in Constructor
Java Code
public class Calculation {
int a;
public Calculation(int a) {
this.a = a;
}
public int add() {
a = a + 10;
try {
a = a + 10;
try {
a = a * 10;
throw new Exception();
} catch (Exception e) {
a = a - 10;
}
} catch (Exception e) {
a = a - 10;
}
return a;
}
public static void main(String[] args) {
try {
Calculation c = new Calculation(2);
System.out.println(c.add()); // Output: 190
} catch (Exception e) {
System.out.println("Exception caught!");
}
}
}
More on Java Exception Handling
Question 133: Java Exception Hierarchy (Continued)
The `Throwable` class is the root of the exception hierarchy. `Exception` and `Error` are its subclasses. Exceptions represent conditions you can recover from, while errors are severe, often unrecoverable problems.
Checked vs. Unchecked Exceptions (Continued)
Question 134: Checked vs. Unchecked Exceptions (Continued)
Checked exceptions are those that the compiler forces you to handle (using `try-catch` blocks or declaring them in the `throws` clause). Unchecked exceptions (including `RuntimeException` and `Error`) don't need to be handled explicitly during compilation.
`try-catch-finally` (Continued)
Question 136: `try`-`catch`-`finally` Blocks (Continued)
A `try` block contains code that might throw an exception. `catch` blocks handle specific exceptions. The `finally` block executes regardless of whether an exception occurred (unless the JVM exits abruptly).
Java Code
public class Main {
public static void main(String[] args) {
try {
int a = 1 / 0;
}
finally {
System.out.println("Finally block executed"); // Output: Finally block executed
}
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
Finally block executed
`throw` and `throws` Keywords
Question 141: `throw` vs. `throws`
The `throw` keyword is used to explicitly throw an exception. The `throws` keyword is used in method signatures to declare that a method might throw one or more checked exceptions. The compiler then forces you to handle these exceptions.
Throwing and Catching Primitive Types
Question 142: Throwing an Integer
Java Code
public class Main {
public static void main(String[] args) {
try {
throw 90; // Compile-time error
} catch (int e) { // Compile-time error
System.out.println("Caught the exception " + e);
}
}
}
Output
Compile-time error: incompatible types
Exception Propagation (Continued)
Question 146: Exception Propagation (Continued)
An unhandled exception propagates up the call stack until a suitable `catch` block is found or the program terminates.
Java Code
class TestExceptionPropagation1 {
void m() {
int data = 50 / 0; // Throws ArithmeticException
}
void n() {
m();
}
void p() {
try {
n();
} catch (Exception e) {
System.out.println("Exception handled"); // Output: Exception handled
}
}
public static void main(String args[]) {
TestExceptionPropagation1 obj = new TestExceptionPropagation1();
obj.p();
System.out.println("Normal flow..."); // Output: Normal flow...
}
}
Nested `try-catch-finally` (Continued)
Question 147: Nested `try-catch-finally` Blocks (Continued)
You can nest `try-catch-finally` blocks. The `finally` block of an inner `try` block executes before the `catch` block of the outer `try` block if an exception is thrown from the inner block.
Java Code
public class Main {
void a() {
try {
System.out.println("a(): Main called");
b();
} catch (Exception e) {
System.out.println("Exception is caught in a()");
}
}
void b() throws Exception {
try {
System.out.println("b(): Main called");
c();
} catch (Exception e) {
System.out.println("Exception is caught in b()");
throw new Exception(); // Re-throwing the exception
} finally {
System.out.println("finally block is called in b()");
}
}
void c() throws Exception {
throw new Exception();
}
public static void main(String args[]) {
Main m = new Main();
try{
m.a();
} catch(Exception e){
System.out.println("Exception is caught in main"); // Output: Exception is caught in main
}
}
}
Output
a(): Main called
b(): Main called
finally block is called in b()
Exception is caught in a()
Exception is caught in main
Exception Handling in Constructor
Question 148: Exception Handling in Constructor
Java Code
public class Calculation {
int a;
public Calculation(int a) {
this.a = a;
}
public int add() {
a = a + 10;
try {
a = a + 10;
try {
a = a * 10;
throw new Exception();
} catch (Exception e) {
a = a - 10;
}
} catch (Exception e) {
a = a - 10;
}
return a;
}
public static void main(String[] args) {
try {
Calculation c = new Calculation(2);
System.out.println(c.add()); // Output: 190
} catch (Exception e) {
System.out.println("Exception caught!");
}
}
}
String Pool in Java
Question 149: String Pool in Java
The String pool is a memory area in the Java heap that stores string literals. This optimizes memory usage by reusing existing strings instead of creating new ones if the same string already exists in the pool. Strings created using the `new` keyword do not directly go into the string pool.
Immutability of Strings
Question 150: Immutability of Strings
Strings in Java are immutable. Once a string object is created, its value cannot be changed. Methods like `concat()` create a new string object instead of modifying the original.
Java Code
class Testimmutablestring {
public static void main(String args[]) {
String s = "Sachin";
s.concat(" Tendulkar");
System.out.println(s); // Output: Sachin
}
}
Reasons for String Immutability
Question 151: Reasons for String Immutability
Immutability prevents unintended modifications and ensures thread safety in concurrent applications. It also enables efficient string sharing (string literals).
Creating String Objects
Question 152: Creating String Objects
Two main ways:
- String literals: Using double quotes (
String s = "hello";
). These go into the string pool. - Using the `new` keyword: (
String s = new String("hello");
). Creates a new object in the heap (and also places the literal "hello" in the String pool).
Number of Objects Created
Question 153: Number of Objects Created
Java Code
String s1 = "Welcome";
String s2 = "Welcome";
String s3 = "Welcome";
Output
One object (in the String pool)
Question 155: Number of Objects Created
Java Code
String s = new String("Welcome");
Output
Two objects (one in the String pool, one in the heap)
String Literals
Question 154: Why String Literals?
Java uses string literals to improve memory efficiency. If a string literal already exists, it's reused.
`==` vs. `equals()`
Question 156: `==` vs. `equals()` for Strings
Java Code
public class Test {
public static void main(String args[]) {
String a = new String("Sharma is a good player");
String b = "Sharma is a good player";
if (a == b) {
System.out.println("a == b");
}
if (a.equals(b)) {
System.out.println("a equals b"); // Output: a equals b
}
}
}
`intern()` Method
Question 157: `intern()` Method
Java Code
public class Test {
public static void main(String args[]) {
String s1 = "Sharma is a good player";
String s2 = new String("Sharma is a good player");
s2 = s2.intern();
System.out.println(s1 == s2); // Output: true
}
}
`String` vs. `StringBuffer` vs. `StringBuilder`
Question 158: `String` vs. `StringBuffer`
Key differences:
Feature | String | StringBuffer |
---|---|---|
Mutability | Immutable | Mutable |
Thread Safety | Thread-safe | Thread-safe |
Performance | Slower for string concatenation | Faster for string concatenation |
Question 159: `StringBuffer` vs. `StringBuilder`
Key differences:
Feature | StringBuffer | StringBuilder |
---|---|---|
Thread Safety | Synchronized (thread-safe) | Not synchronized (not thread-safe) |
Performance | Slower | Faster |
Creating Immutable Classes
Question 160: Creating Immutable Classes
To create an immutable class, declare the class as `final` and make all fields `final`. Do not provide any setter methods.
Java Code
public final class Employee {
final String pancardNumber;
public Employee(String pancardNumber) {
this.pancardNumber = pancardNumber;
}
public String getPancardNumber() {
return pancardNumber;
}
}
`toString()` Method
Question 161: `toString()` Method
The `toString()` method returns a string representation of an object. Overriding this method provides a custom string representation.
Java Code
class Student {
int rollno;
String name;
String city;
Student(int rollno, String name, String city) {
this.rollno = rollno;
this.name = name;
this.city = city;
}
public String toString() {
return rollno + " " + name + " " + city;
}
public static void main(String args[]) {
Student s1 = new Student(101, "Raj", "lucknow");
Student s2 = new Student(102, "Vijay", "ghaziabad");
System.out.println(s1); // Output: 101 Raj lucknow
System.out.println(s2); // Output: 102 Vijay ghaziabad
}
}
`toCharArray()` for Password Storage
Question 162: `toCharArray()` for Password Storage
Using `toCharArray()` to store passwords is often preferred over using `String` because `String` objects can persist in memory longer, creating potential security risks. `toCharArray()` allows you to easily clear the password from memory after use.
Counting Words in a String
Question 163: Counting Words in a String
Java Code
public class Test {
public static void main(String args[]) {
String s = "Sharma is a good player and he is so punctual";
String words[] = s.split("\\s+"); //splits string by spaces
System.out.println("Number of words: " + words.length); // Output: Number of words: 10
}
}
`java.util.regex` Package
Question 164: `java.util.regex` Package
The `java.util.regex` package provides classes for working with regular expressions in Java. Key classes include `Pattern` and `Matcher`.
Metacharacters in Regular Expressions
Question 165: Metacharacters in Regular Expressions
Metacharacters have special meanings in regular expressions (e.g., `^`, `$`, `.`, `*`, `+`). To use them literally, escape them with a backslash (`\`).
Password Validation with Regular Expressions
Question 166: Password Validation Regex
Regular Expression
^[a-zA-Z][a-zA-Z0-9]{7,19}$
Regular Expression Matching
Question 167: Regular Expression Matching
Java Code
import java.util.regex.*;
class RegexExample2 {
public static void main(String args[]) {
System.out.println(Pattern.matches(".s", "as")); // Output: true
System.out.println(Pattern.matches(".s", "mk")); // Output: false
System.out.println(Pattern.matches(".s", "mst")); // Output: false
System.out.println(Pattern.matches(".s", "amms"));// Output: false
System.out.println(Pattern.matches("..s", "mas")); // Output: true
}
}
Advantages of Inner Classes
Question 168: Advantages of Inner Classes
Benefits of inner classes:
- Access to outer class members.
- Improved code organization and readability.
Nested Classes
Question 169: Nested Classes
A nested class is a class declared inside another class or interface. Nested classes can be static or non-static (inner classes).
Disadvantages of Inner Classes
Question 170: Disadvantages of Inner Classes
Drawbacks of inner classes:
- Increased class count; potential performance impact.
- Reduced IDE support compared to top-level classes.
Types of Inner Classes
Question 171: Types of Inner Classes
Three main types:
- Member inner class: Declared inside a class but outside any method.
- Anonymous inner class: A class without a name; created inline.
- Local inner class: Declared inside a method.
Nested vs. Inner Classes
Question 172: Nested vs. Inner Classes
Inner classes are non-static nested classes.
Accessing Local Variables in Inner Classes
Question 173: Accessing Local Variables in Inner Classes
To access a local variable from within a local inner class, the variable must be declared as `final`.
Number of Class Files
Question 174: Number of Class Files Generated
Java Code
public class Person {
String name, age, address;
class Employee {
float salary = 10000;
}
class BusinessMen {
final String gstin = "4433drt3$";
}
public static void main(String args[]) {
Person p = new Person();
}
}
Output
Three: Person.class, Person$Employee.class, Person$BusinessMen.class
Anonymous Inner Classes
Question 175: Anonymous Inner Classes
Anonymous inner classes are unnamed classes defined and instantiated at the point of use. They're commonly used to implement interfaces or extend classes concisely.
Java Code
interface Eatable {
void eat();
}
class TestAnnonymousInner1 {
public static void main(String args[]) {
Eatable e = new Eatable() {
public void eat() {
System.out.println("nice fruits"); // Output: nice fruits
}
};
e.eat();
}
}
Nested Interfaces
Question 176: Nested Interfaces
A nested interface is an interface declared inside another interface or class. They're used to logically group interfaces and improve code organization.
Interfaces Within Classes
Question 177: Interfaces Within Classes
Yes, you can define interfaces within a class. These are nested interfaces.
Classes Within Interfaces
Question 178: Classes Within Interfaces
Yes, interfaces can contain classes; these classes are implicitly static.
Garbage Collection
Question 179: Garbage Collection
Garbage collection in Java is the automatic process of reclaiming memory occupied by objects that are no longer referenced by the program. This prevents memory leaks and improves memory management. The garbage collector runs periodically to identify and remove these unused objects.
`System.gc()` and `Runtime.gc()`
Question 180: `gc()` Method
The `System.gc()` and `Runtime.getRuntime().gc()` methods suggest to the Java Virtual Machine (JVM) that it should perform garbage collection. However, the JVM is not obligated to perform garbage collection immediately; it's up to the JVM to decide when to run garbage collection based on its internal algorithms and available resources.
Java Code
public class TestGarbage1 {
public void finalize() {
System.out.println("object is garbage collected");
}
public static void main(String args[]) {
TestGarbage1 s1 = new TestGarbage1();
TestGarbage1 s2 = new TestGarbage1();
s1 = null;
s2 = null;
System.gc();
}
}
Output (May Vary; JVM-Dependent)
object is garbage collected
object is garbage collected
Making Objects Unreferenced
Question 182: Making Objects Unreferenced
Ways to make an object eligible for garbage collection:
- Setting the reference to `null`:
myObject = null;
- Assigning a different reference:
myObject = anotherObject;
- Creating an anonymous object: `new MyClass();` (no reference is kept).
`finalize()` Method
Question 183: `finalize()` Method
The `finalize()` method is called by the garbage collector on an object before it's garbage collected. Use it for cleanup operations (e.g., closing files or network connections). It is not guaranteed to be called before garbage collection.
Java Code
public class FinalizeTest {
int j = 12;
void add() {
j = j + 12;
System.out.println("J=" + j);
}
public void finalize() {
System.out.println("Object is garbage collected");
}
public static void main(String[] args) {
new FinalizeTest().add(); // Output: J=24
System.gc();
new FinalizeTest().add(); // Output: J=24
}
}
Output (May Vary; JVM-Dependent)
J=24
Object is garbage collected
J=24
Object is garbage collected
Referencing Unreferenced Objects
Question 184: Referencing Unreferenced Objects
Yes, an object that's been marked for garbage collection can be referenced again. In this case, it will not be garbage collected until it becomes unreferenced again.
Garbage Collector Thread Type
Question 185: Garbage Collector Thread Type
The garbage collector thread is a daemon thread.
`final`, `finally`, `finalize`
Question 186: `final`, `finally`, `finalize`
In Java:
Keyword/Block/Method | Purpose |
---|---|
final |
Restricts modification (classes, methods, variables). |
finally |
Block of code that always executes (after `try`-`catch`). |
finalize() |
Method called before garbage collection (for cleanup). |
`Runtime` Class
Question 187: `Runtime` Class
The `Runtime` class provides access to the Java runtime environment. It allows you to interact with the system (e.g., get memory information, execute external processes).
Executing External Processes
Question 188: Executing External Processes
Java Code
public class Runtime1 {
public static void main(String args[]) throws Exception {
Runtime.getRuntime().exec("notepad"); //Opens notepad (or equivalent on your system)
}
}
Input/Output (I/O) Streams
Question 189: InputStream and OutputStream Hierarchy
(This question would require diagrams to best illustrate the inheritance hierarchies. The diagrams should clearly show the inheritance relationships between various input and output stream classes.)
I/O Streams
Question 190: I/O Streams
I/O streams in Java are used for input and output operations. They represent a sequence of bytes or characters flowing from a source to a destination. Java provides several predefined streams (e.g., `System.in`, `System.out`, `System.err`).
`Reader`/`Writer` vs. `InputStream`/`OutputStream`
Question 191: `Reader`/`Writer` vs. `InputStream`/`OutputStream`
The `InputStream`/`OutputStream` classes are byte-oriented; the `Reader`/`Writer` classes are character-oriented. Character streams handle Unicode characters more efficiently.
Superclasses for Streams
Question 192: Superclasses for Streams
The root classes for stream hierarchies are `java.io.InputStream` and `java.io.OutputStream` for byte streams, and `java.io.Reader` and `java.io.Writer` for character streams.
`FileInputStream` and `FileOutputStream`
Question 193: `FileInputStream` and `FileOutputStream`
FileInputStream
reads data from a file; `FileOutputStream` writes data to a file. These are byte streams.
Writing to a File (FileOutputStream)
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]) {
try {
FileOutputStream fout = new FileOutputStream("output.txt");
fout.write(65); // Writes 'A' (ASCII 65)
fout.close();
System.out.println("success..."); // Output: success...
} catch (Exception e) {
System.out.println(e);
}
}
}
Reading from a File (FileInputStream)
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]) {
try {
FileInputStream fin = new FileInputStream("output.txt");
int i = fin.read();
System.out.print((char) i); // Output: A
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Buffered Streams
Question 194: BufferedInputStream and BufferedOutputStream
BufferedInputStream
and BufferedOutputStream
improve I/O performance by using an internal buffer to reduce the number of disk access operations.
String Immutability and Security
Question 162: `toCharArray()` for Password Storage
Storing passwords as a character array (`char[]`) is generally safer than storing them as Strings in Java because Strings are immutable. Once a String object is created, it's stored in memory, and its contents might be vulnerable to memory dumps or other security breaches. A `char[]` allows you to explicitly clear the sensitive data from memory after it's no longer needed using `Arrays.fill(passwordArray, ' ');`
Java Code
char[] password = password.toCharArray();
// ... use password ...
Arrays.fill(password, ' '); // Clear the password from memory
Counting Words in a String
Question 163: Counting Words in a String
Java Code
public class Test {
public static void main(String args[]) {
String s = "Sharma is a good player and he is so punctual";
String[] words = s.split("\\s+"); //splits string by spaces
System.out.println("Number of words: " + words.length); // Output: Number of words: 10
}
}
`java.util.regex` Package (Continued)
Question 164: `java.util.regex` Package (Continued)
The `java.util.regex` package provides classes for working with regular expressions. Key classes include:
- `Pattern` (compiles regular expressions)
- `Matcher` (performs matching operations)
- `MatchResult` (represents a match result)
- `PatternSyntaxException` (indicates errors in regular expression syntax)
Metacharacters
Question 165: Metacharacters in Regular Expressions
Metacharacters in regular expressions have special meanings (e.g., `^` for start of string, `$` for end of string, `.` for any character, `*` for zero or more occurrences). To match a metacharacter literally, escape it with a backslash (`\`).
Password Validation Regex
Question 166: Password Validation Regex
A regular expression to validate a password (starting with an alphabet, followed by alphanumeric characters, length 8-20):
Regular Expression
^[a-zA-Z][a-zA-Z0-9]{7,19}$
Regular Expression Matching Example
Question 167: Regular Expression Matching Example
Java Code
import java.util.regex.*;
class RegexExample2 {
public static void main(String args[]) {
System.out.println(Pattern.matches(".s", "as")); // true
System.out.println(Pattern.matches(".s", "mk")); // false
System.out.println(Pattern.matches(".s", "mst")); // false
System.out.println(Pattern.matches(".s", "amms"));// false
System.out.println(Pattern.matches("..s", "mas")); // true
}
}
Advantages of Inner Classes
Question 168: Advantages of Inner Classes
Advantages of using inner classes in Java:
- They can access members (fields and methods) of their enclosing class, even private ones.
- They help organize code logically, improving readability and maintainability.
- They can be used to create more concise code in some cases.
Nested Classes
Question 169: Nested Classes
A nested class is a class declared within another class. A nested class can be `static` (not associated with an instance of the outer class) or non-static (an inner class).
Disadvantages of Inner Classes
Question 170: Disadvantages of Inner Classes
Disadvantages:
- Can increase code complexity.
- May impact performance (due to increased class loading).
- Reduced IDE support compared to top-level classes.
Types of Inner Classes
Question 171: Types of Inner Classes
Types of inner classes:
- Member inner class: Declared inside a class, outside any method.
- Anonymous inner class: Unnamed class defined inline.
- Local inner class: Declared inside a method.
Nested vs. Inner Classes
Question 172: Nested vs. Inner Classes
Inner classes are non-static nested classes. They have an implicit reference to an instance of the outer class.
Accessing Local Variables
Question 173: Accessing Local Variables in Inner Classes
To access a local variable from within a local inner class, that variable must be declared as `final` (or effectively final in Java 8 and later).
Number of Class Files from Nested Classes
Question 174: Number of Class Files from Nested Classes
Java Code
public class Person {
String name, age, address;
class Employee {
float salary = 10000;
}
class BusinessMen {
final String gstin = "4433drt3$";
}
public static void main(String args[]) {
Person p = new Person();
}
}
Output
Three class files will be created: Person.class, Person$Employee.class, and Person$BusinessMen.class
Anonymous Inner Classes
Question 175: Anonymous Inner Classes
An anonymous inner class is an unnamed class defined and instantiated at the point of use. It's often used for short, simple implementations of interfaces or abstract classes.
Java Code
interface Eatable {
void eat();
}
class TestAnnonymousInner1 {
public static void main(String args[]) {
Eatable e = new Eatable() {
public void eat() {
System.out.println("nice fruits"); // Output: nice fruits
}
};
e.eat();
}
}
Nested Interfaces
Question 176: Nested Interfaces
A nested interface is an interface declared within another interface or class. They improve code organization by grouping related interfaces together.
Interfaces within Classes
Question 177: Interfaces within Classes
Yes, you can define interfaces within classes. These are nested interfaces.
Classes within Interfaces
Question 178: Classes within Interfaces
Yes, you can define classes within interfaces; these nested classes are implicitly static.
Serialization: Transient Keyword
Question 204: `transient` Keyword
The `transient` keyword in Java prevents a field from being serialized. If a field is marked as `transient`, its value will not be saved when the object is serialized and will not be restored when the object is deserialized.
`Externalizable` Interface
Question 205: `Externalizable` Interface
The `Externalizable` interface provides fine-grained control over serialization. Unlike `Serializable`, it requires implementing the `writeExternal()` and `readExternal()` methods, allowing you to customize how the object's state is written and read.
`Serializable` vs. `Externalizable`
Question 206: `Serializable` vs. `Externalizable`
Key differences:
Feature | Serializable |
Externalizable |
---|---|---|
Methods | No methods (marker interface) | writeExternal() and readExternal() methods must be implemented |
Control | Limited control over serialization process | Full control over serialization process |
Performance | Generally slower | Generally faster (more efficient) |
Constructor | No constructor called during serialization | Default constructor must be available and is called during deserialization |
Example: Preventing Serialization with Externalizable
import java.io.*;
class Person implements Serializable {
String name;
public Person(String name) { this.name = name; }
}
class Employee extends Person {
float salary;
public Employee(String name, float salary) {
super(name);
this.salary = salary;
}
private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new NotSerializableException();
}
}
public class Test {
// ... (Serialization/Deserialization code) ...
}
Network Transfer of Serialized Objects
Question 202: Network Transfer of Serialized Objects
Yes, serialized objects can be transferred over a network because they are converted into a stream of bytes. This is commonly used in distributed systems for passing Java objects between different machines.
Deserialization
Question 203: Deserialization
Deserialization reconstructs an object from its serialized representation (byte stream). This is the reverse process of serialization.
Java Code
import java.io.*;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) { this.id = id; this.name = name;}
}
public class Depersist{
public static void main(String args[]) throws Exception{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt"));
Student s = (Student)in.readObject();
System.out.println(s.id + " " + s.name); // Output: 211 ravi
in.close();
}
}
Transient Keyword
Question 204: `transient` Keyword
The `transient` keyword prevents a variable from being serialized. Its value is not preserved when the object is written to a stream and restored from that stream.
`Externalizable` Interface (Again)
Question 205: `Externalizable` Interface (Again)
The `Externalizable` interface provides more control over serialization than `Serializable` by requiring you to explicitly implement the `writeExternal()` and `readExternal()` methods.
Java Socket Programming
Question 207: Java Socket Programming
Java socket programming enables network communication between applications using sockets (endpoints for communication). Socket programming can be connection-oriented (using TCP) or connectionless (using UDP).
Sockets
Question 208: Sockets
Sockets are endpoints for network communication, providing a mechanism for applications to send and receive data.
TCP Connection Steps
Question 209: TCP Connection Steps
Steps involved in a TCP (Transmission Control Protocol) connection:
- Server creates a `ServerSocket` listening on a port.
- Client creates a `Socket` and attempts to connect to the server's IP address and port.
- Server accepts the connection using `accept()`.
- Communication takes place between the client and server sockets.
- Sockets are closed when finished.
Client-Server Example
Question 210: Client-Server Example
MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = dis.readUTF();
System.out.println("message= " + str); // Output: message= Hello Server
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
IP Address to Hostname
Question 211: Converting IP Address to Hostname
Use InetAddress.getByName("ip_address").getHostName()
to convert a numeric IP address to a hostname.
Java Code
import java.net.*;
public class InetDemo {
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getByName("192.168.1.1"); // Replace with a valid IP address
System.out.println("Hostname: " + ip.getHostName());
} catch (Exception e) {
System.out.println(e);
}
}
}
Reflection in Java
Question 212: Reflection in Java
Reflection allows you to inspect and manipulate the structure and behavior of classes at runtime. This is done using the `java.lang.reflect` package.
`java.lang.Class`
Question 213: `java.lang.Class` Class
The `java.lang.Class` class provides methods to get information about a class at runtime (metadata) and to create and manipulate objects dynamically.
Instantiating `Class` Objects
Question 214: Instantiating `Class` Objects
Three common ways:
Class.forName("fully.qualified.ClassName")
object.getClass()
ClassName.class
Java Code (Using Class.forName())
class Simple {
public Simple() {
System.out.println("Constructor of Simple class is invoked");
}
void message() {
System.out.println("Hello Java");
}
}
class Test1 {
public static void main(String args[]) {
try {
Class c = Class.forName("Simple");
Simple s = (Simple) c.newInstance();
s.message(); // Output: Hello Java
} catch (Exception e) {
System.out.println(e);
}
}
}
`javap` Command
Question 216: `javap` Command
The `javap` command disassembles Java class files, showing their contents (fields, methods, etc.).
Accessing Private Methods
Question 217: Accessing Private Methods
You can access private methods using reflection, but this should be avoided unless absolutely necessary, as it can compromise security and encapsulation.
Wrapper Classes
Question 218: Wrapper Classes
Wrapper classes provide object representations of primitive types (e.g., `Integer` for `int`, `Boolean` for `boolean`). Autoboxing and unboxing automatically convert between primitive types and their corresponding wrapper classes.
Autoboxing and Unboxing
Question 219: Autoboxing and Unboxing
Autoboxing automatically converts primitives to their wrapper class objects; unboxing does the reverse. This happens implicitly in many situations.
More on Exception Handling
Question 138: `finally` Block (Continued)
The `finally` block is designed to contain code that *must* execute, whether or not an exception occurs. This is typically used for cleanup tasks (releasing resources).
Java Code
public class Main {
public static void main(String[] args) {
try {
int a = 1 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught"); // Output: ArithmeticException caught
} finally {
System.out.println("Finally block executed"); // Output: Finally block executed
}
}
}
`throw` vs. `throws` (Continued)
Question 141: `throw` vs. `throws` (Continued)
The `throws` clause in a method signature declares checked exceptions that might be thrown by that method. The `throw` keyword is used inside a method to explicitly throw an exception.
Exception Rethrowing
Question 144: Rethrowing Exceptions
Yes, you can rethrow an exception in a `catch` block. This allows you to handle part of an exception and then re-throw it to be handled at a higher level.
Overriding Methods and Exceptions
Question 145: Subclass Exception Declaration
When a subclass overrides a method, it can declare a narrower set of checked exceptions than the superclass. It cannot add checked exceptions, but unchecked exceptions are permitted.
Exception Propagation (Continued)
Question 146: Exception Propagation (Continued)
An unhandled exception propagates up the call stack. It's important to handle exceptions at the appropriate level to prevent program crashes.
Java Code
class TestExceptionPropagation1 {
void m() {
int data = 50 / 0; // Throws ArithmeticException
}
void n() { m(); }
void p() {
try { n(); }
catch (Exception e) {
System.out.println("Exception handled"); // Output: Exception handled
}
}
public static void main(String args[]) {
TestExceptionPropagation1 obj = new TestExceptionPropagation1();
obj.p();
System.out.println("Normal flow..."); // Output: Normal flow...
}
}
Nested `try-catch-finally` (Continued)
Question 147: Nested `try-catch-finally` Blocks (Continued)
The `finally` block of an inner `try` statement will execute before the `catch` block of an outer `try` statement if an exception is thrown from within the inner `try` block.
Java Code
public class Main {
void a() {
try {
System.out.println("a(): Main called"); // Output: a(): Main called
b();
} catch (Exception e) {
System.out.println("Exception is caught in a()"); // Output: Exception is caught in a()
}
}
void b() throws Exception {
try {
System.out.println("b(): Main called"); // Output: b(): Main called
c();
} catch (Exception e) {
System.out.println("Exception is caught in b()");
throw new Exception(); // Re-throwing the exception
} finally {
System.out.println("finally block is called in b()"); // Output: finally block is called in b()
}
}
void c() throws Exception {
throw new Exception();
}
public static void main(String args[]) {
Main m = new Main();
try {
m.a();
} catch (Exception e) {
System.out.println("Exception is caught in main"); // Output: Exception is caught in main
}
}
}
Exception Handling in Constructor
Question 148: Exception Handling in Constructor
Java Code
public class Calculation {
int a;
public Calculation(int a) {
this.a = a;
}
public int add() {
a = a + 10;
try {
a = a + 10;
try {
a = a * 10;
throw new Exception();
} catch (Exception e) {
a = a - 10;
}
} catch (Exception e) {
a = a - 10;
}
return a;
}
public static void main(String[] args) {
try {
Calculation c = new Calculation(2);
System.out.println(c.add()); // Output: 190
} catch (Exception e) {
System.out.println("Exception caught!");
}
}
}
String Manipulation in Java
Question 149: String Pool in Java
The String pool is a special area of memory in the heap where String literals are stored. This improves efficiency by reusing existing strings.
String Immutability
Question 150: Immutability of Strings
Strings in Java are immutable; their values cannot be changed after creation. Methods that appear to modify a string actually return a new string object.
Java Code
class Testimmutablestring {
public static void main(String args[]) {
String s = "Sachin";
s.concat(" Tendulkar");
System.out.println(s); // Output: Sachin
}
}
Reasons for Immutability
Question 151: Reasons for String Immutability
String immutability improves thread safety and enables efficient string sharing.
Creating Strings
Question 152: Creating String Objects
Methods for creating String objects:
- String literals:
String str = "hello";
(uses the string pool) - `new String()` :
String str = new String("hello");
(creates a new object in the heap)
Number of String Objects
Question 153: Number of Objects Created
Java Code
String s1 = "Welcome";
String s2 = "Welcome";
String s3 = "Welcome";
Output
One object (in the String pool)
Question 155: Number of Objects Created
Java Code
String s = new String("Welcome");
Output
Two objects (one in the String pool, one in the heap)
`==` vs. `equals()` for Strings
Question 156: `==` vs. `equals()` for Strings
Java Code
public class Test {
public static void main(String args[]) {
String a = new String("Sharma is a good player");
String b = "Sharma is a good player";
if (a == b) {
System.out.println("a == b");
}
if (a.equals(b)) {
System.out.println("a equals b"); // Output: a equals b
}
}
}
`intern()` Method
Question 157: `intern()` Method
Java Code
public class Test {
public static void main(String args[]) {
String s1 = "Sharma is a good player";
String s2 = new String("Sharma is a good player");
s2 = s2.intern();
System.out.println(s1 == s2); // Output: true
}
}
`String` vs. `StringBuffer`
Question 158: `String` vs. `StringBuffer`
Key differences:
Feature | String | StringBuffer |
---|---|---|
Mutability | Immutable | Mutable |
Thread Safety | Thread-safe | Thread-safe |
Performance | Slower for string concatenation | Faster for string concatenation |
`StringBuffer` vs. `StringBuilder`
Question 159: `StringBuffer` vs. `StringBuilder`
Key differences:
Feature | StringBuffer | StringBuilder |
---|---|---|
Thread Safety | Synchronized (thread-safe) | Not synchronized (not thread-safe) |
Performance | Slower | Faster |
Creating Immutable Classes
Question 160: Creating Immutable Classes
To create an immutable class, make the class itself and all of its fields `final`. Do not provide any setter methods.
File Permissions in Java
Question 195: Setting File Permissions
The `java.nio.file.Files.setPosixFilePermissions()` method is used to set file permissions in Java. You need to provide the file path and a `Set` of `PosixFilePermission` objects.
Filter Streams
Question 196: Filter Streams
Filter streams in Java add extra functionality (e.g., buffering, data transformation) to existing streams. They don't modify the underlying stream but wrap it to add capabilities.
I/O Filters
Question 197: I/O Filters
I/O filters transform data as it's read from one stream and written to another. Multiple filters can be chained together for combined transformations.
Taking Console Input in Java
Question 198: Taking Console Input in Java
Three common methods:
- `BufferedReader` : Efficient for reading lines of text.
- `Scanner` : Flexible for parsing various data types.
- `Console` : For reading text and passwords (doesn't echo passwords).
BufferedReader Example
import java.io.*;
public class Person {
public static void main(String[] args) throws IOException {
System.out.println("Enter the name of the person");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name); // Output: (user input)
}
}
Scanner Example
import java.util.*;
public class ScannerClassExample2 {
public static void main(String args[]) {
String str = "Hello/This is JavaTpoint/My name is Abhishek.";
Scanner scanner = new Scanner(str).useDelimiter("/");
while (scanner.hasNext()) {
System.out.println(scanner.next()); // Output: Hello, This is JavaTpoint, My name is Abhishek.
}
scanner.close();
}
}
Console Example
import java.io.Console;
class ReadStringTest {
public static void main(String args[]) {
Console c = System.console();
System.out.println("Enter your name: ");
String n = c.readLine();
System.out.println("Welcome " + n); // Output: Welcome (user input)
}
}
Serialization in Java
Question 199: Serialization in Java
Serialization is the process of converting an object's state into a byte stream. This allows you to save the object's data to storage (like a file) and reconstruct it later (deserialization). The `Serializable` interface is used to mark classes whose objects can be serialized.
Making a Class Serializable
Question 200: Making a Class Serializable
Implement the `Serializable` interface.
Preventing Serialization in Subclasses
Question 201: Preventing Serialization in Subclasses
To prevent serialization of a subclass when the superclass implements `Serializable`, override the `writeObject()` and `readObject()` methods in the subclass and throw a `NotSerializableException`.
Question 204: `transient` Keyword
The `transient` keyword in Java prevents a member variable from being serialized. When an object is serialized (converted into a byte stream), `transient` variables are ignored; their values are not saved and will not be restored when the object is deserialized.
`Externalizable` Interface
Question 205: `Externalizable` Interface
The `Externalizable` interface provides more control over serialization than `Serializable`. You must implement the `writeExternal()` and `readExternal()` methods to define exactly how the object's state is written and read.
`Serializable` vs. `Externalizable` (Continued)
Question 206: `Serializable` vs. `Externalizable` (Continued)
Comparing `Serializable` and `Externalizable`:
Feature | `Serializable` | `Externalizable` |
---|---|---|
Methods | None (marker interface) | writeExternal() and readExternal() must be implemented |
Control | Automatic serialization | Manual control over serialization |
Performance | Slower | Faster (potentially more efficient) |
Constructor | No constructor call during serialization | Default constructor is called during deserialization |
Java Integer Caching
Question 220: Integer Caching
Java Code
public class Test1 {
public static void main(String[] args) {
Integer i = new Integer(201);
Integer j = new Integer(201);
if (i == j) {
System.out.println("hello");
} else {
System.out.println("bye"); // Output: bye
}
}
}
Object Cloning
Question 221: Object Cloning
Object cloning creates a copy of an object. Java uses the `clone()` method (the class must implement the `Cloneable` interface). This creates a new object with the same state as the original.
Syntax
protected Object clone() throws CloneNotSupportedException
Advantages and Disadvantages of Cloning
Question 222: Advantages and Disadvantages of Object Cloning
Feature | Advantages | Disadvantages |
---|---|---|
Code Reusability | Reduces code duplication. | Requires implementing `Cloneable` and handling potential exceptions. |
Efficiency | Fast way to create copies, especially for arrays. | Only shallow copies by default; deep cloning requires extra work. |
Constructor Control | Clone() does not invoke a constructor. | No control over object initialization during cloning. |
Native Methods
Question 223: Native Methods
A native method in Java is implemented in a language other than Java (like C or C++). The `native` keyword is used in the method signature. Native methods provide access to platform-specific functionalities.
`strictfp` Keyword
Question 224: `strictfp` Keyword
The `strictfp` keyword ensures that floating-point calculations produce the same results across different platforms. It enforces strict adherence to the IEEE 754 standard for floating-point arithmetic.
`System` Class
Question 225: `System` Class
The `System` class provides access to system resources and settings. It provides methods related to I/O operations, memory management, and other system-level functionalities.
Shallow Copies
Question 226: Shallow Copies
A shallow copy creates a new object, but it populates the new object with references to the same objects as the original. Changes to objects within the original object will be reflected in the shallow copy, and vice-versa. Cloning, by default, creates shallow copies.
Singleton Classes
Question 227: Singleton Classes
A singleton class ensures that only one instance of the class exists. This is achieved by making the constructor private and providing a static `getInstance()` method to access the single instance.
Java Code
class Singleton {
private static Singleton single_instance = null;
int i;
private Singleton() { i = 90; }
public static Singleton getInstance() {
if (single_instance == null) {
single_instance = new Singleton();
}
return single_instance;
}
public static void main(String args[]) {
Singleton first = Singleton.getInstance();
System.out.println("First instance integer value:" + first.i); // Output: First instance integer value:90
first.i = first.i + 90;
Singleton second = Singleton.getInstance();
System.out.println("Second instance integer value:" + second.i); // Output: Second instance integer value:180
}
}
Command-Line Arguments
Question 228: Printing Command-Line Arguments
Java Code
class A {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
Output (Example)
sonoo
jaiswal
1
3
abc
Default Layouts in Swing
Question 229: Default Layout for Containers
The default layout manager for `JFrame`, `JDialog`, and `JWindow` is `BorderLayout`. The default layout manager for `JPanel` and `Applet` is `FlowLayout`.
Peerless Components
Question 231: Peerless Components
Lightweight Swing components don't rely on native peer components from the operating system. They're more portable and generally render faster.
Heavyweight Components
Question 234: Heavyweight Components
Heavyweight components in AWT rely on native peers provided by the operating system. They are more platform-dependent.
Scrollbars vs. ScrollPanes
Question 232: Scrollbar vs. ScrollPane
A `Scrollbar` is a component; a `ScrollPane` is a container that manages scrolling for other components.
Applets
Question 235: Applets
Applets are small Java programs that run within a web browser. They are used for client-side dynamic content. Applets are largely deprecated due to security issues.
Applets and Applications
Question 236: Applet and Application
You can create a Java class that functions as both an applet and an application by including a `main` method for execution as a standalone application.
Locale in Java
Question 237: Locale in Java
A `Locale` object represents a geographical region or locale. It specifies language, country, and variant information.
Java Code
import java.util.*;
public class LocaleExample {
public static void main(String[] args) {
Locale locale = Locale.getDefault();
System.out.println(locale.getDisplayCountry()); // Output: (Your Country)
System.out.println(locale.getDisplayLanguage()); // Output: (Your Language)
}
}
Loading Specific Locales
Question 238: Loading Specific Locales
You load a specific locale using `ResourceBundle.getBundle("baseName", locale)`.
Java Beans
Question 239: Java Beans
JavaBeans are reusable software components that follow certain conventions (e.g., getter/setter methods). They are designed to be easily manipulated by visual development tools.
Java Code (Example JavaBean)
package mypack;
public class Employee implements java.io.Serializable {
private int id;
private String name;
public Employee() {}
public void setId(int id) { this.id = id; }
public int getId() { return id; }
public void setName(String name) { this.name = name; }
public String getName() { return name; }
}
Purpose of Java Beans
Question 240: Purpose of Java Beans
JavaBeans are designed for reusability and ease of use in visual development environments. They encapsulate data and behavior into easily manageable components.
Bean Persistence
Question 241: Bean Persistent Property
Bean persistence refers to saving and retrieving the bean's state to and from persistent storage (like a database).
RMI (Remote Method Invocation)
Question 242: What is RMI?
RMI (Remote Method Invocation) in Java allows an object to invoke methods on an object running in a different Java Virtual Machine (JVM).
Stub and Skeleton
Question 243: Purpose of Stub and Skeleton
In RMI:
- Stub: Client-side proxy; acts as a gateway for client requests.
- Skeleton: Server-side proxy; handles incoming requests and forwards them to the remote object.
Steps in Writing an RMI Program
Question 244: Steps in Writing an RMI Program
Steps to create an RMI application:
- Define a remote interface.
- Implement the remote interface.
- Compile and generate stubs and skeletons using `rmic`.
- Start the RMI registry.
- Start the server application.
- Start the client application.
HTTP Tunneling in RMI
Question 245: HTTP Tunneling in RMI
HTTP tunneling in RMI allows RMI traffic to traverse firewalls that block direct TCP connections by encapsulating RMI calls within HTTP requests.
JRMP (Java Remote Method Protocol)
Question 246: JRMP (Java Remote Method Protocol)
JRMP is the default protocol used by RMI for communication. It's a Java-specific protocol that runs over TCP/IP.
RMI and CORBA Interoperability
Question 247: RMI and CORBA Interoperability
RMI can interoperate with CORBA (Common Object Request Broker Architecture) applications by using the Internet Inter-ORB Protocol (IIOP) as the transport protocol.
Question 21: Merging Linked Lists
This program merges two sorted linked lists into one sorted linked list. It does so efficiently in O(n) time without creating a new linked list.
C Code
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
void merge(struct Node* p, struct Node** q) {
struct Node* p_curr = p, *q_curr = *q;
struct Node* p_next, *q_next;
while (p_curr != NULL && q_curr != NULL) {
p_next = p_curr->next;
q_next = q_curr->next;
q_curr->next = p_next;
p_curr->next = q_curr;
p_curr = p_next;
q_curr = q_next;
}
*q = q_curr;
}
int main() {
struct Node* p = NULL, *q = NULL;
push(&p, 3);
push(&p, 2);
push(&p, 1);
printf("List 1:\n");
printList(p);
push(&q, 8);
push(&q, 7);
push(&q, 6);
push(&q, 5);
push(&q, 4);
printf("List 2:\n");
printList(q);
merge(p, &q);
printf("Merged List 1:\n");
printList(p);
printf("Remaining List 2:\n");
printList(q);
return 0;
}
Output
List 1:
1 2 3
List 2:
4 5 6 7 8
Merged List 1:
1 4 2 5 3 6
Remaining List 2:
7 8
Encryption Algorithms
Question 22: Encryption Algorithms
Encryption algorithms use mathematical functions and keys to transform readable data (plaintext) into an unreadable format (ciphertext). The strength of an encryption algorithm depends on the key size and the complexity of the algorithm's operations. Encryption can use block or stream methods.
Algorithm Analysis
Question 23: Algorithm Analysis Criteria
Analyzing algorithms involves evaluating their efficiency in terms of:
- Time complexity: How runtime scales with input size.
- Space complexity: How memory usage scales with input size.
Stacks and Queues
Question 24: Stack vs. Queue
Stacks and queues are linear data structures used to store data:
Feature | Stack | Queue |
---|---|---|
Data Access | LIFO (Last-In, First-Out) | FIFO (First-In, First-Out) |
Operations | Push (add), Pop (remove) | Enqueue (add), Dequeue (remove) |
Implementation | Array or linked list | Array or linked list |
Singly vs. Doubly Linked Lists
Question 25: Singly vs. Doubly Linked Lists
In a singly linked list, each node points to the next node; traversal is one-way. In a doubly linked list, each node points to both the next and previous nodes, allowing for bidirectional traversal.
Creating a Doubly Linked List
Question 254: Creating a Doubly Linked List
Java Code
public class CountList {
class Node {
int data;
Node previous;
Node next;
public Node(int data) { this.data = data; }
}
Node head, tail = null;
public void addNode(int data) {
Node newNode = new Node(data);
if (head == null) {
head = tail = newNode;
head.previous = null;
tail.next = null;
} else {
tail.next = newNode;
newNode.previous = tail;
tail = newNode;
tail.next = null;
}
}
public int countNodes() {
int counter = 0;
Node current = head;
while (current != null) {
counter++;
current = current.next;
}
return counter;
}
public void display() {
Node current = head;
if (head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
public static void main(String[] args) {
CountList dList = new CountList();
dList.addNode(1);
dList.addNode(2);
dList.addNode(3);
dList.addNode(4);
dList.addNode(5);
dList.display(); // Output: Nodes of doubly linked list: 1 2 3 4 5
System.out.println("\nCount of nodes present in the list: " + dList.countNodes()); // Output: Count of nodes present in the list: 5
}
}
Finding Min/Max in Circular Linked List
Question 255: Finding Min/Max in Circular Linked List
Java Code
public class MinMax {
public static class Node {
int data;
Node next;
public Node(int data) { this.data = data; }
}
public Node head = null;
public Node tail = null;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
newNode.next = head;
} else {
tail.next = newNode;
tail = newNode;
tail.next = head;
}
}
public void minNode() {
Node current = head;
int min = head.data;
if (head == null) {
System.out.println("List is empty");
return;
} else {
do {
if (min > current.data) {
min = current.data;
}
current = current.next;
} while (current != head);
System.out.println("Minimum value node in the list: " + min); // Output: Minimum value node in the list: 1
}
}
public void maxNode() {
Node current = head;
int max = head.data;
if (head == null) {
System.out.println("List is empty");
return;
} else {
do {
if (max < current.data) {
max = current.data;
}
current = current.next;
} while (current != head);
System.out.println("Maximum value node in the list: " + max); // Output: Maximum value node in the list: 20
}
}
public static void main(String[] args) {
MinMax cl = new MinMax();
cl.add(5);
cl.add(20);
cl.add(10);
cl.add(1);
cl.minNode();
cl.maxNode();
}
}
Difference Between Odd and Even Level Nodes
Question 256: Difference Between Odd and Even Level Nodes
Java Code
import java.util.LinkedList;
import java.util.Queue;
public class DiffOddEven {
// ... (Node class definition) ...
public int difference() {
int oddLevel = 0, evenLevel = 0, diffOddEven = 0;
int nodesInLevel = 0;
int currentLevel = 0;
Queue<Node> queue = new LinkedList<Node>();
if (root == null) {
System.out.println("Tree is empty");
return 0;
} else {
queue.add(root);
currentLevel++;
while (queue.size() != 0) {
nodesInLevel = queue.size();
while (nodesInLevel > 0) {
Node current = queue.remove();
if (currentLevel % 2 == 0) evenLevel += current.data;
else oddLevel += current.data;
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
nodesInLevel--;
}
currentLevel++;
}
diffOddEven = Math.abs(oddLevel - evenLevel);
}
return diffOddEven;
}
// ... (main method to build and test the tree) ...
}
Output
Difference between sum of odd level and even level nodes: 11