Basic Flashcards

1
Q

Name the 4 OOP principles.

A

Abstraction
Polymorphism
Inheritance
Encapsulation

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

What is Polymorphism?

A

Polymorphism is the

  • provision of single interface which can be implemented by different classes to provide their customized implementation
    or
  • use of single symbol to represent multiple different types

Polymorphism has two types: static (Compile time) and dynamic (runtime).

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

Explain the types of Polymorphism.

A
  1. Compile-time/static
    The implementation to call is determined at compile-time. This is divided into two types:
    (i) Function Overloading: multiple functions, same name but different number/types of parameters
    (ii) Operator overloading: Using ‘+’ to add two numbers and also to concatenate two strings
2. Run-time/dynamic
The implementation to call is determined at run-time. There is only one type:
    (i) Function overriding: parent and child class have methods is exact same signature.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can we overload static/final/private methods in same class?

A

Yes we can.

We cannot “override” static/final/private methods anywhere.

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

Can we override static/final/private methods of parent class?

A

No.

It is possible to override parent class’s static methods as in we can have methods with exact same signatures in both parent and child class, but Java doesn’t call it overriding, as static methods are tied to the class as a whole and inheritance deals with providing customized behaviors for objects.

Final declaration by default does not allow overriding anywhere.

Private methods of parent class will not be visible outside and cannot be overridden.

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

Explain output.

class Animal 
{ 
	protected void getData() 
	{ 
		System.out.println("Inside Animal"); 
	} 
} 
class Dog extends Animal
{ 
	protected void getData() 
	{ 
		System.out.println("Inside Dog"); 
	} 
} 
public class Test 
{ 
	public static void main(String[] args) 
	{ 
		Animal animal = new Dog(); 
		animal.getData(); 
	} 
}

Can we write this:

Dog dog = new Animal ( );

A

Reference variable of parent class Animal is pointing to object of child class Dog, hence the method implementation by class Dog will be called.

===========================================
We cannot write Dog dog = new Animal ( ); as it will give compiler error “Type mismatch: cannot convert from Animal to Dog”

With “new Dog( )” we are assigning the Dog object type to Animal type, which is valid as Dog IS-A Animal.

With “new Animal( )” we are assigning Animal object type to Dog type, which is not valid for inheritance (IS-A relationship).

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

Explain output.

class Employee 
{ 
	void foo ( ) 
	{ 
		System.out.println("Employee"); 
	} 
} 
class Manager extends Employee
{ 
	void foo ( )
	{ 
		System.out.println("Manager"); 
	} 
	public static void main(String [ ] args) 
	{ 
		Manager john = new Employee( ); 
		john.foo ( ); 
	} 
}
A
Compilation error (type mismatch)
---------------------------
The object john is of type Employee (superclass) but referes to Manager (subclass), which violates the IS-A relationship.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain output.

class Animal 
{ 
	protected void run ( ) 
	{ 
		System.out.println("Animal runs"); 
	} 
} 
class Dog extends Animal 
{ 
	protected void eat ( ) 
	{ 
		System.out.println("Dog eats"); 
	} 
	protected void leap() 
	{ 
		System.out.println("Dog leaps"); 
	} 
} 
public class Test 
{ 
	public static void main(String [ ] args) 
	{ 
		Animal animal = new Dog(); 
		animal.leap ( ); 
	} 
}
A

Although the reference variable of parent class is pointing to object of child class, the method leap ( ) does not exist for parent class.

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

Explain output.

interface Animal 
{ 
	void run ( ); 
	void leap ( ); 
} 
abstract class Dog implements Animal 
{ 
	void eat ( ) 
	{ 
		System.out.println (" Dog eats "); 
	} 
} 
public class Corgi extends Dog 
{ 
	public void run ( ) 
	{ 
		System.out.println("Corgi runs"); 
	} 
	public void leap ( ) 
	{ 
		System.out.println("Corgi leaps"); 
	} 
	public static void main ( String [ ] args) 
	{ 
		Dog dog = new Corgi ( ); 
		dog.leap ( ); 
	} 
}
A

Dog implements Animal interface, hence all the methods in Animal replicate for class Dog.

As the reference variable of parent class Dog points to object of child class Corgi, child class’s method implementation will be called.

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

Can we overload main() method?

A

Yes, we can overload main() method by passing different number/types of arguments to it. The JVM will call public static void main (String[] args) as its main method even though we overload it.

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

Why is method overloading not possible by changing only the return type of method?

A

Two otherwise similar methods having int and double as their respective return types will confuse JVM at the time of method calling and hence we cannot have only return type as a way of method overloading.

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

Explain output.

class Demo{
 void test ( ) {
System.out.println("No parameter");
}
void test (int a, int b) {
System.out.println("a and b: "+a+" and "+b);
}
void test (double a) {
System.out.println("a: "+a);
}
public static void main(String[] args){
test();
test(10,20);
test(88);
test(12.3);
}
}
A
No parameter
a and b: 10 and 20
a: 88
a: 12.3
-----------------------------
When the test() method has only one input (88) and there is no exact match for this int parameter, Java will automatically type convert and call the test(double a) method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is upcasting?

A
When reference variable is of parent class and object is of child class, it is called upcasting.
ParentClass var = new ChildClass();

Vice versa is not possible.

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

What is Inheritance?

A

It is the process by which one object (child) acquires properties of another object (parent).

The class which provides basic attributes to be inherited is called Parent Class/Superclass/Base Class.

The class which inherits the above class is called Child Class/Subclass/Derived Class.

Inheritance makes it possible for subclass to define only the unique qualities, as general attributes can be inherited from superclass.

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

How many superclasses can one subclass have?

A

Only one

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

Can a subclass act as a superclass to other classes?

A

Yes

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

Can a class be superclass of itself?

A

No

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

Can a subclass access private member of its superclass?

A

No

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

Is this valid?

class Super{
  //class body
}
class Sub extends Super{
  //class body
}

class Test{

public static void main (String[] args){
 Super sup = new Super();
 Sub sub = new Sub();
 sup=sub;    // 1
 sub=sup;    //2
}
}
A

1 is valid, 2 will give compile-time type mismatch error

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

What can you access with below objects?

  1. Superclass sup = new Superclass();
  2. Superclass sup = new Subclass();
  3. Subclass sub = new Subclass();
  4. Subclass sub = new Superclass();
A
  1. Objects defined by Superclass only
  2. Objects defined by Superclass only
  3. All the objects defined by Superclass and Subclass except Superclass’s private objects
  4. Compilation error (type mismatch: cannot convert from Superclass to Subclass)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How to access method of a superclass?

A

Using super.methodName()

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

Where should call to superclass’s constructor be placed?

A

On the first line inside subclass’s constructor

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

Explain output.

class A{
 void show () {
  System.out.println("Inside A");
}
class B extends A{
  void show (String msg) {
   System.out.println(msg);
}
class Test{
 public static void main(String[] args){
   B obj = new B();
   obj.show("Inside B");
   obj.show();
}
}
A

Inside B
Inside A
————–
The methods are not overridden here, as method overridding needs methods with exact same signature in parent and child class. This is simply method overloading.

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

How JVM determines which overridden method to be called at runtime?

A

From the type of object (not the type of reference variable)

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

Why do we use the keyword super()?

A
  1. To call superclass’s consructor because constructors are not members and hence not automatically inherited.
  2. To call superclass’s non-private member which is hidden by member of subclass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What happens when we do not explicitly call superclass’s parameterless constructor?

A

JVM will implicitly call superclass’s parameterless constructor

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

Explain output.

class A{
  A(){
    System.out.println("Inside A's constructor");
   }
}
class B extends A{
   B(){
     System.out.println("Inside B's constructor");
   }
}
class C extends B{
   C(){
      System.out.println("Inside C's constructor");
   }
}
class Test{
  public static void main(String[] args){
   C obj = new C();
}
}
A
Inside A's constructor
Inside B's constructor
Inside C's constructor
----------------------------------
Whether or not super() is used, constructors are always executed from starting from superclass to subclass.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Why isn’t multiple inheritance not supported by Java?

A

If two parent classes having methods with same signature are inherited by a child class, which in turn acts as a parent class to another classes, then calling super.methodName() will be ambiguos as which method from which parent class to be invoked cannot be decided.

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

What is a literal?

A

A literal is a source code representation of a fixed value, be it an Integer or String.

Literals are represented in the code directly, without any computation.

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

Why do we need to write L or F for long/float numbers ?

A

Java considers a number as int by default unless stated otherwise.

Writing long num=123 will not give an error as 123 is treated as int and is well within the range of int.

Writing logn num=123456789789456 will give an error because the integer literal is not within the range of Integer and to tell Java that its a long data type, we need to write L.

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

Why does array indexing start with zero?

A

When an array is declared, the variable contains the reference to the memory location where the array is stored.

If the array is of size 10, and the first element is stored at memory location 2000, then the 10 elements will be placed contiguously as arrays are continguous data structures. The array declaration variable will then contain the memory address 2000 at which first element is stored.

Next element will be then stored at 2000+1st location, which means the first element is stored at 2000+0th location. Hence the array indexing starts with 0.

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

Why are strings in Java immutable?

A

Strings in Java get limited space for storing, called String pool. When a string is created, the JVM first checks if the same string literal exists in the String pool.

If it does, then the newly created String variable starts referring to the existing String literal. If not, new String literal is created.

When a String literal is being referenced by multiple references, modifying the literal for any one of them would change values for all. Hence Strings are immutable.

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

Why is String class in Java declared final?

A

As Strings are immutable, a String once created cannot be modified. But the modification can be done if String class can be inherited, then the String object from parent class will be available for modification by child class.

To avoid this, String class is declared final.

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

Explain the difference between

  1. String s=”Hello World”

and

  1. String s= new String(“Hello World”)
A

With (1), we are first checking if the String literal “Hello World” exists and assigning the variable ‘s’ to it if it does.

With (2), we are forcefully creating the string literal even if it already exists.

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

What is the difference between count++ and ++count?

A

Both the expressions will add 1 to the count and the difference will only be seen when count is passed as a parameter to some method or assigned to some variable.

count++ (called postincrement) will first pass the old value to method and then increment it.

For eg. x=i++ given i=5 will make x=5 and i=6.

++count (called preincrement) will first increment the value and pass the modified value to the method.

For eg. x=++i given i=5 will make x=6 and i=6.

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

What is the difference between logical AND (&&) and bitwise AND (&) operators?

A

Logical AND operator compares the values of two operands and returns true iff both the operands are true.

Bitwise AND operator when used with numeric operands performs the bitwise AND operation and returns the result.
For eg. int a=6, b=5, then a & b= 4

Bitwise AND operator when used with boolean operands compares both the operands and returns true iff both the operands are true.

Logical AND will short circuit the expression, i.e., if the first operand is false, it will not evaluate second operator. Bitwise AND (in boolean context) will evaluate both the operands in all conditions.

Logical AND in numeric context will produce compilation error.

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

Why does code (1) give compilation error but not code (2)?

  1. int val=50;
    if (val=60) System.out.println(“Yay!”);
  2. boolean flag=false;
    if (flag=true) System.out.println(“Yay!”);
A

Because in code (2) the expression inside ‘if’ returns a boolean value eventually, which is accepted by the compiler.

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

What will be the output of given program?

public String foo (String s){
return “String”;
}

public String foo (Object o){
return “Object”;
}

foo (null) ;

A

String

As the compiler will pick the most specific method implementation, which here is the one accepting String parameter.

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

Why are the outputs of below two lines different?

long num1 = 1000606024365L; //31536000000
long num2 = 1000606024365; //1471228928

A

num1 is explicitly created as “long” with using L suffix, due to which compiler treats it as a long variable and the multiplication is within the range of long.

num2 is treated as an int by compiler and as the multiplication is out of int’s range, it is truncated by removing the MSBs to contain within int.

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

What will be the output of given program?

public String foo (String s){
return “String”;
}

public String foo (String[] str){
return “Array”;
}

foo (null) ;

A

Compilation error (The method foo(String) is ambiguous)

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

What will be the output of given program?

public String foo (String s){
return “String”;
}

public String foo (String[] str){
return “Array”;
}

foo (“Hello”) ;

A

String

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

Define Object.

A

A Java object is a combination of state and behaviour. State is given by the field in class and behaviour is provided by methods.

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

Define Class.

A

A Java class is a blueprint/template from which objects are created.

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

Define Interface.

A

A Java interface is a group of related methods with empty bodies.

They only define the behaviour informally but do not provide the exact description.

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

What is JVM?

A

Java Virtual Machine (JVM) is the virtual machine that enables a system to run

  • Java programs as well as
  • programs written in other languages compiled to Java bytecode

JVM compiles a Java code to bytecode and is platform dependent (different platforms will have different implementation of JVM).

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

What is JRE?

A

Java Runtime Environment (JRE) is

  • JVM
  • Java class library
  • java command and
  • other infrastructure

bundeled together in a package which can be used to compile and execute Java code.

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

What is JDK?

A

Java Development Kit (JDK) is the software development kit used for developing and executing Java applications. It contains

  • JRE
  • java loader (Java)
  • java compiler (javac)
  • java archive (jar)
  • java documentation generator (javadoc)
  • other tools needed for Java application development
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the difference between JVM, JRE and JDK?

A
  • JVM is the specification where working of Java is specified.
- JRE= JVM + Java class library
JRE is the implementation of JVM where we can execute (not develop) Java programs
  • JDK = JRE + development tools
    JDK is the development kit providing all the tools required to develop, compile, debug and execute a Java program.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

Why is JVM called virtual machine? Whats the difference between JVM and VMWare?

A

JVM is called virtual because it does not exist physically, it is a software package that converts Java sourcecode to bytecode.

It is the software implementation of an abstract machine which is more like virtualized processor.

VMWare virtualizes the hardware of the machine on which it is running. It is also a software package installed on a machine so that different guest OSs can sit on top of it.

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

What is JIT?

A

Just In Time (JIT) is a way of executing code that involves compilation during execution of a program- at runtime- rather than compiling prior to execution.

The JIT compiler exists within JVM.

In JIT, not all code is converted to machine code. The source code is first converted to bytecode and as and when the code is needed, it is converted to machine code on the fly.

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

What makes Java platform independent?

A

Java code is converted to bytecode by JVM, which is platform dependent.

JVM is created different for different OSs, which can convert the Java code to bytecode which can run on that machine. Hence Java is platform independent if the JVM is already installed and running on the system.

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

Is Java 100% object oriented?

A

No. Java utilizes the 8 primitive data types (byte, short, int, long, float, double, char and boolean) which are not objects.

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

What is constructor in Java?

A

Constructor is a special type of method in a class which instantiates the class by creating its object.

Constructors must have same name as the class, must not have any return type and are called with “new” keyword.

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

Can a constructor be final/abstract/static/private?

A

Constructor can never be

  • final: when a method is set as final, it means that it cannot be overridden by other method. But according to Java Language Specification, constructors are not members and are never inherited hence are not subject to hiding/overriding.
  • abstract: when a method is set as abstract, it means that it cannot have a body and that the body should be provided by child class’s overriding method. But the constructor is called implicitly when “new” keyword is used and hence cannot lack body.
  • static: when a method is declared static, it means that the method belongs to the class as a whole, not to the object. But the purpose of constructor is to create objects and it must have access to the class fields which are not static.

Constructor can be private to prevent instantiation outside of class (singleton pattern) or that the construction happens only internally (factory pattern).

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

Explain the access modifiers.

A

How a class member (fields and methods) and a class itself can be accessed by rest of the Java code is determined by the access modifiers attached to the class/field/method declaration.

There are 4 types of access modifiers- private, default (no access modifier specified in the declaration), protected and public.

private: member can be accessed in same class only
default: member can be accessed in same class and package only
protected: applies when inheritance is involved. The member can be accessed in same package and subclasses from different packages
public: member can be accessed by any other code

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

What is a wrapper class?

A

Many of the standard data structures of Java such as ArrayList operate on objects and passing them primitive values such as int does not work.

To handle this, Java provides type wrappers, which are classes that encapsulate the primitive type within an object.

There are total 8 wrapper classes (one per primitive type): Byte, Short, Integer, Long, Float, Double, Character and Boolean.

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

What is autoboxing and auto-unboxing in Java?

A

Collections in Java are used to hold objects of same type and we cannot store primitive values in them as they are.

Autoboxing is a process by which a primitive data type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly create an object.

Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed.

Integer iOb = 100; //autoboxing

int i = iOb; //auto-unboxing

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

What is abstract class?

A

The abstract class is the template to define a superclass and declares only the structure of the methods, letting subclasses implement their own implementation. Abstract class can have concrete methods as well.

Any class that contains one or more abstract methods must also be declared abstract. Any subclass of the abstract class must implement all of the abstract methods or be declared abstract itself.

Abstract class cannot be instantiated as it is not fully defined but they can be used to create object references because Java’s approach to runtime polymorphism is implemented through the use of superclass references.

If we have a class Figure which is abstract and it is subclassed by another class Rectangle, then

Figure f = new Figure(); // is invalid

but

Figure f = new Rectangle (); // is valid

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

What is the difference between machine code and byte code?

A

Machine code is the set of instructions in machine language/binary which can be directly executed by CPU whereas byte code is an intermediate code generated by compiling a source code which can be executed by virtual machine.

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

What is Pass-by-value and Pass-by-reference? Which one of these is Java?

A

When a parameter is passed by reference, the caller and the callee are referring to the same variable. If the callee modifies the parameter, the effect is visible to caller’s variable.

When a parameter is passed by value, the caller and the callee are referring to two independent variables. If the callee modifies the parameter, the effect is not visible to caller’s variable.

Java only supports pass by value. As the values of variables can only be primitives or references, it seems like Java passes objects by reference, but that is not true.

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

What are the differences between == and equals method?

A

== is an operator and equals( ) is a method.

== compares references and equals( ) compares the contents. It means == checks if both the objects point to same location in memory whereas equals( ) checks the values of those objects.

equals( ) can throw NPE is first parameter is null.

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

What does 
 in method parameter

public void foo (String 
 s)

mean?

A

The three dots are called ellipsis and the feature is called varargs which was introduced in Java 5. It means that the function can receive multiple parameters of that type.

The method can respond to any calls from:

foo (“apple”)
foo (“apple”, “banana”)
foo (new String[ ] {“apple”, “banana”, “pear”})

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

Explain output.

public static void main (String [ ] args){

int x = 10;

System.out.println (“The value is “+x+x);
}

A

The value is 1010

=================================
When used in a string context, the + operator works as a concatenation operator.

64
Q

Explain output.

public class Person {
    {
        personCount = 10;
    }
    static {
        personCount = 20;
    }
    private static int personCount = 1000;
    {
        personCount = 30;
    }
    static {
        personCount = 40;
    }

public static void main(String[] args) {
System.out.println(Person.personCount);

       Person p = new Person();
       System.out.println(Person.personCount);
       Person.personCount = 100; 
       p = new Person();
       System.out.println(Person.personCount);
    }
}
A
40
30
30
===========================
1. The initialization flow goes like this:
  • static blocks/variables in the order of their declarations
  • regular blocks in the order of their declarations
  1. When no instance is created but the class has static variables/blocks, they will be loaded only once when the class is loaded in JVM for the first time.

Hence when we call Person.personCount in main’s 1st line, the static block/variable declaration order will follow, firstly setting value to 20, followed by static inline declaration of 1000, followed by second static block setting value to 40. So this line prints 40.

  1. Then we create the object and this will trigger regular blocks to be called, firstly setting the value to 10 and then to 30.
  2. We explicitly set the value of personCount to 100 but when we create new instance in next line, the value 100 will be overwritten by two regular blocks, which will be called every time a new object is created, setting the value to 10 and then to 30.
65
Q

Explain output.

class Player {
static String type="ABC";
int age;
//getters and setters
}

public static void main (String [ ] args) {
Player player;

System.out.println( person.getType( ) );

System.out.println( person.getAge( ) );

A

ABC
NullPointerException

=================================
1. The class variable 'type' is static, which means it belongs to the class and not to the instance 'player'. Hence when we invoke the method 'getType( )' on object which is null, it doesn't give NPE as getType( ) being a static method is invoked on the class.

Even if the the variable type was not instantiated with value “ABC”, the first print statement would produce NULL as output but won’t throw NPE.

  1. The class variable ‘age’ is not static and is tied to the object. As the object is null, getAge( ) is invoked on null object, making it throw NPE.
66
Q

How do you chain constructors using this( )?

A

The keyword ‘this’ is used to refer to the current instance. But it can be also used to chain constructors, i.e., calling one constructor of a class from another constructor of same class.

Suppose we hav a class Car with instance variables color, model, serialNumber, a static variable count and we provide two constructors:

Car ( ) {
count++;
serialNumber = count;
}

Car ( String color, String type) {
count++;
serialNumber = count;
this.color = color;
this.type = type;
}

Instead of repeating the code to increment count and assigning it to serialNumber, we can put it inside a initialization block, making sure that it will be called every time a new object of Car is created.

But if we have third constructor which takes color as the only argument and do not want to increment the count nor assign it to serialNumber, then we cannot stop initialization block from executing in this case.

To solve this, we can make one constructor as the source of authority, lets say the no-args constructor.

Car ( ) {
count++;
serialNumber = count;
}

Then we can call this constructor from inside of second constructor, to make sure that count is incremented and serialNumber is assigned the new count. With this, we can also make sure that the third constructor does not call Car( ) and stops the initialization.

Thus, our second constructor will look somewhat like this:

Car ( String color, String type) {
Car( );
this.color = color;
this.type = type;
}

But the syntax is bad and instead of calling it by name, we must call it using this( ).

Hence the correct way is:

Car ( String color, String type) {
this( );
this.color = color;
this.type = type;
}

The ( ) with ‘this’ inform us which constructor is being called. If we are calling a constructor which takes some parameters, then we should provide those parameters.

The ‘this( )’ must be called on the first line of constructor and we can only call ‘this( )’ from inside of another constructor, not from inside of a method (even instance methods).

67
Q

Explain scope.

A

Scope of a variable is the range in code in which it exists, is accessible and at what point it will go away.

There are different levels of scope:

  1. Inside a class when we define an instance member, the scope of that member is across that entire class no matter where in class it is first declared.
  2. The arguments that are passed to a method are available everywhere inside the method.
  3. The variables created inside a method are available from the point they are created, not before that.
68
Q

Explain output.

public static void main(String [ ] args) {

double price = 90_000;

    String model;
        if ( price > 100_000 ) {
            model = "Tesla Model X";
        } else if ( price <= 100_000 ) {
            model = "Tesla Model S";
        }

System.out.println ( model ) ;
}

A

Compilation error

==========================
As the String variable model has not been initialized, it cannot be used.

69
Q

If no imports are listed, which two packages can we still access?

A
  1. The current package

2. The java.lang package

70
Q

Will this code compile?

import java.io.*;

package com.intertech.transport;

public class Truck {

}

A

No, the package statement must be the first statement in a file unless the class is in a default package

71
Q

Will this code compile?

package com.intertech.*;

import java.util.*;

public class Person {

}

A

No, the package statement cannot have wildcard

72
Q

What is classpath?

A

Inside a package, we can have multiple folders and inside these folders, we can have multiple classes. In order to tell the compiler and class loader where to look for classes, we create a system variable which contains path to these classes. This variable is called classpath.

The classpath allows us to tell the compiler and class loader where are we storing our files (the bytecode and other application files). Classpath can contain multiple directories, JARs and zips, separated by semicolon in Windows and colon in *nix.

A classpath says: here’s the list of top folders where the code can be found. We don’t have to list every single directory that has code, just the root folder(s) the compiler and JVM should start their search from. All the subfolders are determined by package and import statements.

73
Q

Explain output.

int j = 2;

String str = null;

switch ( j ) {

case 1: str = “one”;
break;

case 2: str = “two”;

case 3: str = “three”;
break;

case 4: str = “four”;
break;

default: str = “unknown”;
}
System.out.println (str);

A

three

============================
Case 2 catches the switch control and assigns “two” to str. But as there is no break statement, the control falls through and is caught by case 3 even if it is not true.

At case 3, the str is assigned value “three” after which it breaks and prints the value.

74
Q

Will the code compile?

switch (someVariable) {

String msg = “hello”;

case 0: msg = “world”;
break;

default: msg = “all”;
}

A

No.

The only legal members of a switch statement are ‘case’ and ‘default’. We cannot declare a variable inside switch (we can inside case statement and it will be a local variable).

75
Q

What will lines A and B print?

class Animal {

String name= “Chester”;

String type;

public void foo ( ) {
    System.out.println ("Inside Animal");
} }

public class Dog extends Animal{

String color="Grey";

public void foo ( ) {
     System.out.println("Inside Dog");
}

public static void main ( String args [ ] ) {
  Animal animal = new Dog ( );

System.out.println ( animal.color ); // line A

 animal.foo ( ) ;     // line B
} }
A

line A: compilation error (color cannot be resolved or is not a field)

line B: Inside Dog

===========================================

When an object is created in this manner:

Superclass sup = new Subclass( );

The object sup can only access all the members of Superclass.

As color is defined for subclass, it cannot be accessed.
--------------------------------------------------------------------------------
When we are calling a method which exists in superclass Animal and is overridden by subclass Dog, the object animal will call subclass' method implementation.
76
Q

What is the difference between Inheritance and Polymorphism? Is Polymorphism possible without Inheritance?

A

Inheritance is when one class is derived from another existing class. If we have a superclass Person and subclass Student extending Person, Student inherits all the things Person has declared (except for Private members).

Hence Inheritance refers to using the structure and behaviour of superclass in a subclass.

Polymorphism deals with how JVM decides which method to be used based on it type and refers to changing the behaviour of superclass in a subclass.

In Java, polymorphism is possible without Inheritance, as polymorphism shows how the types can stand one for another in operations and still be valid.

For eg., integers and float numbers can be used interchangeably in an operation and this is a form of polymorphism but there is no inheritance involved.

Also the usage of ‘+’ operator in an addition operation and concatenation operation deals with polymorphism but not inheritance.

77
Q

Why are default and no-arg constructors not same?

A

Default constructors are implictly provided by JVM when we do not provide any constructor and this constructor does not have any parameters.

No-arg constructor is the explicit constructor provided by user which does not have any parameters.

78
Q

What is singleton class in Java? How can we make a class singleton?

A

Singleton class has exactly one instance per classloader, which is used when we need only one instance to be accessible from a well-known access point.

For eg. database connection managing class. Instead of creating a new connection per request and keeping track of them, we can create just one connection instance and reuse it.

This can be achieved by
- declaring the constructor private (so that the new operator cannot be used outside of class)

class Person {
public String name;
private Person ( ) {
name="John";
}
  • create a private static instance of the class inside (so that it cannot be accessed from outside of class without an accessor method)
class Person {
private static Person person=null;
public String name;
private Person ( ) {
name="John";
}
  • writing an accessor method as public static getInstance( ) (which returns the class instance if it is not null)
class Person {
private static Person young=null;
public String name;
private Person ( ) {
name="John";
public static Person getInstance ( ){
if(young==null) young=new Person();
return young;
}
}
79
Q

What is the difference between ArrayList and Vector?

A

Arraylist is not synchronized and hence is not thread-safe and fast.

Vector is synchronized and hence thread-safe and slow.

With vector, we can define the increment size. If it is not specified, vector doubles in size when needed whereas arraylist increases its array size by 50%.

80
Q

Explain Vector class.

A

java.util.Vector class implements List interface and provides a dynamic array of objects that can grow/shrink as required.

As opposed to ArrayList, it is synchronized and thread-safe and we can specify the increment capacity. If it is not specified, vector doubles in size, which is not something we get from ArrayList.

81
Q

What is stack memory in Java?

A

To run an application in optimal way, JVM divides memory into stack and heap space.

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

Access to this memory is in LIFO order. Whenever a new method is called, a new block (called stack frame) on top of already existing stack is created, containing values specific to that method (primitives and object references).

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

This memory is thread-safe as each thread operates in its own stack and when it is full, we get java.lang.StackOverFlowError. Access to this memory is fast compared to heap space.

82
Q

What is heap space in Java?

A

Heap space is used for dynamic memory allocation of objects and JRE classes at runtime. New object creation always happens in heap space but the references to these objects are storesi in stack memory. These objects can be accessed from anywhere in application.

This memory model is broken down into 3 parts, called generations.

  • young: space where new objects are created and aged upto a specific threshold. When the threshold is reached, they are moved to old generation.
  • old/tenured: space where long surviving objects are stored.
  • permanent: consists of JVM metadata for runtime classes and methods.

If the heap space is full, we get java.lang.OutOfMemoryError. This space is not thread-safe and needs to be guarded by proper synchronization in code.

83
Q

How is stack memory different from heap space?

A

Stack only stores primitive values and references to objects that are created in heap space whereas all new objects are created in heap.

Stack is used in parts, one at a time during execution of a thread by the thread being executed whereas the entire application uses heap space during runtime.

Stack memory only exists as long as current method is running whereas heap space exists as long as application runs.

Stack memory is automatically allocated and deallocated when a method is called and returned respectively. Heap space is allocated when a new objects is created and deallocated by GC when they are no longer referred.

Stack memory has size limit depending on OS and is usually smaller than heap. There is no size limit for heap.

84
Q

Explain encapsulation principle in Java.

A

Encapsulation is the wrapping up of data and related code together as a single unit so that they stay hidden from any other class and can be accessed through proper accessor functions.

This is done by declaring the member variables private and accessing them via getters/setters.

85
Q

Explain abstraction principle in Java.

A

Abstraction is the process of hiding the implementation details from the user and only providing the functionality.

It is achieved by using abstract classes and interfaces, by providing the methods of the object available to call and what input parameters should be provided. User does not need to know how the method is implemented and what kinds of actions it performs.

86
Q

What is the difference between local variable and instance variable?

A

The local variable is generally declared inside a method or block and only has local scope.

Instance variable is the one created inside a class but outside a method and is tied to the object of class. Thus every object will have its own copy of this variable.

87
Q

What is the difference between String, StringBuilder and StringBuffer?

A

With String class, the strings are stored in Constant String pool whereas with StringBuilder and StringBuffer, they are stored in heap space.

Strings are immutable but objects created with StringBuilder and StringBuffer are mutable.

String and StringBuffer provide thread safety. StringBuilder does not.

In terms of performance, String class is fastest, followed by StringBuilder and StringBuffer.

88
Q

Explain StringBuilder.

A

StringBuilder class objects are similar to String Objects except that they can be modified. Internally, these objects are treated as variable-length array of characters.

If we need to concatenate a large number of strings, StringBuilder should be used instead of regualr Strings.

89
Q

Explain StringBuffer.

A

StringBuffer class is similar to StringBuilder except that it is synchronized and thread-safe. As synchronization is an overhead, it is slow and less efficient than StringBuilder.

90
Q

Explain classloader in Java.

A

Classloader is an abstract class in Java whose objects are responsible for loading of classes during runtime dynamically to JVM. They are part of JRE and are used to load the class being required for application being loaded, rather than loading all of them at once.

There are 3 types of built-in classloaders:

  • bootstrap: loads JDK’s internal classes and Java core libraries as Java classes are loaded by instance of java.lang.ClassLoader which itself is a class and we need something to load itself. They are parent of all other ClassLoader instances and are platform dependent.
  • extension: child of bootstrap classloader which takes care of loading the extension of standard Java core classes used by applications such as logging.
  • system: takes care of loading all application level classes by loading files found in classpath environment variable.
91
Q

Explain final keyword.

A

final keyword is a non-access modifier and has different contexts for variables, methods and classes.

A final variable’s value cannot be changed once assigned. If final variable is not initialized, we can assign value to it via constructor only.

A final method cannot be overridden.

A final class cannot be extended by any class.

92
Q

Explain Collection hierarchy.

A

The Iterable interface is extended by Collection interface, which in turn is extended by Set, List and Queue interfaces.

Set interface is implemented by HashSet class, which is then extended by LinkedHashSet class. Another interface SortedSet extends Set interface, which is then extended by NavigableSet, which is then implemented by TreeSet.

List interface is implemented by ArrayList, Vector and LinkedList.

Queue interface is implemented by LinkedList and PriorityQueue. This way, LinkedList implements List as well as Queue interfaces.

93
Q

What is Map in Java?

A

Map interface is part of java.util package and although not a member of Collection interface family, is considered a collection type. It stores pairs of unique keys and corresponding value.

Map interface is implemented by Hashtable and HashMap and extended by SortedMap interface.

HashMap is extended by LinkedHashMap.

SortedMap is extended by NavigableMap, which in turn is implemented by TreeMap.

94
Q

What is collection in Java?

A

Collection is the framework in Java that acts as an architecture for storing and manipulating group of objects.

At the base of this framework is Collection interface, which is extended by List, Set and Queue interfaces, which in turn are implemented by ArrayList, HashSet, LinkedList etc classes.

95
Q

What are the different types of inheritances?

A

There are 4 types:

  • Single: one parent class, one child class
  • Multi level: one class being extended by another class, which in turn is extended by another class
  • Hierarchical: one parent class, multiple child classes
  • Hybrid: combination of two or more inheritances
96
Q

What are the three types of relationships between Java objects?

A

Composition
Aggregation
Association

97
Q

Explain Composition relation.

A

Composition is a “belongs-to” type of relationship where one object has logically larger structure and contains another object(s) and is often called ‘has-a relationship’.

For eg. two classes Book and Library. The Library class (container) will have collection of Book (member).

Composition is a strong has-a relationship because objects’ lifecycles are tied. If we destroy the Library object then the member Book will be also be destroyed. This does not mean that the Book class can never exist on its own.

In UML,

98
Q

Explain Composition relation.

A

Composition is a “belongs-to” type of relationship where one object has logically larger structure and contains another object(s) and is often called ‘has-a relationship’.

For eg. two classes School and Department. The School class (container) will have collection of Department objects (member).

Composition is a strong has-a relationship because objects’ lifecycles are tied. If we destroy the School object then the member Department will be also be destroyed.

In UML, the filled diamond is at the container and arrowhead is at the member.

99
Q

Explain Aggregation relation.

A

Aggregation is also a ‘has-a relationship’ like Composition except that the objects can exist independently of each other.

For eg. two classes Song and PlayList. The PlayList class (container) will have a collection of Song objects (member).

The playlist can contain multiple songs but without being in a playlist, the song on its own can exist. This way, the member is not tied to only one container and is weaker relationship.

In UML, the empty diamond is at the container and arrowhead is at the member.

100
Q

Explain Association relation.

A

Association is the weakest relationship and none of the objects are parts/members of each other. The relation is set up through their objects and indicates how objects know each other and use each other’s functionality.

For eg. two classes Car and Driver. Car can exist without a Driver and Driver can exist without a car.

Association can be one-to-one, one-to-many, many-to-one, many-ton-many.

One-to-one: one person has one passport

One-to-many: one person has many devices

Many-to-one: many cities belong to one state

Many-ton-many: many students have many teachers

In UML, we mark association between classes with a line without any arrowheads. The types of association can be marked with cardinality.

101
Q

What is UML diagram and cardinality?

A

Unified Modeling Language (UML) is a standard language for specifying and visualizing the artifacts of software system such as objects, classes, inheritance relations between them etc.

Cardinality, i.e., number of elements can be specified in UML in lower bound-upper bound fashion. If one student can take minimum 1 and maximum 5 subjects, then in UML diagram, a 1 will be written at Student side and 1..5 will be written at Subject side.

Similarly, 0..* would mean zero or more, 1..1 would mean exactly one.

102
Q

What is a marker interface?

A

A marker interface has no methods or constants inside it. In other words, an empty interface in Java is called marker interface. Implementing this interface is meant to imply some special treatment of the implementing class.

Java provides many built-in marker interfaces such as Serializable, Cloneable and Remote.

If we try to clone an object that doesn’t implement Cloneable interface, JVM will not let us clone it. Hence Cloneable marker interface is an indicator to JVM that we can call clone( ) method.

103
Q

What is the difference between marker interface and typical interface?

A

Suppose we want to create a marker that indicates whether an object can be deleted from database. In order to delete an entity from database, the object representing this entity has to implement our marker interface, such that in the delete( ) method inside class, we can check if the object being deleted is instance of our marker and only delete it if it is.

Now along with one entity Shape, we also want to delete another entity Person. To do this, we can either add an additional check on our delete( ) method to check if the object is of type person or not. With more types to delete, the code change will be frequent.

The second option is to make Person type implement Shape type, which makes no sense logically.

Hence marker interfaces are used instead of using typical interfaces, as their implementation does not add any methods but it makes objects eligible for special treatment.

104
Q

Explain Serializable.

A

java.io.Serializable is a marker interface in Java which has no methods or constants. It is used to make an object eligible for saving its state into a file, which is called serialization process.

When a class implements java.io.Serializable, all its subclasses are serializable as well. Also if a class Person implements Serializable and it refers to another class Address’s object internally, class Address must also implement Serializable or NotSerializableException is thrown.

105
Q

What is Serialization and Deserialization in Java?

A

Serialization is the conversion of Java object into static stream of bytes that can be saved to database/file or transferred over network. Deserialization is the opposite of this.

Serialization process is instance-independent, i.e., objects can be serialized on one platform and deserialized on another. Classes that are eligible for serialization need to implement Serializable marker interface.

We create an object of ObjectOutputStream class and provide the filename (in which we want to store the stream) to its constructor. Then we call writeObject( ) method on this object and provide it our object that we want to serialize.

To deserialize, we use ObjectInputStream and readObject( ) method.

Static fields in a class belong to class and are not serialized.

106
Q

Explain Cloneable interface.

A

java.lang.Cloneable is a marker interface in Java which has no method. A class that implements this interface is eligible to call clone( ) method (which is a member of Object class) to make field-for-field copy of instances of that class.

By convention, classes that implement Cloneable must override Object.clone( ). If we call this method on object which does not implement Cloneable, CloneNotSupportedException is thrown.

107
Q

What is object cloning?

A

It is a way to create exact copy of an object. To achieve this, the object must implement java.lang.Cloneable interface and override Object.clone( ) method, which creates a new instance of the class of current object and initializes all its fields with exact same contents of corresponding fields.

If we have an immutable object that has an array type field, the getter should always return a clone of array to preserver immutability.

If the class has only primitive data type members then a new instance of class will be created with those values.

If the class contains members of any class type, then the object references to those members will be copied and member references in both original and cloned object will refer to the same object.

108
Q

What are the two types of object cloning?

A

Shallow copy:
- This is the default implementation if we are not cloning all object types (not primitives) referred by the class.

Deep copy:
- In deep copy, the created clone is independent of original object and making changes in cloned object will not affect original object.

109
Q

What is a copy constructor in Java?

A

Copy Constructors are special constructors in a class, which takes argument for its own class type.

With this definition, if we pass an instance of class to its copy constructor, then the constructor will return a new instance of class with values copied from argument instance. Thus it helps to clone an object.

for eg. class Point {
private Integer x, y;
public Point (Point point) {
this.x = point.x;
this.y = point.y;
}
}
110
Q

What is the difference between Collection and Collections in Java?

A

Collection is the top level interface of Java’s collection framework which is inherited by List, Set and Queue data structures.

Collections is a utility class in java.util package and consists of static methods which work on objects of type Collection. 
For eg.,it has a method to find the maximum element in a collection, a method to sort the collection and a method to search for a particular element in a collection.
111
Q

Explain the difference between abstract class and interface.

A

Abstract class and interfaces help us achieve the principle of abstraction.

Both abstract classes and interfaces can have multiple abstract and non-abstract methods.
In case of abstract class, the abstract methods need “abstract” declaration in their signature. For interfaces, abstract methods need not be declared abstract, but non-abstract methods must be declared “default”.

Abstract class can have private instance variables and getter-setter methods, like a normal class. All the variables in interfaces are public static final by default. There is no concept of instance variables for interfaces.

Abstract classes can also have constructor, but they can only be called by constructor chaining in subclasses. Interfaces cannot have constructors.

A class can only extend one abstract class, whereas it can implement multiple interfaces.

Abstract class can have any visibility whereas interface must be either public or default visibility.

112
Q

Explain pass-by-value.

A

In Java, the data can be either a primitive variable or an object type. For a primitive variable, the value is stored in the stack memory and for an object, the value of its reference is stored in stack memory.

With pass-by-value, these values are copied into formal arguments and these arguments are then passed to the method.

int x=1, y=5;
System.out.println (“Before modification: “+x+”, “+y);

modify ( x, y );
System.out.println (“A ftermodification: “+x+”, “+y);

void modify ( int x, int y){
x=10;
y=20;
}

will print

Before modification: 1, 5
After modification: 1, 5

113
Q

What is the difference between import and static import?

A

Regular imports are used to import

  • a specific class [ import java.util.ArrayList ]
  • all classes [ import java.util.* ]
  • public nested class of an enclosing class [ import com.org.A.* ]

Static import is used to import

  • static members
  • nested static class

The static import declaration is analogous to the regular import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

114
Q

When should the static imports be used?

A

Static imports should be used when one requires frequent access to static members from multiple classes.

For eg.
double r = Math.cos ( Math.PI * theta );

Can be rewritten as

import static java.lang.Math.*;
double r = cos(PI * theta);

115
Q

Explain the keyword: static.

A

static keyword can be applied to methods and variables only. Such members would be tied to the class, rather than the instance.

Hence all instances will have same copy of static variable and modifications will be visible to all instances.

As static members are not tied to objects, they can be invoked by class name.

116
Q

Explain the keyword: abstract.

A

abstract keyword can be applied to classes and methods only.

When classes are abstract, they can’t be instantiated and must contain at least one abstract method. Abstract classes are meant to be subclassed.

When methods are abstract, they do not have implementation and they must be overridden in subclasses.

117
Q

Explain the keyword: synchronized.

A

synchronized keyword can be used with instances, static methods and code blocks.

When we use this keyword, we make Java use a monitor lock to provide synchronization on a given code fragment.

118
Q

Explain the keyword: volatile.

A

volatile keyword can be used with instance fields only.

It declares that the field value must be read from and written to main memory- bypassing the CPU cache.

All reads and writes for a volatile variable are atomic.

119
Q

Explain Comparable interface.

A

When working with custom types or trying to compare objects that aren’t directly comparable (such as two objects of class Player), we need to make use of a comparison strategy, which can be built by using either Comparable or Comparator interfaces.

Comparable is an interface in java.lang package, which defines a strategy for comparing objects of same type. This is called the class’s natural ordering.

If we use Collections.sort(playerList), it will give us compile-time error.

Hence in order to sort or compare, we must make our Player class implement Comparable interface, with Player as type argument.

Hence our class declaration will be:
public class Player implements Comparable

This means we must override the compareTo method, which accepts one Player argument and returns an int.
This method returns:

-1 : if current object is less than compared object
0 : if current object is equal to compared object
1 : if current object is greater than compared object

The overridden method compareTo( ) must be consistent with equals( ) method.

Now when we call Collections.sort(playerList), it will compare with our implementation of compareTo.

120
Q

Explain Comparator interface.

A

When working with custom types or trying to compare objects that aren’t directly comparable (such as two objects of class Player), we need to make use of a comparison strategy, which can be built by using either Comparable or Comparator interfaces.

The Comparator interface is in java.util package and defines a compare (arg1, arg2) method with two arguments that represent compared objects and works similarly to Comparable.compareTo( ) method.

If we use Collections.sort(playerList), it will give us compile-time error.

With Comparator, we can provide comparisons based on different parameters by creating classes to implement Comparator interface, with Player as type argument.

With this, if we want to compare the players based on their ages, we will create a class say PlayerAgeComparator, make it implement Comparator and override the compare( Player p1, Player p2) method to compare based on their ages.

If we want another comparison between players’ rankings, we need to create another class implementing Comparator and overriding the compare method.

Now we can call Collections.sort with playerList as first argument and instance of comparator we want to use.

For eg.
Collections.sort(playerList, playerAgeComparator);

will compare the players based on their ages.

121
Q

What is the difference between Comparable and Comparator?

A

When working with custom types or trying to compare objects that aren’t directly comparable (such as two objects of class Player), we need to make use of a comparison strategy, which can be built by using either Comparable or Comparator interfaces.

The Comparable interface is a good choice when used for defining the default ordering or, in other words, if it’s the main and one way of comparing objects.

But since the Comparable interface is needed to be implemented by the class whose objects we want to sort, we cannot make changes to source code at a later stage or if the source code is third party.

This is where we can use Comparator interface. By creating our new class and making it implement Comparator interface, we can write our custom logic for sorting the objects of class.

Also since Comparator implementation needs creation of new classes, it doesn’t litter the domain code.

Finally, with Comparator, we can define multiple different comparison strategies which isn’t possbile when using Comparable.

122
Q

Explain the finalize( ) method.

A

The finalize() method, belonging to Object class, is a special method called by garbage collector while it’s cleaning the memory.

We can override finalize( ) to release system resources when the object is garbage collected.

123
Q

What is enum?

A

Enum is a type of class that can have set of predefined constant values. To create such class, we need to use the enum keyword.

124
Q

What is the difference between String’s substring( ) and subSequence( ) method?

A

subSequence( ) invokes subString( ) method internally and both the methods return the same output, except their return types are different.

  • substring( ) returns a string whereas
  • subSequence( ) returns a CharSequence

The subSequence( ) method was introduced in Java 1.4 because CharSequence interface was introduced and String was implementing this interface.

125
Q

Explain String’s compareTo( ) method.

A

“Apple”.compareTo( “Banana” )

will compare the two strings lexicographically and give one of the three outputs: positive integer, negative integer, zero.

Wrt a dictionary, if first string comes before second string, a negative integer will be returned.
If first string comes after second string, a positive integer will be returned.
If both the strings are same (even case-wise), zero will be returned.

The positive/negative integer returned will be the difference between ASCII values of characters from where the two strings became different.

For eg, the strings Apple and Banana are different from each other right from first character- A and B. ASCII value of A is 65 and that of B is 66, hence -1 will be returned.

126
Q

Can a string be used as expression in switch case?

A

From Java 7 onwards, a string can be used as a switch expression. For earlier versions, we will have to use if-else conditions.

127
Q

What is string interning in Java?

A

String interning is the method of storing only one copy of each distinct immutable string.

This single copy of each string is called intern and is typically looked up by string’s method intern( ). In Java, ll compile-time constant strings are automatically interned using this method.

When the intern( ) method is invoked on a String object, it checks for the string literal in the pool. If it is found, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to new object is returned.

128
Q

Why are string objects are mostly used as a hashmap key?

A

Since strings are immutable, their hashcodes are cached at the time of creation, and need not be calculated again. This makes hashmap processing faster than other objects.

129
Q

Explain the output:

String s1 = "abc";
StringBuffer s2 = new StringBuffer(s1);

System.out.println( s1.equals ( s2 ) );

A

False.

equals( ) method internally calls instanceof and as String and StringBuilder objects are of different types, it will return false although their contents are same.

130
Q

Explain the output.

public static void foo ( String s ) {
System.out.println ( “String” );
}

public static void foo ( StringBuffer sb ){
System.out.println ( “StringBuffer” );
}

public static void main ( String[ ] args ) {
foo ( null );
}

A

Compile-time error: The method foo(String) is ambiguous

As we are passing null object and both String and StringBuffer are essentially objects.

131
Q

Explain the output.

public static void foo ( String s ) {
System.out.println ( “String” );
}

public static void foo ( StringBuffer sb ){
System.out.println ( “StringBuffer” );
}

public static void main ( String[ ] args ) {
foo ( “Hey” );
}

A

String

As we are passing a string object and StringBuffer is not same as String object, it will call the foo( ) method with String argument.

132
Q

How many String objects were created:

String s1 = new String("Hello");  
String s2 = new String("Hello");
A

2.

With new operator, a new object will be created even if the same literal exists in the String pool.

133
Q

Explain Iterator interface.

A

An interface inside java.util package, the iterator provides methods to iterate over a collection. It is associated with Collection framework in Java.

It defines two main methods: hasNext( ) and next( ).

For eg. If we have a list of strings,

ArrayList fruits = new ArrayList( ){ {
			add("Apple");
			add("Banana");
			add("Cherry");
			add("Durian");
			} 
		};

Then we can obtain an iterator instance on it with iterator( ) method.

Iterator iterator = fruits.iterator( );

while(iterator.hasNext ( )) {
System.out.println(iterator.next ( ));
}

With iterator.remove( ), we can remove objects one-by-one from beginning of a collection while the iteration is in process.

Hence if we write

while(iterator.hasNext ( )) {
System.out.println(iterator.next ( ));
iterator.remove( );
}

It will print Apple and then remove it from the list. Then it will print Banana and remove it from the list.

134
Q

Explain Enumeration interface.

A

An interface inside java.util package, the Enumeration defines the methods by which one can enumerate the elements (obtain one at a time) from a collection. It is similar to iterator interface in concept, except enumeration is generic and iterator is associated with Collection framework.

It defines two main methods- hasMoreElements( ) and nextElement( ).

For eg. If we have a list of strings,

ArrayList fruits = new ArrayList( ){ {
			add("Apple");
			add("Banana");
			add("Cherry");
			add("Durian");
			} 
		};

Then we can obtain an enumeration instance on it with the help of utility class, Collections.

Enumeration basket = Collections.enumeration( fruits );

while(basket.hasMoreElements ( )) {
System.out.println( basket.nextElement ( ) );
}

135
Q

What is the difference between Enumeration and Iterator?

A

Both of them are interfaces in java.util package and do the same work but Enumeration is generic whereas Iterator is associated with Collection framework.

Enumeration is twice as fast as Iterator but Iterator provides thread safety.

Iterator provides a remove( ) method with which we can modify the collection during iteration. Enumeration acts as a read-only interface and we cannot manipulate the elements.

The methods in Enumeration are hasMoreElements( ) and nextElement( ) whereas in iterator they are named hasNext( ) and next( ).

136
Q

What is the difference between path and classpath?

A

PATH is an environment variable used by OS to locate the executables.

CLASSPATH is specific to Java and is used by JVM to locate Java class files.

137
Q

Which package is imported by default in Java projects?

A

java.lang package

138
Q

Can a class be declared private/protected/final/static?

A
  1. private: A top-level class cannot be declared private as it will not be accessible anywhere. Inner class can be private.
  2. protected: Protected class will be visible inside same package and to its subclasses outside package. This raises two problems:
  • If we need a protected class to be visible outside its package, we need to extend it. If all classes are allowed to extend this class then it is similar to declaring it public.
  • If the new class extends protected class, then it won’t be able to extend any other class.
    Hence top-level class cannot be declared protected. Inner class can be protected .
  1. final: a class can be declared final, restricting it being subclassed.
4. static: A top-level class cannot be declared static but an inner class can be.
Declaring something static means that it will belongs to the class as a whole, not to its object. This definition loses its meaning for a class getting declared static.
139
Q

Explain Java nested classes.

A

Java nested class is any class defined inside body of another class.

public class Main {
	class Domain{
	}
}

Java Nested classes are divided into two types: (1) static nested class and (2) java inner class.

All the nested classes declared static are of first type and rest are second type.

Java inner classes (type 2) are further divided into 2 types: local inner and anonymous inner.

140
Q

Explain static nested class.

A

If the nested class is static, then it’s called a static nested class. Static nested classes can access only static members of the outer class. A static nested class is the same as any other top-level class and is nested for only packaging convenience.

public class Animal{
private String name;
//getters and setters
static class Food{
private boolean herbivore;
//getters and setters
}
}

The static nested class will be accessed as:

Animal.Food dinner = new Animal.Food( );
dinner.setHerbivore( true );

There is no need to create object of top-level class first.

141
Q

Explain Java inner class.

A

If the nested class is not static, it is called Java inner class. Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.

Since inner classes are associated with the instance, we can’t have any static variables in them.

The object of java inner class is a part of the outer class object and to create an instance of the inner class, we first need to create an instance of outer class.

public class Animal {
private String name;
//getters and setters
class Food{
private boolean herbivore;
//getters and setters
}
}

The inner class will be accessed as:

 Animal elephant= new Animal();
Animal.Food dinner = elephant.new Food();
dinner.setHerbivore(true);
142
Q

Explain local inner class.

A

A type of Java inner class (meaning non-static nested class), this class is defined inside a method, hence local to the method.

Since they are not associated with object, local inner classes can only be default, abstract or final.

public class Animal {
private String name;
//getters and setters
public void eat( ){
class Food{
private boolean herbivore;
//getters and setters
}
}
}

The class Food can access all the members of class Animal and the method eat( ) in which it is defined. But the class Food cannot modify any of these variables as they are effectively final (if not declared final explicitly).

The local inner class can also be declared inside a static block or if-else block but its scope will be limited.

143
Q

Explain anonymous inner class.

A

A local inner class without name is called anonymous inner class. It is defined and instantiated in single statement.

Anonymous classes always either extend a class or implement an interface. Since anonoymous class has no name, it cannot have a constructor.

interface Food {
public String eat();
}

public class Animal {
private String name;
//getters and setters
Food dinner = new Food( ) {
		@Override
		public String eat( ) {
			return "meat";
		}
	};
}
144
Q

Can we access non-static members of outer class inside a static nested class?

A

No, we can only access static members of outer class inside static nested class.

145
Q

Can a Java inner class have static members in it?

A

Except for static final fields, Java inner classes cannot have static members in them.

146
Q

Can we access all the members of outer class inside a Java inner class?

A

Yes, we can access all the static/non-static and public/private members of outer class inside a Java inner class.

147
Q

Can we declare local inner classes as private/protected /public?

A

No, local inner classes can only be default, abstract or final.

148
Q

What is the main difference between static and non-static nested classes?

A

There is no need to instantiate the outer class to access static nested classes. But, to access non-static nested classes, instantiation of the outer class is must.

149
Q

Identify and correct the problem with below code.

class A
{
    class B
    {
        static void methodB()
        {
            System.out.println("Method B");
        }
    }
}
A

As class B is an inner class (which means it is non-static), it cannot have a static member in it (except for static final field).

150
Q

What will be the output of the following program?

class X{
static int x=3131;
static class Y{
static int y=x++;
static class Z{
static int z=y++;
}
}
}

public static void main(String[ ] args){
System.out.println(“Value of x:” + X.x);
System.out.println(“Value of y:” + X.Y.y);
System.out.println(“Value of z:” + X.Y.Z.z);
}

A

Value of x:3131
Value of y:3131
Value of z:3131

151
Q

Can a static nested class have non-static members in it?

A

Yes.

152
Q

How to access the count variable of class Color?

class Fruit {

	class Color{
		int hue=10;
	}

}

A

Fruit fruit= new Fruit( );

Fruit.Color color =fruit.new Color( );

System.out.println(color.hue);

OR

new Fruit( ).new Color( ).hue;

153
Q

Will the below program print “SUCCESS” when it is executed?

class A
{
    {
        new B();
    }
    static class B
    {
        {
            new A().new C();
        }
    }
    class C
    {
        {
            System.out.println("SUCCESS");
        }
    }
}
public class MainClass
{
    public static void main(String[] args)
    {
        new A();
    }
}
A

No.

new A( ) calls new B( ), but inside B’s constructor, we are again calling new A( ), making them dependent on each other. Hence the program will terminate with StackOverflowError.

154
Q

Identify and correct the problem with below code.

class A
{
    String s = "AAA";
    void methodA( )
    {
        System.out.println(s);
    }
    static class B
    {
        void methodB( )
        {
            methodA();
        }
    }
}
A

As class B is static, it won’t be able to access the non-static method methodA( ) of enclosing class and the code will give compilation error- Cannot make a static reference to the non-static method methodA() from the type B.

We need to first create an instance of class A and call methodA( ) with that instance.

For eg. new A( ).methodA( );

155
Q

Identify and correct the problem with below code.

abstract class A
{
    {
        System.out.println(1);
    }
    static
    {
        System.out.println(2);
    }
}
public class MainClass
{
    public static void main(String[] args)
    {
        A a = new A() { };
    }
}
A

There is no problem with the code and it will print
2
1