Java is one of the most popular technical programming language world wide. As Java is secure and it has a huge acceptance as a programming language in the world. It is mostly used in enterprise application and have good job scope either in country or overseas. Java developer and J2EE developer must go through each before Java interview.
If you are looking for Java interview questions and answers for experienced or freshers. then below core java questions and answers is prefect source for you.
Java Question and Answer provided here is self sufficient to crack interview in multinational companies and product companies. The questions list is not at all complicated and point to point. The answers are very clear and clearly given in order to satisfy the requirement of any developer and professionals. J2EE questions and answers include topics like OOPs, Multithreading Concepts, Java Basics, JDBC, JVM, JDK, JRE, inheritance, Overloading and Overriding etc.
All questions are collected from expert Java developers on their past interview experience.
Best Java Interview Questions and Answers
There are many interview questions are available, but we have provided the unique java Questions and Answers based on the experience of the Java professionals having 10+ experience working in top companies like google, yahoo, amazon, flipkart, visa, allianz etc. Many Java developers are already placed in these companies by just preparing below java questions and answers.
Q1) Which of the following main method declarations will fail in compilation?
a. public static void main(String args)
b. public static void Main(String args[])
c. public void main(String args[])
d. public static main(String args[])
Answer : d
Reason: All methods in java should have return type.
Q2) Which of the following assignment is incorrect?
a. int a= (int) 10.0;
b. double d=10;
c. float f=3.4;
d. int b=(byte) 4;
Answer : c
Reason: Float values should be suffixed with f or should be type casted to float.
Q3) What is the difference between == and equals() method on String class?
Answer: == is used to compare the address of String whereas equals is used to compare the content of the String.
Q4) What is the Output of the following?
class Test
{ public static void main(String args[])
{
String a=”SEO”;
String a1=new String(“SEO”);
String a2=”SEO”;
System.out.println((a==a1) +”,”+(a==a2));
}
Output: false,true
Explanation: String a1 will be created in Heap Memory, String a2 will be returning String a address as the value (“SEO”) is already present in String constant pool
Q5) Why primitive data types are still used in Java?
Primitive Data types are performance effective than Wrapper classes in most of the instances, as no object creation is required.
Q6) What is the output of the below program?
class T
{
String t;
public Test(String val)
{
t=val;
}
public void print()
{
System.out.println(t);
}
public static void main(String args[])
{
T s1=new T(“Test”);
s1.print();
T s2=new T();
s2.sam=”Test2″;
s2.print();
}
}
a. Compilation error
b. Runtime error
c. Test
d. Test2
Answer: a
Reason: When parameterized constructor , default constructor will not be created by JVM.
Q7) What is the use of this keyword in Java?
Answer : ‘this’ keyword is used to refer the current object.
Q8) Select all to which final keyword can be permitted.
a. Variable
b. Method
c. Class
d. Interface
Answer : a,b,c
Reason: final is not permitted for interface.
Q9) When will the finalize() method be invoked?
Answer: finalize() will be invoked before an object is destroyed.
Q10) Explain method overriding?
Explanation: Two methods having same name and same signature in both Parent and Sub class is called method overriding.
Q11) Which of the following is not true about static keyword?
a. Single copy of static data members is created for all objects.
b. Static methods can be invoked without creating objects for the class.
c. Static methods can access only static variables.
d. Non Static methods cannot access static variables.
Answer: d
Q12) ‘Super’ keyword can be used to access which of the following from Parent class?
Constructors
Methods
Data Members
All the above
Answer : d
Q13)Constructors are called in which of the below order?
Super class to Derived classes
Derived Classes to Super Class
Answer : a
Q14)Objects cannot be created for abstract classes
True
False
Answer : a
Q15)Which of the following is true for the below program?
final class Sample
{
int a;
}
a. Objects cannot be created for class Sample
b. Sample class cannot be inherited.
c. Methods in class Sample cannot be overridden.
Sample class cannot extend any other class.
Answer : b
Reason: Final classes cannot be inherited.
Q16)Predict the output of below program?
class Sample
{
public static void main(String args[])
{
try
{
int a=5/0;
}
catch(Exception ex)
{
System.out.println(“Exception is printed”);
}
catch(ArithmeticException ex)
{
System.out.println(“ArithmeticException is printed”);
}
}
}
a. Compilation Error
b. Runtime Error
c. Exception is printed
d. ArithmeticException is printed
Answer: a
Reason: Exception should be ordered in catch blocks in order Derived class to Super class.
Q17) finally block will be executed only when exception occurs.
True
False
Answer : False
Q18) Checked and Unchecked Exception – Differentiate
Explanation : Checked exceptions are compile time exceptions and Unchecked Exceptions are runtime exceptions.
Q19) A derived class overridden method can throw Checked Exception which was not thrown by same method in Super class.
True
False
Answer : False
Explanation : Overridden methods can only throw runtime exceptions if they are not thrown by super class method.
Q20) Synchronized methods are thread safe methods.
True
False
Answer : True
Explanation : Once a thread starts executing a synchronized method any other thread has to wait until the method finish it.
Q21) What does the below snippet does in a multithreading environment?
Thread t1=new Thread();
t1.start();
a. Invokes start() method
b. Invokes run() method
c. Invokes begin() method
d. Invokes main() method
Answer : b
Reason: When a thread objects calls start(), run() method of Thread class will be executed.
Q22) What is the name of Java concept achieved below?
int i=5;
Integer i1=i;
Enumeration
Autoboxing
Unboxing
Annotation
Answer : Autoboxing
Reason: Autboxing is the concept of automatically converting a primitive data type into equivalent wrapper class object.
Q23) What is ‘out’ in System.out.println() ?
a.Static member of System class
b.Non Static member of System class
c.Object of System class
d.Final member of System class
Answer : a
Reason: ‘out’ is static data member in System class of type PrintStream
Q24) In what class print() and println() methods are available?
PrintStream
InputStream
OutputStream
PrintWriter
Answer : PrintWriter
Q25) Which type of classes can work on different types of data?
Abstract Class
Final Class
Super class
Generic class
Answer : d
Reason: Generic classes are classes which can operate on any type of data.
Become an JAVA Certified Expert in 25Hours
Q26) StringBuffer and StringBuilder – Difference
Answer : StringBuffer is Thread-safe (Synchronized Methods) & StringBuilder is not thread safe (Non-Synchronized Methods)
Q27) Which of the following doesn’t allow duplicate values?
ArrayList
LinkedList
HashSet
Stack
Answer : HashSet
Explanation : HashSet is a class which implements Set Interface and Set do not allow duplicate values.
Q28)Which of the following is not an interface in java?
Collection
List
Set
Vector
Answer : d
Q29)Which of the following data structure in Java is used to store key value pairs?
List
Set
Map
Stack
Answer : c
Q30) Which of the following is sorted by default
ArrayList
LinkedList
TreeSet
HashSet
Answer : c
Reason: TreeSet is the class which implements SortedSet interface and SortedSet is the interface which provides sorting by default.
Q31) Which of the following interfaced is required to achieved cloning?
Serializable
Cloneable
Appendable
Closeable
Answer : b
Q32) Method used to deserialize and serialize objects respectively.
writeObject(),readObject()
readObject(),writeObject()
read(),write()
write(),read()
Answer : b
Q33) Which among the following is a Character Stream class?
FileInputStream
FileReader
FileOutputStream
InputStreamReader
Answer : b
Reason: FileReader is a byte stream class.
Q34) Which of the following is not a markable interface?
Serializable
Cloneable
Remote
ActionListener
Answer : d
Q35) Which of the following packages will be imported automatically by JVM?
util
lang
io
awt
Answer: b
Q36) Which of the following packages Date class belongs to?
util
lang
io
awt
Answer: a
Q37)Which among the following is super class of all class in Java?
Object
Super
ObjectInput
ObjectInstance
Answer : a
Q38) Which of the following is not a lightweight component?
Jbutton
JLabel
JTextField
TextField
Answer : d
Reason: TextField belongs to AWT Component which is hard weight by nature.
Q39) Which of the following is not a Listener interface in java?
ActionListener
ComponentListener
ItemListener
MouseListener
Answer : b
Q40) What is the use of Adapter classes in Java?
Adapter classes are used to provide default implementation of the available listeners in java. So as to reduce the overhead of providing implementation of all the methods in the Listener interface.
Q41) Predict the output of the below program.
class Sample
{
public static void main(String args[])
{
int count=0;
for(int i=0;i<5;i++)
{
if(i==3)
{
continue;
}
count++;
}
System.out.println(count);
}
}
Answer : 4
Reason: Continue will break out of the current iteration.
Q42) Predict the output of the below program.
class Sample
{
public static void main(String args[])
{
int count=0;
for(int i=0;i<5;i++)
{
if(i==3)
{
break;
}
count++;
}
System.out.println(count);
}
}
Answer : 3
Reason: break will break out of the all consecutive iterations.
Q43) All methods declared in an interface have which of the following property implicitly?
Final
Static
Abstract
Super
Answer : 3
Reason: All methods in an interface are abstract by nature.
Q44) All data members declared in an interface have which of the following property implicitly?
Final
Static
Abstract
Super
Answer : a
Reason : All data members in an interface are final by nature.
Q45) Which of following interface is used for multiple sorting?
Comparable
Comparator
Cloneable
Serializable
Answer : b
Q46) Which of the following interface has compareTo method declaration?
Comparable
Comparator
Cloneable
Serializable
Answer : a
Reason: Comparable provides compareTo method, Comparator provides compare method declaration.
Q47) Predict the output of the below program.
class Sample
{
public static void main(String args[])
{
double d=5.0/0.0;
System.out.println(d);
}
}
Compilation Error
Arithmetic Exception on runtime
Infinity
Exception on runtime
Answer : c
Reason: Infinity constant will be printed if divide by scenario happens in double variable.
Q48) Which of the following is not a type of access modifier in Java?
Public
Private
Default
Protected
None of the above
Answer : e
Q49) Which of the following is not part of java.net package?
Socket
ServerSocket
URL
Serialize
Answer : d
Q50) Which of the following created immutable Strings?
String
StringBuffer
StringBuilder
StringAppender
Answer : a
Get JAVA Online Training
Q51) What will be the output if you execute the below code snippet?
public class Sample {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put(1,”a”);
hm.put(2,”b”);
hm.put(3,”c”);
hm.put(1,”d”);
System.out.println(hm.toString());
}
}
{1=d, 2=b, 3=c}
{1=d, 2=b, 1=a}
{1=a, 2=b, 3=c,1=d}
{1=a, 2=b, 3=c}
Answer : a
Q52) What will be the output if you execute the below code snippet?
public class Sample {
public static void main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println(“1”);
break;
case 2:
System.out.println(“2”);
break;
case 3:
System.out.println(“3”);
break;
case 4:
System.out.println(“4″);
break;
case 2:
System.out.println(” “);
break;
default:
System.out.println(“Default”);
}
}
}
The code will show compile time errors
The code runs successfully and displays nothing
The code runs successfully and displays 2.
The code will show run time errors
Answer : a
Q53) What will be the output if you execute the below code snippet?
class Square {
public int calculateArea(int a) {
return aa; } } public class Cube extends Square { public int calculateArea(int a) { return aa*a;
}
public static void main(String[] args) {
Square b = new Cube();
System.out.println(b.calculateArea(3));
}
}
The output 27 is displayed
The output 9 is displayed
The code shows runtime error
The code shows compile time error
Answer : a
Q54) Which of the following is true? Choose only one
static methods can be overloaded and overridden.
static methods can be overloaded but cannot be overridden.
static methods can be overridden but cannot be overloaded.
static methods can neither be overloaded nor be overridden.
Answer : b
Q55) The below code snippet will compile. Say true or false
class Base {
int foo(int a) {
return a;
}
}
public class Derived extends Base{
protected int foo(int a) {
return a+a;
}
public static void main(String[] args) {
Base b = new Derived();
}
}
True
False
Answer : a
Q56) A constructor can be static and final. Say true or false
True
False
Answer : b
Q57) All the fields in the interface are
public
b. static , final, public
abstract
public and final
Answer : b
Q58) Which of the following statement is correct. Choose only one.
StringBuilder is thread safe and StringBuffer is not thread safe.
Both StringBuffer and StringBuilder are thread safe.
Both StringBuilder and StringBuffer are mutable. StringBuilder is not thread safe but StringBuffer is thread safe.
StringBuilder is not threadsafe and immutable. StringBuffer is thread safe and mutable.
Answer : c
Q59) Which of the following is not a method of String class?
append(String s)
replace(char oldChar, char newChar)
charAt(int index)
matches(String regex)
Answer : a
Q60) Suppose there is an entity named Car and another entity named Engine. Which of the following is more appropriate for the relationship between Car and Engine?
Aggregation
Composition
Inheritance
Association
Answer : b
Q61) What will be the output if you execute the below code snippet?
public class Sample {
static void replaceString(String s)
{
s=s.replace(“A”,”Z”);
System.out.println(s);
}
public static void main(String[] args) {
String s1=”A”;
replaceString(s1);
System.out.println(s1);
}
}
A A
A Z
Z A
Z Z
Answer : c
Q62) Which of the following would you use in case of storing unique elements with the order of insertion?
LinkedHashSet
HashSet
HashMap
TreeMap
Answer : a
Q63) What will happen if the following code snippet is run?
public class Sample2 {
public static void main(String args[]){
try {
throw new InterruptedException();
}
catch(Exception e){
System.out.println(e);
}
}
}
InterruptedException is caught
Exception is caught
Exception is not caught
Nothing is displayed
Answer : a
Q64) What are the different types of inheritance among classes in java?
Multilevel, Multiple, Single, Heirarchial
Multilevel, Multiple, Single, Hybrid
Multilevel, Multiple, Single, Heirarchial,Hybrid
Multilevel, Single, Heirarchial,Hybrid
Answer : d
Q65) What will be the output if the following code snippet is run?
class Animal { }
public class Dog extends Animal {
public static void findInstance(Animal a) {
if (a instanceof Dog) {
System.out.println(“This is Dog instance”);
} else if (a instanceof Animal) {
System.out.println(“This is Animal instance!”);
}
}
public static void main(String args[]) {
Animal a = new Dog();
findInstance(a);
}
}
a.This is Dog instance
b.This is Animal instance
c. ClassCastException is thrown
d.Runtime Error occurs
Answer : a
Q66) What will be the output if the following code snippet is run?
public class Sample {
public static void main(String st[]){
String s1 = new String(“string”);
String s2 = “string”;
boolean b1 = s1==s2;
boolean b2 = s1.equals(s2);
System.out.print(b1);
System.out.print(” “+b2);
}
}
true true
false true
true false
false false
Answer : b
Q67) Overloading of methods cannot be done by changing only the
Type of arguments
order of arguments
number, type and order of arguments
return type of method
Answer : d
Q68) What will be the output if the following code snippet is run?
public class Sample5 {
static void m1(byte b) {
System.out.println(++b);
}
public static void main(String[] args) {
m1(1);
}
}
2 is displayed
1 is displayed
Runtime exception is thrown
Code will not compile
Answer : d
Q69) Try block cannot be blank and must contain a statement. Say True or False
true
false
Q70) Which of the following is true about local variables?
a. Local variables can be final but cannot be static or transient. Local variables cannot be public, private or protected.
Local variables can be final or static but cannot be transient. Local variables can be private only.
Local variables can be final , static and transient. Local variables can be private only.
Local variables cannot be final, static, transient.
Answer : a
Q71) What will be the output if the following code snippet is run?
public class Test {
public static void dec(double d) {
d = d – 3;
}
public static void main(String args[]) {
double d = 13;
dec(d);
System.out.println(d);
}
}
13 is displayed
0 is displayed
10 is displayed
0 is displayed
Answer : b
Q72) What will be the output if the following code snippet is run?
public class Sample
{
public static void main(String[] args)
{
byte b= 2;
int n = 100;
long l = n;
Double d = (double)Integer.valueOf(n);
System.out.println(b);
System.out.println(n);
System.out.println(n);
System.out.println(d);
}
}
ClassCastException will be thrown
Compiler time error occurs
Displays output as
2
100
100
100.0
Displays output as
2
100
100 l
100.0d
Answer : c
Q73) What will be the output if the following code snippet is run?
public class Sample {
public static void main(String args[])
{
boolean b = false;
do{
System.out.println(“inside do while loop”);
b=true;
}while(!b);
}
}
Nothing is printed
do while loop keeps on running after entering an infinite loop
it prints “inside do while loop”
Runtime Exception is thrown
Answer : c
Q74) The use of this() and super() is allowed inside static method and constructor. Say true or false.
true
false
Answer : b
Q75)
interface A {
public int display();
}
abstract class B implements A {
}
public class Example extends B {
public int display() {
return 0;
}
}
In the above code, what changes need to be done to compile it successfully?
Implement the display method in class B
Overload the display method in class Example
Remove the class B
No changes needed.
Answer : d
Get JAVA 100% Practical Training
Q76) How to send a cookie in the response?
HttpServletResponse.addCookie(Cookie).
HttpServletResponse.setCookie(Cookie).
HttpServletResponse.sendCookie(Cookie).
setCookie(HttpServletResponse response).
Answer : a
Q77) In a class can a local variable be static?
Answer : No
Q78) Which of the following method is used to send control to another servlet and is defined under RequestDispacther interface?
sendRedirect()
b. forward()
send()
redirect()
Answer : b
Q79) What will be the output if the following code snippet is run?
<%! int a=10; %>
<% int a=5; %>
<% int b=2; %>
Result is <%= a*b %>
Displays 20
You cannot re declare a
Displays 10
Error is displayed
Answer : c
Q80) This is responsible for managing the lifecycle of a servlet.
Application server
Web container
Application container
Web server
Answer : b
Q81) With java 7, which of the following is supported in switch statement?
Enum
Character
String
constant
Answer : c
Q82) Which of the following code gives minimum value in the given list ?
list.stream()
.mapToInt(v -> v)
.findMin() ;
list.stream()
.mapToInt(v -> v)
.min()
.orElse(Integer.MAX_VALUE);
list.stream()
.min(Comparator.naturalOrder)
.get();
d.List.stream(list)
.mapToInt(v -> v)
.min();
Answer : b
Q83) What is the type of lambda expressions?
Object
functional interface
Interface
Object variable
Answer : b
Q84) Which of the following is not a method of Optional class in java 8?
IsPresent()
OfNullable(T val)
OrElse(T t)
IsPresentorNull()
Answer : d
Q85) What will be the output if the following code snippet is run?
public class Sample {
public static void main (String[] args)
{
String myString = “123s4”;
int foo = Integer.parseInt(myString);
System.out.println(foo);
}
}
ClassCast exception is thrown
Compile time Exception is thrown
NumberFormatException is thrown
Code displays “123s4”
Answer : c
Q86) Which of the following is not a built in java annotation?
@Override
@SuppressWarnings
@Deprecated
@Inherit
Answer : d
Q87) The below code does not compile. Please identify the cause.
import java.io.IOException;
class Super
{
void show() {
System.out.println(“super class “);
}
}
public class Sub extends Super
{
void show() throws IOException
{
System.out.println(“sub class”);
}
}
CheckedException cannot be used with throws keyword
Sub class overridden method cannot throw CheckedException
CheckedException should be handled with try and catch block
The code is correct
Answer : b
Q88) Which of the following is not true about lambda expressions?
Lambda expressions are a way to replace anonymous classes
Lambda expressions helps in the implementation of functional interfaces
The scope of lambda expressions is not limited to its enclosing class
The lambda expressions uses target typing to infer the type of arguments
Answer : c
Q89) Which of the following illustrates the relationship in the below statement correctly?
House has a room which is luxurious
Class Room extends House{ luxury();}
Class House {private LuxuryType Room;}
Class Room {private House (Luxury luxury);}
Class Room {private Luxury house;}
Answer : b
Q90) Which of the following is correct implementation of NavigableSet?
NavigableSet al=new NavigableSet ();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
NavigableSet al=new TreeSet();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
Set al=new NavigableSet ();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
TreeSet al=new NavigableSet ();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
Answer : b
Q91) Which of these methods will cause the currently running threads to stop executing until the thread it joins with completes its task?
join()
wait()
wait(int num)
resume()
Answer : a
Q92) The keyword synchronized can be applied to
Methods, variables, block
Methods, blocks, static blocks
Variables, methods
Methods and blocks
Answer : b
Q93) Which tag is used to force the container to load as the server starts?
Answer : a
Q94) Which of the following is true about ServletContext?
One per web application
One per session
One per context
One per web config
Answer : a
Q95) Which of the following is not a http method?
GET
REPLACE
PUT
HEAD
Answer : b
Q96) Which of the following not a class in collection hierarchy?
SortedSet
TreeSet
LinkedHashSet
HashSet
Answer : a
Q97) Which of the below driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol?
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver
Vendor thin driver
Answer : c
Q98) If a String s= “Hi I am Good”. How to separate each word of a String?
Answer : By using Split(“ ”) method
Q99) Which of the following is not a keyword in java?
implements
package
throws
Integer
Answer : d
Q100) How to find the size of the given array named arrayNum?
size()
length
length()
size
Answer : f
Q100) why java is called platform independent?
Answer : Class files generated in windows OS can be ran on different machines irrespective of OS such as mac,linux etc .
Get JAVA 100% Practical Training
Q101) Is JVM platform idependent or Platform dependent.
Answer : JVM is platform dependent.
Q102) explain why JVM is platform dependent?
Answer : Different OS has respective JVM installed in systems which makes JVM platform dependent and java platform independent.
Q103) Where are objects stored in JVM?
Answer : In Heap
Q104) How many copies exist when String Object is created?
Answer : Two copies are created when String s1=new String(); is executed.
One in String Pool and in Heap
Q105) How would you handle Null pointer exception, explain through code.
Answer :
String s1=”Hello GangBoard!!”;
If(null!=s1 && s1.isEmpty)
{System.out.println(“Hello Karthik”);
}
Q106) what is an Exception?
Answer : Exception is an Object thrown due to run time errors or abortion of system.
Q107) can main() be overloaded?
Answer : Yes it can be overloaded
Q108) What is String Literal ?
Answer : when String is declared as below it is called as String Literal.
String s1;
String literals are stored in only String pool unlike String objects.
Q109) what is default scope of spring bean?
Answer : Singleton
Q110) What is IOC?
Answer : IOC is called as Inversion of control where the Spring container looks after the object creation and the life cysle of cycle .
Q111) what is output of below?
Answer :
String s1=”hi”;
String s2=new String ();
s2=”hi”;
If(s1==s2)
{
System.out.println(“hello Karthik”);
}
Else
{
Sytem.out,println(“Hi GangBoard”);
}
Output:
Hi GangBoard
Q112) what is output of below?
String s1=”hi”;
String s2=new String ();
s2=”hi”;
If(S1.equals(s2))
{
System.out.println(“hello Karthik”);
}
Else
{
Sytem.out,println(“Hi beasant”);
}
Answer: hello Karthik
Q113) what is output of below?
Answer :
String s1=”hello GangBoard!!”;
String s2=s1.subString(0,4);
System.out.println(s2);
output:hell
Q114) which exceptions are required to handle?
Answer : checked exceptions
Q115) Example of unchecked exceptions.
Answer : ArrayOutOfBoundsException,null pointer,divide by zero
Q116) Can a method be invoked without creating the object of that class?
Answer : yes, static classes n methods doesn’t require object to be created to invoke a method.
Q117) Which methods are loaded into JVM when program is executed?
Answer : static methods
Q118) When ArrayList and LinkedList are recommended to use?
Answer :
When there are frequent read operations ArrayList is best to use as it uses RandomAccess
When there are frequent Removal/ Write operations LinkedList is best to use because in ArrayList positions should be adjusted but in LinkedList works storing the address of next element.
Q119) why generics are used?
Answer :
Generics are type safe
ArrayList a1=new ArrayList();
It allows only String to be stored in this case.
Q120) Which collection do Hashmap internally uses?
Answer : LinkedList
Q121) What is java?
Answer : Java is fast, secure, reliable and object oriented programming language.It can be used for creating desktop application,web application,mobile application.
Q122) What is oops?
Answer : Object oriented programming system..Its a one kind of methodology used to create program
Q123) Oops concepts in java?
Answer :
Encapsulation
Inheritance
Polymorphism
Abstraction
Q124) Why Encapsulation?
Answer : It provide security and we can modify easily
Q125) Why Polymorphism?
Answer : It has many method with same name.Its used to avoid naming complexcity.
Get JAVA 100% Practical Training
Q126) Why Inheritance?
Answer : It is used for Reusability
Q127) Why Abstraction?
Answer : Hide the data and showing essential details only
Q128) Types of Polymorphism?
Answer :
Static or comple time polymorphism.
Example : method Overloading
Dynamic or runtime polymorphism.
Example : method Overring
Q129) Difference between overload and override?
Answer :
Overload means same method name with different parameter in a single class.
Override means same method in a parent and child class
Q130) How many types of relationshilp in java?
Answer :
IS_A example inheritace
HAS_A example Aggrigation
Q131) What is Inheritance?
Answer : Reusability.Derived the data from parent class to child class
Q132) Is java support multiple Inheritance?
Answer : No. because multiple inheritance can cause ambiguity
Q133) Why object oriented programming?
Answer :
We con eliminate the redundant code use of inheritance
We can easily upgrade from small to large programs
We can reduce program complexity
Q134) What is class?
Answer : It is a combination of variables and methods.It is used to define template or blueprint
Q135) How to achieve multiple inheritance in java?
Answer : By interface
Q136) How to avoid method override in java?
Answer : If you make method as final can not override.
Q137) What is the this keyword in java?
Answer : It is used to refer current class variable
Q138) How to achieve encapsulation in java?
Answer : By private keyword
Q139) What is the use of getter and setter method in java?
Answer : It is used to access private data variables in outside of class.
Q140) What is the use of package in java?
Answer : We can remove naming collision.
Q141) What is wrapper class in java?
Answer : It is a converting mechanism used to convert primitive to object and object to primitive
Q142) What is autoboxing?
Answer : It is a automatic conversion compiler convert primitive type to object wrapper class
Q143) What is unboxing?
Answer : It is a automatic conversion compiler convert object to primitive type.
Q144) What is contructor?
Answer : It is a method will invoke at the time of object creation and initialize the values to properties
Q145) Types of contructor in java?
Answer :
Default constructor
Parameterized constructor
Q146) What is checked exceptions in java?
Answer :
This kinds of exception will check at compile time.
For example : IOException,ClassNotFoundException,FileNotFoundException
Q147) What is unchecked exceptions in java?
Answer :
This kinds of exception will check at run compile time.
For example : ArithmeticException,NullPointerException.
Q148) Difference between final and finally?
Answer :
Final is a non access modifiers.
Finally is a block in exception handling.
Q149) Difference between throw and throws?
Answer :
Throw is used to call custom exception.
Thorws used to declare multiple exceptions in method signature
Q149) Can I start thread two times?
Answer :No
Q150) What is serialization?
Answer : It is a interface used to convert object to byte.
JAVA Modules For Better Job Opportunities
Q151) What is deserialization?
Answer : Reverse operation of serialization
byte value is converted to object.
Q152) Can we remove the objects during iteration?
Answer :
Using list-iterator
ListIterator itr= balls.listiterator()
While()
{
Itr.hasNext()
Itr.remove();
}
}
Q153) How to sort the collection ?
Answer : Using sort() method with the help of comparable interface.
Q154)Tree set is used for what purpose ?
Answer : Getting the collection in ascending order or sorted order
Duplicate values not allowed in treeset
Q155) How to make a class immutable ?
Answer : Declare the class is final
Do not provide setter methods
Field should be final
Q156) What is yield() method in java?
Answer :
This method is used in the concepts of thread
Thread which is not doing any important task during the execution any other thread which is important to run during the process, so yield method helps to achieve the completion of important thread, else current thread continue to run.
Q157) Default scope in spring?
Answer : Singleton scope
Q158) How to handle exception in spring mvc?
Answer : @ExceptionHandler methods to handle , For own exceptions and in ResponseBodywe can write the custom exception to show.
Q159) What is the use of @Qualifier in spring annotation?
Answer : When more beans created in same name to identify to which one call first based on the request we can use to identify and do the @Autowired
Q160) What is externalization?
Answer : Used for serialization
Externalization which extends serialization
Q161) What is transient keyword?
Answer : Transient keyword used in serialization
When the particular variable in a file which don’t need to save in the receiving end file, then we use transient keyword
Q162) Please explain about ops concept with real time example?
Answer :
Polymorphism
Abstraction
Encapsulation
Inheritance
Polymorphism is in which we can identified by one action has different forms, Suppose talking is the feature given god to humans, but for animals the way of communication will be different
Abstraction is the process in which we can relate it with phone, We are able to dial the numbers but what happening inside we exactly don’t know
Making an entity into single unit, Suppose we have a pack of biscuit, But biscuit is made up of different ingredients, like wheat, vanilla, etc
Inheritance= Inheritance is the concept in which we can compare the relationship between parent and child, A child have two set of 23 chromosomes which is from parents.
Q163) Difference in overloading and overriding, In your project have you use
Answer : Overriding in which happening in two different class, Methods and signature will be Same.
Overloading mostly in one class , Method is same but signature is different In my project i have use overriding.
Q164) Have you use super keyword?
Answer : Super keyword is used to invoke the parent method or class and getting the features/characteristics in the child class
Q165) How the memory related concept are you familiar with JVM, Can you explain about that?
Answer : Heap ,stack,Pc,Program counter register
Native method, Class area
Q166) Did multiple inheritance is supported in java?
Answer : No
Q167) How to achieve that?
Answer : Using interface
Q168) How you write interface in code
Answer : Interfaces is used replacement of multiple inheritance
In interface we will defining the methods that action is going t perform
In the implementation class we will overriding all the methods and write the logic
Q169) If there is parking of vehicle project is given to you which collection you will use to solve the issue
Answer : ConcurrentHashMap
Q170) What is singleton class
Answer : A class which returns only one object is called singleton class
Q171) When we clone the singleton we get a same object but as per singleton only one object created so how to resolve the issue
Answer : By override clone method and write a throw an exception Clone Not Supported Exception, so we can avoid the issues.
Q172) How portability is achieved in Java?
Answer : Java code is translated into byte code by javac. This byte code is interpreted by Java Virtual Machine(JVM). Any computer that has JVM can execute the byte code. So only requirement for executing java programs is presence of JVM. This is how portability is achieved in Java.
Q173) What are the two major differences between Java and C++?
Answer : There are no pointers in Java.
Java does not support multiple inheritance
Q174) What are the basic data types in Java?
Answer : byte, short, int, long, float, double, boolean
Q175) What is boxing/unboxing?
Answer : For all primitive data type such as int, float, etc., there are corresponding wrapper classes such a Integer, Float etc. Converting a primitive data to corresponding object is called Boxing. Similarly, converting objects to corresponding primitive data type I called unboxing.
Q176) Do primitive data item have same size all over the world?
Answer : Yes, primitive data types have the same size all over the world. This is for portability reasons
Sizes:
byte: 8 bits
short : 16 bits
int: 32 bits
long: 64 bits
float: 32 bits
double: 64 bits
Q177) What is constructor?
Answer : Constructor is a method whose name is same as the class name. Constructor is invoked when an object is created.
Q178) Does Java has destructor?
Answer : Java does not have destructor unlike in C++, but finalize() method is called when an object is destructed.
Q179) What is Garbage Collection?
Answer : In Java destruction of objects is not done by the programmer. That is done by Garbage Collector, which runs once in a while to destroy(recycle) unreferenced objects.
Q180) What is the use of ”this” keyword?
Answer :
This keyword can be used when an instance data member and method parameter have the same name:
class A{
int ii;
void fff(int ii){
this.ii = 100;//refers to instance data member ii – not the //parameter ii
}
}
Another situation is when we want to call one constructor from another constructor of the same class:
class AAA{
AAA(int iii){
//do something
}
AAA(int kkk, int mmm){
this(kkk);//calls single argument constructor
//do something
}
}
The call to another contructor using this must be the first statement .
Q181) What is super keyword?
Answer : The keyword super refers to the super class. This keyword can be used in two situations:
Calling super class constructor from subclass contructor:
class Base{
Base(int ii){
// do something
}
}
Class Sub{
Sub(int kkk){
super(kkk);//calls Base class contructor
// dosomething
}
}
The call to super class constructor must be the first statement in the subclass constructor.
Another situation is when super class and subclass have instance members with same name:
class Super{
public int ijk;
}
Class Sub extends Super{
public int ijk;//same name
void f(){
ijk = 55;// refers to this class’s ijk
super.ijk = 99;//refers Super’s ijk
}
}
Q182) What is exception?
Answer : Exception is an object that is “thown” from try block during runtime and the thrown exception is “caught” in catch handler. The handler is expected to “handle” the caught exception. All exception classes are subclasses of “throwable” class.
Q183) What is the difference between error and exception?
Answer : The programmer is not expected to catch an error because they are handled by the system. Example for error is stack overflow. Exceptions are expected to be handed by the programmer.
Q184) What is “throws” keyword?
Answer : When a method throws a (checked) exception it must either handle the exception itself or it must mention that the method throws that exception like this:
void fff() throws InterruptedException{
// code
}
In this case the method that calls this method expected to handle the exception when it is thrown from fff().
Q185) What is thread?
Answer : Multiple threads can be running at the same time when a Java program is executing.
Q186)What are the two ways of implementing threads in Java?
Answer :
Extend Thread class
Implement Runnable interface.
Q187) When you should we extend Thread class and when we should implement Runnable interface?
Answer : Generally if want to only implement run() method we should go for Runnable interface( Runnable has only one method: run()). Implementing Runnable helps the class to extend some other class.
If we want to override other0 methods( apart from run() )of Thread class then we should extend Thread class.
Q188) What is abstract mehod?
Answer : Abstract method is a method without a body.
Q189) What is “final” keyword?
Answer : Final keyword i s used in three situations:
Value of a data member that is declared as final cannot be changed.
A method that is declared as final cannot be overridden.
A class that has been declared as final cannot be subclassed.
Q190)What are the states of a thread?
Answer :
Initial
Runnable
Waiting
Blocked
Terminated
Q191) What is the base class for all classes?
Answer : Object class
Q192) In java program which package is automatically imported?
Answer : java.lang package is automatically imported
Q193) What is the basic difference between inputstream/outputstream classes and reader/writer classes?
Answer : Inputstream/outputstream read/write bytes
reader/writer read/write characters.
Q194) What is pushbackinputstream / pushbackreader?
Answer : They can “push” read data back into the stream. It is done using unread() method.
Q195) What are the collection interfaces?
Answer :
Collection
List
Queue
Deque
Set
SortedSet
NavigableSet
Q196) What is the purpose of iterable interface?
Answer : Any collection that wants to use for statement like this
for(int ii : coll){
// do something with the collection element ii
}
must implement iterable interface.
Q197) What is the difference between ArrayList and array?
Answer :Size of Arraylist will change when elements are added/deleted. But size of array is fixed.
Q198) What are two ways of declaring arrays in Java?
Answer :
int a[];
int[] a;
Q199) Explain public static void main(String args[])
Answer :
public indicates main can be accessed from anywhere.
static indicates there is no need for an object to invoke main.
void indicates main does not return anything.
args[] are the command line parameters.
Q200) What are static members of a class?
Answer : Static data members are data items that are common to all instances of the class. They can be accessed by the class name. There is only one copy of static data member for a class.
Static methods can be called by using class name alone.
Get JAVA Training with Real time Live Projects
Q201) What are checked/unchecked exceptions?
Answer : Checked exceptions must be caught by the method that throws the exception or must be declared in “throws” clause. For unchecked exceptions this is not mandatory.
Q202) What is var-args in a method?
Answer : Consider the following method:
void ffff(int … v){
// do something
}
This method accepts zero or more int parameters. For e.g:
ffff(10,30);
ffff(55);
ffff();
Q203) What are the restrictions for var-arg parameters?
Answer : The variable argument list must be the last argument.
There can be only one variable length argument list in a method.
Q204) Show how variable length arguments when combined with method overloading might lead to ambiguity.
Answer :
Consider the following two methods:
void abc(int … vv){
// do something
}
void abc(boolean … bb){
// do something
}
Now the call
abc();
resolves to both methods – hence this call is ambiguous.
Q205) What is the basic difference between interface and abstract method?
Answer : A class can implement any number of interfaces – a class can extend only one abstract class.
All methods in interface are public- methods in abstract class can have any access level
Methods in interface cannot have body – there can be methods with body in abstract class.
Q206) Why strings are immutable in Java?
Answer : For performance reasons. Since strings are immutable, certain optimizations are possible.
Q207) Is bytecode ever compiled?
Answer : Bytecode is compiled by the JIT(Just In Time) Compiler if it will improve performance.
Q208) What is the distinguishing feature of Sets?
Answer : A set cannot have duplicate items.
Q209) What is TreeSet?
Answer : In a TreeSet, items are retrieved in ascending order of their values.
Q210) What are the methods of Object class?
Answer :
equals()
hashcode()
wait()
getClass()
toString()
notify()
notifyAll()
Q211) Explain to String() method.
Answer : If an object is passed when a String is expected, toString() method is called.
Q212) What is the difference between == and equals() method?
Answer :
==compares whether the objects are same
equals() checks whether the objects have the same value.
Q213) When parameters are passed by reference and when they are passed by value?
Answer : Object are passed by reference and primitive data items are passed by value.
Q214) Explain “finally” block.
Answer : Once control goes inside a try block, after that no matter what happens, “finally” block is executed.
Typically any release of resources is done in finally block.
Q215) What is “inner class”?
Answer : Inner class is non-static class declared within another class. Inner class can access the members of the enclosing class.
Q216) How can we make garbage collection happen in our code?
Answer : Calling gc() starts garbage collection.
Q217) What are applets?
Answer : Applets are small programs that run in the client’s browser. Applets are downloaded from the web server and executed in the client side. Appletviewer can be used to execute applets during testing stage.
Q218) What is the difference in finally and finalize in java?
Answer : Finally, is a java block where finalize is used in garbage collection.
Q219) Why Java is Platform independent language?
Answer : Java is platform independent because jvm compiler compiles the program to bytecode, this bytecode you can execute anywhere without modification the bytecode.
Q220) Which compiler Java will use ?
Answer : Jit ( Just in compiler).
Q221) What is the use of JIT ?
Answer : Jit first time compiles the whole program, next time compilation process it just compiles whichever the code got modified. So it wont compile whole program all the time. This is one reason Java performance is high.
Q222) Why Java is Secure?
Answer : Java is secure because it is an object oriented language, here data will be secured inside the class, data you cannot freely access without the permission. You can apply different secure access by using access modifiers and access specifiers.
Q223) Why Java is not pure OOPs language ?
Answer : Because Java support primitive types.
Q224) Can we use static public void main() ?
Answer : Yes we can use.
Q225) Can we overload the main() method ?
Answer : Yes we can overload but Java will pick only public static void main() method for the starting execution.
Are You Interested in JAVA Course ? Click here
Q226) What are OOPS concepts ?
Answer :
Encapsulation
Inheritance
Abstraction
Inheritance
Q227) What is the use of Encapsulation ?
Answer : Encapsulation makes sure that data will be hidden from outside the world.
It’s like capsule, data will not directly accessible. Everything you will write in the Class.
Data will be declared using variable and method is used use that data for business logic.
Q228) How to stop class to be inherited ?
Answer : You can use final keyword to the class. Which prevents inheritance.
Q229) What is the use of inheritance?
Answer : Inheritance is used for preventing the invention of wheel again, that means if already the code is there you can reuse, and save the time.
Q230) How can you achieve polymorphism?
Answer : You can overload the methods and constructors to achieve overloading.
Q231) What is singleton design pattern ?
Answer : Singleton design pattern makes sure that at all the time only one instance be maintained
Q232) What is the use of static variable ?
Answer : Static variable is available throughout the class level and only one copy will be shared among all the objects. If you one object modified the values all other objects will get the updated copy.
Q233) What is the class Loader ?
Answer : It is used to load the class, and contains the metadata about the class.
Q234) What are exceptions?
Answer: Exceptions are the abnormal errors occurred in the program.
Q235) What are the types of Exceptions ?
Answer: Checked and unchecked exceptions.
Q236) What are checked and unchecked exceptions?
Answer: Checked exceptions need to be handled at the compile time and unchecked exception no need to handle at the compile.
Q237) What are different checked exceptions?
Answer : IOExceptions, SQLExceptions, FIleNotFoundExceptions.
Q238) How to handle the checked exceptions?
Answer: By used try-catch block we can handle the checked exceptions.
Q239) Can use try without a catch?
Answer: Yes we can use.
Q240) What is the use of finally block?
Answer: Finally block will be executed before the end of the execution of the class, so you can write any closing of resources which you might be using in the program. Like you opened a file, you need to close the stream, if you have connected to the database, close the connection, etc.
Q241) Difference between system.exit() and return?
Answer: System.exit() completely halts your program, but where a return will continue to work
Q242) Can use instantiate abstract class?
Answer: No.
Q243) Can we extend more than class?
Answer: No we can’t extend more than one class
Q244) Can we implement more than one interface?
Answer: Yes we can implement more than one interface.
Q245) Difference between throw and throws?
Answer: Throw is used to explicitly throw the exceptions.
Throws is used along the method to notify the calling instance that it might throw an exception.
Q246) What is the super class for exception?
Answer : Class Exception.
Q247) What are thread?
Answer : Thread is a separate path of execution, it has its own space in the program to execute.
Q248) Difference between multitasking and multithreading?
Answer : Multitasking- It will execute multiple tasks at the same time
Multithreading- Single task contains multiple threads and each thread will do unique task
Q249) How to create the threads?
Answer : By using implementing interface or extending the class
Q250) How to start the thread?
Answer : By using start() method on the thread class
Q251) What is Java?
Answer: Java is an object-oriented, and robust programming language unveiled by Sun Microsystems in the year 1955. Java is mostly used for application development besides the hundreds of other uses it has.
Q252) What are the major features of Java?
Answer:
Object-Oriented
Robust
Portable
Secure
Multithreaded
Platform independent
Q253) What are method overriding and method overloading?
Answer:
Method overriding:
If a method which is already present in the parent class is declared in sub-class as well, then it is method overriding.
Method overloading:
If there is more than one method with the same name in a class, then it is known as method overloading.
Q254) What is the difference between Java, C, and C++?
Answer:
C C++ Java
Procedural language Object-oriented language Object-oriented language
Inheritance isn’t supported Supports multiple inheritances Interfaces instead of multiple inheritances
Platform dependent Platform dependent Platform independent
Only compiler is used Only compiler is used Both compiler and interpreter are used
Pointers are used Pointers are used Pointers aren’t supported
No exception handling Supports exception handling Supports exception handling
Q255) What is an abstract class?
Answer: If a class is declared with the keyword ‘abstract’, then it is an abstract class. However, this abstract class may have abstract and non-abstract methods.
Q256) What are classes and objects in Java?
Answer:
Class: A class is a template for object creation. Classes may contain variables, objects and methods.
Object: An object is an instance of a class. These methods can be used to invoke methods.
Q257) What is inheritance and how is it done?
Answer: Inheritance is a process in which the child object acquires all the properties of the parent object. The child class may contain additional methods and variables along with the inherited properties from the parent class.
Syntax:
class subclassName extends superclassName
{
//methods
}
Q258) What are sub classes and inner classes?
Answer:
Subclass: In inheritance, the class that inherits properties from parent class is a subclass.
Inner class: An inner class is a class which is a member of another class. There are 4 types of inner classes:
Nested inner class
Static nested class
Local inner class
Anonymous inner class
Q259) Differentiate between ‘equals()’ and ‘==’ in Java.
Answer:
‘equals()’: When checking two strings to see if they’re similar, the equals() method is used. This is because the string is immutable.
‘==’: This is used when comparing two operands. If this is used with strings, then it compares the addresses of those strings.
Q260) What are packages in Java?
Answer: A package in Java contains all the similar classes, interfaces and even sub-packages. They are categorized into 2 types: built-in packages and user-defined packages. These packages help prevent name conflicts.
Q261) Are there pointers in Java? Why or why not?
Answers: Java doesn’t support pointers, unlike C and C++. This is because, without pointers, Java programs won’t be able to reference memory locations illegally. This is one of the reasons why Java is a secure language.
Q262) What are the various access modifiers in Java?
Answer: Access modifiers are used to restrict access to certain methods, constructors and classes. There are 4 access modifiers: public, private, default, protected.
Access levels:
Public: class, sub-class, package, everywhere
Protected: class, cub-class, package
Default: class, package
Private: class
Q263) What is the difference between local variable and instance variable?
Answer:
Local variable:
A local variable is a variable that’s declared in the body of a method. That local variable can only be used within the method.
Instance variable:
Instance variables are declared outside a method but within a class. These instance variables don’t contain the static keyword.
Q264) What are OOPs concepts in Java?
Answer: Java contains 4 major OOPs concepts:
Abstraction
Encapsulation
Polymorphism
Inheritance
Q265) What are the differences between static and non-static methods in Java?
Answer:
Static Method Non-static Method
Contains the static keyword Doesn’t contain the static keyword
Can’t use non-static instance variables and methods Can access any static method and variable without creating an object
Belongs to a class Belongs to an object of the class
Q266) Differentiate between StringBuilder and StringBuffer.
Answer:
StringBuilder:
Mutable
Not thread-safe
Non-synchronized
Less efficient
Less reliable
StringBuffer:
Mutable
Thread-safe
Synchronized
More efficient
More reliable
Q267) Are strings in Java mutable or immutable?
Answer: All the strings in Java are immutable. This means when a string object is created, it’s data cannot be modified. However, a new string object may be created to store data.
Q268) What is the difference between array and array list?
Answer:
Array:
Fixed size (size cannot be changed)
length is used to calculate length of array
Assignment operator is used to add elements
Can be multi-dimensional
ArrayList:
Dynamic (size can be changed)
sizeof() is used to find the size of array list
add() is used to add elements to ArrayList
Is always single-dimensional
Q269) What is a copy constructor?
Answer: A copy constructor contains a single parameter and takes the same class as its parameter. This copy constructor is used to duplicate an already existing object of a class.
Q270) Differentiate between HashMap and Hashtable in Java.
Answer:
HashMap:
Non-synchronized
It is fast
It inherits AbstractMap class
It allows one null key
It allows multiple null values
HashTable:
Synchronized
It is slow
It inherits Dictionary class
It doesn’t allow any null keys
It doesn’t allow any null values
Q271) Differentiate between HashSet and TreeSet in Java.
Answer:
HashSet:
Provides ordering
Uses equals() method for comparison
It allows one null element
It is internally implemented by HashMap
It is fast
TreeSet:
Doesn’t provide ordering
Uses compareTo() method for comparison
It doesn’t allow any null objects
It is internally implemented by TreeMap
It is slow
Q272) What are collections in Java?
Answer: A collection in java is a structure used to store and perform operations like insertion, deletion, searching, and sorting on a group of objects.
Q273) What are maps in Java?
Answer: The map is an interface in java. It contains keys which are mapped to values. There should not exist any duplicate keys and each key can only map to one value.
Q274) What is an exception?
Answer: An exception is an abnormality which interrupts the smooth running of a Java program. This exception can be a hardware or a software error which disrupts the program during run-time.
Q275) What are the various types of exceptions in Java?
Answer: There are two types of exception in Java:
Checked exceptions:
IOException
SQLException
DataAcessException
ClassNotFoundException
InstantiationException
Unchecked exceptions:
NullPointerException
ArrayIndexOutOfBoundsException
IllegalArgumentException
IllegalStateException
NumberFormatException
ArithmeticException
Q276) What are various exception handling mechanisms?
Answer: Exception handling mechanisms are used to handle exceptions and restore the smooth running of a Java program.
Checked exceptions are declared in the throws clause of a method and can be checked during compile-time. But unchecked exceptions are not declared in throws clause and are only checked during run-time.
Exceptions can be caught using the try-catch-finally blocks. The code which is expected to generate an exception is written in the try block and the exception is caught in the catch block. The finally block contains code that will run no matter what the try-catch blocks generate.
Exceptions can also be caught using custom exception handling. In order to do this, you need to extend the Exception class. The user can provide code that will be generated if there exists an exception.
Q277) What is a thread in Java?
Answer: A thread is a light-weight process. With the help of threads, multiple tasks can run simultaneously within a single process.
Q278) What is meant by synchronization in Java?
Answer: Whenever a thread accesses shared resources, this access should be controlled. This is called synchronization. If the access by these threads are controlled, then there will be consistency and thread interference can be prevented.
Q279) What is meant by serialization in Java?
Answer: Serialization means converting the state of an object to a byte-stream. In order to serialize an object we have to call the writeObject() method. This serialization is platform-independent. An object can be serialized in one platform and deserialized in another.
Q280)What are final and super keywords in Java?
Answer:
Super keyword:
It is used when we are referencing parent class objects.
Final keyword:
It is used only with a variable, method, or a class. Final keyword tells us that if it declared for a variable, then it cannot be modified (constant). If final keyword is used with a class, then it cannot be inherited, and when used with a method, it cannot be overridden.
Q281) Explain Java? and how does Java enables high performance?
Answer: Java is a platform-independent, object-oriented, portable, multi-thread, high-level programming language. Collection of objects is considering as Java. We use Java for developing lots of websites, games and mobile applications. For high performance, Java uses Just in time compiler.
Q282) What is serialization?
Answer: Serialization converts an object to a stream of bytes for safety purposes. We can save it as a file, store in DB or send it by the network. We can also recreate the state of an item when needed.
Q283) What is a Java virtual machine?
Answer: JVM helps the computer to run the Java program or other languages. It acts as a run-time engine. Java code is compiled into bytecode to run on any computer.
Q284) Define constructor?
Answer: It is an instant and special method having the same name as the class. A constructor can be overloaded and a section of code to load newly created objects. If a constructor is created with a parameter then another constructor can be created without a parameter.
Q285) Describe variables? Name them
Answer: A name for a memory location is variable. And it is called a basic unit of storage in a program. You can change the stored value during the program execution.
Local variables
Instant variables
Static variables
Q286) Define the classloader?
Answer: Classloader is a Java runtime environment to load Java classes into Java virtual machine. It loads class files from the network, file system, and other sources. In java, there is 3 built-in classloader.
Extension
System/application
Bootstrap
Q287) What are the wrapper class?
Answer: A wrapper class wraps or contains primitive data types. The Java primitives change into the reference types. It contains a field when we create an object. Primitive data types are stored in this field. Thus a primitive value is also be wrapped.
Q288) Define a package and its advantages?
Answer: The collection of classes, sub-packages, and interfaces are bundled together is called packages. We can modularize the code and optimize its reuse. The code can also be imported by other classes and reused.
It helps to remove name clashes.
Provide access protection to manage the code.
The classes and interfaces are easily maintained because of proper structure.
It contains hidden classes to use within the packages.
Q289) Define the JIT compiler?
Answer: JIT is a program to help in changing the Java bytecode into instructions. It improves the performance of Java applications at the run time and known as the integral parts of the Java Runtime Environment.
Q290) What are the special keywords in Java? Name them
Answer: The special keywords in Java are access modifiers. Constructor, variable, scope of a class, data member or method is restricted. Default, private, protected and the public are four types of access modifiers.
Q291) What are garbage collectors? and types.
Answer: It implicit memory management and destroy the unused objects to relieve the memory. It automatically removes the unreferenced objects to make the memory efficient. There are 4 types of garbage collectors.
Serial garbage
G1 garbage
CMS garbage
Parallel garbage
Q292) Tell the smallest piece of programmed instructions? How does it create?
Answer: A thread, A scheduler executes independently. All programs having one thread is called the main thread. JVM creates the main thread when the program starts its execution. The main ( ) of the program is invoked by the main thread. Thread is created –
By implementing the Runnable interface and extending the thread.
Q293) What executes a set of statements?
Answer: Finally block always executes a set of statements. It is with a try block of any exception occurs or not. It does not execute the program by calling System.exit( ) or by a fatal error.
Q294) What refers to Multi-threading?
Answer: Synchronization, it keeps all concurrent threads in execution. Memory consistency errors are avoided by synchronization. Execution of multiple threads accesses the same objects and fields. The thread holds the monitor when the method is considered as synchronized.
Q295)Tell the purpose of final, finally and finalize?
Answer:
Final cannot be overridden, inherited or change. For restrict the class, variable and method.
Finally, is used for putting important code and executed the exception is handled or not.
Finalize is for cleaning up processing before the object is collected in the garbage.
Q296) Where we use a different signature?
Answer: In method overloading signature must be different. The same class method shares the same name. Every single method should be the indifferent number of parameters or different orders or types of parameters. For “adding” or “extending” and known as a compile-time polymorphism.
Q297) What is Run-time polymorphism?
Answer: Method Overriding is run-time polymorphism having the same signature. Inheritance is required in Method Overriding. It is used to change existing behavior. The subclass has the same method od same number, name, parameters, return type.
Q298) Name the method that belongs to the class?
Answer: In Java, the static method belongs to the class and access only static data. It calls only other static methods and directly accessed by the class name. To define variables, static is used.
Q299) Describe Object-oriented paradigm?
Answer: The programming paradigm based on data and methods is called object-oriented programming. Paradigm incorporates the advantages of reusability and modularity. Objects are instances of classes to interact with one another. It designs programs and applications.
Q300) In Java, what is an object?
Answer: A real-time entity of some behavior and state is called an object. It is an instance of a class with instance variables. The new keyword is for creating the object of the class.
Q301) What is an object-based programming language?
Answer: JavaScript, VBScript is an object-based language and has in-built objects. All the concepts of OOPs such as polymorphism and inheritance are not followed by object-based languages.
Q302) Name the constructor used in Java?
Answer:
Default constructor – It is used to perform the task on object creation and to initialize the instance variable with default values. The constructor does not accept any value. If no constructor is defined in the class, then a default constructor is invoked implicitly by the compiler.
Parameterized constructor – This constructor accepts the arguments. It initializes the instance variables with the given values.
Q303) How to copy the values of the item to others in Java?
Answer: We can print the values by using the constructor, to allow the values of one object to other and the design of clone. In Java, there is no copy constructor.
Q304 ) Explain the Java method?
Answer: The Java method is invoked explicitly and is to disclose the nature of an item, it has an entry. Its name is not the same as the class name. It is not given by the finder.
Q305) Describe the static variables?
Answer: The static variable belongs to the class and makes the memory-efficient of the program. It refers to the common property of all objects. At the moment when class is loading, it gets the memory in the department field.
Q306) Define aggregation?
Answer: Aggregation is described as a has-a relationship and has an entity reference. And having a relationship between two classes. The weak relationship is represented by aggregation.
Q307) What is a super keyword? Mention its uses.
Answer: The Super keyword is a hint variable is to mention at once parent class item with the concept of inheritance, the keyword comes into the picture.
It appeals soon the parent class technique and constructor.
Refers directly parent class instance variable.
It is used to initialize the base class variables.
Q308) What is method overriding? Name the rules and use them.
Answer: In Java method overriding is when a subclass has the specific implementation or the same method as in the parent class.
Rules
It should have the same name and signature as in the parent class.
IS-A relationship should be in between two classes.
Uses
For runtime polymorphism
To give the specific implementation already provided by its superclass.
Q309) What are polymorphism and its types?
Answer: Polymorphism is used in a different context and define the situations. When a single object refers to the super or sub-class depends on the reference type is polymorphism. Many forms are considered as polymorphism.
Q310) Explain the OOPs concepts in Java?
Answer: For programmers to create the components for re-using in different ways. OOPs is known as programming style. The four concepts are
Abstraction
Inheritance
Polymorphism
Encapsulation
Interface
Q311) What is stored in a heap memory?
Answer: Java String pool is a collection of Strings are stored. If you create a new object, the string pool confirms the object is in the pool or not. The same reference is returned to the variable if it is already in the pool.
Q312) How to call one constructor to another to the current object?
Answer: By constructor chaining. It is occurred by inheritance. The task of a subclass constructor is to call the superclass constructor. There are two ways to do constructor chaining.
Within the same class using the keyword “this” ( )
From base class using the keyword “super” ( )
Q313) Tell the nature of Java strings?
Answer: The nature of string objects are immutable which is cached in the string pool. The state of string object cannot be modified after the creation. Java creates a new string object if you update the value of the particular object.
Q314) What is the interface of the Util package? It’s characteristics.
Answer: Map in Java is the interface of the Util package. It is used to map a key and a value. It is different from other collection types. And it is not the subset of the main collection interface.
Duplicate keys are not contained
The order of a map is depending upon the specific implementation
Q315) Describe Java Stack memory?
Answer: Stack memory is in the Last-In-First-Out order to free memory. It is used for the execution of a thread. It contains local primitives and reference to other objects. To define the stack memory, we use –Xss. The memory of the stack is considered short-lived.
Please comment, if you are looking for more Java interview questions and answers. Node Interview Questions React Questions Angular Interview Questions