JAVA Interview Questions and Answers

java interview questions and answers

In case you’re searching for Java Interview Questions and answers for Experienced or Freshers, you are at the correct place. There is parcel of chances from many presumed organizations on the planet. The Java advertise is relied upon to develop to more than $5 billion by 2020, from just $180 million, as per Java industry gauges. In this way, despite everything you have the chance to push forward in your vocation in Java Development. Gangboard offers Advanced Java Interview Questions and answers that assist you in splitting your Java interview and procure dream vocation as Java Developer.

Best Java Interview Questions and Answers

Do you believe that you have the right stuff to be a section in the advancement of future Java, the GangBoard is here to control you to sustain your vocation. Various fortune 1000 organizations around the world are utilizing the innovation of Java to meet the necessities of their customers. Java is being utilized as a part of numerous businesses. To have a great development in Java work, our page furnishes you with nitty-gritty data as Java prospective employee meeting questions and answers. Java Interview Questions and answers are prepared by 10+ years experienced industry experts. Java Interview Questions and answers are very useful to the Fresher or Experienced person who is looking for the new challenging job from the reputed company. Our Java Questions and answers are very simple and have more examples for your better understanding.

By this Java Interview Questions and answers, many students are got placed in many reputed companies with high package salary. So utilize our Java Interview Questions and answers to grow in your career. 

Q1) Which of the following main method declarations will fail in compilation?

  1. public static void main(String args)
  2. public static void Main(String args[])
  3. public void main(String args[])
  4. public static main(String args[])

Answer : d
Explanation: All methods in java should have return type.

Q2) Which of the following assignment is incorrect?

  1. int a= (int) 10.0;
  2. double d=10;
  3. float f=3.4;
  4. int b=(byte) 4;

Answer : c
Explanation : 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 Sample
{        public static void main(String args[])
{
String a=”Dhoni”;
String a1=new String(“Dhoni”);
String a2=”Dhoni”;
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 (“Dhoni”) 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 Sample
{
String sam;
public Sample(String val)
{
sam=val;
}
public void print()
{
System.out.println(sam);
}
public static void main(String args[])
{
Sample s1=new Sample(“Test”);
s1.print();
Sample s2=new Sample();
s2.sam=”Test2″;
s2.print();
}

}

  1. Compilation error
  2. Runtime error
  3. Test
  4. Test2

Answer: a
Explanation : 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.

  1. Variable
  2. Method
  3. Class
  4. Interface

Answer : a,b,c
Explanation : 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) Which of the following is not true about static keyword?

  1. Single copy of static data members is created for all objects.
  2. Static methods can be invoked without creating objects for the class.
  3. Static methods can access only static variables.
  4. Non Static methods cannot access static variables.

    Answer: d

Q11) Explain method overriding?

Explanation: Two methods having same name and same signature in both Parent and Sub class is called method overriding.

Q12) ‘Super’ keyword can be used to access which of the following from Parent class?

  1. Constructors
  2. Methods
  3. Data Members
  4. All the above

Answer : d

Q13)Constructors are called in which of the below order?

  1. Super class to Derived classes
  2. Derived Classes to Super Class

Answer : a

Q14)Objects cannot be created for abstract classes

  1. True
  2. False

Answer : a

Q15)Which of the following is true for the below program?

final class Sample
{
int a;
}

  1. Objects cannot be created for class Sample
  2. Sample class cannot be inherited.
  3. Methods in class Sample cannot be overridden.
  4. Sample class cannot extend any other class.

Answer : b
Explanation : 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”);
}
}
}

  1. Compilation Error
  2. Runtime Error
  3. Exception is printed
  4. ArithmeticException is printed

Answer: a
Explanation : Exception should be ordered in catch blocks in order Derived class to Super class.

Q17) finally block will be executed only when exception occurs.

  1. True
  2. 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.

  1. True
  2. 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.

  1. True
  2. 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();

  1. Invokes start() method
  2. Invokes run() method
  3. Invokes begin() method
  4. Invokes main() method

Answer : b
Explanation : 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;

  1. Enumeration
  2. Autoboxing
  3. Unboxing
  4. Annotation

Answer : Autoboxing
Explanation : 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
Explanation : ‘out’ is static data member in System class of type PrintStream

Q24) In what class print() and println() methods are available?

  1. PrintStream
  2. InputStream
  3. OutputStream
  4. PrintWriter

Answer : PrintWriter

Q25) Which type of classes can work on different types of data?

  1. Abstract Class
  2. Final Class
  3. Super class
  4. Generic class

Answer : d
Explanation : Generic classes are classes which can operate on any type of data.

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?

  1. ArrayList
  2. LinkedList
  3. HashSet
  4. 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?

  1. Collection
  2. List
  3. Set
  4. Vector

Answer : d

Q29)Which of the following data structure in Java is used to store key value pairs?

  1. List
  2. Set
  3. Map
  4. Stack

Answer : c

Q30) Which of the following is sorted by default

  1. ArrayList
  2. LinkedList
  3. TreeSet
  4. HashSet

Answer : c
Explanation : 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?

  1. Serializable
  2. Cloneable
  3. Appendable
  4. Closeable

Answer : b

Q32) Method used to deserialize and serialize objects respectively.

  1. writeObject(),readObject()
  2. readObject(),writeObject()
  3. read(),write()
  4. write(),read()

Answer : b

Q33) Which among the following is a Character Stream class?

  1. FileInputStream
  2. FileReader
  3. FileOutputStream
  4. InputStreamReader

Answer : b
Explanation : FileReader is a byte stream class.

Q34) Which of the following is not a markable interface?

  1. Serializable
  2. Cloneable
  3. Remote
  4. ActionListener

Answer : d

Q35) Which of the following packages will be imported automatically by JVM?

  1. util
  2. lang
  3. io
  4. awt

Answer: b

Q36) Which of the following packages Date class belongs to?

  1. util
  2. lang
  3. io
  4. awt

Answer: a

Q37)Which among the following is super class of all class in Java?

  1. Object
  2. Super
  3. ObjectInput
  4. ObjectInstance

Answer : a

Q38) Which of the following is not a lightweight component?

  1. Jbutton
  2. JLabel
  3. JTextField
  4. TextField

Answer : d
Explanation : TextField belongs to AWT Component which is hard weight by nature.

Q39) Which of the following is not a Listener interface in java?

  1. ActionListener
  2. ComponentListener
  3. ItemListener
  4. 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
Explanation : 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
Explanation : break will break out of the all consecutive iterations.

Q43) All methods declared in an interface have which of the following property implicitly?

  1. Final
  2. Static
  3. Abstract
  4. Super

Answer : 3
Explanation : All methods in an interface are abstract by nature.

Q44) All data members declared in an interface have which of the following property implicitly?

  1. Final
  2. Static
  3. Abstract
  4. Super

Answer : a
Explanation : All data members in an interface are final by nature.

Q45) Which of following interface is used for multiple sorting?

  1. Comparable
  2. Comparator
  3. Cloneable
  4. Serializable

Answer : b

Q46) Which of the following interface has compareTo method declaration?

  1. Comparable
  2. Comparator
  3. Cloneable
  4. Serializable

Answer : a
Explanation : 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);
}
}

  1. Compilation Error
  2. Arithmetic Exception on runtime
  3. Infinity
  4. Exception on runtime

Answer : c
Explanation : 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?

  1. Public
  2. Private
  3. Default
  4. Protected
  5. None of the above

Answer : e

Q49) Which of the following is not part of java.net package?

  1. Socket
  2. ServerSocket
  3. URL
  4. Serialize

Answer : d

Q50) Which of the following created immutable Strings?

  1. String
  2. StringBuffer
  3. StringBuilder
  4. StringAppender

Answer : a      

Q51) What will be the output if you execute the below code snippet?

public class Sample {

public static void main(String[] args) {

HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,”a”);
hm.put(2,”b”);
hm.put(3,”c”);
hm.put(1,”d”);

System.out.println(hm.toString());

}
}

  1. {1=d, 2=b, 3=c}
  2. {1=d, 2=b, 1=a}
  3. {1=a, 2=b, 3=c,1=d}
  4. {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”);

}
}
}

  1. The code will show compile time errors
  2. The code runs successfully and displays nothing
  3. The code runs successfully and displays 2.
  4. 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 a*a;
}

}

public class Cube extends Square {

public int calculateArea(int a) {

return a*a*a;
}

public static void main(String[] args) {
Square b = new Cube();
System.out.println(b.calculateArea(3));
}

}

  1. The output 27 is displayed
  2. The output 9 is displayed
  3. The code shows runtime error
  4. The code shows compile time error

Answer : a

Q54)   Which of the following is true? Choose only one

  1. static methods can be overloaded and overridden.
  2. static methods can be overloaded but cannot be overridden.
  3. static methods can be overridden but cannot be overloaded.
  4. 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();
}
}

  1. True
  2. False

Answer : a

Q56)   A constructor can be static and final.  Say true or false

  1. True
  2. False

Answer : b

Q57)   All the fields in the interface are

  1. public
  2. b. static , final, public
  3. abstract
  4. public and final

Answer : b

Q58)   Which of the following statement is correct. Choose only one.

  1. StringBuilder is thread safe and StringBuffer is not thread safe.
  2. Both StringBuffer and StringBuilder are thread safe.
  3. Both StringBuilder and StringBuffer are mutable. StringBuilder is not thread safe but   StringBuffer is thread safe.
  4. 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?

  1. append(String s)
  2. replace(char oldChar, char newChar)
  3. charAt(int index)
  4. 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?

  1. Aggregation
  2. Composition
  3. Inheritance
  4. 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);

}

}

  1. A A
  2. A Z
  3. Z A
  4. Z Z

Answer : c

Q62) Which of the following would you use in case of storing unique elements with the order of insertion?

  1. LinkedHashSet
  2. HashSet
  3. HashMap
  4. 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);
}

}
}

  1. InterruptedException is caught
  2. Exception is caught
  3. Exception is not caught
  4. Nothing is displayed

Answer : a

Q64) What are the different types of inheritance among classes in java?

  1. Multilevel, Multiple, Single, Heirarchial
  2. Multilevel, Multiple, Single, Hybrid
  3. Multilevel, Multiple, Single, Heirarchial,Hybrid
  4. 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);
}
}

  1. true true
  2. false true
  3. true false
  4. false false

Answer : b

Q67) Overloading of methods cannot be   done by changing only the

  1. Type of arguments
  2. order of arguments
  3. number, type and order of arguments
  4. 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);
}
}

  1. 2 is displayed
  2. 1 is displayed
  3. Runtime exception is thrown
  4. Code will not compile

Answer : d

Q69) Try block cannot be blank and must contain a statement. Say True or False

  1. true
  2. false

Q70)   Which of the following is true about local variables?

  1. a. Local variables can be final but cannot be static or transient. Local variables cannot be public, private or protected.
  2. Local variables can be final or static but cannot be transient. Local variables can be private only.
  3. Local variables can be final , static and transient. Local variables can be private only.
  4. 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);
}
}

  1. 13 is displayed
  2. 0 is displayed
  3. 10 is displayed
  4. 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);
}
}

  1. ClassCastException will be thrown
  2. Compiler time error occurs
  3. Displays output as

2
100
100
100.0

  1. 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);
}
}

  1. Nothing is printed
  2. do while loop keeps on running after entering an infinite loop
  3. it prints “inside do while loop”
  4. Runtime Exception is thrown

Answer : c

Q74)   The use of this() and super() is allowed inside static method and constructor. Say true or false.

  1. true
  2. 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
  1. Remove the class B
  • No changes needed.

Answer : d

Q76)   How to send a cookie in the response?

  1. HttpServletResponse.addCookie(Cookie).
  2. HttpServletResponse.setCookie(Cookie).
  3. HttpServletResponse.sendCookie(Cookie).
  4. 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?

  1. sendRedirect()
  2. b. forward()
  3. send()
  4. 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 %>

  1. Displays 20
  2. You cannot re declare a
  3. Displays 10
  4. Error is displayed

Answer : c

Q80)   This is responsible for managing the lifecycle of a servlet.

  1. Application server
  2. Web container
  3. Application container
  4. Web server

Answer : b

Q81)   With java 7, which of the following is supported in switch statement?

  1. Enum
  2. Character
  3. String
  4. constant

Answer : c

Q82) Which of the following code gives minimum value in the given list ?

  1. list.stream()

.mapToInt(v -> v)
.findMin() ; 

  1. list.stream()

.mapToInt(v -> v)
.min()
.orElse(Integer.MAX_VALUE);

  1. list.stream()

.min(Comparator.naturalOrder)
.get();

d.List.stream(list)
.mapToInt(v -> v)
.min();
Answer : b

Q83)  What is the type of lambda expressions?

  1. Object
  2. functional interface
  3. Interface
  4. Object variable

Answer : b

Q84) Which of the following is not a method of Optional class in java 8?

  1. IsPresent()
  2. OfNullable(T val)
  3. OrElse(T t)
  4. 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);
}
}

  1. ClassCast exception is thrown
  2. Compile time Exception is thrown
  3. NumberFormatException is thrown
  4. Code displays “123s4”

Answer : c

Q86) Which of the following is not a built  in java annotation?

  1. @Override
  2. @SuppressWarnings
  3. @Deprecated
  4. @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”);
}
}

  1. CheckedException cannot be used with throws keyword
  2. Sub class overridden method cannot throw CheckedException
  3. CheckedException should be handled with try and catch block
  4. The code is correct

Answer : b

Q88) Which of the following is not true about lambda expressions?

  1. Lambda expressions are a way to replace anonymous classes
  2. Lambda expressions helps in the implementation of functional interfaces
  3. The scope of lambda expressions is not limited to its enclosing class
  4. 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

  1. Class Room extends House{ luxury();}
  2. Class House {private LuxuryType Room;}
  3. Class Room {private House (Luxury luxury);}
  4. Class Room {private Luxury house;}

Answer : b

Q90) Which of the following is correct implementation of NavigableSet?

NavigableSet<String> al=new NavigableSet <String>();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
NavigableSet<String> al=new TreeSet<String>();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
Set<String> al=new NavigableSet <String>();
al.add(“Ram”);
al.add(“Veer”);
al.add(“Ram”);
al.add(“Ajay”);
TreeSet <String> al=new NavigableSet <String>();
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?

  1. join()
  2. wait()
  3. wait(int num)
  4. resume()

Answer : a

Q92) The keyword synchronized can be applied to

  1. Methods, variables, block
  2. Methods, blocks, static blocks
  3. Variables, methods
  4. Methods and blocks

Answer : b

Q93) Which tag is used to force the container to load as the server starts?

  1. <load-on-startup>
  2. <load-init>
  3. <load-startup>
  4. <server-startup>

Answer : a

Q94) Which of the following is true about ServletContext?

  1. One per web application
  2. One per session
  3. One per context
  4. One per web config

Answer : a

Q95) Which of the following  is not a http method?

  1. GET
  2. REPLACE
  3. PUT
  4. HEAD

Answer : b

Q96) Which of the following not a class in collection hierarchy?

  1. SortedSet
  2. TreeSet
  3. LinkedHashSet
  4. 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?

  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver
  4. 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?

  1. implements
  2. package
  3. throws
  4. Integer

Answer : d

Q100) How to find the size of the given array named arrayNum?

  1. size()
  2. length
  3. length()
  4. 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 .

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 Besant!!”;
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 beasant”);
}
Output:
Hi besant
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 Besant!!”;
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<String> a1=new ArrayList<String>();
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 :

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. 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.

Q126) Why Inheritance?

Answer : It is used for Resusability

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.

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<Balls> 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 :

  1. Extend Thread class
  2. 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:

  1. Value of a data member that is declared as final cannot be changed.
  2. A method that is declared as final cannot be overridden.
  3. A class that has been declared as final cannot be subclassed.

Q190)What are the states of a thread?

Answer :

  1. Initial
  2. Runnable
  3. Waiting
  4. Blocked
  5. 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 :

  1. Collection
  2. List
  3. Queue
  4. Deque
  5. Set
  6. SortedSet
  7. 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.

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 :

  1. The variable argument list must be the last argument.
  2. 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 :

  1. equals()
  2. hashcode()
  3. wait()
  4. getClass()
  5. toString()
  6. notify()
  7. 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.

Q226) What are OOPS concepts ?

Answer :

  1. Encapsulation
  2. Inheritance
  3. Abstraction
  4. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Looking for Online Training