CORE Flashcards

1
Q

In Java, does the finally block get executed if we insert a return statement
inside the try block of a try-catch-finally?

A

Yes, it will get executed.
Note that there are some cases in which the finally block will not get executed, such as the following:
- If the virtual machine exits during try/ catch block execution.
- If the thread which is executing during the try/ catch block gets killed.

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

What is the difference between final, finally, and finalize?

A

To speak in very general terms, final is used to control whether a variable, method, or class is “changeable:’ The finally keyword is used in a try/ catch block to ensure that a segment of code is always
executed. The finalize() method is called by the garbage collector once it determines that no more
references exist.

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

Explain the differences between TreeMap, HashMap, and
LinkedHashMap. Provide an example of when each one would be best.

A

All offer a key->value map and a way to iterate through the keys. The most important distinction between
these classes is the time guarantees and the ordering of the keys.
- HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the
keys is essentially arbitrary. It is implemented by an array of linked lists.
• TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through
the keys in sorted order, you can. This means that keys must implement the Comparable interface.
TreeMap is implemented by a Red-Black Tree.

-LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is
implemented by doubly-linked buckets.

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

What structure would you use in following scenario: Suppose you were creating a mapping of names to Person objects. You might want to periodically
output the people in alphabetical order by name.

A

TreeMap

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

What structure would you use in the following scenario: you need the ordering of keys to match the ordering of insertion. This might be useful in a caching situation, when you want to delete the oldest item.

A

LinkedHashMap

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

What structure would you use in the following scenario: you need to get key,value pairs data in alphabetical order

A

TreeMap

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

Explain what object reflection is in Java and why it is useful.

A

Object Reflection is a feature in Java that provides a way to get reflective information about Java classes and
objects, and perform operations such as:
[1] Getting information about the methods and fields present inside the class at runtime.
[2] Creating a new instance of a class.
[3] Getting and setting the object fields directly by getting field reference, regardless of what the access
modifier is.

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

Is java pass by value or by reference?

https://www.baeldung.com/java-pass-by-value-or-pass-by-reference

A

The fundamental concepts in any programming language are “values” and “references”. In Java, Primitive variables store the actual values, whereas Non-Primitives store the reference variables which point to the addresses of the objects they’re referring to.

Both values and references are stored in the stack memory.In case of primitives, the value is simply copied inside stack memory which is then passed to the callee method; in case of non-primitives, a reference in stack memory points to the actual data which resides in the heap. When we pass an object, the reference in stack memory is copied and the new reference is passed to the method.

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

Describe what happen when Passing Primitive Types to methods?

https://www.baeldung.com/java-pass-by-value-or-pass-by-reference

A

The Java Programming Language features eight primitive data types. Primitive variables are directly stored in stack memory. Whenever any variable of primitive data type is passed as an argument, the actual parameters are copied to formal arguments and these formal arguments accumulate their own space in stack memory.

The lifespan of these formal parameters lasts only as long as that method is running, and upon returning, these formal arguments are cleared away from the stack and are discarded.

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

Describe what happen when passing Object references to method?

https://www.baeldung.com/java-pass-by-value-or-pass-by-reference

A

In Java, all objects are dynamically stored in Heap space under the hood. These objects are referred from references called reference variables.

A Java object, in contrast to Primitives, is stored in two stages. The reference variables are stored in stack memory and the object that they’re referring to, are stored in a Heap memory.

Whenever an object is passed as an argument, an exact copy of the reference variable is created which points to the same location of the object in heap memory as the original reference variable.

As a result of this, whenever we make any change in the same object in the method, that change is reflected in the original object. However, if we allocate a new object to the passed reference variable, then it won’t be reflected in the original object.

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

What could happen when parameters would be pass by reference?

https://www.baeldung.com/java-pass-by-value-or-pass-by-reference

A

When a parameter is pass-by-reference, the caller and the callee operate on the same object.

It means that when a variable is pass-by-reference, the unique identifier of the object is sent to the method. Any changes to the parameter’s instance members will result in that change being made to the original value.

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

What happens exactly in below code:
baeldung.com/java-pass-by-value-or-pass-by-reference

public class PrimitivesUnitTest {

@Test
public void whenModifyingPrimitives_thenOriginalValuesNotModified() {
    
    int x = 1;
    int y = 2;
   
    // Before Modification
    assertEquals(x, 1);
    assertEquals(y, 2);
    
    modify(x, y);
    
    // After Modification
    assertEquals(x, 1);
    assertEquals(y, 2);
}

public static void modify(int x1, int y1) {
    x1 = 5;
    y1 = 10;
} }
A

Let’s try to understand the assertions in the above program by analyzing how these values are stored in memory:

The variables “x” and “y” in the main method are primitive types and their values are directly stored in the stack memory
When we call method modify(), an exact copy for each of these variables is created and stored at a different location in the stack memory
Any modification to these copies affects only them and leaves the original variables unaltered

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

What heppen in this piece of code:
baeldung.com/java-pass-by-value-or-pass-by-reference

public class NonPrimitivesUnitTest {

@Test
public void whenModifyingObjects_thenOriginalObjectChanged() {
    Foo a = new Foo(1);
    Foo b = new Foo(1);

    // Before Modification
    assertEquals(a.num, 1);
    assertEquals(b.num, 1);
    
    modify(a, b);
    
    // After Modification
    assertEquals(a.num, 2);
    assertEquals(b.num, 1);
}
 
public static void modify(Foo a1, Foo b1) {
    a1.num++;
   
    b1 = new Foo(1);
    b1.num++;
} }

class Foo {
public int num;

public Foo(int num) {
    this.num = num;
} }
A

a) Let’s analyze the assertions in the above program. We have passed objects a and b in modify() method that has the same value 1. Initially, these object references are pointing to two distinct object locations in a heap space

b) When these references a and b are passed in the modify() method, it creates mirror copies of those references a1 and b1 which point to the same old objects

c) In the modify() method, when we modify reference a1, it changes the original object. However, for a reference b1, we have assigned a new object. So it’s now pointing to a new object in heap memory.

Any change made to b1 will not reflect anything in the original object:

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

What happen in below code:
educative.io/courses/java-interview-handbook/NEX9nXBGzBp

public class SuperList {

// Constructor
public SuperList(int n) { 1.       List superList; 2.       allocate(superList, n);
}

// Method that does initialization
void allocate(List list, int n) { 3.       list = new ArrayList<>(n);
} }
A

When the program control returns to line 2, superList is still null because it was never passed in and assigned the ArrayList object.

In Java, we are copying the reference or the address the reference data type variable holds and passing it, and not the actual variable.

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

What value will be printed from the following snippet?
educative.io/courses/java-interview-handbook/NEX9nXBGzBp

    String[] students = new String[10];
    String studentName = "You are an awesome developer";
    students[0] = studentName;
    studentName = null;
    System.out.println(students[0]);
A

You are an awesome developer

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

How does method overloading match work in Java?
https://www.educative.io/courses/java-interview-handbook/xlxWYp8YvyJ

A

Question # 2
How does method overloading match work in Java?

Methods of a class can be overloaded in Java by:

Changing the number of parameters

Changing the type of the parameters passed into the methods

Note that methods can’t be overloaded by changing the return types of the methods, as it may cause ambiguity. While overloading has nothing to do with polymorphism, Java programmers also refer to method overloading as Compile Time Polymorphism because the method that is going to get called will be decided at compile time.

The compiler uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable. There may be more than one such method, in which case the most specific one is chosen. Typically, varargs methods are the last chosen, if they compete with other candidate methods because they are considered less specific than the ones receiving the same parameter type.

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

Can the main method be overloaded?

https://www.educative.io/courses/java-interview-handbook/xlxWYp8YvyJ

A

Yes, the static main method can be overloaded. But only public static void main(String[] args) will be used when your class is launched by the JVM even if you specify one or two command-line arguments. However, programmatically one can invoke the overloaded versions of the main method.

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

Consider the following overloaded methods and determine which method will be invoked for the call myOverloadedMethod(5)?
https://www.educative.io/courses/java-interview-handbook/xlxWYp8YvyJ

void myOverloadedMethod(long arg) {
    System.out.println("Method with long invoked");
}

void myOverloadedMethod(int arg) {
    System.out.println("Method with int invoked");
}
A

Method with int invoked

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

List the access modifiers in Java?
https://www.educative.io/courses/java-interview-handbook/RMjBvpKEmOz

A

There are four accessibility levels in Java. They are listed below in order of increasing restrictiveness:

public
package private
protected
private

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

Explain the protected access modifier?
https://www.educative.io/courses/java-interview-handbook/RMjBvpKEmOz

A

The protected modifier specifies that a member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another or the same package.

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

Explain the private modifier?
https://www.educative.io/courses/java-interview-handbook/RMjBvpKEmOz

A

The private modifier specifies that the member can only be accessed in its own class. Note that top level classes can’t be marked private or protected but nested ones can be.

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

What is the Object class?

A

The Object class is the superclass directly or indirectly of every other class in Java. The Object class itself doesn’t have any superclass. In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Implicit Object Superclass
// Class is implicity a derived class
// of the Object class
public class ObjectSubclass {

}

(new ObjectSubclass()) instanceof Object // Prints true

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

What are the methods defined in the Object class?

A

The methods defined in the Object class include:

clone()
equals()
hashCode()
finalize()
getClass()
toString()

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

What is the output of the below snippet?

String obj1 = new String("abc");
String obj2 = new String("abc");
System.out.println(obj1 == obj2);
A

ANSWER: false

The equals() method provided in the Object class uses the identity operator == to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal — that is, if the object references are pointing to the same address in memory. This is the reason the statement new Integer(5) == new Integer(5) will output false because the two integer objects have different memory addresses even though their values are the same.

The case of String class is a little tricky. Compiler optimization can cause string literals to point to a single string object if the same literal is repeated many times in the code. Therefore, a snippet like below can result in true or false depending on how the program is compiled.

String myStr = “abc”;
System.out.println(myStr == “abc”);
Always use the equals() method when comparing strings!

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

What is wrong with the BadCloneExample class shown below?

public class BadCloneExample {

List seen = new ArrayList<>();
int current = -1;

public void add(int newCurrent) {
    seen.add(current);
    current = newCurrent;
}

public void clearHistory() {
    seen.clear();
}

public BadCloneExample clone() {
    BadCloneExample clone = new BadCloneExample();
    clone.current = current;
    clone.seen = seen;
    return clone;
} }
A

The Object class’s clone() method can be overridden by classes in Java. However, the most common mistake is to copy reference variables. In the given code snippet, the clone method copies the reference to the list field seen. This makes two objects point to the same list field. Look at the snippet below:

 BadCloneExample bce = new BadCloneExample();
 bce.add(5);
 bce.add(6);
 BadCloneExample prev = bce.clone();
 // will print [-1, 5]
 System.out.println(prev.seen);
 // clears out the list field
 bce.clearHistory();
 // user sees [] but expects [-1,5]
 System.out.println(prev.seen); The two objects point to the same field and operations by the original object cascade to the clone.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Answer the question based on the following snippet:

public class Employees {

List list = new ArrayList<>();

public Employees() {

}

public void add(String name) {
    list.add(new Person(name));
}

public Employees clone() {
    Employees clone = new Employees();
    for (Person person : list) {
        clone.list.add(person);
    }
    return clone;
} }

class Person {

String name;

public Person(String name) {
    this.name = name;
} }

What will be the output of the following snippet?

    Employees apple = new Employees();
    apple.add("Tim Cook");
    Employees microsoft = apple.clone();
    microsoft.list.get(0).name = "Satya Nadella";

    System.out.println(apple.list.get(0).name);
A

ANSWER: )
Satya Nadella

The purpose of the above question is to drive home the fact that correct implementation of the clone method, requires appropriately copying nested reference variables.

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

Answer the question based on the following setup:

public class Celebrity {

String name;
int age;

public Celebrity(String name, int age) {
    this.name = name;
    this.age = age;
}

public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof Celebrity) || obj == null)
        return false;

    Celebrity otherCeleb = (Celebrity) obj;
    return name.equals(otherCeleb.name);
} }

What will be the output of the below snippet:

    Celebrity realKardashian = new Celebrity("Kim", 17);
    Celebrity kardashianClone = new Celebrity("Kim", 17);
    System.out.println(realKardashian.equals(kardashianClone));
A

ANSWER:

The above questions explain why one needs to override the hashCode() method whenever we override the equals() method for a class. The vice-versa is not necessary that is if you override the hashCode method it is not a must to override the equals method. Let’s try to understand why that is so. Whenever, we use a hash-based collection, it uses:

hashCode() method to find the right bucket

equals() method to match the object we are looking for

In the example snippet in the quiz above, the two celebrity objects are equal but when we search for the second object in the hash set we are unable to find it because it has a different hashcode than the first celebrity object that has been added to the set. The value returned by hashCode() is the object’s hash code, which is the object’s memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object’s implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

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

What will be the output of the programme:

import java.util.HashSet;

class Demonstration {

@SuppressWarnings("unchecked")  
public static void main( String args[] ) {
    
    HashSet set = new HashSet();
    Celebrity realKardashian = new Celebrity("Kim", 17);
    Celebrity kardashianClone = new Celebrity("Kim", 17);
    set.add(realKardashian);

    if (set.contains(kardashianClone)) {
        System.out.println("Kim is a celebrity");
    } else {
        System.out.println("Can't find Kim");
    }

    System.out.println(realKardashian.equals(kardashianClone)); 
    System.out.println(realKardashian.hashCode() + " " +kardashianClone.hashCode());      
} }

class Celebrity {

String name;
int age;

public Celebrity(String name, int age) {
    this.name = name;
    this.age = age;
}

public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof Celebrity) || obj == null)
        return false;

    Celebrity otherCeleb = (Celebrity) obj;
    return name.equals(otherCeleb.name);
} }
A

ANSWER: Can’t find Kim
true
685325104 460141958

The above questions explain why one needs to override the hashCode() method whenever we override the equals() method for a class. The vice-versa is not necessary that is if you override the hashCode method it is not a must to override the equals method. Let’s try to understand why that is so. Whenever, we use a hash-based collection, it uses:

hashCode() method to find the right bucket

equals() method to match the object we are looking for

In the example snippet in the quiz above, the two celebrity objects are equal but when we search for the second object in the hash set we are unable to find it because it has a different hashcode than the first celebrity object that has been added to the set. The value returned by hashCode() is the object’s hash code, which is the object’s memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object’s implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

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

Explain the finalize() method in the Object class?

A

The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage. Object’s implementation of finalize() does nothing — you can override finalize() to do cleanup, such as freeing up resources.

The finalize() method may be called automatically by the system, but when it is called, or even if it is called, is uncertain. Therefore, you should not rely on this method to do your cleanup for you. For example, if you don’t close file descriptors in your code after performing I/O and you expect finalize() to close them for you, you may run out of file descriptors.

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

Consider the snippet below:

void myMethod(Object input) {
    // Your awesome code here    
}

myMethod("123")
myMethod(new Integer(5)) Is there a way your method can find out if the object passed in is an integer or a string?
A

Yes, the getClass() method returns a Class object, which has methods you can use to get information about the class, such as its name getSimpleName(), its superclass getSuperclass(), and the interfaces it implements getInterfaces(). The getClass() method is final and can’t be overridden.

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

What will be the output of the following snippet of code? Can you explain the result?

Integer.valueOf(1).equals(Long.valueOf(1))

A

The output will be false. Even though the values are the same, i.e. one, but the objects are of different types. One is of type Integer and other is of type Long.

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

What will be printed on the console, if we create an object of the following class and invoke it’s print method?

public class SpecialPerson {

String fullName = init();
String name = "batman";

public SpecialPerson() {
    name = "superMan";
}

private String init() {
    return name;
}

public void print() {
    System.out.println(fullName);
} }
A

ANSWER: NULL

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

Can a class have a static constructor to initialize static fields?

A

ANSWER: NO

There’s no such thing as a static constructor in java. A constructor only exists in the context of creating a new instance or object of a class. Static fields of a class can be initialized in the static block.

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

Can we change the contents of a final array as in the code snippet below?

final int[] array = new int[5];
array[0] = 1;
A

It may appear counterintuitive, but we can actually change the contents of the array even though it is marked as final. The array variable points to a particular start location in the memory where the contents of the array are placed. The location or the memory address can’t be changed.

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

What are static initialization blocks?

A

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. It can be used to initialize static fields of a class. A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

Static Initialization Block Example
public class EducativeCourse {

static String courseName;
static String version;

// We have two static initialization blocks
static {
    version = "1.0";
}

static {
    courseName = "Java Interview Bible";
} } The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Can initialization block also be used to initialize instance fields?

A

Yes,

initialization blocks
final methods
can be used to initialize instance fields. Both of them are alternatives to using a constructor.
Initialization Using Final Method and Initialization Block
public class EducativeCourse {

String courseName = setCourseName();

String version;

// initialization block
{
    version = "1.0";
}

// final method used for intialization
private String setCourseName() {
    return "Java Interview Bible";
} } Note that we could have marked the setCourseName as non-final and not have a compile error. However, non-final methods used during initialization can cause problems as the object may not be fully constructed. Using a method for initialization may be useful if subclasses want to reuse the initialization method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Explain the concept of class in Java?

A

A class in object orientated languages is the fundamental building block of any program. It can be thought of as a blueprint and its instance objects as manifestations of that blueprint. A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Except for primitive types (int, double, float, char etc), all objects (String, Lists, Runnable, etc) in Java are instances of a class.

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

What is the root class in Java?

or

What class is the superclass of all classes in Java?

A

The java.lang.Object class is the super class of all classes in Java. All classes implicitly extend the object class. All objects including arrays are instances of the Object class.

38
Q

What are nested classes?

A

Java allows defining a class within another class. A nested class is a member of its enclosing class. Nested classes can be either static or non-static.

Static Nested Class
Non-Static Nested Class or Inner Class. The following classes are also considered inner classes.
Local Class
Anonymous Class
The below code snippet shows an outer class declaring a static and a non-static nested class.

Static and Non-static Nested Classes
public class OuterClass {

String myName = "outerclass";
private static String staticName = "outerclass";

private class InnerClass {

    String myName = "innerClass";

    void printNames() {
        System.out.println(
                "I can access both static & non-static members of my outer class : " + staticName + " " + myName);
    }
}

void createInnerClassInstance() {
    // Creating inner class instance
    InnerClass ic = new InnerClass();
    ic.printNames();
}

static class StaticInnerClass {

    String myName = "staticInnerClass";

    void printName() {
        System.out.println("I can access static members of my outerclass but not non-static ones: " + staticName);
    }
} } The above snippet can be executed in the code widget below.
39
Q

What are non-static nested classes or inner classes?

A

Non-static nested classes are called inner classes.

example
public class OuterClass {

String myName = "outerclass";

private class innerClass {

    String myName = "innerClass";

    void printNames() {
        System.out.println("I am the inner class");
    }
} } The following two types of classes are also referred to as inner classes.

Local Classes
Anonymous Classes
Note, that inner classes can access instance fields declared in the enclosing class. However, nested static classes can’t access instance fields of the enclosing class.

Serialization of inner classes including local and anonymous classes is discouraged for compatibility issues across different JRE implementations.

40
Q

What are static nested classes?

A

A class defined within an outer class and marked static is called a static nested or static inner class. A static nested class is behaviorally similar to a top-level class that has been nested in another top-level class for packaging convenience.

41
Q

Can nested classes be declared private?

A

Yes. A top-level class can only be marked public or package private. But a nested class can be declared private, public, protected, or package private.

42
Q

What are some of the use-cases of nested classes?

A

The primary purpose of nested classes is logically grouping related classes in one place and improving encapsulation.

Say, you write a class to hold all the employees of a company. It may make sense to nest an employee iterator class as it iterates only on the objects of the employee class.

43
Q

What would be the output of the method sayName in the code below?

class Demonstration {
public static void main( String args[] ) {
OuterClass oc = new OuterClass();
oc.sayName();
}
}

class OuterClass {

String myName = "outerClass";

private class InnerClass {

    String myName = "innerClass";

    void printName() {
        System.out.println("I am " + myName);
    }
}

void sayName() {
    InnerClass ic = new InnerClass();
    ic.printName();
    System.out.println("I am " + myName);
} }
A

A)
I am innerClass
I am outerClass

The InnerClass declares a variable by the same name as the OuterClass. The InnerClass’s field myName will shadow the OuterClass’s field myName and will be printed instead.

44
Q

Can a top-level class in Java be declared static?

A

no, Only nested classes can be marked as static.

45
Q

What is a class?

A

A class in object orientated languages is the fundamental building block of any program. It can be thought of as a blueprint and its instance objects as manifestations of that blueprint. A class, in the context of Java, are templates that are used to create objects, and to define object data types and methods. Except for primitive types (int, double, float, char etc), all objects (String, Lists, Runnable, etc) in Java are instances of a class.

46
Q

https://www.educative.io/courses/java-interview-handbook/qVAox7lExGp

[1] What are nested classes?
[2] When to use nested classes?
[3] What are static nested classes?
[4] What is the difference between static and non-static nested classes?
[5] Can nested classes be declared private?
[6] Can a top-level class in Java be declared static?

A

[1] Java allows defining a class within another class. A nested class is a member of its enclosing class. Nested classes can be either static or non-static.

a) Static Nested Class
b) Non-Static Nested Class or Inner Class. The following classes are also
considered inner classes:
- Local Class
- Anonymous Class

[2] Nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code.

[3] A class defined within an outer class and marked static is called a static nested or static inner class. A static nested class is behaviorally similar to a top-level class that has been nested in another top-level class for packaging convenience.

[4] Note, that inner classes can access instance fields declared in the enclosing class. However, nested static classes can’t access instance fields of the enclosing class.

[5] Yes. A top-level class can only be marked public or package private. But a nested class can be declared private, public, protected, or package private.

[6] No

47
Q

[1] What are the local classess?

A

[1] A class that is defined in a block is called a local class. A block is a group of zero or more statements between balanced braces. Usually, local classes are defined inside a method, though they can also be defined inside a for loop or even an if statement. Local classes do have access to members of their enclosing class. They can also access local variables, but they need to be declared final.

When local classes use variables in the scope of the outer class, they are said to have captured the variable.

EXAMPLE
class LocalClassExample {
public void someMethod() {

    String name = "mainClass";

    // Declare our local class
    class LocalClass {
        String myName = "superFineLocalClass";

        public LocalClass(String name) {
            this.myName = name;
        }

        public void print() {
            System.out.println("My name is " + myName + " and I am enclosed by " + name);
        }
    }


    LocalClass lc1 = new LocalClass("test");
    LocalClass lc2 = new LocalClass("rest");

    lc1.print();
    lc2.print();      

  } }
48
Q

[1] What is an anonymous class and when to use it?

A

An anonymous class is an inner class that does not have a name. It should be used in place of a local class when the intended use is only one time.

49
Q

[1] What is an abstract class?
[2] Can an abstract class be declared final?
[3] Since abstract classes can’t be instantiated, can they have a constructor?

A

[1] An abstract class can’t be instantiated, but it can be subclassed. An abstract class usually contains abstract and non-abstract methods that subclasses are forced to provide an implementation for. An abstract method is a method that is declared without an implementation. Any method marked abstract will force subclasses to provide an implementation for. Non-abstract methods will also have a method body that serves as the default implementation. Subclasses may choose to override the default implementation with their own. If a class includes abstract methods, then the class itself must be declared abstract.

Abstract classes may also implement an interface but will not be required to provide an implementation for interface methods since it can’t be instantiated. Below is an example Person class.

[2] No
[3] Yes

50
Q

[1] What is a final class?

A

A class marked final can’t be extended or inherited from. The String class is one such example. You may want to make a class final if it is not designed for inheritance or you want to forbid any changes by subclassing.

51
Q

[1] What is a super keyword?

A
  • If a method overrides one of its superclass’s methods, the overridden can be invoked through the use of the keyword super.
  • The super keyword can also be used to refer to a hidden field of the super type.
  • Interface default methods can be invoked using the super keyword.
  • Constructors for superclasses can be invoked using the super keyword.
52
Q

Explain the finalize method?

educative.io/courses/java-interview-handbook/g7gq6LMB2xZ

A

The finalize() method is a protected and non-static method of the java.lang.Object class and is also sometimes called the finalizer. The finalize() method is invoked by the JVM when an object is garbage collected. A user can override the finalize() in his class to dispose of system resources or to perform cleanup tasks.

53
Q

Why should finalize not be used?

educative.io/courses/java-interview-handbook/g7gq6LMB2xZ

A

There are several reasons to not override the finalize() method which are listed below:

a) It is not possible to predict when the garbage collector will invoke the finalize() method or if the garbage collector will even run before your Java program exits. Therefore, if you have any resource cleanup code in the finalize() method, it may not be invoked at all or in time to free-up resources and may cause a program crash.

b) Using finalize() may affect portability of a program as garbage collection algorithms are JVM implementation dependent and the same program may perform well on one system and not as well on another.

c) Performance may be negatively impacted when using finalizers as JVM executes more number of operations when constructing and destroying objects with non-empty finalizers.

d) If a finalizer throws an exception, the finalization process is canceled, and the exception is ignored, leaving the object in a corrupted state without any notification.

54
Q

What is the difference between an interface and an abstract class in Java?

A

Following are the main differences between an abstract class and an interface

An abstract class can have final, static, or class member variables whereas an interface can only have variables that are final and static by default.

An abstract class can have static, abstract, or non-abstract methods. An interface can have static, abstract, or default methods.

Members of an abstract class can have varying visibility of private, protected, or public. Whereas, in an interface all methods and constants are public.

A child class can define abstract methods with the same or less restrictive accessibility, whereas a class implementing an interface must define the interface methods with the exact same accessibility which is public.

When inheriting an abstract class, a concrete child class must define the abstract methods. An abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.

In contrast, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.

A class can only extend another class, but it can implement multiple interfaces. Similarly, an interface can extend multiple interfaces. An interface never implements a class or an interface.

55
Q

When should we use an abstract class and when should be use an interface?

A

An abstract class holds shared state or functionality and its purpose is to avoid code duplication amongst its descendant classes. It provides structure to code by abstracting an entity or concept in the application domain. Use an abstract class when subclasses share state or use common functionality. Or you require to declare non-static, non-final fields or need access modifiers other than public.

On the contrary, an interface is only a promise to provide state or functionality and doesn’t have any state to be shared amongst its implementors. Use an interface if you expect unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes. Interfaces are also used in instances where multiple inheritance of type is desired. Lastly, use an interface if you want to specify the behavior of a certain type but aren’t concerned who implements the behavior.

An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses include HashMap, TreeMap, and ConcurrentHashMap which share many methods including get, put, isEmpty, containsKey, and containsValue that AbstractMap defines.

An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map. By reading this list of interfaces, one can infer that an instance of HashMap can be cloned, is serializable, and has the functionality of a map.

56
Q

What are default methods of an interface?

A

Imagine a situation where you want to add a new method to an existing interface, that is implemented by several classes. The addition of the new method will also cause you to update all the classes that implement the interface. This may not be practical or possible if your code is publicly shared. One possible mitigation in this situation is to add a default implementation for the method in the interface.

Another possibility in such a situation is to define a new interface that extends the interface in which a new method needs to be added. Any new classes can implement the new interface.

A class can implement an interface without needing to provide an implementation for default methods, though it can provide one if it wanted to.

SAMPLES:
public interface PersonActions {

// abstract method
void sayHello();

// default method
default void sayBye() {
    System.out.println("Say bye in english and override method for other languages.");
}

// static method
static void printTotalPossibleActions() {
    System.out.println("Total possible acitons = 2");
}

}

57
Q

What are marker interfaces?

A

Yes, above is perfectly compilable code. An interface may have no methods at all. Such an interface can be useful to refer to objects of a bunch of classes that are related and implement the empty interface. Such interfaces are also called marker interfaces. In other words, we use the interface as a type. In Java,

java.io.Serializable
java.lang.Cloneable
java.rmi.Remote
are examples of marker interfaces.

58
Q

What are functional interfaces in Java?

A

A functional interface is an interface that contains only one abstract method. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. For instance the Runnable interface used in multithreading has a single method run().

public interface Runnable {
void run();
}

59
Q

Can classes implementing an interface provide implementation for the static methods of an interface?

class Demonstration implements InterfaceWithStaticMethod{
public static void main( String args[] ) {
printName();
InterfaceWithStaticMethod.printName();
}

public static void printName() {
  System.out.println("Demonstration class");
} }

interface InterfaceWithStaticMethod {

static void printName() {
System.out.println(“Interface with InterfaceWithStaticMethod”);
}

}

A

NO

The statement is nonsensical. Static methods and variables are associated with the interface. They may be invoked in the code using interface reference like interaceName.someStaticMethod() but can’t be overridden like default or abstract methods of the interface.

60
Q

What is the difference between Comparable interface and Comparator interface?

https://www.educative.io/courses/java-interview-handbook/BnE91N3qxpx

A

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface to compare its instances.
Consider a Movie class that has members like, rating, name, year. Suppose we wish to sort a list of Movies based on year of release. We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface.

Now, suppose we want to sort movies by their rating and names as well. When we make a collection element comparable(by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Comparator.

Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.
Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects.
To compare movies by Rating, we need to do 3 things :

1) Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()).
2) Make an instance of the Comparator class.
3) Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator.

  • Comparable is meant for objects with natural ordering which means the object itself must know how it is to be ordered. For example Roll Numbers of students. Whereas, Comparator interface sorting is done through a separate class.
  • Logically, Comparable interface compares “this” reference with the object specified and Comparator in Java compares two different class objects provided.
  • If any class implements Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and objects will be sorted based on there natural order defined by CompareTo method.
  • A basic differentiating feature is that using comparable we can use only one comparison. Whereas, we can write more than one custom comparators as you want for a given type, all using different interpretations of what sorting means.
  • Like in the comparable example we could just sort by only one attribute, i.e., year but in the comparator, we were able to use different attributes like rating, name, and year as well.
61
Q

What is inheritance?

A

In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a superclass is called a subclass or a derived class.

62
Q

What are the benefits of inheritance?

A

The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write and debug them yourself. Furthermore, inheritance allows for improved code structuring thus increasing readability and maintainability.

In summary code reusability is the prime benefit of inheritance.

63
Q

What is polymorphism? Can you give an example?

educative.io/courses/java-interview-handbook/JYY8J2g1gGg

A

Poly means many and morph means shape or form. Polymorphism is thus, the ability in programming to present the same interface for differing underlying forms or data types. Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code. The beauty of polymorphism is that code working with different classes does not need to know which class it is using since they’re all used the same way. Polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

The classic textbook example of polymorphism is a Shape class. We derive Circle, Triangle, and Rectangle classes from the parent class Shape, which exposes an abstract method draw(). The derived classes provide their custom implementations for the draw() method. Now it is very easy to render the different types of shapes all contained within the same array by calling the draw() method on each object. This saves us from creating separate draw methods for each shape e.g. drawTriangle(), drawCircle() etc.

64
Q

Is multiple class inheritance supported in Java?

A

In multiple inheritance a derived class extends or inherits from two or more classes.

Java doesn’t support multiple class inheritance. A derived class can only extend a single super class.

65
Q

Is multiple interface inheritance supported in Java?

A

The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface. An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements.

Implementing an interface is not the same as extending a class. The implementing class doesn’t inherit any behavior from the interfaces, other than default methods and constants. Some developers would say implementing multiple interfaces one can simulate multiple inheritance, however, though that gets us closer to multiple inheritance it is still not true multiple inheritance as the implementing class will not inherit mutable state.

Thought of another way, interfaces allow multiple inheritance of types. Multiple inheritance allows one object to act like it belongs to several unrelated different classes at once.

66
Q

What is the diamond problem?

A

Java avoids the diamond problem by disallowing multiple inheritance. Consider the following classes
public abstract class Language {

public abstract void sayHello();

}

public class Punjabi extends Language {

String lang = "punjabi";

public void sayHello() {
    System.out.println("Kiddaan");
} }

public class Marathi extends Language {

String lang = "marathi";

public void sayHello() {
    System.out.println("Namaskaar");
} }

public class BiLingual extends Punjabi, Marathi {

public void greet() {
    super.sayHello();
}

}

When an instance of the class BiLingual is created and the method greet is invoked, which implementation of the sayHello method should be executed? In fact, the above code will not compile because Java doesn’t allow multiple inheritance, but if it did then this would an example of the inheritance diamond problem.

67
Q

Can the diamond problem occur if we use interfaces instead of classes?

https://www.java67.com/2017/08/default-methods-in-interface-multiple.html

A

Since Java 8 interfaces are allowed to have default methods, which may create the diamond setup. Note that in the case of classes, only a single class can be inherited from therefore the diamond setup can never happen. With interfaces, the setup does happen, but the resulting code isn’t compilable. Take a look at the following snippet where we replace classes with interfaces from the previous question.

public interface Language {

void sayHello();

}

public interface Punjabi extends Language {

String lang = "punjabi";

default void sayHello() {
    System.out.println("O Kiddaan");
}

}

public interface Marathi extends Language {

String lang = "Marathi";

default void sayHello() {
    System.out.println("Namaskaar");
}

}

public class MultiLingual implements Punjabi, Marathi {

// Must provide implementation for the sayHello
// method, otherwise the code will not compile
// even though both the interfaces provide for 
// default implementations
public void sayHello() {
    System.out.println("I forgot how to say hello in both " + Marathi.lang  + " & " + Punjabi.lang);
} }

The above code will only compile if we provide the definition for the sayHello method in the MultiLingual class.

Note that both the interfaces define a variable constant lang. We can easily invoke the one we intend by providing the fully qualified name to disambiguate between the two constants with the same name.

class Demonstration {
public static void main( String args[] ) {
(new MultiLingual()).sayHello();
}
}

interface Language {

void sayHello();

}

interface Punjabi extends Language {

String lang = "punjabi";

default void sayHello() {
    System.out.println("O Kiddaan");
}

}

interface Marathi extends Language {

String lang = "Marathi";

default void sayHello() {
    System.out.println("Namaskaar");
}

}

class MultiLingual implements Punjabi, Marathi {

// Must provide implementation for the sayHello
// method, otherwise the code will not compile
// even though both the interfaces provide 
// default implementations
// UNCOMMENT THE BELOW METHOD FOR SUCCESSFUL COMPILATION
/*public void sayHello() {
    System.out.println("I forgot how to say hello in both " + Marathi.lang  + " & " + Punjabi.lang);
}*/ }
68
Q

We have similar code to the previous questions but now we are implementing multiple interfaces and extending a class too with an implementation for the sayHello method. Do you think the code will compile?
public interface Marathi {

String lang = "marathi";

default void sayHello() {
    System.out.println("Namaskaar");
}

}

public interface Punjabi {

String lang = "punjabi";

default void sayHello() {
    System.out.println("O Kiddaan");
}

}

public class Kashmiri {

String lang = "kashmiri";

public void sayHello() {
    System.out.println("aadaab");
} }

public class Trilingual extends Kashmiri implements Punjabi, Marathi {

public void converse() {
    // invokes Kashmiri class's sayHello method
    sayHello();

    // invokes default implementation of the Punjabi interface
    Punjabi.super.sayHello();

    // invokes default implementation of the Marathi interface
    Marathi.super.sayHello();
} }
A

Yes, the code compiles and runs because to the compiler there’s no ambiguity. The Kashmiri class’s implementation of the sayHello method gets preference over the default implementations of the two interfaces for the sayHello method. Note that we have dropped the uber interface Language as in Java most cases are not a diamond but a V problem.

The bottom line is the compiler shouldn’t confront any ambiguity with the way the developer sets-up the inheritance hierarchy.

69
Q

Will the below code compile?
public interface Language {

default void sayHello() {
    System.out.println("01101000 01100101 01101100 01101100 01101111 ");
} }

public interface Marathi extends Language{}

public interface Punjabi extends Language {}

public class BiLingual implements Punjabi, Marathi {void converse() {sayHello();}}

A

YES

The above code will compile and invoke the default implementation of the sayHello method in the Language interface.

70
Q

Consider the setup below:

public class Language {

static String lang = "base language";

static protected void printLanguage() {
    System.out.println(lang);
}

protected Language sayHello() {
    System.out.println("----");
    return this;
} }

public class Spanish extends Language {

static String lang = "Spanish";

static protected void printLanguage() {
    System.out.println(lang);
}

protected Language sayHello() {
    System.out.println("Ola!");
    return this;
} }
A

The sayHello method in the Spanish class overrides the method from the base class Language

71
Q

Consider the class setup below:
public interface Vehicle {

default void whatAmI() {
    System.out.println("I am a vehicle");
} } public interface SevenSeater extends Vehicle {}

public interface SUV extends Vehicle {

default void whatAmI() {
    System.out.println("I am a SUV");
} }

public class TeslaModelX implements SUV, SevenSeater {

public void identifyMyself() {
    whatAmI();
} }
A

I am a SUV

Even though Seven Seater interface inherits the default method from the vehicle interface but is ignored in favor of the overridden method in the SUV interface.

72
Q

What are Lambda expressions?

A

Lambda expressions allow us to pass code as data or functionality as a method argument. They increase the expressiveness of Java language making code more readable and concise. Lambda expressions can be used to replace writing anonymous classes, when the class implements a functional interface. A functional interface has only a single abstract method and may have default or static methods. Let’s see an example below.

WITH ANONYMOUS CLASS

// A functional interface
interface DoStuff {
void work();
}

public static void main( String args[] ) {
  
  DoStuff ds = new DoStuff() {
    public void work() {
      System.out.println("I ran via anonymous class");
    }
  };
  ds.work();
}

Using lambda expression, we can write the above in a much nicer and concise way as following
// A functional interface
interface DoStuff {
void work();
}

public static void main( String args[] ) {
  
  DoStuff ds1 = ()-> System.out.println("I ran via lambda expression");
  ds.work();
}

class Demonstration {
public static void main( String args[] ) {

  DoStuff ds1 = ()-> System.out.println("I ran via lambda expression");
  DoStuff ds2 = new DoStuff() {
    public void work() {
      System.out.println("I ran via anonymous class");
    }
  };
  ds1.work();
  ds2.work();
} }

// A functional interface
interface DoStuff {
void work();
}

73
Q

Why can lambdas only be used with functional interfaces?

A

If you could assign a lambda expression to an interface having more than one abstract method (i.e. a nonfunctional interface), the lambda expression can only implement one of the methods, leaving the other methods of the interface unimplemented.

74
Q

Can lambda expression have parameters?

A

Sure they can. Lambda expressions can have zero, one, or multiple parameters. Let’s see how we’ll rewrite a comparator being passed into a constructor of a priority queue using lambdas.

Comparator using Anonymous Class:
Comparator descendingComparator = new Comparator() {

        @Override
        public int compare(Integer i1, Integer i2) {
            return i2 - i1;
        }
    };
    PriorityQueue q = new PriorityQueue(descendingComparator);

Comparator using Lambda:
Comparator descendingComparator = (i1, i2) -> {
return i2 - i1;
};

    PriorityQueue q = new PriorityQueue(descendingComparator);
75
Q

Can lambda expressions return values?

A

Indeed they can. Below is an example of an interface that raises a given value x to its y-th power.

Example Functional Interface:
interface RaiseToPower {

    int raiseToX(int x);
  
} For convenience, we can create interface objects that always compute the square or the cube of a given value.

Lamda Returning Value:
RaiseToPower square = (x) -> {return xx;};
RaiseToPower cube = (x) -> {return x
x*x;};

The lambda expressions return either a square or a cube of the given value. Whenever lambdas return a value we can’t skip the enclosing curly braces. Look at the below snippet where we skip the curly braces.

Example of Lambdas Expression
Runnable f = () -> System.out.println(“Hello”);
f.run();

Usually, the Runnable interface is used in multithreading, but we borrow it here for a trivial print statement to show how curly braces can be skipped.

76
Q

What does it mean effectively final variable in the context of lambdas?

A

It means that a non-final local variable whose value never changes after initialization is called “Effectively Final”. This concept was introduced because prior to Java 8 we could not use a non-final local variable in an anonymous class. If you have access to a local variable in Anonymous class, you have to make it final.

77
Q

Why local variables that are accessed from the lambda expression must be final or effective final?

A

The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems.

78
Q

Can lambda expressions capture variables in the outer scope?

A

Lambda expressions can capture local, instance, and static variables

79
Q

Why should we use generics in Java?
https://www.educative.io/courses/java-interview-handbook/JYPvL44ngKD

A

1) Enforcing stronger type checking at compile time for greater type-safety
2) Elimination of casts
3) Implementation of generic algorithms

80
Q

What is a generic type?

A

A generic type is a generic class or interface that is parameterized over types. For instance, the LinkedList class in java is a generic class.

81
Q

What is a type parameter?

A

The E in the generic class LinkedList is called a type parameter. By convention, type parameter names are single, uppercase letters. The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)

K - Key

N - Number

T - Type

V - Value

S, U, V - 2nd, 3rd, 4th types

82
Q

What is the unchecked or unsafe operations warning?

A

The term “unchecked” means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety.

For instance weh have List list = new ArrayList();
list.add(1);
//above code in not type safe and will produce “unchecked operation warning.

We should provide type in diamond brackets to avoid this issue.
List list = new ArrayList<>();
list.add(1);

These warnings are usually encountered when mixing legacy code (before generics) with generic code.

83
Q

What are generic methods?

educative.io/courses/java-interview-handbook/qV6nlXRLQ9r

A

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter’s scope is limited to the method where it is declared. The scope of the type variable is local to the method itself. it may appear in the method signature and the method body, but not outside the method. A generic method can appear in a class which itself is not generic. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method’s return type. Below is an example of a generic method.

EXAMPLE:

class Demonstration {

 void printType(T item) {
 
  System.out.println(item);
  
}
  
public static void main( String args[] ) {
    Demonstration demo = new Demonstration();
    demo.printType("string");
    demo.printType(5);
    demo.printType(23.23f);
}

}

84
Q

What is raw type?
https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

A

A raw type is the name of a generic class or interface without any type arguments. For example, given the generic Box class:

public class Box {
public void set(T t) { /* … */ }
// …
}
To create a parameterized type of Box, you supply an actual type argument for the formal type parameter T:

Box intBox = new Box<>();
If the actual type argument is omitted, you create a raw type of Box:

Box rawBox = new Box();
Therefore, Box is the raw type of the generic type Box. However, a non-generic class or interface type is not a raw type.

Raw types show up in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0. When using raw types, you essentially get pre-generics behavior — a Box gives you Objects. For backward compatibility, assigning a parameterized type to its raw type is allowed:

Box stringBox = new Box<>();
Box rawBox = stringBox; // OK
But if you assign a raw type to a parameterized type, you get a warning:

Box rawBox = new Box(); // rawBox is a raw type of Box
Box intBox = rawBox; // warning: unchecked conversion
You also get a warning if you use a raw type to invoke generic methods defined in the corresponding generic type:

Box stringBox = new Box<>();
Box rawBox = stringBox;
rawBox.set(8); // warning: unchecked invocation to set(T)
The warning shows that raw types bypass generic type checks, deferring the catch of unsafe code to runtime. Therefore, you should avoid using raw types.

The Type Erasure section has more information on how the Java compiler uses raw types.

85
Q

What is a generic type?

A

We say that a class or an interface is now parameterized over types and is considered generic. The type parameter is the variable that can take on different values and the generic class runs the same code with the value of the type parameter substituted.

class Printer {

void print(T t) {
    System.out.println("printing : " + t.toString());
} }
86
Q

What are generic methods?

https://www.educative.io/courses/java-interview-handbook/N0PWqnx3k6K

A

Generic methods are methods that introduce their own type parameters (T, U, V, etc). This is similar to declaring a generic type, but the type parameter’s scope is limited to the method where it is declared.

Generic class with generic method
class SimpleClass {

 void genericMethod(T t) {
    System.out.println(t);
} } Note that both the class and the method define T as the type parameter. The type parameter T the method defines over shadows the type parameter T the class defines. This allows us to invoke the method like below:

SimpleClass sc = new SimpleClass();
sc.genericMethod(Integer.valueOf(10)); The class instance is parameterized on String whereas the generic method is parameterized on Integer.
87
Q

What are bounded type parameters?

A

When you want to restrict the types that can be used as type arguments in a parameterized type, you can do so by bounding the type parameter. For instance, say you are designing a specialized collection class that should only contain numbers. The type parameter can be bounded by the Number class to ensure that consumers of your specialized collection can never add items which aren’t of type Number or one of its subclass.

class NumberCollectionBounded {

List list = new ArrayList<>();

// Print if the integer portion is greater
public void printGreater(T other) {
    for (T item : list) {
        if (item.intValue() > other.intValue())
            System.out.println(item);
    }
}

public void add(T item) {
    list.add(item);
} } We can bound the type parameter using the extends keyword followed by the class name. Note that by bounding the type parameter, the following snippet would not compile, and runtime exception wouldn't occur.

// compile error
NumberCollectionBounded myStringList2 = new NumberCollectionBounded<>(); Also on variables declared of type T, we can invoke methods like intValue() without requiring casting.
88
Q

Can we have multiple bounds specified for a type parameter?

A

Yes, a type parameter can have multiple bounds, but it can be bounded by at most one class and as many interfaces as desired. The class must be mentioned first in the list of bounding types. We can modify our earlier class to also be bounded by interfaces Comparable and Serializable

class NumberCollectionBounded {
     // ... class body
} Note that when we bound a type by an interface, we really mean that the type parameter T implements the interface. The correct way to implement comparison in the NumberCollectionBounded would be to bound the type parameter by Comparable interface. This will also simplify the comparison as we would be able to invoke the compareTo() method on variables of type T.
89
Q

What is the ? used for in generics?

educative.io/courses/java-interview-handbook/qVxVMGXK8m2

A

In generic code, the question mark, ?, called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable and sometimes even as a return type.

Note that the wildcard can only be used in defining arguments to a method in a method signature. It can’t appear in the return type expression.

90
Q

What is an intern() String method?

A

The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool.

Note that, if another String with the same contents exists in the String constant pool, then a new object won’t be created and the new reference will point to the other String.

91
Q

[1] What is Serialization?
[2] [1] What is Deserialization?

A

[1] Encoding an object as a byte stream is called serializing the object. Once an object has been serialized, its encoding can be transmitted from one running virtual machine to another or stored on disk for deserialization later.

[2] Deserialization is the opposite of serialization, that is converting a byte stream into an object in memory. Similar to serialization, two hook methods are provided for deserialization, which can be used to control the reading behaviour.

92
Q

What is the transient keyword used for?

A

Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized. For example:

93
Q

Can static fields be serialized?

A

Static variables belong to a class and not to any individual instance and therefore don’t get serialized.