100+ Core Java Interview Questions And Answers-
Are you preparing for a service-based company like TCS, Infosys, Mindtree, etc? and you want to know the type of questions? then you are in the right place.
These are the most important question that the interviewer will ask you in your technical interview.
Unlike other sites this section will not contain Questions like what is java, difference between JRE JDK, etc.
In this section you will get actual interview questions.
Core Java Interview Questions
Core Java|OOps Concepts Related Questions
Q1. What is OOPs and OOPs Concepts?
Ans :Object-Oriented Programming System (OOps) is model in programming languages based on concepts of objects and classes.
OOps concepts are:
- Abstraction
- Inheritance
- Polymorphism
- Encapsulation
Q2. Explain Abstraction In the real world?
Ans: Abstraction refers to the act of representing essential features without including the background details(complexities).
In simple terms hiding complexities and displaying necessary details only.
In real world take an example of online banking transaction where end user are shown only User interface of Payments gateways and complexities that is how actual transaction and operations is been performed are kept hidden from end user. This what abstraction is.
Q3. Code to Achieve Abstraction
/*
code for Abstraction */
abstract class OnlineBank{
abstract int displaybalance();
}
class SavingAccount extends OnlineBank{
int displaybalance(){
return 50000;
}
class CurrentAccount extends Onlinebank{
int displaybalance(){
return 150000;
}
class main{
OnlineBank b =new SavingAccount();
System.out.println("Balance in Saving Account="+b.displaybalance()+"Rs");
OnlineBank b =new CurrentgAccount();
System.out.println("Balance in Current Account="+b.displaybalance()+"Rs");
}
}
Output:
Balance in Saving Account= 50000 Rs
Balance in Current Account= 150000 Rs
Q4. Can we declare Abstract method without using abstract class?
Ans:No, if there is a abstract method they must be declare in abstract class.
Q5. Difference between Abstract class and Interface?
Abstract Class | Interface |
---|---|
Abstract class can only have a method body. | Interface can only have abstract methods. |
Abstract class can have constructors | Interface cannot have constructors. |
Members of Abstract class can be public private protected | Members of Interface are public by default. |
Abstract keyword is used to declare class as Abstract. | Interface keyword is used to declare an Interface. |
Q6. What is inheritance, list its Types?
Ans: Inheritance is the process by which one class acquires properties of other class. or mechanism of deriving new class from old class is called as Inheritance.
Types of Inheritance-
- Single
- Multilevel
- Hierarchical
- Hybrid
- Multiple
Q7. Is Multiple Inheritance Supported in Java if No Why, And if Yes How?
No, Java not supports Multiple Inheritance. Because it leads to the diamond problem.
Since multiple inheritance is not supported in java classes, but with the help of interface we can achieve multiple inheritance.
Q8. Code to achieve Multiple Inheritance?
/* Code To Achieve Multiple Inheritance */
interface A{
void showa();
}
interface B{
void showb();
}
class C implements A,B{
public void showa()
{
System.out.println("I Am In A");
}
public void showb()
{
System.out.println("I Am In B");
}
}
class multiple{
Public static void main(String args[]){
C c= new C();
c.showa();
c.showb();
}
}
Output:
I Am In A
I Am In B
Q9. What is Polymorphism and its types?
Ans: Polymorphism in java is a concept by which we can perform single action by different means/ways. Polymorphism is the Greek word in which poly means many and morph means form hence many forms.
There Are two Types of Polymorphism:-
- Compile time- Achieved by Method Overloading.
- Run Time- Achieved by Method Overriding.
Q10. Code to implement Method Overloading?
/*
Java Program to implement Method Overloading */
class Area{
int area(int side){
return(side*side);
}
double area(double circle){
return(3.14*radius*radius);
}
int area(int len,int wid){
return(len*wid);
}
class Shape{
public static void main(String args[]){
Area s=new Area();
System.out.println("Area of Square:"+s.area(5));
System.out.println("Area of circle:"+s.area(10.2));
System.out.println("Area of Rectangle:"+s.area(10,2));
}
}
Output:
Area of Square: 25
Area of circle: 326.685
Area of Square: 20
Q11. Code to implement Method Overriding?
/*Code to implement Method Overiding */
class A{
public void show(){
System.out.println("I am in A");
}
}
class B extends A
{
public void show()
{
super.show();
System.out.println("I am in B");
}
}
class Inherits{
public static void main(String args[]){
B b1= new B();
b1.show();
}
}
Output:
I am in A
I am in B
Q12. Difference between Method Overloading and Method Overriding?
Method Overloading | Method Overriding |
---|---|
In Method Overloading,Methods of same class shares the same name but each method must have different parameter. | In Method Overriding sub class have the same methods with same name and exactly same number and types of parameters |
It is a compile time polymorphism. | It is a run time polymorphism. |
May or may require Inheritance to implement method overloading. | Always requires Inheritance to implement method overriding. |
Q13. What is upcasting and downcasting in java?
i. When a reference variable of parent class refers to the object of child class,it is known as Upcasting.Converting a subclass to super class type.
reference variable of parent class—–>object of child class
ii.Converting Super class type to sub class is know as downcasting.
Q14. Write a Code to Explain Upcasting in Java?
/*
Java Program to demonstrate Upcasting in Java */
class Parent{
void example(){
System.out.println("In a Method of parent class");
}
}
public class Base extends Parent{
void example(){
System.out.println("In a Method of parent class");
}
public static void main(String args[]){
Parent p=(Parent) new Base();
p.example();
}
}
Q15. Write a code to Explain Downcasting in Java?
/*
Java Program to demonstrate Downcasting in Java */
class Parent{
void example(){
System.out.println("In a Method of parent class");
}
}
public class Base extends Parent{
void example(){
System.out.println("In a Method of parent class");
}
public static void main(String args[]){
Parent P= new Base()
Sub sub=(Sub) P ;
sub.example();
}
}
Q16. Differentiate Between Constructor and Methods?
Constructor | Methods |
---|---|
Constructors are the special methods whose tasks is to initialize object of its class. | Method are the set of instruction that are called at any given point during our program execution. |
Constructors don’t have return type. | It has return type. |
Constructor cannot be declared as final. | Method can be declared as final. |
The Name of constructor must be same as class name | Method Name can be any. |
Q17. What is the Static Variable in Java?
Ans: Static Variables are the variables, we assign memory only once at the time of class loading. Using a Static variable it makes your program efficient as it saves memory.
Q18. Demonstrate the use of Static Variables with the help of Java Program?
/*
Java Static Variable */
class StaticExample{
int EmployeeNo;
String EmployeeName;
static string department="Testing";
StaticExample(int eno,String n)
EmployeeNo=eno;
EmployeeName=n;
}
void display(){
System.out.println(EmployeeNo+""+EmployeeName+""+department);
}
public static void main(String args[]){
StaticExample S1= new StaticExample(1000,Manthan);
StaticExample S2= new StaticExample(1001,Nived);
S1.display();
S2.display();
}
Output:
1000 Manthan Testing
1001 Nived Testing
Q19. What is Static Method?
Ans: Static methods can be called without using objects.Static methods can only call other static method and static variables defined in the class.
Syntax: static return_type method_name(parameter_list)
Q20. Code for to demonstrate the use of Static Method
/*
Java Program To demonstrate the use of Static method */
class example
{
static void show(){
System.out.println("I am in Static Method");
}
public static void main(String args[]){
System.out.println(I am in main);
show();
}
}
Output:
I am in main
I am in Static Meethod
Q21. Difference Between Static Method and Instance Method?
Static Method | Instance Method |
---|---|
To call static method we don’t require to create Objects. | To call Instance method we need to create object for it. |
They are efficient as it save space. | They are not efficient in terms of memory, dedicated memory is allocated to each instance method. |
Example: public static int{ square(int n){ return n*n;}} | Example: public int square(int n){ return n*n; } |
Q22. Can we make Constructor Static ?
Ans: We know that Constructors invokes as soon as we create objects. And Static (method, block, or variable) belongs to class not the object. Hence that is why there no sense in making Constructor as static. If you try to make Constructor Static Compiler will throw an error.
Q23. Can we Execute Program without Main Method?
Ans: Yes,We can execute Program without main method also.
Q24. Can we Make Abstract Method Static?
Ans: If we make the Abstract method as static in java then they became part of the class. Therefore we can call them from anywhere, then what is the use of abstraction, Hence this is not allowed in java.
Core Java|Question on Some Important Keywords in Java.
Q25. Explain the Significance of this Keyword in Java?
Ans:Many times it is necessary to refers to its own object in a method or constructor.To allow this Java defines ‘this’ keyword.
this is used inside the method or constructor to refers to its own object.
Q26. Demonstrate the use of this keyword with Example?
/* Java Program To Demonstrate The use of This Keyword */
class Data{
int a ,b;
void setdata(){
a=10;
b=20;
void setdata(int a,int b){
this.a=a;
yhis.b=b;
}
void showdata(){
System.out.println("A="+a);
System.out.println("B="+b);
}
}
class Mydata{
public static void main(String arga[]){
Data d1= new Data();
d1.setdata(100,200);
d1.showdata();
}
}
Output:
A=100
B=200
Q27. What is Constructor Chaining and how it is performed?
Ans: Constructor Chaining is the process of calling one constructor from another constructor of the class with the help of the current class object.
This keyword is used to perform constructor chaining within same class.
Q28. Code To Demonstrate Constructor Chaining?
/* Java Program for Constructor Chaining */
class student{
int rollno,age;
String name;
public student(int age){
this.age=age;
}
public student(int rollno,int age){
this(age);
this.rollno=rollno;
}
public student(int rollno,String name){
this(rollno,age);
this.name=name;
}
public static void main(String args[]){
student std=new student(100,17,"Shyam");
System.out.println("RollNo"+std.rollno+"Age:+age +"Name:"+name);
}
}
Output:
Rollno:100 Age:17 Name:Shyam
Q29. Explain the significance of Super Keyword in Java?
Ans: The Keyword “Super” is a special keyword in java use for inheritance. whenever the subclass needs to refer to its immediate superclass, the “super” keyword is used.
There are two main uses of Super keyword:
- Accessing members from super class that has been hidden by members of the subclass.
- Calling super class constructor.
Q30. Code for Super Keyword?
/* Java Program to Implement Super Keyword */
Class Shape{
String colour="Black";
Shape(){System.out.println("Shape is Created");}
}
class Square extends Shape{
String colour="Red";
void colourprint(){
System.out.println(colour);
System.out.println(super.colour);
}
class test{
public static void main(String args[]){
Square s= new Square();
s.colourprint();
}
}
Black
Red
Q31 Differentiate Between this and Super Keyword?
This Keyword | Super Keyword |
---|---|
This Keyword is to refer current class context. | Super Keyword is to refer to Parent class context. |
Used to invoke current class method. | Used to invoke immediate parent class method. |
Q32. What is Object Cloning?
Ans:It is a process of creating exact copy of an object.
Q34. Explain the Significance of Final Keyword?
Ans: Following Are the Uses of Final Keyword
- One use of the final keyword is to make constant variables,i.e we cannot change the value of the variable.
- It is used for preventing method overriding,i.e is method is declared as the final method cannot be overridden.
- Used to prevent Inheritance,i.e we cannot extends the parent class
Q35. Write a code to Explain the Final Keyword?
/*
Java Program To demonstrate Use of Final Keyword */
class A{
final void show(){System.out.printlb("I am in A");}
}
class B extends A{
void show(){System.out.printlb("I am in B");}
}
class Example(){
public static void main(String args[])
B b1 = new B();
b1.show();
}
show() in B cannot override show() in A; overridden method is final
void show()
1 error
Core Java|String Related Questions
Q36. What is String in Java? Is String is a datatype?
Ans: String is a class in java, In Java.lang package. It is not a primitive datatype like: int, float, and double.
String is an important class in java which is used to perform various operations like:
Split, trim, String to uppercase and lowercase and vice versa, concatenation and various other complex operation converting other types to string type, etc.
Q37. What are the different ways of creating a String Object?
Ans: There are two ways of creating String in Java:
- Creating String using new Keyword.
- String str= new String(”Noteshacker’);
- Simple declaration using double quotes
- String str=”NotesHacker”;
When we create a String using double quotes, JVM looks in the String pool to find if there is any other String with the same value/name. If same string found it refers to that String object else create a new object in the String pool.
When we use the new operator, Java Virtual Machine will create the new String Object, but initially it is not stored in string pool.
Q38. String is Immutable in Java?
Ans: First of all Immutable means: Once something is created it cannot be changed.
Yes, String is Immutable that is once we create its object, its value cannot be changed.
Q39: What is the Difference Between String and String Buffer?
String | StringBuffer |
---|---|
String is a major Class. | StringBuffer is a peer class of String. |
The length of the String is fixed. | String Length is flexible. |
The contents of objects cannot be modified. | The contents of objects can be modified. |
Object can be created by assigning String Constants enclosed in double quotes. | Objects can be created by calling the constructor of the StringBuffer class using new. |
Ex: String s=”NotesHacker“; | Ex: StringBuffer s= new StringBuffer(“NotesHacker”); |
Q40. Differentiate StringBuilder and StringBuffer?
StringBuilder | StringBuffer |
---|---|
StringBuilder are not thread safe. | Stringbuffer is thread safe. |
It is not Synchronized | It is synchronized. |
They are faster. | StringBuffer is slower as thread is safe. |
Q41. How many Objects will be created in the following code?
String s1="NotesHacker";
String s2=new String("NotesHacker");
In the above example Two object will be created,Object created using string literal s1 is stored in string constant pool.
Object created using new operator is stored in the heap section s2.
Q42. Java Program to Check Whether String is Palindrome or Not?
Ans: It is one of the favorite Question of Interview and mostly asked:
Click here to view Solution
Q43 Which class is final among three classes-String, StringBuffer and StringBuilder?
Ans: All the three classes are final,this type of question are asked to confuse.
Q44. What is String intern() method ?
Ans: String Interning is a process of creating only one unique copy of distinct string value that must be immutable.
For example: if a name lets say-Noteshacker appears 10 times by interning you must ensure that only one Noteshacker is allocated with memory.
Q45. Code To demonstrate String intern() method?
public class Intern{
public static void main(String args[]){
String s1=new String("Noteshacker");
String s2="Noteshacker";
String s3=s1.intern();
System.out.println(s2==s3);// return true as reference variable are pointing to sameinstance
}
}
Output: true
Q46: What toString Method in Java used for?
Ans: Java.lang.Interger.toString method is used to return string objects representing this integer value.
Q47. Demonstrate the use of toString method using Java Program?
public class test{
public static void main(String args[]){
int s=5;
System.out.println(s.toString());
}
}
Output: 5
Q48: Some important Java String Program?
Please practice these following programs because these kinds of question are asked in interview for sure 100% assurity.
Core Java |Array Related Questions
Q49. What is Array in java?
Ans:An Array is a Structure that is collection of similar types of elements.An Array is a homogeneous data type where it can hold only elements of one data type.
Q50. Can we change the Size of Array at Runtime?
Ans: no we cannot change the size of array at runtime.
Q51. Can we declare an array without assigning the size of an array?
Ans: No we cannot declare array without assigning it size.if we try to do so it will throw compile time error
Q52. What is the default value of Arrays?
When new Array is initialized the default value is as follows:
- For byte,short,int,long-default value is 0.
- Float,double-default value is 0.0.
- Boolean-default value is false.
- Object -default value is null.
Q53. What is Jagged array?
Ans: Jagged Array are multidimensional Array,i.e Array having different length.
Q54. Where is the memory allocated for java?
Ans: In Java,Memory for arrays is always allocated on heap as array in java are considered as object.
Q55. differentiate between Array and Arraylist?
Array | ArrayList |
---|---|
Size of Array are fixed(Static) which means we cannot change the size of array. | Size of ArrayList is not fixed(dynamic),size of ArrayList changes when new elements are added to it. |
We can store both primitive as well as objects in Array. | We can only store objects in ArrayList. |
Q56. Demonstrate the use of ArrayList with Java Example?
/*java ArrayList Example */
import java.util.*;
public class ArrayExample{
public static void main(String args[]){
ArrayList<Integer> list= new ArrayList<>();
list.add(Integer.valueOf(100)).
list.add(200);
list.add(300);
System.out.println("List:");
for(Integer i:list){
System.out.println(i);
}
}
}
Q57. Most Important Array Programing Question
Here is the list of most important Java Array Programs.
Core Java|Java Exception Handling Related Questions
Q59. What are Exceptions in Java?
Ans: An Exception is a problem that arises during the execution of a program.An Exception is a condition that is cause by run -time error in program.
Q60. What are the Types of Exceptions?
Ans: There are basically two types of exceptions:
- Checked Exceptions
- UnChecked Exceptions.
Checked Exceptions: Exceptions that are handled at compile-time are called as checked Exceptions.example-ClassNotFoundException
UnChecked Exceptions: Exceptions that are handled at runtime are called as unchecked exceptions.example-NullPointerException
Q61. What is Exception Handling in Java?
Ans:The Process of handling run-time errors thrown by an error causing condition and then try to catch error conditions and display appropriate message for taking corrective action,This Task is called as Exception Handling.
Q62. List Built-in Exceptions?
Sr.No | Exception Type | Cause of Exception |
---|---|---|
1. | ArithmeticException | Arithmetic error such as diving number by zero. |
2. | ArraysOutOfBoundExceptions | Caused when array index is out of bound. |
3. | IOException | Caused by an attempt to access a non existed file. |
4. | NullPointerException | Caused by referencing a null object. |
Q63. What is try block/Clause in Exception Handling?
Ans: Try :The Program statement that you want to monitor for exceptions are contained within try block.if an exception occurs within try block,it is thrown.
The try is the keyword used for the block of code that causes an error condition and throws exceptions.
Q64. What is the Catch block/Clause in Exception Handling?
Ans: Your Code can catch the exceptions using catch and then throw it in some rational manner.
The catch keyword is used for the block of code that catches the exception thrown by the try block and handles it.
Catch Block is added immediately after try block.
Q65. What is the Finally block/clause in Exception Handling?
Ans: Any code that must be executed before method return are written in finally block.
A finally block is always executed.finally block can be used to handle any exception generated at try.
Q66.Demonstrate the use of the above three clauses with java code?
/* demonstration of try catch and finally */
class MyException
{
public static void main(String args[]){
try{
int a=10,b=0,c;
c=a/b;//exception occurred
}
catch(ArithmeticException e){
System.out.println("EXception caught:"+e);//exception caught
}
finally{
System.out.println("Statement out of try-catch block");//this will be always executed
}
}
}
Q67. Difference between Throw and Throws keyword in Exception Handling?
Throw | Throws |
---|---|
If you want to throw exception explicitly then you need use the throw clause. | When there is no appropriate catch block to handle exception,compiler will not run the program.A throws clause list the types of exceptions that a method can throw. |
Syntax: throw Throwable_instance | Syntax:datatype_methodname(parameter_list) throws(exception_list) |
Q68. Code to demonstrate the use of the Throw & Throws Clause?
/*import java.lang.*;
public class test{
public static void main (string args[])throws Exception{
int num1=10,num2=20;
if(num1>num2)
throw new Exception("Number 1 is greater");
else
throw new Exception("Number 2 is greater");
}
}
Core Java| Java Multithreading Related Questions
Q69. What is the thread?
Ans: A Thread is the smallest unit of executable code or single task is also called as thread.
Each thread has its own local variables, program counter and lifetime.
Q70.Explain various stages of Thread
Ans:A thread can be in various stages of execution:
- A thread can be running.
- Thread can be ready to run.
- Running thread can be suspended.
- It can be blocked.
- Suspended thread can resume.
- At any time thread can be terminated.
Q71. What is thread priority?
Ans: In Java, each thread is assigned a priority and according to their priority its is schedule for running. The same priority threads are given equal treatment by java scheduler and therefore they share processor on first come first serve basis (fifs).
Q72. difference between Multiprocessing and Multithreading?
Mutltiprocessing | Multithreading |
---|---|
Multiprocessing means executing several programs at a time using more than one processor. | Multithreading means executing different parts of programs simultaneously. |
A program or process is the smallest unit in multiprocessing. | A thread is a smallest unit in multithreading. |
Several jobs can run at a same time. | Same job can be broken into several sub jobs and then executed simultaneously and later result can be combined at the end of processing. |
Q73. How thread are created in java?
Ans: Three are the two ways of creating threads in java.
- Implement the runnable interface(java.lang.runnable)
- define a class that implements the runnable interface.The Runnable interface has only one method,run() that is to be defined in the method with code to be executed by a thread.
- By extending Thread class(java.lang.Thread)
- User-specified Thread class is created by extending the class Thread and overriding its run(), method.
Q74. Program for creating thread using runnable interface ?
class MyThread1 implements Runnable{
Thread t;
String s=null;
My Thread(String s1){
s=s1;
t=newThread(this);
t.start();
}
public void run(){
System.out.println(s);
}
}
public class RunnableThread{
public static void main(String args[]){
MyThread1 m1= new MyThread1("Thread Started");
}
}
Q75. Program for creating a thread by extending the thread class?
class MyThread extends thread{
String s=null;
MyThread(String s1){
s=s1;
start()
}
public void run(){
System.out.println(s);
}
}
public class RunThread{
public static void main(String args[]){
MyThread m1- new Mythread("Thread Started");
}
}
Conclusion:
Hope these questions will help in Cracking your Interview, if you want to add some more questions to this you can mail us-
info@noteshacker.com