Basic Flashcards
Name the 4 OOP principles.
Abstraction
Polymorphism
Inheritance
Encapsulation
What is Polymorphism?
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).
Explain the types of Polymorphism.
- 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.
Can we overload static/final/private methods in same class?
Yes we can.
We cannot âoverrideâ static/final/private methods anywhere.
Can we override static/final/private methods of parent class?
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.
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 ( );
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).
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 ( ); } }
Compilation error (type mismatch) --------------------------- The object john is of type Employee (superclass) but referes to Manager (subclass), which violates the IS-A relationship.
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 ( ); } }
Although the reference variable of parent class is pointing to object of child class, the method leap ( ) does not exist for parent class.
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 ( ); } }
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.
Can we overload main() method?
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.
Why is method overloading not possible by changing only the return type of method?
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.
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); } }
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.
What is upcasting?
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.
What is Inheritance?
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 many superclasses can one subclass have?
Only one
Can a subclass act as a superclass to other classes?
Yes
Can a class be superclass of itself?
No
Can a subclass access private member of its superclass?
No
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 } }
1 is valid, 2 will give compile-time type mismatch error
What can you access with below objects?
- Superclass sup = new Superclass();
- Superclass sup = new Subclass();
- Subclass sub = new Subclass();
- Subclass sub = new Superclass();
- Objects defined by Superclass only
- Objects defined by Superclass only
- All the objects defined by Superclass and Subclass except Superclassâs private objects
- Compilation error (type mismatch: cannot convert from Superclass to Subclass)
How to access method of a superclass?
Using super.methodName()
Where should call to superclassâs constructor be placed?
On the first line inside subclassâs constructor
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(); } }
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 JVM determines which overridden method to be called at runtime?
From the type of object (not the type of reference variable)
Why do we use the keyword super()?
- To call superclassâs consructor because constructors are not members and hence not automatically inherited.
- To call superclassâs non-private member which is hidden by member of subclass
What happens when we do not explicitly call superclassâs parameterless constructor?
JVM will implicitly call superclassâs parameterless constructor
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(); } }
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.
Why isnât multiple inheritance not supported by Java?
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.
What is a literal?
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.
Why do we need to write L or F for long/float numbers ?
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.
Why does array indexing start with zero?
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.
Why are strings in Java immutable?
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.
Why is String class in Java declared final?
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.
Explain the difference between
- String s=âHello Worldâ
and
- String s= new String(âHello Worldâ)
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.
What is the difference between count++ and ++count?
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.
What is the difference between logical AND (&&) and bitwise AND (&) operators?
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.
Why does code (1) give compilation error but not code (2)?
- int val=50;
if (val=60) System.out.println(âYay!â); - boolean flag=false;
if (flag=true) System.out.println(âYay!â);
Because in code (2) the expression inside âifâ returns a boolean value eventually, which is accepted by the compiler.
What will be the output of given program?
public String foo (String s){
return âStringâ;
}
public String foo (Object o){
return âObjectâ;
}
foo (null) ;
String
As the compiler will pick the most specific method implementation, which here is the one accepting String parameter.
Why are the outputs of below two lines different?
long num1 = 1000606024365L; //31536000000
long num2 = 1000606024365; //1471228928
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.
What will be the output of given program?
public String foo (String s){
return âStringâ;
}
public String foo (String[] str){
return âArrayâ;
}
foo (null) ;
Compilation error (The method foo(String) is ambiguous)
What will be the output of given program?
public String foo (String s){
return âStringâ;
}
public String foo (String[] str){
return âArrayâ;
}
foo (âHelloâ) ;
String
Define Object.
A Java object is a combination of state and behaviour. State is given by the field in class and behaviour is provided by methods.
Define Class.
A Java class is a blueprint/template from which objects are created.
Define Interface.
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.
What is JVM?
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).
What is JRE?
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.
What is JDK?
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
What is the difference between JVM, JRE and JDK?
- 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.
Why is JVM called virtual machine? Whats the difference between JVM and VMWare?
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.
What is JIT?
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.
What makes Java platform independent?
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.
Is Java 100% object oriented?
No. Java utilizes the 8 primitive data types (byte, short, int, long, float, double, char and boolean) which are not objects.
What is constructor in Java?
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.
Can a constructor be final/abstract/static/private?
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).
Explain the access modifiers.
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
What is a wrapper class?
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.
What is autoboxing and auto-unboxing in Java?
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
What is abstract class?
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
What is the difference between machine code and byte code?
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.
What is Pass-by-value and Pass-by-reference? Which one of these is Java?
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.
What are the differences between == and equals method?
== 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.
What does ⊠in method parameter
public void foo (String ⊠s)
mean?
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â})
Explain output.
public static void main (String [ ] args){
int x = 10;
System.out.println (âThe value is â+x+x);
}
The value is 1010
=================================
When used in a string context, the + operator works as a concatenation operator.
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); } }
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
- 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.
- Then we create the object and this will trigger regular blocks to be called, firstly setting the value to 10 and then to 30.
- 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.
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( ) );
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.
- 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.
How do you chain constructors using this( )?
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).
Explain scope.
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:
- 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.
- The arguments that are passed to a method are available everywhere inside the method.
- The variables created inside a method are available from the point they are created, not before that.
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 ) ;
}
Compilation error
==========================
As the String variable model has not been initialized, it cannot be used.
If no imports are listed, which two packages can we still access?
- The current package
2. The java.lang package
Will this code compile?
import java.io.*;
package com.intertech.transport;
public class Truck {
}
No, the package statement must be the first statement in a file unless the class is in a default package
Will this code compile?
package com.intertech.*;
import java.util.*;
public class Person {
}
No, the package statement cannot have wildcard
What is classpath?
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.
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);
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.
Will the code compile?
switch (someVariable) {
String msg = âhelloâ;
case 0: msg = âworldâ;
break;
default: msg = âallâ;
}
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).
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 } }
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.
What is the difference between Inheritance and Polymorphism? Is Polymorphism possible without Inheritance?
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.
Why are default and no-arg constructors not same?
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.
What is singleton class in Java? How can we make a class singleton?
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; } }
What is the difference between ArrayList and Vector?
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%.
Explain Vector class.
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.
What is stack memory in Java?
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.
What is heap space in Java?
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.
How is stack memory different from heap space?
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.
Explain encapsulation principle in Java.
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.
Explain abstraction principle in Java.
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.
What is the difference between local variable and instance variable?
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.
What is the difference between String, StringBuilder and StringBuffer?
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.
Explain StringBuilder.
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.
Explain StringBuffer.
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.
Explain classloader in Java.
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.
Explain final keyword.
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.
Explain Collection hierarchy.
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.
What is Map in Java?
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.
What is collection in Java?
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.
What are the different types of inheritances?
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
What are the three types of relationships between Java objects?
Composition
Aggregation
Association
Explain Composition relation.
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,
Explain Composition relation.
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.
Explain Aggregation relation.
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.
Explain Association relation.
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.
What is UML diagram and cardinality?
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.
What is a marker interface?
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.
What is the difference between marker interface and typical interface?
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.
Explain Serializable.
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.
What is Serialization and Deserialization in Java?
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.
Explain Cloneable interface.
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.
What is object cloning?
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.
What are the two types of object cloning?
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.
What is a copy constructor in Java?
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; } }
What is the difference between Collection and Collections in Java?
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.
Explain the difference between abstract class and interface.
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.
Explain pass-by-value.
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
What is the difference between import and static import?
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.
When should the static imports be used?
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);
Explain the keyword: static.
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.
Explain the keyword: abstract.
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.
Explain the keyword: synchronized.
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.
Explain the keyword: volatile.
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.
Explain Comparable interface.
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.
Explain Comparator interface.
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.
What is the difference between Comparable and Comparator?
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.
Explain the finalize( ) method.
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.
What is enum?
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.
What is the difference between Stringâs substring( ) and subSequence( ) method?
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.
Explain Stringâs compareTo( ) method.
â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.
Can a string be used as expression in switch case?
From Java 7 onwards, a string can be used as a switch expression. For earlier versions, we will have to use if-else conditions.
What is string interning in Java?
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.
Why are string objects are mostly used as a hashmap key?
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.
Explain the output:
String s1 = "abc"; StringBuffer s2 = new StringBuffer(s1);
System.out.println( s1.equals ( s2 ) );
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.
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 );
}
Compile-time error: The method foo(String) is ambiguous
As we are passing null object and both String and StringBuffer are essentially objects.
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â );
}
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.
How many String objects were created:
String s1 = new String("Hello"); String s2 = new String("Hello");
2.
With new operator, a new object will be created even if the same literal exists in the String pool.
Explain Iterator interface.
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.
Explain Enumeration interface.
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 ( ) );
}
What is the difference between Enumeration and Iterator?
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( ).
What is the difference between path and classpath?
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.
Which package is imported by default in Java projects?
java.lang package
Can a class be declared private/protected/final/static?
- private: A top-level class cannot be declared private as it will not be accessible anywhere. Inner class can be private.
- 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 .
- 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.
Explain Java nested classes.
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.
Explain static nested class.
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.
Explain Java inner class.
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);
Explain local inner class.
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.
Explain anonymous inner class.
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"; } }; }
Can we access non-static members of outer class inside a static nested class?
No, we can only access static members of outer class inside static nested class.
Can a Java inner class have static members in it?
Except for static final fields, Java inner classes cannot have static members in them.
Can we access all the members of outer class inside a Java inner class?
Yes, we can access all the static/non-static and public/private members of outer class inside a Java inner class.
Can we declare local inner classes as private/protected /public?
No, local inner classes can only be default, abstract or final.
What is the main difference between static and non-static nested classes?
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.
Identify and correct the problem with below code.
class A { class B { static void methodB() { System.out.println("Method B"); } } }
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).
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);
}
Value of x:3131
Value of y:3131
Value of z:3131
Can a static nested class have non-static members in it?
Yes.
How to access the count variable of class Color?
class Fruit {
class Color{ int hue=10; }
}
Fruit fruit= new Fruit( );
Fruit.Color color =fruit.new Color( );
System.out.println(color.hue);
OR
new Fruit( ).new Color( ).hue;
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(); } }
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.
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(); } } }
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( );
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() { }; } }
There is no problem with the code and it will print
2
1