Java Interview Questions for 10 Years Experience

author image Hirely
at 05 Jan, 2025

Question: How to generate a random number in Java?

Answer:

In Java, there are several ways to generate random numbers. The most common methods are using the java.util.Random class, Math.random(), and ThreadLocalRandom. Below are the different approaches for generating random numbers in Java:


1. Using java.util.Random Class

The Random class is a part of the java.util package and provides methods for generating random numbers of various types (integers, doubles, booleans, etc.).

Example (Generate a random integer):

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        // Create an instance of Random class
        Random random = new Random();

        // Generate a random integer (within the range of int values)
        int randomInt = random.nextInt();
        System.out.println("Random Integer: " + randomInt);

        // Generate a random integer within a specific range (e.g., 0 to 99)
        int randomIntInRange = random.nextInt(100); // range: [0, 100)
        System.out.println("Random Integer (0 to 99): " + randomIntInRange);

        // Generate a random boolean
        boolean randomBool = random.nextBoolean();
        System.out.println("Random Boolean: " + randomBool);
    }
}

Explanation:

  • random.nextInt() generates a random integer.
  • random.nextInt(100) generates a random integer between 0 (inclusive) and 100 (exclusive).
  • random.nextBoolean() generates a random boolean (true or false).

2. Using Math.random()

The Math.random() method returns a random double value between 0.0 (inclusive) and 1.0 (exclusive). You can scale and shift the result to generate a random number within a specific range.

Example (Generate a random double):

public class RandomExample {
    public static void main(String[] args) {
        // Generate a random double between 0.0 and 1.0
        double randomDouble = Math.random();
        System.out.println("Random Double: " + randomDouble);

        // Generate a random integer between 0 and 99
        int randomIntInRange = (int)(Math.random() * 100); // range: [0, 100)
        System.out.println("Random Integer (0 to 99): " + randomIntInRange);
    }
}

Explanation:

  • Math.random() generates a double between 0.0 (inclusive) and 1.0 (exclusive).
  • To get a number in a specific range (e.g., 0 to 99), multiply the result by the range size (e.g., 100) and cast to int.

3. Using ThreadLocalRandom (Java 7 and above)

ThreadLocalRandom is part of the java.util.concurrent package and is preferred for multi-threaded environments. It avoids contention among threads that use the same Random object, making it more efficient in concurrent applications.

Example (Generate a random integer):

import java.util.concurrent.ThreadLocalRandom;

public class RandomExample {
    public static void main(String[] args) {
        // Generate a random integer between 0 and 99
        int randomInt = ThreadLocalRandom.current().nextInt(100); // range: [0, 100)
        System.out.println("Random Integer (0 to 99): " + randomInt);

        // Generate a random double between 0.0 and 1.0
        double randomDouble = ThreadLocalRandom.current().nextDouble();
        System.out.println("Random Double: " + randomDouble);

        // Generate a random boolean
        boolean randomBool = ThreadLocalRandom.current().nextBoolean();
        System.out.println("Random Boolean: " + randomBool);
    }
}

Explanation:

  • ThreadLocalRandom.current().nextInt(100) generates a random integer between 0 and 99.
  • ThreadLocalRandom.current().nextDouble() generates a random double between 0.0 (inclusive) and 1.0 (exclusive).
  • ThreadLocalRandom.current().nextBoolean() generates a random boolean.

4. Using SecureRandom (for Cryptography)

If you need cryptographically secure random numbers (for example, for generating encryption keys), you should use java.security.SecureRandom instead of the Random class.

Example (Generate a random integer):

import java.security.SecureRandom;

public class RandomExample {
    public static void main(String[] args) {
        // Create an instance of SecureRandom
        SecureRandom secureRandom = new SecureRandom();

        // Generate a random integer
        int randomInt = secureRandom.nextInt();
        System.out.println("Secure Random Integer: " + randomInt);

        // Generate a random integer in a specific range (e.g., 0 to 99)
        int randomIntInRange = secureRandom.nextInt(100); // range: [0, 100)
        System.out.println("Secure Random Integer (0 to 99): " + randomIntInRange);
    }
}

Explanation:

  • SecureRandom is used for generating cryptographically strong random numbers.
  • It is slower than Random, but suitable for cryptographic applications that require a higher level of security.

Summary of Methods:

MethodDescriptionUse Case
java.util.RandomGenerates pseudo-random numbers.General-purpose random number generation.
Math.random()Returns a random double between 0.0 and 1.0.Quick and simple random number generation.
ThreadLocalRandomMore efficient for multi-threaded applications.Multi-threaded environments.
java.security.SecureRandomGenerates cryptographically secure random numbers.Cryptographic applications.

Conclusion:

  • Use Random for general-purpose random number generation in single-threaded applications.
  • Use Math.random() for simple, one-line random number generation (returns a double).
  • Use ThreadLocalRandom in multi-threaded environments for better performance.
  • Use SecureRandom for cryptographic applications requiring high security.

Question: What is an interface in Java, and how is it different from an abstract class?

Answer:

In Java, both interfaces and abstract classes are used to define abstract behaviors that can be implemented by other classes. However, they have significant differences in terms of purpose, syntax, and usage.


Interface in Java

An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It cannot contain instance fields or method implementations (except for default and static methods introduced in Java 8).

  • Purpose: Interfaces define a contract of what a class can do, but not how it does it. The class that implements the interface is expected to provide concrete implementations for the abstract methods defined in the interface.

Syntax of an Interface:

interface MyInterface {
    // Constant declaration (public, static, final by default)
    int CONSTANT_VALUE = 100;

    // Abstract method (public by default)
    void abstractMethod();

    // Default method (can have a body, available from Java 8)
    default void defaultMethod() {
        System.out.println("This is a default method.");
    }

    // Static method (can have a body, available from Java 8)
    static void staticMethod() {
        System.out.println("This is a static method in the interface.");
    }
}

Key Points about Interfaces:

  1. Methods in interfaces are implicitly abstract (except default and static methods).
  2. Interfaces support multiple inheritance, meaning a class can implement multiple interfaces.
  3. Interface fields are implicitly public, static, and final.
  4. Cannot instantiate an interface directly (e.g., MyInterface obj = new MyInterface(); is not allowed).
  5. Default and static methods allow some behavior to be defined directly within the interface, but non-static methods must still be implemented by the implementing class.

Example of Using an Interface:

class MyClass implements MyInterface {
    // Implementing the abstract method from the interface
    @Override
    public void abstractMethod() {
        System.out.println("Implemented abstract method.");
    }

    // Optionally, overriding default method
    @Override
    public void defaultMethod() {
        System.out.println("Overridden default method.");
    }
}

Abstract Class in Java

An abstract class is a class that cannot be instantiated and may have abstract methods (methods without implementation), but it can also contain concrete methods (methods with implementation).

  • Purpose: Abstract classes are used to define common behavior for subclasses, but some methods are left abstract for subclasses to implement.

Syntax of an Abstract Class:

abstract class MyAbstractClass {
    // Instance field (can be initialized)
    int value = 10;

    // Concrete method (can be used by subclasses)
    void concreteMethod() {
        System.out.println("This is a concrete method.");
    }

    // Abstract method (must be implemented by subclasses)
    abstract void abstractMethod();
}

Key Points about Abstract Classes:

  1. Methods can be both abstract (without implementation) and concrete (with implementation).
  2. Abstract classes can have constructors, instance fields, and methods (both abstract and concrete).
  3. Only one abstract class can be extended because Java does not support multiple inheritance of classes.
  4. Can provide default behavior for some methods while forcing subclasses to implement others.
  5. Can have access modifiers on methods and fields (e.g., protected, private, etc.), whereas methods in interfaces are implicitly public.

Example of Using an Abstract Class:

class MyConcreteClass extends MyAbstractClass {
    @Override
    public void abstractMethod() {
        System.out.println("Implemented abstract method.");
    }
}

Key Differences Between an Interface and an Abstract Class

FeatureInterfaceAbstract Class
MethodsCan only have abstract methods (except default and static methods in Java 8 and later).Can have both abstract methods and concrete methods.
Field DeclarationFields are public, static, and final by default.Can have instance variables with any access modifiers.
Multiple InheritanceSupports multiple inheritance (a class can implement multiple interfaces).Supports single inheritance (a class can extend only one abstract class).
ConstructorCannot have constructors.Can have constructors.
Method ImplementationMethods cannot have an implementation unless they are default or static (Java 8+).Can have fully implemented methods.
Default ImplementationDefault methods can provide implementation.Cannot provide default method implementations.
Access ModifiersMethods in interfaces are implicitly public.Methods and fields can have any access modifier (public, private, protected).
InstantiationCannot instantiate directly.Cannot instantiate directly.
PurposeDefines a contract of methods for a class to implement.Defines a base class with common behavior, leaving specific behavior to subclasses.

When to Use an Interface vs Abstract Class

  • Use an Interface:

    • When you want to define a contract or common behavior that multiple classes can implement.
    • When your class needs to implement multiple behaviors (since Java allows a class to implement multiple interfaces).
    • When you do not need to share state (fields) between classes.
  • Use an Abstract Class:

    • When you want to share common behavior and state between related classes.
    • When some methods should have default behavior, and others need to be implemented by subclasses.
    • When you want to define a base class that cannot be instantiated directly, but still share common fields and methods.

Example Comparison:

Interface Example:

interface Animal {
    void makeSound(); // Abstract method
    
    default void breathe() {  // Default method
        System.out.println("Breathing...");
    }
}

class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

Abstract Class Example:

abstract class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }

    void sleep() {
        System.out.println(name + " is sleeping.");
    }

    abstract void makeSound(); // Abstract method
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}

Conclusion:

  • Interface: Used for defining abstract behaviors and ensuring that a class implements certain methods, typically when you need multiple inheritance or to define a contract.
  • Abstract Class: Used for defining a base class with some implemented methods and some abstract methods, typically when there is shared functionality between related classes.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Java interview questions, Java interview experiences, and details about various Java job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now