Examness

Programming

Java Interview Questions

Language, collections, concurrency, JVM and Spring.

235 questions

  1. 1.

    What are the differences between throw and throws?

    Beginner

    Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.

    Example:

    /**
     * Throw in Java
     */
    public class ThrowExample {
        void checkAge(int age) {
            if (age < 18)
                throw new ArithmeticException("Not Eligible for voting");
            else
                System.out.println("Eligible for voting");
        }
    
        public static void main(String args[]) {
            ThrowExample obj = new ThrowExample();
            obj.checkAge(13);
            System.out.println("End Of Program");
        }
    }

    Output

    Exception in thread "main" java.lang.ArithmeticException: 
    Not Eligible for voting
    at Example1.checkAge(Example1.java:4)
    at Example1.main(Example1.java:10)

    Example:

    /**
     * Throws in Java
     */
    public class ThrowsExample {
        int division(int a, int b) throws ArithmeticException {
            int t = a / b;
            return t;
        }
    
        public static void main(String args[]) {
            ThrowsExample obj = new ThrowsExample();
            try {
                System.out.println(obj.division(15, 0));
            } catch (ArithmeticException e) {
                System.out.println("You shouldn't divide number by zero");
            }
        }
    }

    Output

    You shouldn\'t divide number by zero

    ↥ back to top

  2. 2.

    What are the ways to instantiate the Class class?

    Beginner

    1. Using new keyword:

    MyObject object = new MyObject();

    2. Using Class.forName():

    MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

    3. Using clone():

    MyObject anotherObject = new MyObject();
    MyObject object = (MyObject) anotherObject.clone();

    4. Using object deserialization:

    ObjectInputStream inStream = new ObjectInputStream(anInputStream );
    MyObject object = (MyObject) inStream.readObject();

    ↥ back to top

  3. 3.

    What is the main objective of garbage collection?

    Beginner

    The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects. This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

  4. 4.

    What is JIT compiler?

    Beginner

    Just-In-Time (JIT) Compiler: It is used to improve the performance. The compiler is part of the Java Runtime Environment (JRE). It translates Java bytecode into native machine code at runtime. Therefore, reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java Virtual Machine (JVM) to the instruction set of a specific CPU.

  5. 5.

    What are the functional interfaces Supplier , BooleanSupplier, DoubleSupplier, IntSupplierand LongSupplier?

    Beginner

    Supplier (provider) - the interface through which a function is implemented that takes nothing to the input, but returns the result of the class to the output T;

    Supplier < LocalDateTime > now =  LocalDateTime::now;
    now.get();
    • DoubleSupplier- the supplier is returning Double;
    • IntSupplier- the supplier is returning Integer;
    • LongSupplier- the supplier is returning Long.

    ↥ back to top

  6. 6.

    What are the functional interfaces Consumer<T>, DoubleConsumer, IntConsumerand LongConsumer?

    Beginner

    Consumer<T>(consumer) - the interface through which a function is implemented that receives an instance of the class as an input T, performs some action with it, and returns nothing.

    Consumer<String> hello = (name) ->  System.out.println( " Hello, "  + name);
    hello.accept( " world " );
    • DoubleConsumer- the consumer receiving the input Double;
    • IntConsumer- the consumer receiving the input Integer;
    • LongConsumer- the consumer receiving the input Long.

    ↥ back to top

  7. 7.

    Java Virtual Machine (JVM)

    Beginner

    The JVM acts as an abstraction layer between Java code and the underlying hardware or operating system. It interprets and executes Java bytecode, ensuring consistent behavior across different platforms.

  8. 8.

    What is the purpose of using javap?

    Beginner

    The javap command displays information about the fields, constructors and methods present in a class file. The javap command ( also known as the Java Disassembler ) disassembles one or more class files.

    ```java /**

    • Java Disassembler

    */ class Simple { public static void main(String args[]) { System.out.println("Hello World"); } }

    cmd> javap Simple.class

    
    Output
    

    Compiled from ".java" class Simple { Simple(); public static void main(java.lang.String[]); }

    
     
     ↥ back to top
  9. 9.

    When can you use super keyword?

    Beginner

    The super keyword is used to access hidden fields and overridden methods or attributes of the parent class. Following are the cases when this keyword can be used: Accessing data members of parent class when the member names of the class and its child subclasses are same. To call the default and parameterized constructor of the parent class inside the child class. Accessing the parent class methods when the child classes have overridden them. The following example demonstrates all 3 cases when a super keyword is used. class Parent { protected int num = 1 ; Parent(){ System.out.println( "Parent class default constructor." ); } Parent(String x){ System.out.println( "Parent class parameterised constructor." ); } public void foo () { System.out.println( "Parent class foo!" ); } } class Child extends Parent { private int num = 2 ; Child(){ //super constructor call should always be in the first line // super(); // Either call default super() to call default parent constructor OR super ( "Call Parent" ); // call parameterised super to call parameterised parent constructor. System.out.println( "Child class default Constructor" ); } void printNum () { System.out.println(num); System.out.println( super .num); //prints the value of num of parent class } @Override public void foo () { System.out.println( "Child class foo!" ); super .foo(); //Calls foo method of Parent class inside the Overriden foo method of Child class. } } public class DemoClass { public static void main (String args[]) { Child demoObject= new Child(); demoObject.foo(); / This would print - Parent class parameterised constructor. Child class default Constructor Child class foo! Parent class foo! / } }

  10. 10.

    Why is Java a platform independent language?

    Beginner

    Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems. The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

  11. 11.

    What are the functional interfaces Predicate<T>, DoublePredicate, IntPredicateand LongPredicate?

    Beginner

    Predicate<T>(predicate) - the interface with which a function is implemented that receives an instance of the class as input Tand returns the type value at the output boolean.

    The interface contains a variety of methods by default, allow to build complex conditions ( and, or, negate).

    Predicate < String > predicate = (s) -> s.length () >  0 ;
    predicate.test("foo"); // true 
    predicate.negate().test("foo"); // false
    • DoublePredicate- predicate receiving input Double;
    • IntPredicate- predicate receiving input Integer;
    • LongPredicate- predicate receiving input Long.

    ↥ back to top

  12. 12.

    What is the purpose of filter() method in streams?

    Beginner

    The method filter() is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition.

    ↥ back to top

  13. 13.

    What is ZonedDateTime?

    Beginner

    java.time.ZonedDateTime- an analogue java.util.Calendar, a class with the most complete amount of information about the temporary context in the calendar system ISO-8601. It includes a time zone, therefore, this class carries out all operations with time shifts taking into account it.

    ↥ back to top

  14. 14.

    Can the main method be Overloaded?

    Beginner

    Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - public static void main (string[] args) Consider the below code snippets: class Main { public static void main (String args[]) { System.out.println( " Main Method" ); } public static void main ( int [] args) { System.out.println( "Overloaded Integer array Main Method" ); } public static void main ( char [] args) { System.out.println( "Overloaded Character array Main Method" ); } public static void main ( double [] args) { System.out.println( "Overloaded Double array Main Method" ); } public static void main ( float args) { System.out.println( "Overloaded float Main Method" ); } }

  15. 15.

    What is the static import?

    Beginner

    The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.

    /**
     * Static Import
     */
    import static java.lang.System.*;
    
    class StaticImportExample {
    
        public static void main(String args[]) {
            out.println("Hello");// Now no need of System.out
            out.println("Java");
        }
    }

    ↥ back to top

  16. 16.

    What is the difference between Collection and Stream?

    Beginner

    Collections allow you to work with elements separately, while streams do not allow this, but instead provides the ability to perform functions on data as one.

    ↥ back to top

  17. 17.

    What are the final methods of working with streams you know?

    Beginner
    • findFirst() returns the first element
    • findAny() returns any suitable item
    • collect() presentation of results in the form of collections and other data structures
    • count() returns the number of elements
    • anyMatch()returns trueif the condition is satisfied for at least one element
    • noneMatch()returns trueif the condition is not satisfied for any element
    • allMatch()returns trueif the condition is satisfied for all elements
    • min()returns the minimum element, using as a condition Comparator
    • max()returns the maximum element, using as a condition Comparator
    • forEach() applies a function to each object (order is not guaranteed in parallel execution)
    • forEachOrdered() applies a function to each object while preserving the order of elements
    • toArray() returns an array of values
    • reduce()allows you to perform aggregate functions and return a single result.
    • sum() returns the sum of all numbers
    • average() returns the arithmetic mean of all numbers.

    ↥ back to top

  18. 18.

    What are the restrictions that are applied to the Java static methods?

    Beginner

    If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.

    There are a few restrictions imposed on a static method

    • The static method cannot use non-static data member or invoke non-static method directly.
    • The this and super cannot be used in static context.
    • The static method can access only static type data ( static type instance variable ).
    • There is no need to create an object of the class to invoke the static method.
    • A static method cannot be overridden in a subclass

    Example:

    /**
     * Static Methods
     */
    class Parent {
        static void display() {
            System.out.println("Super class");
        }
    }
    
    public class Example extends Parent {
        void display()  // trying to override display() {
           System.out.println("Sub class");  
        }
    
        public static void main(String[] args) {
            Parent obj = new Example();
            obj.display();
        }
    }

    This generates a compile time error. The output is as follows −

    Example.java:10: error: display() in Example cannot override display() in Parent
    void display()  // trying to override display()
         ^
    overridden method is static
    
    1 error

    ↥ back to top

  19. 19.

    What are the default values assigned to variables and instances in java?

    Beginner

    There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. If it is a reference, then it will be assigned to null. If it is numeric, then it will assign to 0. If it is a boolean, then it will be assigned to false. Etc.

  20. 20.

    What are the functional interfaces UnaryOperator<T>, DoubleUnaryOperator, IntUnaryOperatorand LongUnaryOperator?

    Beginner

    UnaryOperator<T>(unary operator) takes an object of type as a parameter T, performs operations on them and returns the result of operations in the form of an object of type T:

    UnaryOperator < Integer > operator = x - > x * x;
    System.out.println(operator.apply ( 5 )); // 25
    • DoubleUnaryOperator- unary operator receiving input Double;
    • IntUnaryOperator- unary operator receiving input Integer;
    • LongUnaryOperator- unary operator receiving input Long.

    ↥ back to top