java interview questions Flashcards

1
Q

List some important features of Java.

A

Ease of learning: Java is considered to be an easy-to-learn and understand language.

Security: Java is a secure language. The applications developed using this language are virus and tamper-proof.

OOP: OOP means Object-Oriented Programming Language. While Java is not considered to be purely object-oriented, the inclusion of features such as data abstraction, inheritance, and data-encapsulation, makes Java an object-oriented programming language. Thus, as such, everything in Java is considered an object.

Independent Platform: This is an important Java feature. Java does not depend on any specific platform and as long as the system has JRE installed, Java bytecode will be interpreted.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

why java is secure?

A

Security API’s
Security manager
Void of Pointers
Memory management(garbage collector)
Compile-time checking
Cryptographic Security
Java Sandbox
Exception Handling
Java Class Loader
More details

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Name the types of memory allocations in Java.

A

tAnother popular Java interview question is about memory allocation. Five important types of memory allocations in Java are - Heap memory, Class memory, Native method stock memory, Stack memory, and Program-counter memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what is stack memory in java?

A

Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects referred from the method that are in a heap.

Access to this memory is in Last-In-First-Out (LIFO) order. Whenever we call a new method, a new block is created on top of the stack which contains values specific to that method, like primitive variables and references to objects.

When the method finishes execution, its corresponding stack frame is flushed, the flow goes back to the calling method, and space becomes available for the next method.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what are key features of stack memory in java?

A

Some other features of stack memory include:

  1. It grows and shrinks as new methods are called and returned, respectively.
  2. Variables inside the stack exist only as long as the method that created them is running.
    It’s automatically allocated and deallocated when the method finishes execution.
  3. If this memory is full, Java throws java.lang.StackOverFlowError.
  4. Access to this memory is fast when compared to heap memory.
  5. This memory is threadsafe, as each thread operates in its own stack.
    source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is heap space in java?

A

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory.

These objects have global access and we can access them from anywhere in the application.

We can break this memory model down into smaller parts, called generations, which are:

  1. Young Generation – this is where all new objects are allocated and aged. A minor Garbage collection occurs when this fills up.
  2. Old or Tenured Generation – this is where long surviving objects are stored. When objects are stored in the Young Generation, a threshold for the object’s age is set, and when that threshold is reached, the object is moved to the old generation.
  3. Permanent Generation – this consists of JVM metadata for the runtime classes and application methods.

source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what are some key features of java heap memory?

A
  1. It’s accessed via complex memory management techniques that include the Young Generation, Old or Tenured Generation, and Permanent Generation.
  2. If heap space is full, Java throws java.lang.OutOfMemoryError.
  3. Access to this memory is comparatively slower than stack memory
  4. This memory, in contrast to stack, isn’t automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage.
  5. Unlike stack, a heap isn’t threadsafe and needs to be guarded by properly synchronizing the code.
    source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what is JVM?

A

Java Virtual Machine (JVM) is an implementation of a virtual machine which executes a Java program.

The JVM first interprets the bytecode. It then stores the class information in the memory area. Finally, it executes the bytecode generated by the java compiler.

It is an abstract computing machine with its own instruction set and manipulates various memory areas at runtime.

Components of the JVM are:

Class Loaders
Run-Time Data Areas
Execution Engine
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is classloader in JVM?

A

We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, JVM creates the bytecode, which is platform and machine-independent. The bytecode is stored in a .class file. When we try to use a class, the ClassLoader loads it into the memory.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

what are built-in classloader in java?

A

There are three types of built-in ClassLoader in Java.

  1. Bootstrap Class Loader – It loads JDK internal classes. It loads rt.jar and other core classes for example java.lang.* package classes.
  2. Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
  3. System Class Loader – This classloader loads classes from the current classpath. We can set classpath while invoking a program using -cp or -classpath command line option.
    source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what is JRE?

A

Java Runtime Environment (JRE) is a bundle of software components used to run Java applications.

Core components of the JRE include:

An implementation of a Java Virtual Machine (JVM)
Classes required to run the Java programs
Property Files
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is JDK?

A

Java Development Kit (JDK) provides environment and tools for developing, compiling, debugging, and executing a Java program.

Core components of JDK include:

JRE
Development Tools
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

what is class area of memory in java?

A

The class method area is the memory block that stores the class code, variable code(static variable, runtime constant), method code, and the constructor of a Java program. (Here method means the function which is written inside the class). It stores class-level data of every class such as the runtime constant pool, field and method data, the code for methods.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

what is program counter register memory in java?

A

Each JVM thread that carries out the task of a specific method has a program counter register associated with it. The non-native method has a PC that stores the address of the available JVM instruction whereas, in a native method, the value of the program counter is undefined. PC register is capable of storing the return address or a native pointer on some specific platform.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

what are native method stacks in java?

A

Also called C stacks, native method stacks are not written in Java language. This memory is allocated for each thread when it’s created And it can be of a fixed or dynamic nature.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

As a language, Java is considered platform-independent. Why?

A

Java is considered to be platform-independent because it does not depend on any hardware or software. When the Java programmer compiles Java code, the compiler converts the code into bytecode that can be run on different platforms. The only constraint is that the platform must have JRE (runtime environment) or Java Virtual Machine (JVM) installed on it.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is data-encapsulation in Java?

A

Data-encapsulation in Java is the process of hiding the variables (data) and the code applied to the data in a single unit. It is a significant feature of object-oriented programming. This helps Java developers to isolate different objects from each other and to create modules for each. By this, all objects would have their own behaviors, attributes, and functions. It prevents data or object mixing, hides data, enhances security.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are wrapper classes in Java?

A

Java, as a programming language, supports primitive data types. Wrapper classes help convert these primitive data types into objects or reference types and vice versa. Thus, the wrapper classes are so named because they ‘wrap’ these data types into identifiable objects of the specific data classes the primitive data types belong to. This Java interview question can help the interviewer assess whether you are comfortable using both old and new data types.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are constructors in Java?

A

In Java, constructors can be understood as a block of codes applied to an object to initialize it. It can be understood as a special method for initializing an object. Constructors are called when a class instance is created such as creating an object using the new() keyword. When a class does not contain a constructor, a default constructor, provided by the Java compiler, is automatically called.

There are two types of Java constructors - default and parameterized. When no parameters are defined, the constructor is called a default constructor. When specific parameters are defined for a constructor, it is called a parameterized constructor. While you may be using the Java programming language for some time, this Java interview question shows the interviewer that you know the technicalities too.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Why is Java not considered to be purely object-oriented?

A

Java supports primitive data types such as boolean, int, byte, long, float, etc. An object-oriented language must only support objects. However, the primitive data types are not objects, hence Java is not considered to be purely object-oriented.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

how use of pointers slows down garbage collection ?

A

because, it may happen that you hold some reference to the object somewhere, and GC only collects objects which have no references left.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Does Java use pointers? If not, why?

A

No, unlike C++, Java doesn’t use pointers. Java’s main focus is simplicity. The use of pointers complicates the process, especially for new java programmers. The use of pointers can also lead to possible errors. Moreover, pointers grant direct access to memory and thus, compromise security. By excluding pointers from Java, a certain amount of abstraction is achieved. Java has automatic Garbage Collectors, the use of pointers can slow down the garbage collection process. This advanced Java interview question deals with the intricacies of the language and answering it can help set you apart from other candidates.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

why do you need to use synchronization in java?

A

To prevent thread interleaving or interference
To provide consistency to the program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

what is the difference between pass-by-value and pass-by-reference?

A
  • Pass-by-reference: When a method is called, the method arguments reference the same variable in memory as the caller.
  • Pass-by-value: When a method is called, the caller passes a copy of the argument variables to the method resulting in two values in memory.
    source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Can you override static methods in Java?

A

No. While it is possible to hide the parent static method with a static method of the same signature class, this is not called overriding in the strict sense. This is because, during the run-time, no polymorphism can take place.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Can you access a static method a class A from outside using an object of type A?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

can method1 and method2 print i and k?

public class Test {

    static int i;

    int k;

    public static void method1() {
        System.out.println(i);
        System.out.println(k);
    }

    public void method2() {
        System.out.println(i);
        System.out.println(k);
    }
}
A

method1 can only print i and will throw error on printing k because, a non-static variable cannot be accessed from a static method or context.
method2 can print both i and k without any errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Can you override static methods in Java?

A

No. While it is possible to hide the parent static method with a static method of the same signature class, this is not called overriding in the strict sense.

public class Test {

    static int i;

    int k;

    public static void method1() {
        System.out.println(i);
        System.out.println(k);
    }

    public static void method2() {

    }

    public void method3() {
        System.out.println(i);
        System.out.println(k);
    }
}

public class Test2 extends Test {

    public static void method1() {
        // this is possible
    }

    @Override
    public static void method2() {
       // this is not possible, it will give error 
			 as: static methods cannot be annotated 
			 with @override
    }

    @Override
    public void method3() {
        // this is possible
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What do you understand about ClassLoader in Java?

A

ClassLoader is an integral element of the JRE (Java Runtime Environment). The function of the ClassLoader is to dynamically load Java classes directly to the JVM (Java Virtual Machine) during program execution, without notifying the Java run time system. The file to be executed is first loaded by ClassLoaders. Bootstrap, Extension, and Application are the ClassLoaders in Java. This is an advanced Java interview question and answering it can establish your expertise.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are the prospects of session management in servlets?

A

A session is any ongoing random conversation between a client and the server. The communication between the two is composed of requests and responses from both sides. There are several ways of managing a session. Applying cookies, using session management API, authenticating the user, hidden fields in HTML, and rewriting URL are some ways of session management. However, the most common way of managing a session is using a session ID when the communication between a client and the server takes place. This Java interview question shows your application orientation to the client.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What Is a JIT Compiler?

A

When we compile our Java program (e.g., using the javac command), we’ll end up with our source code compiled into the binary representation of our code – a JVM bytecode. This bytecode is simpler and more compact than our source code, but conventional processors in our computers cannot execute it.

To be able to run a Java program, the JVM interprets the bytecode. Since interpreters are usually a lot slower than native code executing on a real processor, the JVM can run another compiler which will now compile our bytecode into the machine code that can be run by the processor. This so-called just-in-time compiler is much more sophisticated than the javac compiler, and it runs complex optimizations to generate high-quality machine code.
more detailed explaination

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Highlight the importance of Java as a language.

A

Java is a very secure programming language as it is hard to bug or tamper with. It is also very easy to learn and comprehend when developing applications. Most importantly, Java is a self-dependent language that runs on its own JRE platform.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Why is Java considered to be a platform-independent language?

A

Java is considered platform-independent as it does not depend on any software or hardware. However, it is flexible enough to be run on different platforms with the condition that the platform has a JRE environment installed on it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Can you explain what you understand by the term Inheritance?

A

The term inheritance occurs when one class in a code extends to another. This means that codes used in one class can be reused in another class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the purpose of encapsulation?

A
  • Data Hiding: it is a way of restricting the access of our data members by hiding the implementation details. Encapsulation also provides a way for data hiding. The user will have no idea about the inner implementation of the class. It will not be visible to the user how the class is storing values in the variables. The user will only know that we are passing the values to a setter method and variables are getting initialized with that value.
  • Increased Flexibility: We can make the variables of the class read-only or write-only depending on our requirements. If we wish to make the variables read-only then we have to omit the setter methods like setName(), setAge(), etc. from the above program or if we wish to make the variables write-only then we have to omit the get methods like getName(), getAge(), etc. from the above program
  • Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements.
    Testing code is easy: Encapsulated code is easy to test for unit testing.
  • Freedom to programmer in implementing the details of the system: This is one of the major advantage of encapsulation that it gives the programmer freedom in implementing the details of a system. The only constraint on the programmer is to maintain the abstract interface that outsiders see.
    source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the solution where multiple inheritances is not possible to achieve?

A

The solution to this problem is to use interfaces instead of inheritance. Interfaces allow a class to define multiple behaviors without the need to extend multiple classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is a constructor in Java?

A

A block of code used to initialize an object is called a constructor. The constructor must share the same name as the class and it has no return type. Default and parameterized constructors are the two types of constructors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the difference between the creation of a string using new() and that of literal?

A

A new object is created when using new() whereas using literal, the object already existing might return with the same name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

what is a thread in java?

A

A thread in Java is the direction or path that is taken while a program is being executed. Generally, all the programs have at least one thread, known as the main thread, that is provided by the JVM or Java Virtual Machine at the starting of the program’s execution. At this point, when the main thread is provided, the main() method is invoked by the main thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

what is multithreading in java?

A

Multi threading in java is simply executing multiple threads in a program.
best video to understand

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

how to implement threads in java?

A

you can implement threads in two ways:
1. By extending Thread class
2. By implementing Runnable interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

which method is best while implementing multithreading in java? extending threads class or implementing runnable interface.

A

implementing runnable interface is a better choice because, it increases flexibility by letting you add more interfaces to implement in your class. Other classes can also extend your class.
Since, java doesn’t allow multiple inheritance, extending Thread class limits you.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

what is synchronization in java?

A

Synchronization in Java is the process that allows only one thread at a particular time to complete a given task entirely.

By default, the JVM gives control to all the threads present in the system to access the shared resource, due to which the system approaches race condition.

Now, let’s take a real-world example to understand the concept of race condition clearly and how you could avoid the same using Synchronization.

Imagine a classroom where three teachers are simultaneously present to teach the same class. In this scenario, the classroom acts as a shared resource, and the three teachers are the threads. All of them can’t teach at the same time. This scenario when looked at in the context of a computer language is referred to as Race Condition, where there are multiple threads present to do a given task.

To solve the above problem, we use Synchronization in Java. It is also a good practice especially when the threads update the data concurrently.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

what is lambda in java?

A

Java 8 brought a powerful new syntactic improvement in the form of lambda expressions. A lambda is an anonymous function that we can handle as a first-class language citizen. For instance, we can pass it to or return it from a method.

Before Java 8, we would usually create a class for every case where we needed to encapsulate a single piece of functionality. This implied a lot of unnecessary boilerplate code to define something that served as a primitive function representation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

how to implement sychronization in java?

A

Synchronization in Java is done by using the synchronized keyword. This keyword can be used on top of a method or a block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

what are the types of synchronization in java?

A

There are two types of Synchronization in Java, as mentioned below-

Process Synchronization
When multiple threads are executed simultaneously process synchronization ensures that they reach a particular state and agree to a certain set of actions.

Thread Synchronization
When multiple threads want to access the same resource, thread synchronization makes sure that only one thread gains access at a time.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What is the importance of synchronization?

A

Synchronization helps to execute threads one after another. It also prevents memory constituency errors due to shared access methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Does Java use Pointers and give a reason?

A

Java does not use pointers. This is because they are not safe and can increase the complexity of the program. Pointers are the exact opposite of Java’s simplicity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is OOP?

A

OOP is an abbreviation for Object-Oriented Programming. It is a model where programs are organized around objects rather than functions and logic. Its main focus is on objects more than using logic and is mainly preferred for large and complex codes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What is Double Brace Initialization?

A

we can combine the creation and initialization in a single statement; this is where we make use of double braces:

@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
    Set<String> countries = new HashSet<String>() {
        {
           add("India");
           add("USSR");
           add("USA");
        }
    };
 
    assertTrue(countries.contains("India"));
}

As can be seen from above example, we are:

Creating an anonymous inner class which extends HashSet
Providing an instance initialization block which invokes the add method and adds the country name to the HashSet
Finally, we can assert whether the country is present in the HashSet
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

why using double brace initialization is considered anti-pattern?

A

Disadvantages of using double braces are:

  1. Obscure, not widely known way to do the initialization
  2. It creates an extra class every time we use it
    Doesn’t support the use of the “diamond operator” – a feature introduced in Java 7
  3. Doesn’t work if the class we are trying to extend is marked final
  4. Holds a hidden reference to the enclosing instance, which may cause memory leaks
  5. It’s due to these disadvantages that double brace initialization is considered as an anti-pattern.
    source
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

what is composition in java?

A

Composition is a “belongs-to” type of relationship. It means that one of the objects is a logically larger structure, which contains the other object. In other words, it’s part or member of the other object.

Alternatively, we often call it a “has-a” relationship (as opposed to an “is-a” relationship, which is inheritance).

For example, a room belongs to a building, or in other words a building has a room. So basically, whether we call it “belongs-to” or “has-a” is only a matter of point of view.

Composition is a strong kind of “has-a” relationship because the containing object owns it. Therefore, the objects’ lifecycles are tied. It means that if we destroy the owner object, its members also will be destroyed with it. For example, the room is destroyed with the building in our previous example.

Note that doesn’t mean, that the containing object can’t exist without any of its parts. For example, we can tear down all the walls inside a building, hence destroy the rooms. But the building will still exist.

In terms of cardinality, a containing object can have as many parts as we want. However, all of the parts need to have exactly one container.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

what is aggregation in java?

A

Aggregation is also a “has-a” relationship. What distinguishes it from composition, that it doesn’t involve owning. As a result, the lifecycles of the objects aren’t tied: every one of them can exist independently of each other.

For example, a car and its wheels. We can take off the wheels, and they’ll still exist. We can mount other (preexisting) wheels, or install these to another car and everything will work just fine.

Of course, a car without wheels or a detached wheel won’t be as useful as a car with its wheels on. But that’s why this relationship existed in the first place: to assemble the parts to a bigger construct, which is capable of more things than its parts.

Since aggregation doesn’t involve owning, a member doesn’t need to be tied to only one container. For example, a triangle is made of segments. But triangles can share segments as their sides.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

what is association in java?

A

Association is the weakest relationship between the three. It isn’t a “has-a” relationship, none of the objects are parts or members of another.

Association only means that the objects “know” each other. For example, a mother and her child.
In Java, we can model association the same way as aggregation:

class Child {}

class Mother {
    List<Child> children;
}

But wait, how can we tell if a reference means aggregation or association?

Well, we can’t. The difference is only logical: whether one of the objects is part of the other or not.

Also, we have to maintain the references manually on both ends as we did with aggregation:

class Child {
    Mother mother;
}

class Mother {
    List<Child> children;
}

source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is a Singleton class in Java?

A

A singleton class is a class that is capable of possessing only one object at a time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

give some usecases for singleton in java?

A

Logging System
In a logging system, we may want to have only one instance of the logger, as multiple loggers can cause inconsistent and hard-to-read logs. In this case, we can apply the Singleton pattern to create a single logger instance that can be accessed from different parts of the code.

package org.example;

public class Logger {
    private static Logger instance;

    private Logger() {
        // private constructor to prevent instantiation from outside the class
    }

    public static Logger getInstance() {
        if(instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    public void log(String message) {
        // log the message
    }

    public static void main(String[] args) {
        Logger instance1 = Logger.getInstance();
        Logger instance2 = Logger.getInstance();
        /**
         * both prints the same instance
         * org.example.Logger@7cf10a6f
         * org.example.Logger@7cf10a6f
         */
        System.out.println(instance1);
        System.out.println(instance2);
    }
}

Database Connection
In a web application that uses a database, we may want to create a single database connection instance to avoid creating multiple connections that can cause performance issues. By using the Singleton pattern, we can create a single database connection instance that can be shared across the application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

how to implement a singleton class in java?

A

The most popular approach is to implement a Singleton by creating a regular class and making sure it has:

a private constructor
a static field containing its only instance
a static factory method for obtaining the instance

package org.example;

public class Logger {
    private static Logger instance;

    private Logger() {
        // private constructor to prevent instantiation from outside the class
    }

    public static Logger getInstance() {
        if(instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    public void log(String message) {
        // log the message
    }

    public static void main(String[] args) {
        Logger instance1 = Logger.getInstance();
        Logger instance2 = Logger.getInstance();
        /**
         * both prints the same instance
         * org.example.Logger@7cf10a6f
         * org.example.Logger@7cf10a6f
         */
        System.out.println(instance1);
        System.out.println(instance2);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Define a Java string pool.

A

The Java string pool is a repository of strings stored in the Java virtual machine (JVM). The pool stores only one instance of each literal string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What is the difference between JVM and JRE?

A

JRE has class libraries and other JVM files however, it does not have any tools for Java development such as a debugger and compiler. While JVM has a Just In Time(JIT) tool to convert all the Java codes into compatible machine language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What is method overloading in Java?

A

It’s a process of creating multiple method signatures using one method. There are two ways of achieving this i.e changing the return type of the method and varying the number of arguments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

What are the five stages of a thread’s lifecycle?

A

The stages of a thread’s lifecycle are as follows:

  1. Newborn state- This is where a new thread is created. In this newborn state, the code has not been run or executed as yet.
  2. Runnable state- A thread that is ready to run is put into the runnable state. The code may be running or ready to run at any given time but at this stage, the thread scheduler provides the time for the thread to run.
  3. Running state- This stage is when the thread receives a CPU moving from the runnable to the running state.
  4. Blocked state- When the thread is inactive for a period of time temporarily, the thread is said to be in a blocked state.
  5. Dead state- Also known as the terminated state. This is when the thread has either finished its job and exists or when some unexpected event occurs such as a segmentation fault.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Define what is enumeration in Java.

A

Enumeration also known as enum, is an interface in Java. It allows the sequential access of the elements stored in the collection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Can you define Java packages and their significance?

A

Java packages can be defined as a collection of classes and interfaces which are bundled together while they relate to one another. It also helps developers to group a code for reuse and after being packaged it can be imported in other classes for repurposing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What is JPA?

A

JPA stands for Java Persistence API. It enables developers to create the persistence layer for desktop/ web applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Why is Java considered dynamic?

A

Java is considered as Dynamic because of Byte code [a class file]. A source code written in one platform,
that can be executed in any platform. And it also loads the class files at run time.
Anything that happens at run time is considered as Dynamic.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What are the steps involved when connecting to a database in Java?

A

Steps needed to connect to a database in Java are as follows:

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connects
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

what is serialization in java?

A

Serialization is the conversion of the state of an object into a byte stream; deserialization does the opposite. Stated differently, serialization is the conversion of a Java object into a static stream (sequence) of bytes, which we can then save to a database or transfer over a network.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

how to implement serialization in java?

A

The serialization process is instance-independent; for example, we can serialize objects on one platform and deserialize them on another. Classes that are eligible for serialization need to implement a special marker interface, Serializable.

Both ObjectInputStream and ObjectOutputStream are high level classes that extend java.io.InputStream and java.io.OutputStream, respectively. ObjectOutputStream can write primitive types and graphs of objects to an OutputStream as a stream of bytes. We can then read these streams using ObjectInputStream.

The most important method in ObjectOutputStream is:

public final void writeObject(Object o) throws IOException;

This method takes a serializable object and converts it into a sequence (stream) of bytes. Similarly, the most important method in ObjectInputStream is:

public final Object readObject() 
  throws IOException, ClassNotFoundException;

This method can read a stream of bytes and convert it back into a Java object. It can then be cast back to the original object.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What is the difference between an array and a vector?

A

An array groups data of the same primitive type and is static, while vectors can hold data of different types. Vectors are dynamic though.

The Vector class is a thread-safe implementation of a growable array of objects. It implements the java.util.List interface and is a member of the Java Collections Framework. While it’s similar to ArrayList, these classes have significant differences in their implementations.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

how vectors work in java?

A

The Vector class is designed to function as a dynamic array that can expand or shrink according to the application’s needs. Thus, we can access the objects of the Vector using the indices. Additionally, it maintains the insertion order and stores duplicate elements.

Every Vector aims to enhance its storage handling by keeping track of both the capacity and the capacityIncrement. The capacity is nothing but the size of the Vector. The size of the Vector increases as we add elements to it. Therefore, the capacity remains consistently equal to or greater than the Vector‘s size.

Every time the length of a Vector reaches its capacity, the new length is calculated:

newLength = capacityIncrement == 0 ? currentSize * 2 : currentSize + capacityIncrement
Copy
Similar to ArrayList, the iterators of the Vector class are also fail-fast. It throws a ConcurrentModificationException if we try to modify the Vector while iterating over it. However, we can access the iterator’s add() or remove() methods to structurally modify the Vector.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

How is garbage collection done in Java?

A

Garbage collection in Java is done automatically by the Java Virtual Machine (JVM) at runtime. The JVM uses a garbage collection algorithm to identify and reclaim memory from objects that are no longer in use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

How do you create a copy of an object?

A

To create a copy of an object in Java, you can use the clone() method of the Object class. This method creates a shallow copy of the object, meaning that only the object’s references are copied, not its values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Are primitive data types passed-by-value or passed-by-reference in java?

A

Primitives – like int and byte – are always stored and passed as the exact value and not a reference to the value. This is fine because the largest primitive – long – is typically the same amount of memory as the reference would be, and primitives are always immutable, so they can’t be changed anyway.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

what is shallow copy?

A

In some cases, we may want to create a copy of a value so that two different pieces of code see different copies of the same value. This allows one to be manipulated differently from the others, for example.

The simplest way to do this is to make a shallow copy of the object. This means we create a new object that contains all the same fields as the original, with copies of the same values.

For relatively simple objects, this works fine. However, if our objects contain other objects, then only the reference to these will be copied. This, in turn, means that the two copies contain references to the same value in memory.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

what is deep copy of an object?

A

This is where we copy each field from the original to the copy, but as we do so, we perform a deep copy of those instead of just copying the references.
This will then mean that the new copy is an exact copy of the original, but in no way connected so that no changes to one will be reflected in the other.
source

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

Outline the difference between queue and stack.

A

The main difference between stack and queue is that stack is based on LIFO (Last in first out) while a queue is based on FIFO( First in first out) principle. Both are used as placeholders for the collection of data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

During program compilation, what type of exceptions are caught?

A

Checked exceptions can be caught during the time of program compilation. The checked exceptions must be handled by using the try catch block in the code to successfully compile the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

How are destructors defined in Java?

A

Java has its own garbage collection mechanism which destroys automatically objects when they are no longer referenced. Hence no destructors need to be defined.

76
Q

Is it possible to find the actual size of an object on the heap?

A

Yes, it is possible to find the size of an object on the heap in Java. The object size can be calculated by calling the Object.getSize(Object)) method.

77
Q

what are nested classes in java?

A

Simply put, Java allows us to define classes inside other classes. Nested classes enable us to logically group classes that are only used in one place, write more readable and maintainable code and increase encapsulation.

There are several types of nested classes available in the language:

Static nested classes
Non-static nested classes
Local classes
Anonymous classes
source

78
Q

what is a static nested class in java?

A

Here are a few points to remember about static nested classes:

As with static members, these belong to their enclosing class, and not to an instance of the class
They can have all types of access modifiers in their declaration
They only have access to static members in the enclosing class
They can define both static and non-static members
Let’s see how we can declare a static nested class:

public class Enclosing {
    
    private static int x = 1;
    
    public static class StaticNested {

        private void run() {
            // method implementation
        }
    }
    
    @Test
    public void test() {
        Enclosing.StaticNested nested = new Enclosing.StaticNested();
        nested.run();
    }
}

source

79
Q

what is a non-static nested class in java?

A

here are a few quick points to remember about non-static nested classes:

They are also called inner classes
They can have all types of access modifiers in their declaration
Just like instance variables and methods, inner classes are associated with an instance of the enclosing class
They have access to all members of the enclosing class, regardless of whether they are static or non-static
They can only define non-static members
Here’s how we can declare an inner class:

public class Outer {
    
    public class Inner {
        // ...
    }
}

If we declare a nested class with a modifier static, then it’s a static member one. Otherwise, it’s an inner class. Even though syntactically the difference is just a single keyword (i.e., static), semantically there is a huge difference between these kinds of nested classes. Inner class instances are bound to the enclosing class ones and therefore they have access to their members. We should be aware of this issue when selecting whether to make a nested class be an inner one.

To instantiate an inner class, we must first instantiate its enclosing class.

Let’s see how we can do that:

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

source

80
Q

what is a local class in java?

A

Local classes are a special type of inner classes – in which the class is defined inside a method or scope block.

Let’s see a few points to remember about this type of class:

They cannot have access modifiers in their declaration
They have access to both static and non-static members in the enclosing context
They can only define instance members
Here’s a quick example:

public class NewEnclosing {
    
    void run() {
        class Local {

            void run() {
                // method implementation
            }
        }
        Local local = new Local();
        local.run();
    }
    
    @Test
    public void test() {
        NewEnclosing newEnclosing = new NewEnclosing();
        newEnclosing.run();
    }
}

source

81
Q

what is an anonymous class in java?

A

Anonymous classes can be used to define an implementation of an interface or an abstract class without having to create a reusable implementation.

Let’s list a few points to remember about anonymous classes:

They cannot have access modifiers in their declaration
They have access to both static and non-static members in the enclosing context
They can only define instance members
They’re the only type of nested classes that cannot define constructors or extend/implement other classes or interfaces
To define an anonymous class, let’s first define a simple abstract class:

abstract class SimpleAbstractClass {
    abstract void run();
}
Now let’s see how we can define an anonymous class:

public class AnonymousInnerUnitTest {
    
    @Test
    public void whenRunAnonymousClass_thenCorrect() {
        SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
            void run() {
                // method implementation
            }
        };
        simpleAbstractClass.run();
    }
}

source

82
Q

what is shadowing in nested classes in java?

A

The declaration of the members of an inner class shadow those of the enclosing class if they have the same name.

In this case, the this keyword refers to the instances of the nested class and the members of the outer class can be referred to using the name of the outer class.

Let’s see a quick example:

public class NewOuter {

    int a = 1;
    static int b = 2;

    public class InnerClass {
        int a = 3;
        static final int b = 4;

        public void run() {
            System.out.println("a = " + a); // 3
            System.out.println("b = " + b); // 4
            System.out.println("NewOuterTest.this.a = " + NewOuter.this.a); // 1
            System.out.println("NewOuterTest.b = " + NewOuter.b); // 2
            System.out.println("NewOuterTest.this.b = " + NewOuter.this.b); //2
        }
    }

    @Test
    public void test() {
        NewOuter outer = new NewOuter();
        NewOuter.InnerClass inner = outer.new InnerClass();
        inner.run();

    }
}

source

83
Q

What is Final keyword in Java?

A

The final keyword in Java is used to indicate that a variable, method, or class cannot be changed or overridden. It is used to create constants that cannot be changed, and to prevent a method from being overridden by a subclass.

84
Q

State the difference between float and double variables.

A

Float only takes 4 bytes in memory while double takes twice the bytes as that of a float in memory. Double is also a double-precision decimal number while float is a single-precision floating-point decimal number.

85
Q

How do you create threads in Java?

A

Threads can be created in two ways, by either extending the thread or by implementing the runnable interface.

86
Q

Explain Out Of Memory Error in Java.

A

This error occurs when JVM runs out of memory. OutOfMemoryError is the subclass of Java.lang

87
Q

What is exception propagation?

A

If an exception is not caught, it is thrown from the stack and falls down the call stack to the previous procedure. If then it is not caught there, it will fall back again to the previous function. The process repeats until caught or the call stack reaches the bottom.

88
Q

Define JCA in Java.

A

JCA is an abbreviation of Java Cryptography Architecture and is used by developers to combine it with security applications. It, therefore, gives a platform and provides architecture and application programming interfaces that enable encryption and decryption.

89
Q

What is Spring in Java?

A

It is an application framework in Java and inversion of control containers of Java. It creates enterprise applications in Java.

90
Q

What is Late Binding?

A

Late binding is also known as dynamic binding or run-time binding. Late Binding happens when the method’s code segment is unknown until it is called during the runtime.

91
Q

Explain the reason why the delete function is faster in the linked list than in an array.

A

The function is faster in Java as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list.

92
Q

what are daemon threads in java?

A

Java offers two types of threads: user threads and daemon threads.

User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it.

On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads.

Since daemon threads are meant to serve user threads and are only needed while user threads are running, they won’t prevent the JVM from exiting once all user threads have finished their execution.

That’s why infinite loops, which typically exist in daemon threads, will not cause problems, because any code, including the finally blocks, won’t be executed once all user threads have finished their execution. For this reason, daemon threads are not recommended for I/O tasks.

However, there’re exceptions to this rule. Poorly designed code in daemon threads can prevent the JVM from exiting. For example, calling Thread.join() on a running daemon thread can block the shutdown of the application.
source

93
Q

what is the use of daemon threads in java?

A

Daemon threads are useful for background supporting tasks such as garbage collection, releasing memory of unused objects and removing unwanted entries from the cache. Most of the JVM threads are daemon threads.

source

94
Q

how to create a daemon thread in java?

A

To set a thread to be a daemon thread, all we need to do is to call Thread.setDaemon(). In this example, we’ll use the NewThread class which extends the Thread class:

NewThread daemonThread = new NewThread();
daemonThread.setDaemon(true);
daemonThread.start();

Any thread inherits the daemon status of the thread that created it. Since the main thread is a user thread, any thread that is created inside the main method is by default a user thread.

The method setDaemon() can only be called after the Thread object has been created and the thread has not been started. An attempt to call setDaemon() while a thread is running will throw an IllegalThreadStateException:

@Test(expected = IllegalThreadStateException.class)
public void whenSetDaemonWhileRunning_thenIllegalThreadStateException() {
    NewThread daemonThread = new NewThread();
    daemonThread.start();
    daemonThread.setDaemon(true);
}

source

95
Q

how to check if a thread is daemon thread or not ?

A

to check if a thread is a daemon thread, we can simply call the method isDaemon():

@Test
public void whenCallIsDaemon_thenCorrect() {
    NewThread daemonThread = new NewThread();
    NewThread userThread = new NewThread();
    daemonThread.setDaemon(true);
    daemonThread.start();
    userThread.start();
    
    assertTrue(daemonThread.isDaemon());
    assertFalse(userThread.isDaemon());
}

source

96
Q

What is the difference between&raquo_space;> and&raquo_space; operators?

A

Signed Right Shift [»]
The right shift operator shifts all the bits to the right. The empty space in the left side is filled depending on the input number:

When an input number is negative, where the leftmost bit is 1, then the empty spaces will be filled with 1
When an input number is positive, where the leftmost bit is 0, then the empty spaces will be filled with 0

Unsigned Right Shift [»>]
This operator is very similar to the signed right shift operator. The only difference is that the empty spaces in the left are filled with 0 irrespective of whether the number is positive or negative. Therefore, the result will always be a positive integer.
source

97
Q

Define Polymorphism.

A

Polymorphism in Java is when we have many forms/classes related to each other by inheritance. A single object can refer to the sub and super class depending on the reference type which is called polymorphism’

98
Q

Explain what is Ordered in collections.

A

An ordered collection means that the elements of the collection have a specific order. The order is independent of the value. A List is an example.

A sorted collection means that not only does the collection have order, but the order depends on the value of the element. A SortedSet is an example.

In contrast, a collection without any order can maintain the elements in any order. A Set is an example.
source

99
Q

Define the term finally block.

A

A finally block in Java is a block of code that is always executed after a try/catch block, regardless of whether or not an exception has been thrown.

100
Q

List the different types of Garbage Collectors in Java.

A

These are the different types of collectors:

Serial Garbage Collector
Parallel Garbage Collector
CMS Garbage Collector
G1 Garbage Collector

101
Q

Explain the difference between System.out and System.err.

A

System.out is used to display messages and results while System.err is used to display error messages.

102
Q

what are fail-safe and fail-fast iterators in java?

A

Fail-Fast systems abort operation as-fast-as-possible exposing failures immediately and stopping the whole operation.

Whereas, Fail-Safe systems don’t abort an operation in the case of a failure. Such systems try to avoid raising failures as much as possible.

source

103
Q

how fail-fast iterators work in java?

A

Fail-fast iterators in Java don’t play along when the underlying collection gets modified.

Collections maintain an internal counter called modCount. Each time an item is added or removed from the Collection, this counter gets incremented.

When iterating, on each next() call, the current value of modCount gets compared with the initial value. If there’s a mismatch, it throws ConcurrentModificationException which aborts the entire operation.

Default iterators for Collections from java.util package such as ArrayList, HashMap, etc. are Fail-Fast.

ArrayList<Integer> numbers = // ...

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
    Integer number = iterator.next();
    numbers.add(50);
}

In the code snippet above, the ConcurrentModificationException gets thrown at the beginning of a next iteration cycle after the modification was performed.

The Fail-Fast behavior isn’t guaranteed to happen in all scenarios as it’s impossible to predict behavior in case of concurrent modifications. These iterators throw ConcurrentModificationException on a best effort basis.

If during iteration over a Collection, an item is removed using Iterator‘s remove() method, that’s entirely safe and doesn’t throw an exception.

However, if the Collection‘s remove() method is used for removing an element, it throws an exception:

ArrayList<Integer> numbers = // ...

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
    if (iterator.next() == 30) {
        iterator.remove(); // ok!
    }
}

iterator = numbers.iterator();
while (iterator.hasNext()) {
    if (iterator.next() == 40) {
        numbers.remove(2); // exception
    }
}

source

104
Q

how fail-safe iterators work in java?

A

Fail-Safe iterators favor lack of failures over the inconvenience of exception handling.

Those iterators create a clone of the actual Collection and iterate over it. If any modification happens after the iterator is created, the copy still remains untouched. Hence, these Iterators continue looping over the Collection even if it’s modified.

However, it’s important to remember that there’s no such thing as a truly Fail-Safe iterator. The correct term is Weakly Consistent.

That means, if a Collection is modified while being iterated over, what the Iterator sees is weakly guaranteed. This behavior may be different for different Collections and is documented in Javadocs of each such Collection.

The Fail-Safe Iterators have a few disadvantages, though. One disadvantage is that the Iterator isn’t guaranteed to return updated data from the Collection, as it’s working on the clone instead of the actual Collection.

Another disadvantage is the overhead of creating a copy of the Collection, both regarding time and memory.

Iterators on Collections from java.util.concurrent package such as ConcurrentHashMap, CopyOnWriteArrayList, etc. are Fail-Safe in nature.
~~~
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

map.put(“First”, 10);
map.put(“Second”, 20);
map.put(“Third”, 30);
map.put(“Fourth”, 40);

Iterator<String> iterator = map.keySet().iterator();</String>

while (iterator.hasNext()) {
String key = iterator.next();
map.put(“Fifth”, 50);
}
~~~
In the code snippet above, we’re using Fail-Safe Iterator. Hence, even though a new element is added to the Collection during the iteration, it doesn’t throw an exception.

The default iterator for the ConcurrentHashMap is weakly consistent. This means that this Iterator can tolerate concurrent modification, traverses elements as they existed when Iterator was constructed and may (but isn’t guaranteed to) reflect modifications to the Collection after the construction of the Iterator.

Hence, in the code snippet above, the iteration loops five times, which means it does detect the newly added element to the Collection.
source

105
Q

What is the difference between Java and C++ in terms of language compatibility?

A

C++, which is based on the C programming language, is compatible with most other high-level languages whereas Java is not compatible with C++.

106
Q

what is copy constructor in java?

A

A copy constructor in a Java class is a constructor that creates an object using another object of the same Java class.

That’s helpful when we want to copy a complex object that has several fields, or when we want to make a deep copy of an existing object.

107
Q

how to create a copy constructor in java?

A

To create a copy constructor, we can first declare a constructor that takes an object of the same type as a parameter:

public class Employee {
    private int id;
    private String name;
  
    public Employee(Employee employee) {
    }
}

Then, we copy each field of the input object into the new instance:

public class Employee {
    private int id;
    private String name;
    
    public Employee(Employee employee) {
        this.id = employee.id;
        this.name = employee.name;
    }
}

What we have here is a shallow copy, which is fine since all of our fields – an int and a String in this case – are either primitive types or immutable types.

If the Java class has mutable fields, then we can instead make a deep copy inside its copy constructor. With a deep copy, the newly created object is independent of the original one because we create a distinct copy of each mutable object:

public class Employee {
    private int id;
    private String name;
    private Date startDate;

    public Employee(Employee employee) {
        this.id = employee.id;
        this.name = employee.name;
        this.startDate = new Date(employee.startDate.getTime());
    }
}

source

108
Q

Define the term ‘this’ keyword in Java.

A

The term is a particular word designed as a reference keyword. It is used to refer to the current class properties like method, variable, instance, and constructors

109
Q

Give the reason why generics are used in Java.

A

Let’s imagine a scenario where we want to create a list in Java to store Integer.

We might try to write the following:

List list = new LinkedList();
list.add(new Integer(1)); 
Integer i = list.iterator().next();

Surprisingly, the compiler will complain about the last line. It doesn’t know what data type is returned.

The compiler will require an explicit casting:

Integer i = (Integer) list.iterator.next();

No contract could guarantee that the return type of the list is an Integer. The defined list could hold any object. We only know that we are retrieving a list by inspecting the context. When looking at types, it can only guarantee that it is an Object and therefore requires an explicit cast to ensure that the type is safe.

This cast can be annoying — we know that the data type in this list is an Integer. The cast is also cluttering our code. It can cause type-related runtime errors if a programmer makes a mistake with the explicit casting.

It would be much easier if programmers could express their intention to use specific types and the compiler ensured the correctness of such types. This is the core idea behind generics.

Let’s modify the first line of the previous code snippet:

List<Integer> list = new LinkedList<>();

By adding the diamond operator <> containing the type, we narrow the specialization of this list to only Integer type. In other words, we specify the type held inside the list. The compiler can enforce the type at compile time.

In small programs, this might seem like a trivial addition. But in larger programs, this can add significant robustness and makes the program easier to read.

source

110
Q

How does a single try block and multiple catch blocks co-exist in a Java Program?

A

One or more catch blocks can follow a try block, though each catch must have a unique exception handler. Multiple tasks can now be performed using the Java multi-catch block.

111
Q

what is super keyword in java?

A

Simply put, we can use the super keyword to access the parent class.
source

112
Q

what will happen on running the main class?

public class SuperKeywordExample {
    public SuperKeywordExample() {
        System.out.println("Parent class default constructor");
    }
}

class ChildClass extends SuperKeywordExample {
    public ChildClass() {
        super();
    }

    public static void main(String[] args) {
        ChildClass childClass = new ChildClass(); // will calling this print "Parent class default constructor"?
    }
}
A

Yes, it will print the message because super() is used to access the default constructor of the parent class.

113
Q
public class SuperKeywordExample {

    String message = "Hello from parent class";

    public SuperKeywordExample() {
        System.out.println("Parent class default constructor");
    }
}

public class ChildClass extends SuperKeywordExample {
    
    String message = "Hello, from child class";
    public ChildClass() {
        super();
    }

    void printMessage() {
        System.out.println(super.message);
    }

    @Test
    public void test() {
       printMessage(); 
    }
}

what will be printed on running the test?

A

Parent class default constructor
Hello, from parent class

Why the parent class constructor was called?
Because that is how Java works. The constructors of the parent classes are called, all the way up the class hierarchy through Object, before the child class’s constructor is called.
source

114
Q

Explain the reason why the delete function is faster in the linked list than in an array.

A

The function is faster in Java as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list.

115
Q

What is the difference between interface and abstract classes?

A

The interface has only abstract methods in it whereas an abstract class can have both abstract and non-abstract methods.

115
Q

how to declare an abstract class?

A

We define an abstract class with the abstract modifier preceding the class keyword

116
Q

can we instantiate an abstract class?

A

No

117
Q

can a class extend another abstract class?

A

Yes

118
Q

If a class defines one or more abstract methods, then the class itself must be declared abstract. True or false?

A

true

119
Q

An abstract class can declare both abstract and concrete methods. True or false?

A

true

120
Q

A subclass derived from an abstract class must either implement all the base class’s abstract methods or be abstract itself. True or false?

A

true

121
Q

what should we use: abstract class or interface, when we want to encapsulate some common functionality in one place (code reuse) that multiple, related subclasses will share

A

abstract class

122
Q

what should we use: abstract class or interface, when we need to partially define an API that our subclasses can easily extend and refine

A

abstract class

123
Q

what should we use: abstract class or interface, when the subclasses need to inherit one or more common methods or fields with protected access modifiers

A

abstract class

124
Q

define functional interfaces in java?

A

It’s recommended that all functional interfaces have an informative @FunctionalInterface annotation. This clearly communicates the purpose of the interface, and also allows a compiler to generate an error if the annotated interface does not satisfy the conditions.

Any interface with a SAM(Single Abstract Method) is a functional interface, and its implementation may be treated as lambda expressions.

Note that Java 8’s default methods are not abstract and do not count; a functional interface may still have multiple default methods.

125
Q

how ‘Function’ interface in java works?

A

The most simple and general case of a lambda is a functional interface with a method that receives one value and returns another. This function of a single argument is represented by the Function interface, which is parameterized by the types of its argument and a return value:

public interface Function<T, R> { … }

One of the usages of the Function type in the standard library is the Map.computeIfAbsent method. This method returns a value from a map by key, but calculates a value if a key is not already present in a map. To calculate a value, it uses the passed Function implementation:

Map<String, Integer> nameMap = new HashMap<>();
Integer value = nameMap.computeIfAbsent("John", s -> s.length());

In this case, we will calculate a value by applying a function to a key, put inside a map, and also returned from a method call. We may replace the lambda with a method reference that matches passed and returned value types.

Remember that an object we invoke the method on is, in fact, the implicit first argument of a method. This allows us to cast an instance method length reference to a Function interface:

Integer value = nameMap.computeIfAbsent("John", String::length);

The Function interface also has a default compose method that allows us to combine several functions into one and execute them sequentially:

Function<Integer, String> intToString = Object::toString;
Function<String, String> quote = s -> "'" + s + "'";

Function<Integer, String> quoteIntToString = quote.compose(intToString);

assertEquals("'5'", quoteIntToString.apply(5));

The quoteIntToString function is a combination of the quote function applied to a result of the intToString function.
source

126
Q

Why Interfaces Need Default Methods?

A

Like regular interface methods, default methods are implicitly public; there’s no need to specify the public modifier.

Unlike regular interface methods, we declare them with the default keyword at the beginning of the method signature, and they provide an implementation.

Let’s look at a simple example:

public interface MyInterface {
    
    // regular interface methods
    
    default void defaultMethod() {
        // default method implementation
    }
}

The reason why the Java 8 release included default methods is pretty obvious.

In a typical design based on abstractions, where an interface has one or multiple implementations, if one or more methods are added to the interface, all the implementations will be forced to implement them too. Otherwise, the design will just break down.

Default interface methods are an efficient way to deal with this issue. They allow us to add new methods to an interface that are automatically available in the implementations. Therefore, we don’t need to modify the implementing classes.

In this way, backward compatibility is neatly preserved without having to refactor the implementers.
source

127
Q

how backward compatibility is preserved in using default methods in interfaces in java?

A

In Java, default methods in interfaces were introduced in Java 8 to allow the addition of new methods to interfaces without breaking existing implementations. Default methods provide a way to add new functionality to interfaces without requiring all implementing classes to provide an implementation for the new methods.

When a new method is added to an interface as a default method, implementing classes that do not override the default method will automatically inherit the default implementation. This ensures backward compatibility because existing classes that implement the interface will still compile and run without modification.

128
Q

what happens when a class implements two interfaces with same default methods. Does the code even compile?

A

Default interface methods are a pretty nice feature, but there are some caveats worth mentioning. Since Java allows classes to implement multiple interfaces, it’s important to know what happens when a class implements several interfaces that define the same default methods.

To better understand this scenario, let’s define a new Alarm interface and refactor the Car class:

public interface Alarm {

    default String turnAlarmOn() {
        return "Turning the alarm on.";
    }
    
    default String turnAlarmOff() {
        return "Turning the alarm off.";
    }
}

With this new interface defining its own set of default methods, the Car class would implement both Vehicle and Alarm:

public class Car implements Vehicle, Alarm {
    // ...
}

In this case, the code simply won’t compile, as there’s a conflict caused by multiple interface inheritance (a.k.a the Diamond Problem). The Car class would inherit both sets of default methods. So which ones should we call?

To solve this ambiguity, we must explicitly provide an implementation for the methods:

@Override
public String turnAlarmOn() {
    // custom implementation
}
    
@Override
public String turnAlarmOff() {
    // custom implementation
}

We can also have our class use the default methods of one of the interfaces.

Let’s see an example that uses the default methods from the Vehicle interface:

@Override
public String turnAlarmOn() {
    return Vehicle.super.turnAlarmOn();
}

@Override
public String turnAlarmOff() {
    return Vehicle.super.turnAlarmOff();
}

Similarly, we can have the class use the default methods defined within the Alarm interface:

@Override
public String turnAlarmOn() {
    return Alarm.super.turnAlarmOn();
}

@Override
public String turnAlarmOff() {
    return Alarm.super.turnAlarmOff();
}

It’s even possible to make the Car class use both sets of default methods:

@Override
public String turnAlarmOn() {
    return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn();
}
    
@Override
public String turnAlarmOff() {
    return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff();
}

source

129
Q

what are static interface methods?

A

In addition to declaring default methods in interfaces, Java 8 also allows us to define and implement static methods in interfaces.

Since static methods don’t belong to a particular object, they’re not part of the API of the classes implementing the interface; therefore, they have to be called by using the interface name preceding the method name.

To understand how static methods work in interfaces, let’s refactor the Vehicle interface and add a static utility method to it:

public interface Vehicle {
    
    // regular / default interface methods
    
    static int getHorsePower(int rpm, int torque) {
        return (rpm * torque) / 5252;
    }
}

Defining a static method within an interface is identical to defining one in a class. Moreover, a static method can be invoked within other static and default methods.

Let’s suppose that we want to calculate the horsepower of a given vehicle’s engine. We just call the getHorsePower() method:

Vehicle.getHorsePower(2500, 480));

The idea behind static interface methods is to provide a simple mechanism that allows us to increase the degree of cohesion of a design by putting together related methods in one single place without having to create an object.

The same can pretty much be done with abstract classes. The main difference is that abstract classes can have constructors, state, and behavior.

Furthermore, static methods in interfaces make it possible to group related utility methods, without having to create artificial utility classes that are simply placeholders for static methods.
source

130
Q

Highlight the difference between the ‘throws’ and ‘throw’ keywords in Java.

A

Throws can be used to declare multiple exceptions whereas throw can throw one exception at a time

131
Q

What Is an Immutable Object?

A

An immutable object is an object whose internal state remains constant after it has been entirely created. This means that once the object has been assigned to a variable, we can neither update the reference nor mutate the internal state by any means.

132
Q

Why Is String Immutable in Java?

A

The key benefits of keeping this class as immutable are caching, security, synchronization, and performance.

133
Q

Explain why string being immutable helps in caching in java?

A

The String is the most widely used data structure. Caching the String literals and reusing them saves a lot of heap space because different String variables refer to the same object in the String pool. String intern pool serves exactly this purpose.

Java String Pool is the special memory region where Strings are stored by the JVM. Since Strings are immutable in Java, the JVM optimizes the amount of memory allocated for them by storing only one copy of each literal String in the pool. This process is called interning:

String s1 = "Hello World";
String s2 = "Hello World";
         
assertThat(s1 == s2).isTrue();

Because of the presence of the String pool in the preceding example, two different variables are pointing to same String object from the pool, thus saving crucial memory resource.
source

134
Q

Explain how string being immutable helps in security in java?

A

The String is widely used in Java applications to store sensitive pieces of information like usernames, passwords, connection URLs, network connections, etc. It’s also used extensively by JVM class loaders while loading classes.

Hence securing String class is crucial regarding the security of the whole application in general. For example, consider this simple code snippet:

void criticalMethod(String userName) {
    // perform security checks
    if (!isAlphaNumeric(userName)) {
        throw new SecurityException(); 
    }
	
    // do some secondary tasks
    initializeDatabase();
	
    // critical task
    connection.executeUpdate("UPDATE Customers SET Status = 'Active' " +
      " WHERE UserName = '" + userName + "'");
}

In the above code snippet, let’s say that we received a String object from an untrustworthy source. We’re doing all necessary security checks initially to check if the String is only alphanumeric, followed by some more operations.

Remember that our unreliable source caller method still has reference to this userName object.

If Strings were mutable, then by the time we execute the update, we can’t be sure that the String we received, even after performing security checks, would be safe. The untrustworthy caller method still has the reference and can change the String between integrity checks. Thus making our query prone to SQL injections in this case. So mutable Strings could lead to degradation of security over time.

It could also happen that the String userName is visible to another thread, which could then change its value after the integrity check.

In general, immutability comes to our rescue in this case because it’s easier to operate with sensitive code when values don’t change because there are fewer interleavings of operations that might affect the result.
source

135
Q

why string being immutable helps in synchronization in java?

A

Being immutable automatically makes the String thread safe since they won’t be changed when accessed from multiple threads.

Hence immutable objects, in general, can be shared across multiple threads running simultaneously. They’re also thread-safe because if a thread changes the value, then instead of modifying the same, a new String would be created in the String pool. Hence, Strings are safe for multi-threading.
source

136
Q

how string being immutable impacts performance in java?

A

As we saw previously, String pool exists because Strings are immutable. In turn, it enhances the performance by saving heap memory and faster access of hash implementations when operated with Strings.

Since String is the most widely used data structure, improving the performance of String have a considerable effect on improving the performance of the whole application in general.
source

137
Q

what does finalize() method do in java?

A

The finalize() method is called the finalizer.

Finalizers get invoked when JVM figures out that this particular instance should be garbage collected. Such a finalizer may perform any operations, including bringing the object back to life.

The main purpose of a finalizer is, however, to release resources used by objects before they’re removed from the memory. A finalizer can work as the primary mechanism for clean-up operations, or as a safety net when other methods fail.
source

138
Q

What a Checked Exception is?

A

Checked Exceptions are a type of Exception that the compiler checks for during the compilation process.

139
Q

Clarify the difference between the start() and run() methods in the thread class.

A

Start() method creates a new thread, while the code inside run() executes in the new thread.

140
Q

State the disadvantage of synchronization.

A

It is not recommended to implement all methods. This is because if one thread accesses the synchronized code then the next thread will have to wait. This will end result in slow performance.

141
Q

Outline the purpose of transient variables

A

Let’s first understand the serialization before moving to transient as it is used in the context of serialization.

Serialization is the process of converting an object into a byte stream, and de-serialization is the opposite of it.

When we mark any variable as transient, then that variable is not serialized. Since transient fields aren’t present in the serialized form of an object, the de-serialization process would use the default values (which are null or 0) for such fields when creating an object out of the serialized form.8

The transient keyword is useful in a few scenarios:

We can use it for derived fields
It is useful for fields that do not represent the state of the object
We use it for any non-serializable references
When we want to store sensitive information and don’t want to send it through the network
source

142
Q
public class Book implements Serializable {
    // existing fields    
    
    private final transient String bookCategory = "Fiction";

    // getters and setters
}
assertEquals("Fiction", book.getBookCategory());

will the above assertion fail? If not then explain why?

A

The final modifier makes no difference when it has literal initialization. When a variable of type String is declared as final and transient, its value is determined at compile-time and is stored in the class’s constant pool. Since it is final, it’s value can’t be change after it’s initialization. Hence, its value will be taken from the class and not null.
source

143
Q
public class Book implements Serializable {
    // existing fields    
    
    private final transient String bookCategoryNewOperator = new String("Fiction with new Operator");

    // getters and setters
}
assertNull(book.getBookCategoryNewOperator());

Will the above assertion fail? If not then explain why?

A

In this case, using a new operator to initialize a String will create the object in the Heap memory and the default value for this object when we deserialize will be null.
source

144
Q

Define SerialVersionUID.

A

Simply put, we use the serialVersionUID attribute to remember versions of a Serializable class to verify that a loaded class and the serialized object are compatible.

The serialVersionUID attributes of different classes are independent. Therefore, it is not necessary for different classes to have unique values.

Now, if we change the id, then we would get an exception because:
By changing the serialVersionUID of the class, we modified its version/state. As a result, no compatible classes were found during deserialization, and an InvalidClassException was thrown.

If serialVersionUID is not provided in a Serializable class, the JVM will generate one automatically. However, it is good practice to provide the serialVersionUID value and update it after changes to the class so that we can have control over the serialization/deserialization process. We’ll take a closer look at it in a later section.
source

145
Q

What is the sleep() method in a thread?

A

The sleep method is used to sleep the currently executing thread for a given amount of time. Sleep is used to delay the execution period because once the thread wakes up it can move to the runnable state.

146
Q

State the difference between notify() and notifyAll() methods in Java.

A

Notify() is used to send a signal to wake up a single thread in the waiting pool while notifyAll() sends the signal to wake up all the threads in the waiting pool.

147
Q

Explain the difference between TreeSet and HashSet.

A

TreeSet maintains the elements in the sorted order. On the other hand, the elements in HashSet are inserted in random order.

148
Q

Define Public and private access specifiers

A

Public and private access specifiers are methods and instance variables known as members. Public members are visible in the same package as well as outside whereas private members are visible in the same classes only and not for other classes in the same packages.

149
Q

Explain what the yield method of the Thread class does.

A

As the official documentation suggests, yield() provides a mechanism to inform the “scheduler” that the current thread is willing to relinquish its current use of processor but it’d like to be scheduled back soon as possible.

The “scheduler” is free to adhere or ignore this information and in fact, has varying behavior depending upon the operating system.
source

150
Q

Explain the wait() method.

A

This method is used to make the thread wait in the waiting pool. Once executed during the thread execution then instantly the thread gives up the lock on the object and goes into the waiting pool.

151
Q

Does Java work on a “pass by reference” or “pass by value” phenomenon?

A

Java works only as a “pass by value” as “pass by reference” needs the assistance of pointers. Java does not have pointers.

152
Q

Explain the default values assigned to variables and instances in Java.

A

For a numerical value, it is O, for the boolean value, it is false and NULL value for objects

153
Q

Number of primitive data types in Java are?

A

There are 8 types of primitive data types- int, char, boolean, byte, long, float, short, double.

154
Q

What is the size of float and double in java?

A

The size of float and double in java is 32 and 64.

155
Q

Automatic type conversion is possible in which of the possible cases?
1. Byte to int
2. int to long
3. long to int
4. short to int

A

Answer: 2, 4
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:

The two data types are compatible.
When we assign a value of a smaller data type to a bigger data type.
For Example, in java, the numeric data types are compatible with each other but no automatic conversion is supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other.

156
Q

Find the output of the following code.

int Integer = 24;
char String = ‘I’;
System.out.print(Integer);
System.out.print(String);
1. complilation error
2. exception
3. I
4. 24 I

A

24 I will be printed.

157
Q

Find the output of the following program.

public class Solution{
       public static void main(String[] args){
                     short x = 10;
                     x =  x * 5;
                     System.out.print(x);
       }
}
  1. 50
  2. 10
  3. compile error
  4. exception
A

This will give compile error - “Lossy conversion from int to short”

158
Q

Find the output of the following program.

public class Solution{
public static void main(String[] args){
byte x = 127;
x++;
x++;
System.out.print(x);
}
}
1. -127
2. 127
3. 129
4. 2

A

Range of byte data in java is -128 to 127. But the byte data type in java is cyclic in nature.

159
Q

Find the output of the following program.

public class Solution{
       public static void main(String[] args){
               int[]  x = {120, 200, 016};
               for(int i = 0; i < x.length; i++){
                        System.out.print(x[i] + “ “);
               }                   
       }
}

what would be the printed value?

A

Answer: 120 200 14
016 is an octal number, its equivalent decimal number is 14.

160
Q

Arrays in java are:
1. Object references
2. objects
3. primitive data types
4. none

A

Answer: 2
Arrays are objects in java. It is a container that holds a fixed number of items of a single type.

161
Q

In which of the following is toString() method defined?
1. java.lang.Object
2. java.lang.String
3. java.lang.util
4. none

A

answer: java.lang.Object

162
Q

Identify the output of the following program.

String str = “abcde”;
System.out.println(str.substring(1, 3));
A

answer: bc
str.substring(start, end) returns the string from s[start] till s[end - 1]

163
Q

Identify the output of the following program.

String str = “Hellow”;
System.out.println(str.indexOf(‘t));
A

Since, t isn’t present in the string str, it returns -1.

164
Q

What does the following string do to given string str1.

String str1 = “Interviewbit”.replace(‘e’,’s’);
A

replace() replaces all the occurrences of the oldcharacter by the newcharacter.

165
Q

How many objects will be created in the following?

String a = new String(“Interviewbit”);
String b = new String(“Interviewbit”);
Strinc c = “Interviewbit”;
String d = “Interviewbit”;
  1. 2
  2. 3
  3. 4
  4. none
A

Using the new keyword creates an object everytime. Hence, 2 objects are created for first two statement. Next, a string is declared which creates another object. For the fourth statement, since, a string ”Interviewbit” already exists, it doesn’t create an additional object again. Hence, answer is 3.

166
Q

Output of Math.floor(3.6)?

A

answer: 3.0

167
Q

How many objects will be created in the String pool?

String a = new String(“Interviewbit”);
String b = new String(“Interviewbit”);
Strinc c = “Interviewbit”;
String d = “Interviewbit”;
  1. 2
  2. 3
  3. 4
  4. none
A

in total, three objects are explicitly created using the new keyword, but only two new objects are created in the string pool (due to the use of string literals).

168
Q

What is the implicit return type of constructor?
1. No return type
2. A class object in which it is defined
3. void
4. none

A

Answer: 2
implicit return type of constructor is the class object in which it is defined.

169
Q

Identify the correct way of declaring constructor.

Public class Solution {}

  1. Solution() {}
  2. Public Solution() {}
  3. Solution(void) {}
  4. both 1 and 2
A

answer: 4

170
Q

Output of following Java Program?

class Base {
    public void show() {
       System.out.println("Base::show() called");
    }
}
  
class Derived extends Base {
    public void show() {
       System.out.println("Derived::show() called");
    }
}
  
public class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
A

In the above program, b is a reference of Base type and refers to an abject of Derived class. In Java, functions are virtual by default. So the run time polymorphism happens and derived fun() is called.

171
Q

What is the use of final keyword in Java?

  1. When a class is made final, a subclass of it can not be created.
  2. When a method is final, it can not be overridden.
  3. When a variable is final, it can be assigned value only once.
  4. All of the above
A

Answer: 4

172
Q
class Base {
    final public void show() {
       System.out.println("Base::show() called");
    }
}
  
class Derived extends Base {
    public void show() {
       System.out.println("Derived::show() called");
    }
}
  
class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
  1. Base::show() called
  2. Derived::show() called
  3. Compiler Error
  4. Runtime Error
A

Answer: 3. Final methods cannot be overridden.

173
Q
class Base {
    public static void show() {
       System.out.println("Base::show() called");
    }
}
  
class Derived extends Base {
    public static void show() {
       System.out.println("Derived::show() called");
    }
}
  
class Main {
    public static void main(String[] args) {
        Base b = new Derived();
        b.show();
    }
}
  1. Base::show() called
  2. Derived::show() called
A

Answer: 1
Like C++, when a function is static, runtime polymorphism doesn’t happen.

174
Q

Which of the following is FALSE about arrays in Java?

  1. A java array is always an object
  2. Length of array can be changed after creation of array
  3. Arrays in Java are always allocated on heap
A

Answer: 2
In Java, arrays are objects, they have members like length. The length member is final and cannot be changed. All objects are allocated on heap in Java, so arrays are also allocated on heap.

175
Q
Predict the output of following Java program
class T {
  int t = 20;
  T() {
    t = 40;
  }
}
class Main {
   public static void main(String args[]) {
      T t1 = new T();
      System.out.println(t1.t);
   }
}
  1. 20
  2. 40
  3. Compiler Error
A

Answer: 2
The values assigned inside constructor overwrite the values initialized with declaration.

176
Q

Which of the following is FALSE about abstract classes in Java
1. If we derive an abstract class and do not implement all the abstract methods, then the derived class should also be marked as abstract using ‘abstract’ keyword
2. Abstract classes can have constructors
3. A class can be made abstract without any abstract method
4. A class can inherit from multiple abstract classes

A

Answer: 4
While it’s true that you cannot directly instantiate an abstract class in Java using the new keyword, an abstract class can still have a constructor for several reasons:

  1. Initialization: Abstract classes often have fields that need to be initialized when an instance of a concrete subclass is created. The constructor in the abstract class can handle this initialization logic.
  2. Code Reusability: An abstract class can contain common functionality that is shared among its subclasses. By providing a constructor in the abstract class, you can centralize common initialization code, reducing redundancy in the code of concrete subclasses.
  3. Forcing Initialization: The constructor in an abstract class can enforce certain fields to be initialized, either directly or through method calls. This helps ensure that subclasses adhere to a specific initialization protocol.
177
Q

Which of the following is true about inheritance in Java.
1) In Java all classes inherit from the Object class directly or indirectly. The Object class is root of all classes.
2) Multiple inheritance is not allowed in Java.
3) Unlike C++, there is nothing like type of inheritance in Java where we can specify whether the inheritance is protected, public or private.

a. 1, 2 and 3
b. 1 and 2
c. 2 and 3
d. 1 and 3

A

Answer: a

178
Q
class Test {
public static void swap(Integer i, Integer j) {
      Integer temp = new Integer(i);
      i = j;
      j = temp;
   }
   public static void main(String[] args) {
      Integer i = new Integer(10);
      Integer j = new Integer(20);
      swap(i, j);
      System.out.println("i = " + i + ", j = " + j);
   }
}
  1. i = 10, j = 20
  2. i = 20, j = 10
  3. i = 10, j = 10
  4. i = 20, j = 20
A

Answer: 1
Parameters are passed by value in Java. Hence, swap() method just swapped the values in seperate copies and not the original objects, since references are not passed in java.

179
Q

Output of following Java program

class Main {
 public static void main(String args[]){
   final int i;
   i = 20;
   System.out.println(i);
 }
}
  1. 20
  2. Compiler Error
  3. 0
  4. Garbage value
A

There is no error in the program. final variables can be assigned value only once. In the above program, i is assigned a value as 20, so 20 is printed.

180
Q
class Base {
  public final void show() {
       System.out.println("Base::show() called");
    }
}
class Derived extends Base {
    public void show() {  
       System.out.println("Derived::show() called");
    }
}
public class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
  1. Derived::show() called
  2. Base::show() called
  3. Compiler Error
  4. Exception
A

Answer: 3
./Main.java:7: error: show() in Derived cannot override show() in Base
public void show() {
^
overridden method is final
1 error

181
Q

Which of the following is/are true about constructors in Java?

1) Constructor name should be same as class name.
2) If you don’t define a constructor for a class,
a default parameterless constructor is automatically
created by the compiler.
3) The default constructor calls super() and initializes all
instance variables to default value like 0, null.
4) If we want to parent class constructor, it must be called in
first line of constructor.

a. 1
b. 1, 2
c. 1, 2 and 3
d. 1, 2, 3 and 4

A

Answer: d

182
Q

Output of following Java program

class Point {
  int m_x, m_y;
   
  public Point(int x, int y) { m_x = x; m_y = y; }
  public Point() { this(10, 10); }
  public int getX() { return m_x; }
  public int getY() { return m_y; }
   
  public static void main(String args[]) {
    Point p = new Point();
    System.out.println(p.getX());
  }
} 

a. 10
b. 0
c. compiler error

A

Answer: a

183
Q
final class Complex {
    private  double re,  im;
    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }
    Complex(Complex c)
    {
      System.out.println("Copy constructor called");
      re = c.re;
      im = c.im;
    }            
    public String toString() {
        return "(" + re + " + " + im + "i)";
    }            
}
class Main {
    public static void main(String[] args) {
        Complex c1 = new Complex(10, 15);
        Complex c2 = new Complex(c1);    
        Complex c3 = c1;  
        System.out.println(c2);
    }
}
  1. Copy constructor called
    (10.0 + 15.0i)
  2. Copy constructor called
    (0.0 + 0.0i)
  3. (10.0 + 15.0i)
  4. (0.0 + 0.0i)
A

Answer: 1

184
Q

Which of the following is/are true about packages in Java?
1) Every class is part of some package.
2) All classes in a file are part of the same package.
3) If no package is specified, the classes in the file
go into a special unnamed package
4) If no package is specified, a new package is created with
folder name of class and the class is put in this package.
a. Only 1, 2 and 3
b. Only 1, 2 and 4
c. Only 4
d. Only 1 and 3

A

Answer: 1
In Java, a package can be considered as equivalent to C++ language’s namespace.

185
Q
class Test
{
    public static void main (String[] args) 
    {
        int arr1[] = {1, 2, 3};
        int arr2[] = {1, 2, 3};
        if (arr1.equals(arr2))
            System.out.println("Same");
        else
            System.out.println("Not same");
    }
}
A

Not same

186
Q

Predict the output of following Java program

class Main {
   public static void main(String args[]) {
      try {
         throw 10;
      }
      catch(int e) {
         System.out.println("Got the  Exception " + e);
      }
  }
}
  1. Got the Exception 10
  2. Got the Exception 0
  3. Compiler Error
A

In Java only throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown as exception. So basic data type can no be thrown at all. Following are errors in the above program
Main.java:4: error: incompatible types
throw 10;
^
required: Throwable
found: int
Main.java:6: error: unexpected type
catch(int e) {
^
required: class
found: int
2 errors

187
Q
class Base extends Exception {}
class Derived extends Base  {}
 
public class Main {
  public static void main(String args[]) {
   // some other stuff
   try {
       // Some monitored code
       throw new Derived();
    }
    catch(Base b)     { 
       System.out.println("Caught base class exception"); 
    }
    catch(Derived d)  { 
       System.out.println("Caught derived class exception"); 
    }
  }
} 
  1. Caught base class exception
  2. Caught derived class exception
  3. Compiler Error because derived is not throwable
  4. Compiler Error because base class exception is caught before derived class
A

Answer: 4
Main.java:12: error: exception Derived has already been caught
catch(Derived d) { System.out.println(“Caught derived class exception”); }

188
Q

Predict the output of the following program.

abstract class demo
{
    public int a;
    demo()
    {
        a = 10;
    }
 
    abstract public void set();
     
    abstract final public void get();
 
}
 
class Test extends demo
{
 
    public void set(int a)
    {
        this.a = a;
    }
 
    final public void get()
    {
        System.out.println("a = " + a);
    }
 
    public static void main(String[] args)
    {
        Test obj = new Test();
        obj.set(20);
        obj.get();
    }
}
  1. a = 10
  2. a = 20
  3. Compilation error
A

Answer: 3
Final method can’t be overridden. Thus, an abstract function can’t be final.

189
Q
A