Adv Java Interview Questions

Top most important Adv Java interview questions and answers by Experts:

Here is a list of Top most important Adv Java interview questions and answers by Experts.If you want to download Adv Java interview questions pdf free ,you can register with RVH techguru. Our experts prepared these Adv Java interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in Adv Java ,Register for Adv Java online training here.

1) Explain run time polymorphism in Java ?
Polymorphism can be explained as an object’s ability to adapt to the program’s context and take multiple forms. The method overriding is an example of run time polymorphism. You can have a method in a subclass, which overrides the method in its super classes with the same name and signature. At run time, Java virtual machine determines the appropriate method to be called.
2) What are the rules (method access permission and exception) that needs to be followed, during method overloading and overriding ?

During method Overloading, method name should remain same. But method signature can vary. Components of signature that can vary are
• Number of arguments
• Datatype of arguments
• Order of arguments
During method Overriding, make sure that the method is not throwing checked exceptions that are new or higher than those declared by the overridden method.But we can’t override Static and Final methods.

3) What is the difference between an Interface and abstract class?
Abstract Interface
Supports Single inheritance Supports Multiple inheritance
Supports abstract and Non-abstract methods Allows only abstract methods
Supports Non-static and non-final variables also. Variables must be static and final(implicitly)
Supports non public member Only public members are allowed
Using extends keyword Using implements keyword
It can invoke if main exists Pure abstract
Faster Flexible
4) Explain the difference between compile time and run time polymorphism in Java ?
Compile time Polymorphism Run time Polymorphism
Method are called at compile time Method are called at run time
Ex: Overloading Ex: Overriding
5) What is the difference between Overloading and Overriding ?
Overloading Overriding
Methods are overloaded during compile time Method overriding takes place during runtime
All the overloaded methods should be placed in the same class We can override methods in sub class
We can overload static methods Static methods can’t be overridden
Methods are bonded together using static binding. Overridden method are bonded via dynamic bonding based upon actual Object.
To overload a method, method signature needs to be changed There is no need to change the signature
Private and final method can be overloaded. Private and final method can’t be overridden
Method is relatively fast. Method is relatively slow.
6) What is the difference between class and object ?
Class Object
Template/Blue print of an object. It is an instance of a class. Object have states and behaviors.
A logical construct. A Physical reality.

7) What are the major object oriented concepts in Java ?
Abstraction
It denotes the critical properties of an object which differentiate from other object and thus provide crisply defined conceptual boundaries relative to the perspective viewer.

Encapsulation
Encapsulation can be explained as a mechanism which binds the code and the data it manipulates. It also keeps them safe from external intervention and misuse.

Inheritance:
One object inherits the properties and methods of another Object.

Polymorphism
It is an ability of an object to take on many forms. Ex: Compile time polymorphism – method over loading. Run time polymorphism – method overriding

8) Why Java is not supporting multiple inheritance ?

Main features of java are very Simple. if multiple inheritance is supported, it creates ambiguity around Diamond problem and it does complicate the design and creates problem during casting, chaining etc. So Java will support multi-inheritance via single inheritance with interfaces to overcome above issues.

9) What is meant by final keyword in Java ?
• If final variable is used in front of variable, we can’t change the value.
• If the variable is used in front of method, it can’t be overridden.
• If it is used in front of Class, class can’t be extended by any other class.

10) What is meant by static keyword in Java ?

A static is a member of a class that’s not associated with instance. So static members can be accessed without creating an instance of a class.
11) What is meant by JVM ?
JVM(Java Virtual Machine) is a run time environment for the compiled java class files. Main function of JVM is to convert byte code(.class file) to machine code and send appropriate commands to underlying machine for execution.
12) Can abstract class implements another interface ?
Yes. It’s just a special case of implementation by which subclasses are forced to implement the methods.
13) Can abstract class extend another abstract class?
Yes. It is perfectly valid for an abstract class to extend another abstract class.
14) Can a interface extend another interface?
Yes. An interface can extend another interface in Java.
15) What Is Stack?
• Each Java thread have a private JVM stack, created along with thread.
• Stack stores frames. Frames are used for storing data (Variable and Object Data as well as partial results) and to perform operations such as
o Dynamic linking
o Dispatch exceptions when error occurs
o Return values when methods are invoked. Since the stack can’t be accessed directly, it push and pop frames.
• It is not mandatory that the Java virtual machine stack had to be continuous.
• JVM throws StackOverflowError, if any computation inside a thread needs larger JVM stack than allocated .

16) What Is Heap?
• When JVM starts, heap is created
• Heap is the runtime data area of the JVM
• It is shared by all the threads inside the JVM
• It allocates memory for all class instances and arrays
• Heap storage for objects is reclaimed by garbage collector when it is not used.
• JVM throws OutOfMemoryError, If a computation needs more heap than what can be supplied by the automatic storage management system.

17) Can you explain about Upcasting and Downcasting in Java ?
• Upcasting : Casting a Sub class to Super class. Upcasting is called as widening.
• Downcasting : Casting a Super class to Sub class. Downcasting is called as narrowing.

18) Can you explain about Implicit and Explicit type casting ?

Implicit casting (widening conversion) :

When JVM encounters a data type of lower size which occupies less memory, it is assigned to a data type of higher size implicitly by the JVM. This is also known as automatic type conversion. For Example
int i = 1; // 4 bytes
double d = i; // 8 bytes

Explicit casting:

When a data type of higher size which occupies more memory, needs to be assigned to a data type of lower size, it is called explicit casting. This type of casting won’t be done implicitly by the JVM. This casting operation should be performed by the programmer. For example
double d = 1.0;
int i = (int) d;

19) Can you explain about markable interface in Java ?
Interfaces with no methods are known as Marker interface. Some of the markable interfaces are
java.lang.Cloneable
java.io.Serializable
java.util.EventListener
20) Can you explain about reflection in Java ?

If a programmer wants to access entities or invoke methods in a program dynamically, i.e. if the programmer is unaware of the methods and variables that needs to be invoked at runtime but unaware of it while coding, we can use reflection. For example
Method method = ABC.getClass().getMethod(“doSomething”, null);
method.invoke(ABC, null);
21) Can you explain about java.lang.class ?

When JVM creates an instance of a class, it creates an object “java.lang.Class object” which describes the type of the object. This class object is shared by all the objects of a class. If you want to access the class object of an instance, use getClass() method of the object. This method is inherited from java.lang.Object
Ex: Created two instances class called Programmer
Programmer A = new Programmer();
Programmer B = new Programmer();
// For check Instances
if(A.getClass() == B.getClass())
{
System.out.println(“A and B are instances of same class”);
}else{
System.out.println(“A and B are instances of different class”);
}

22) Can you explain about Singleton class in Java ?

Singleton class is used to control no of object created for a class, limiting the number to one. But if the situation changes in future, it allows to create more objects without affecting existing clients.
23) Can you explain about Static class in Java ?

A class can be made static provided that the class is a nested class. A nested class is class which is defined inside a class. But top class can’t me made static. Example :
public class Test
{
static class StaticInnerClass
{
public static void innerMethod()
{ System.out.println(“Static Inner Class!”); }
}
public static void main(String args[])
{
Test.StaticInnerClass.innerMethod();
}
}

24) Can you explain about volatile Keywords in Java ?
• Volatile keyword is used to indicate the threads using a common variable that, the variable which is declared as Volatile can be updated by multiple threads. So threads should not cache the threads locally and in turn should get the value for the variable from main memory.
• If a variable is declared as volatile, it won’t be serialized.

25) What are the advantages of organizing classes and interfaces into a package ?
• Determination of a category of a file is simplified.
• Name space collision is avoided.
• Access restriction can be applied with the use of packages.
• Packages provide reusability of code

26) Can you explain about Java naming convention ?

Common Naming conventions as below :
• package names always start with lowercase characters. Ex: java.util
• Class names always begin with a capital letter and followed next word start with a capital letter. Ex: GregorianCalendar
• Java Naming convention specifies that instances and other variables must start with lowercase followed next word should be capital letter. Ex : MyClass myClass = new MyClass();
• Constant variables are declared using “static final” modifiers. And such variables must contain only UpperCase charachters and multiple words must be seperated using ‘_’. Ex: static final char END_OF_FILE = ‘e’;
• Methods in Java also follow the same like Objects and variables. For example
void myMethod(){
String strVal = “ABCD”;
}
27) How to call a garbage collector in java?
System.gc() or Runtime.getRuntime().gc().

28) What are the new features available in Java 1.7 ?
• Strings in switch Statement
• Type Inference for Generic Instance Creation
• Multiple Exception Handling
• Support for Dynamic Languages
• Try with Resources
• Java nio Package
• Binary Literals, underscore in literals
• Diamond Syntax
• Automatic null Handling

29) What are the advantage of Inheritance in Java ?
• Re-usability : Inheritance helps derived class to use methods of base class without rewriting them
• Extensibility : Extending the base class logic as per business logic of the derived class
• Data hiding : Allows base class to keep some private data which can’t be altered by the derived class
30) Why String is immutable in Java ?
 String is a special type of immutable class. Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can’t be changed once constructed.
 
31) Can you explain about information hiding in Java ?

Information hiding helps objects to hide critical information from other other objects accessing it. It effectively decouples the method being invoked from the internal workings of a function. By doing so, object can change the hidden portions of the function without changing the calling code. Encapsulation is a common technique programmers use to implement information hiding.
32) Can you explain about encapsulation in Java ?

Encapsulation helps java to bind code and data it manipulates, restrict outside interference and misuse of data. It also hides irrelevant details of an object.
33) Can you explain about the access modifier in Java ?

Access modifiers specifies the access levels of a variable or method. Java access modifiers are public, private, protected, default modifier (Default access modifier).
Access Modifiers Same Class Same Package Subclass Other packages
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

34) What is the difference between super() and this() in Java ?
If you want to access methods of the base class from derived class “super” keyword is used. To access methods of the same class “this” keyword is used.

35) Can you explain about the constructor in Java ?
• Java constructors are special methods that are called when an object is instantiated.
• When objects are instantiated, arguments passed to the constructor will initialized the variables in an object.
• Name of the constructor should be same as the name of the Class. It can’t have any return type.
• A class can have multiple constructors. Calling a constructor from another constructor in the same class is called Constructor chaining.
• All classes have a default empty constructor.

36) Can constructor take parameters ?

Yes. Constructor can take arguments.

37) Can you explain about the default constructor in Java ?

When a constructor is not specified explicitly, java compiler automatically creates a “Default Constructor”. When we creates and object instance, default constructor initialize variables with it’s default values.

38) What are the common reasons to define a default constructor ?
• To construct an object with default values.
• To initialize an object that doesn’t need parameters in that initialization process.
• To redefine the scope of the constructor. By making the default constructor private, Java prevents everyone other than the class from constructing an object.

39) Can you explain about native method in Java ?
• Native is non access modifier. It can be applied only to method.
• It indicates the Platform-Dependent implementation of method or code.

40) Can you explain about strictfp keyword in Java ?
If we want floating point values to be consistent across platforms, then we need to use “strictfp”as per IEEE 754 standard. When a program runs on multiple platforms, precision of floating point differ which in turn given different results. strictfp helps to enforce the precision across all platforms. For example
Class Level – public strictfp class StrictFpModifierExample{}
Method Level – public strictfp void example() {}

41) Can you explain about String pool ?

String Pool is a pool of strings stored in Java heap memory. String objects can be created either by new operator or by specifying the values in double quotes.
Case 1 : When a new string is created using double quotes, JVM searches string pool for the string with the same value. if it finds a string which matches the values, it will return the reference of the string. Else it will create a new string in the pool and returns that reference.
String s1 = “Cat”;
String s2 = “Cat”;
if(s1 == s2) System.out.println(“equal”); //Prints equal.
Case 2 : When new operator is used to create a string, String class will be forced to create a new String object. To put the newly created string into the pool or assign it to another string, use intern().
String n1 = new String(“ABCD”);
String n2 = new String(“ABCD”);
if(n1 == n2) System.out.println(“equal”); //No output.

42) Differences between String, StringBuffer and StringBuilder in Java ?

String StringBuffer StringBuilder
Immutable Mutable mutable
String operations such as append would be less efficient String operations such as append would be more efficient, String operations such as append would be more efficient
– synchronized Not synchronized.
– versions 1.4 or below you’ll have to use StringBuffer. StringBuilder was introduced in Java 1.5

43) What are the advantage of using unicode characters ?
• Much larger number of characters or group of characters
• Contains some non western European characters
• Supported by all modern technologies
• Enhance integration opportunities
• Easy conversion from legacy code pages

44) Can you explain about literals in Java ?

Literals are used to represent a fixed value in source code. Literals don’t require computation. For Example, we will have a look at using literals to assign a value to an int variable.
int Days = 7;
45) Is it possible to override an overloaded method in Java ?
Yes. We can override an overloaded method if that method in not a static or final.

46) What is the maximum size of an int ?

-(2 power 31) to (2 power 31-1) or -2,147,483,648 to 2,147,483,647

47) Can you explain about autoboxing and unboxing in Java ?

When primitive data types are automatically converted into it’s wrapper type, it is called boxing. The opposite operation of converting wrapper class objects to it’s primitive type is known as unboxing.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); //autoboxing – primitive to object
int number = list.get(0); // unboxing

48) How to change the heap size of a JVM ?

The old generation’s default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
Format – java -Xms <initial size> -Xmx <maximum size> program
Example – java -Xms64m -Xmx128m Myprogram
49) Is it possible to have multiple public classes in Java ?
As per java language specification, there can be only one public class in a file (.java) and file name should be same as public class name. If you want another class accessible in other places, you may create a separate java file.
50) What are Variable Arguments or varargs?
Variable Arguments allow calling a method with different number of parameters. Consider the example method sum below. This sum method can be called with 1 int parameter or 2 int parameters or more int parameters.
//int(type) followed … (three dot’s) is syntax of a variable argument.
public int sum(int… numbers) {
//inside the method a variable argument is similar to an array.
//number can be treated as if it is declared as int[] numbers;
int sum = 0;
for (int number: numbers) {
sum += number;
}
return sum;
}

public static void main(String[] args) {
VariableArgumentExamples example = new VariableArgumentExamples();
//3 Arguments
System.out.println(example.sum(1, 4, 5));//10
//4 Arguments
System.out.println(example.sum(1, 4, 5, 20));//30
//0 Arguments
System.out.println(example.sum());//0
}
51) What are Asserts used for?
Assertions are introduced in Java 1.4. They enable you to validate assumptions. If an assert fails (i.e. returns false), AssertionError is thrown (if assertions are enabled). Basic assert is shown in the example below
private int computerSimpleInterest(int principal,float interest,int years){
assert(principal>0);
return 100;
}
52) When should Asserts be used?
Assertions should not be used to validate input data to a public method or command line argument. IllegalArgumentException would be a better option. In public method, only use assertions to check for cases which are never supposed to happen.
53) What is Garbage Collection?
Garbage Collection is a name given to automatic memory management in Java. Aim of Garbage Collection is to Keep as much of heap available (free) for the program as possible. JVM removes objects on the heap which no longer have references from the heap.
54) Can you explain Garbage Collection with an example?
Let’s say the below method is called from a function.
void method(){
Calendar calendar = new GregorianCalendar(2000,10,30);
System.out.println(calendar);
}
An object of the class GregorianCalendar is created on the heap by the first line of the function with one reference variable calendar.
After the function ends execution, the reference variable calendar is no longer valid. Hence, there are no references to the object created in the method.
JVM recognizes this and removes the object from the heap. This is called Garbage Collection.
55) When is Garbage Collection run?
Garbage Collection runs at the whims and fancies of the JVM (it isn’t as bad as that). Possible situations when Garbage Collection might run are
• when available memory on the heap is low
• when cpu is free
56) What are best practices on Garbage Collection?
Programmatically, we can request (remember it’s just a request – Not an order) JVM to run Garbage Collection by calling System.gc() method.
JVM might throw an OutOfMemoryException when memory is full and no objects on the heap are eligible for garbage collection.
finalize() method on the objected is run before the object is removed from the heap from the garbage collector. We recommend not to write any code in finalize();
57) What are Initialization Blocks?
Initialization Blocks – Code which runs when an object is created or a class is loaded
There are two types of Initialization Blocks
Static Initializer: Code that runs when a class is loaded.
Instance Initializer: Code that runs when a new object is created.
58) What is a Static Initializer?
Look at the example below:Code within static{ and } is called a static initializer. This is run only when class is first loaded. Only static variables can be accessed in a static initializer. Even though three instances are created static initializer is run only once.
public class InitializerExamples {
static int count;
int i;

static{
//This is a static initializers. Run only when Class is first loaded.
//Only static variables can be accessed
System.out.println(“Static Initializer”);
//i = 6;//COMPILER ERROR
System.out.println(“Count when Static Initializer is run is ” + count);
}

public static void main(String[] args) {
InitializerExamples example = new InitializerExamples();
InitializerExamples example2 = new InitializerExamples();
InitializerExamples example3 = new InitializerExamples();
}
}
Example Output
Static Initializer
Count when Static Initializer is run is 0
59) What is an Instance Initializer Block?
Let’s look at an example : Code within instance initializer is run every time an instance of the class is created.
public class InitializerExamples {
static int count;
int i;
{
//This is an instance initializers. Run every time an object is created.
//static and instance variables can be accessed
System.out.println(“Instance Initializer”);
i = 6;
count = count + 1;
System.out.println(“Count when Instance Initializer is run is ” + count);
}

public static void main(String[] args) {
InitializerExamples example = new InitializerExamples();
InitializerExamples example1 = new InitializerExamples();
InitializerExamples example2 = new InitializerExamples();
}

}
Example Output

Instance Initializer
Count when Instance Initializer is run is 1
Instance Initializer
Count when Instance Initializer is run is 2
Instance Initializer
Count when Instance Initializer is run is 3

60) What are Regular Expressions?
Regular Expressions make parsing, scanning and splitting a string very easy. We will first look at how you can evaluate a regular expressions in Java – using Patter, Matcher and Scanner classes. We will then look into how to write a regular expression.
61) What is Tokenizing?
Tokenizing means splitting a string into several sub strings based on delimiters. For example, delimiter ; splits the string ac;bd;def;e into four sub strings ac, bd, def and e.
Delimiter can in itself be any of the regular expression(s) we looked at earlier.
String.split(regex) function takes regex as an argument.
62) Can you give an example of Tokenizing?
private static void tokenize(String string,String regex) {
String[] tokens = string.split(regex);
System.out.println(Arrays.toString(tokens));
}

tokenize(“ac;bd;def;e”,”;”);//[ac, bd, def, e]

63) How can you Tokenize using Scanner Class?
private static void tokenizeUsingScanner(String string,String regex) {
Scanner scanner = new Scanner(string);
scanner.useDelimiter(regex);
List<String> matches = new ArrayList<String>();
while(scanner.hasNext()){
matches.add(scanner.next());
}
System.out.println(matches);
}

tokenizeUsingScanner(“ac;bd;def;e”,”;”);//[ac, bd, def, e]
64) How do you add hours to a date object?
Lets now look at adding a few hours to a date object. All date manipulation to date needs to be done by adding milliseconds to the date. For example, if we want to add 6 hour, we convert 6 hours into millseconds. 6 hours = 6 * 60 * 60 * 1000 milliseconds. Below examples shows specific code.
Date date = new Date();

//Increase time by 6 hrs
date.setTime(date.getTime() + 6 * 60 * 60 * 1000);
System.out.println(date);

//Decrease time by 6 hrs
date = new Date();
date.setTime(date.getTime() – 6 * 60 * 60 * 1000);
System.out.println(date);