Top Java Interview Questions and Answers for Experienced Programmers
If you haven't checked the Basic and Intermediate java Interview questions, then you can check them out here. In this tutorial, we are going to take a look at more advanced java programming questions that you might need for your next Java Programming Interview.
You can read each of these 30 questions and prepare for your next interview. All the Best!
1. Is the Empty .java file name a valid source file name?
You can save your Java program with just .java only. You will need to compile it by javac .java and run it by the java class name.
2. What is Polymorphism?
Polymorphism allows us to perform a single task in different ways. "poly and "morphs" are two greek words that form polymorphism and mean different forms.
3. What are the 2 types of polymorphism in Java?
Polymorphism in Java has 2 types-
- Compile-time Polymorphism
- Runtime polymorphism
4. What is Runtime Polymorphism?
Runtime polymorphism also called dynamic method dispatch is a process that calls an overridden method resolved at runtime instead of compile time. It calls an overridden method through the reference variable of a superclass.
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
running safely with 60km.
5. Can you achieve Runtime Polymorphism by data members?
Data Members cannot be overridden and method overriding is used for runtime polymorphism. You can override the member functions but cannot the data members. No, you can't achieve runtime polymorphism by data members.
6. What is the output of this program?
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
90
7. What is Multithreading in Java
Thread is a small unit of a process and Multithreading in Java allows us to run multiple threads simultaneously. The process is heavyweight, takes more memory, and occupies the CPU for a longer time which may lead to a performance issue with the system. To overcome these issue process is broken into small units of independent sub-process. This sub-process is called threads that can perform the independent task efficiently. So nowadays computer systems prefer to use thread over the process and use multithreading to perform multitasking. Learn More.
8. What is the output of the following Java program?
class BaseTest
{
void print()
{
System.out.println("BaseTest:print() called");
}
}
public class Test extends BaseTest
{
void print()
{
System.out.println("Test:print() called");
}
public static void main (String args[])
{
BaseTest b = new Test();
b.print();
}
}
Test:print() called
9. What is Java instanceOf operator?
The Java instanceOf operator is a logical operator that evaluates to true if the object on the left-hand side of the expression refers to a class (or interface) that is either the same or an ancestor of the type on the right-hand side.
This operator is mostly used when we want to determine whether one object belongs to another, also known as type casting.
look at the following example-
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
true
10. What is Abstraction?
Abstractions allow us to hide the implementation details and show the functionality to the user. It displays only the necessary information to the users and hides the rest.
Abstraction shows what the object does and hides how it does it from the user. There are two ways to do this-
11. What is the abstract class?
A class that is declared using an abstract keyword is known as an abstract class. An abstract class may or may not have abstract methods. We cannot create objects of an abstract class.
It is used to achieve abstraction but it does not provide 100% abstraction because it can have concrete methods.
Syntax-
abstract class class_name { }
12. Why Use Wrapper Classes?
As we knew that in Java when input is given by the user, it is in the form of a String. To convert a string into different data types, Wrapper classes are used.
We can use wrapper class each time when want to convert primitive to object or vice versa. Learn More. Consider the following example-
class WrapperPrimitiveDemo1
{
public static void main(String[] args)
{
Integer a = new Integer(12);
System.out.println("Old value = "+a);
xyz(a);
System.out.println("New Value = "+a);
}
private static void xyz(Integer a)
{
a = a + 10;
}
}
Output:

13. What is the output of the following program?
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
running safely
14. Is the following program written correctly? If yes then what will be the output of the program?
abstract class Calculate
{
abstract int multiply(int a, int b);
}
public class Main
{
public static void main(String[] args)
{
int result = new Calculate()
{
@Override
int multiply(int a, int b)
{
return a*b;
}
}.multiply(12,32);
System.out.println("result = "+result);
}
}
384
Ans: The program is correct. The definition of abstract class multiply is declared in the abstract class Calculation
15. Where will you use charAt()
method?
String charAt()
the function returns the character located at the specified index. Learn more methods of String Handling here. Consider the following example-
public class Demo {
public static void main(String[] args) {
String str = "studytonight";
System.out.println(str.charAt(2));
}
}
u
16. What are the methods of file class?
S.no. |
Method |
Description |
1 |
createTempFile(String prefix, String suffix) |
It is used to create an empty file. |
2 |
createNewFile() |
It is used for creating a new file, which is empty and has an abstract pathname. |
3 |
canWrite() |
It is used to check whether the application can modify a file that has an abstract path. |
4 |
canExecute() |
It is used to check whether the application can execute a file that has an abstract path. |
5 |
canRead() |
It is used to check whether the application can read a file that has an abstract path |
6 |
isAbsolute() |
It is used to check whether the abstract pathname is absolute or not. |
7 |
isDirectory() |
It is used to check whether the file with abstract pathname is a directory. |
8 |
isFile() |
It is used to check whether the file with abstract pathname is a file. |
9 |
getName() |
It is used to get the name of the file. |
10 |
getParent() |
It is used to get the name of the Parent file |
11 |
toPath() |
It is used to get objects of java.nio.file.Path. |
12 |
toURI() |
It is used to create a URL of a file with an abstract pathname. |
13 |
listFiles() |
It is used for getting an array of the abstract pathname. |
14 |
getFressSpace() |
It is used for getting the number of unallocated bytes. |
15 |
list(FilenameFilter filter) |
It is used for getting an array of strings with the name of the file which has an abstract pathname. |
16 |
mkdir() |
It is used to create a directory name. |
17. What is the difference between throw and throws keyword?
throw keyword |
throws keyword |
1) The throw keyword is used to throw an exception explicitly. |
The throws keyword is used to declare an exception. |
2) The checked exceptions cannot be propagated with throw only. |
The checked exception can be propagated with throws |
3) The throw keyword is followed by an instance. |
The throws keyword is followed by class. |
4) The throw keyword is used within the method. |
The throws keyword is used with the method signature. |
5) You cannot throw multiple exceptions. |
You can declare multiple exceptions |
18. What is the output of the following Java program?
public class Main{
public static void main(String []args){
try
{
throw 90;
}
catch(int e){
System.out.println("Caught the exception "+e);
}
}
}
Main.java:6: error: incompatible types: int cannot be converted to Throwable
throw 90;
^
Main.java:8: error: unexpected type
catch(int e){
^
required: class
found: int
2 errors
19. What is exception propagation?
Exception propagation is an action taken or an event that occurs when an exception has been thrown and not caught within the code. It allows developers to propagate an exception throughout the call stack, enabling them to get more detailed information about what caused the exception.
Exception propagation propagates exceptions up the call stack without allowing any throwing after it has been done. Throwing an exception again would be equivalent to not using exception propagation at all.
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
exception handled
normal flow...
20. What is the output of the following Java program?
public class Main
{
void a()
{
try{
System.out.println("a(): Main called");
b();
}catch(Exception e)
{
System.out.println("Exception is caught");
}
}
void b() throws Exception
{
try{
System.out.println("b(): Main called");
c();
}catch(Exception e){
throw new Exception();
}
finally
{
System.out.println("finally block is called");
}
}
void c() throws Exception
{
throw new Exception();
}
public static void main (String args[])
{
Main m = new Main();
m.a();
}
}
a(): Main called
b(): Main called
finally block is called
Exception is caught
21. Name some classes present in java.util.regex package.
Here are the classes and interfaces present in java.util.regex package-
- MatchResult Interface
- Matcher class
- Pattern class
- PatternSyntaxException class
22. What is the purpose of toString() method in Java?
The purpose of toString() method in Java is to convert any object into a serialized string representation. if you want to print an object, the java compiler calls the toString() method on that object. You can return the values of the object by overriding the toString() method of the object class.
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
101 Raj lucknow
102 Vijay ghaziabad
23. Write a Java program to count the number of words present in a string?
public class Test
{
public static void main (String args[])
{
String s = "Sharma is a good player and he is so punctual";
String words[] = s.split(" ");
System.out.println("The Number of words present in the string are : "+words.length);
}
}
The Number of words present in the string are : 10
24. Write a regular expression to validate a password. A password must start with an alphabet and follow by alphanumeric characters; Its length must be between 8 to 20.
Regular expressions are used to specify patterns of characters. The regular expression to validate a password will be ^[a-zA-Z][a-zA-Z0-9]{8,19}. This pattern has ^ which represents the start of the regex. [a-zA-Z] represents that the first character must be an alphabet, [a-zA-Z0-9] represents numbers and alphanumeric characters, and {8,19}represents the length of the password.
25. What is the output of the following Java program?
import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(".s", "as")); //line 4
System.out.println(Pattern.matches(".s", "mk")); //line 5
System.out.println(Pattern.matches(".s", "mst")); //line 6
System.out.println(Pattern.matches(".s", "amms")); //line 7
System.out.println(Pattern.matches("..s", "mas")); //line 8
}}
true
false
false
false
true
26. What is a nested class?
Nested Class is a class that can be defined inside another class or interface. You can use these nested classes to group classes and interfaces, it will be in a more readable format. The nested class can access all data members of the outer class including private members and methods.
the syntax for nested classes-
class Java_Outer_class{
//code
class Java_Nested_class{
//code
}
}
27. What are the types of inner classes (non-static nested classes) used in Java?
There are 3 types of inner classes in java-
Type |
Description |
Member Inner Class |
A Member class is created within the class and outside method. |
Anonymous Inner Class |
An Anonymous Inner class is used to implement an interface. |
Local Inner Class |
A Local Inner class is created within the method. |
28. What is the output of the following program?
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
nice fruits
29. What is Garbage Collection?
Garbage collection is an automatic process that manages the creation of objects, allocation of various memory chunks, their release when they are no longer needed, and eventually, the freeing up of memory space.
It is an important process that determines how quickly your application will run, how much memory it will use, and whether or not there will be any errors. Look at the following example-
Demo demo = new Demo();
demo = null; // ready for garbage collection
We've set null to the object reference which makes it able for garbage collection.
Demo demo = new Demo();
Demo demo2 = new Demo();
demo2 = demo // referring object
As you can see above, you can set a new reference to make it non-reference an object.
30. How can an object be unreferenced?
There are 3 ways to unreferenced an object, they are-
- By nulling the reference
- By assigning a reference to another
- By anonymous object etc.