100 Java Interview
100 Java Interview
Q2. In project when we will instance & static varaibles give the scenario?
Ans: instance variables every object separate memory created.
where as static varaibles for all object single copy created per class.
class Emp
{ int eid;
String ename;
double esal;
for-each loop conditions are not apply it will print the data from start to end.
int[] a = {1,2,3,4....1000};
for (int x : a)
{ System.out.println();
}
object is real world entity contains properties & behaviours is called object.
single class possible to create multiple objects, every object needs memory.
Ans: Constructor is a special method to write the logics, these logics are
automatically executed during object creation.
constructor name & class-name should same.
No return type but arguments are allowed.
Bitwise operators can be used for bitwise calculations & logical conditions
sop(10&5) // 6 // int
SOP(10>20 & 30<40) // false // boolean
Q13. What are the entry controlled loop & exit controll loop?
Ans: Entry controlled loop : for,while
for (initialization;condition ;inc/dec)
{ body
}
while (condition)
{ body
}
class Demo
{ static
{ System.out.println("Demo class static block");
}
}
class Test
{ public static void main(String[] args)throws Exception
{ //Demo d = new Demo();
Class.forName("Demo");
}
}
Q17. How to call the constructor in java?Is it one constructor can call multiple
constructors?
Ans: To call the constructor use this keyword.
this(10) : calling 1-arg constructor
this(10.5,'a') : calling 2-arg constructor
this("ratan",false,20.3f) : calling 3-arg constructor
Inside the constructor, the constructor calling this keyword should be first line.
So one constructor can call only one constructor.
class Test
{ Test()
{ this(10);
System.out.println("0-arg cons");
}
Test(int a)
{ this(10,20);
System.out.println("1-arg cons");
}
public static void main(String[] args)
{ new Test();
}
}
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
DURGASOFT
Q18. What is method recursion?
Ans: Method recursion : method calling itself is called recursion?
class Test
{ static void validate(int num)
{ if (num>0)
{ System.out.println("My Number is..."+num);
validate(--num);
}
else
{ System.out.println("Your number is Negative....");
}
}
public static void main(String[] args)
{ Test.validate(10);
}
}
Q19. What are the Different ways to call the static members in java?
Ans: we can access the static variables in three ways,
a. Using class-name [it is recommanded]
b. Direct access
c. Access using object name.
class Test
{ static int num = 10;
public static void main(String[] args)
{ System.out.println(Test.num);
System.out.println(num);
in switch based on the argument data the matched case will be executed.
switch(argument)
{ case label-1 : statement(s); break;
case label-2 : statements; break;
default : statements; break;
}
Q21. When we will use for vs. while loops in Application?
Ans: case 1:
for loop is recommended when we have the : start , end_cond , incre/decre
for (initialization;condition;inc/dec)
{ Logics Here....
}
for (int j=1;j<=10 ;j++)
{ System.out.println("Good Morning....");
}
while loop is recommended when we have the only condition check.
while (condition){
}
ArrayList names = {"ratan","anu","sravya"};
while(names.hasNext())
{ System.out.println(names.next());
}
case 2:
if you know number of iterations use for loop. :: for(int
i=1;i<=5;i++)
if you do not no number of iterations use while loop :: while(true)
Q23. What is the difference between the normal import & static import?
Ans: There are two types of imports
a. normal import
Here we can access both instance & static data. But here
access the static data using class-name.
import com.tcs.info.Test;
b. static import
using static import it is possible to access only static data
directly without using class-name. It is not possible to access instance data.
import static com.tcs.info.Test.*;
If the class contains private constructor, it is not possible to create the object
outside of the class.
We can prevent the object creation of outside the class by declaring the private
constructor.
Q26. Can we access sub-packages data when we import main package with *?
Ans: No, not possible.
The main packages contains sub packages also.
java.lang
java.lang.annotation
java.lang.instrument
java.lang.invoke
java.lang.management
java.lang.ref
java.lang.reflect
import java.lang.*;
When we import main package with * it is possible to access only main
package classes,
but not sub packages classes, to Access the sub package classes import sub
packages also.
import java.lang.*;
import java.lang.annotation.*
In general we have five types of inheritance but java support three types.
In java one class can extends only one class at a time. If we are extending more than
one class we will get error message.
class Parent
{ void eat()
{ System.out.println("idly............");
}
}
class Child extends Parent
{ void eat()
{ System.out.println("poori/ dosa.....");
}
public static void main(String[] args)
{ Child c = new Child();
c.eat();
}
}
Q33. What are the rules to fallow while overriding the method?
Ans: Overriding Rules: 9-rules
1. Overridden method signature & overriding method signature must be same.
2. final methods are not possible to override.
3. Method return types must be same at primitive level.
4. Method return types can be changed at object level using Co-variant return
type.
5. private methods are not possible to override.
6. Same & increasing level permissions are valid but not possible to decrease
the permission.
7. static methods are not possible to override.
8. overridden method not throws any exception,
then overriding method can throws unchecked but not checked.
9. overridden method throws exception then
overriding method can throws same exception
overriding method not throws any exception
overriding method can throws child exception
overriding method can not throws parent exception
class Dog {}
class Puppy extends Dog{}
class Parent
{ Dog info()
{ return new Dog();
}
}
class Child extends Parent
{ Puppy info()
{ return new Puppy();
}
}
Method hiding:
static methods we will hide.
Method signature must be same in parent & child classes.
Here method execution decided by class-name.
Observation :
a. The parent & child classes methods are instance is called method overriding
b. The parent & child classes methods are static is called method hiding.
c. In parent & child one method is instance, one method is static is not allowed.
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Test x = (Test)t.clone();
System.out.println(x.num1+" "+x.num2);
}
}
initially your class does not support cloneing process. So your class must implements
Cloneable.
java.lang.Cloneable ----> provides cloning capabilities
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
DURGASOFT
java.io.Serializable ----> provides Serialization capabilities
java.util.RandomAccess ----> data accessing capabilities
The above process is deep cloning creating duplicate objects.
One more cloning is shallow cloneing. creating duplicate references.
Test t1 = new Test();
Test t2 = t1; // here t2 also is pointing to t1 object
Garbage collector will collect the garbage. Garbage means an object without
reference.
When the JVM Running,Then only the garbage collector will run automatically to
destory the un-used objects.
Q47. What are the Different ways to call the Garbage Collector?
Ans: We can call the GC in two ways
i. System class : gc() : static method
ii. Runtime class : gc() : instance method
only Runtime class gc() method can call the garbage collector directly. The
System.gc() internally calls Runtime class gc() to call the Garbage Collector.
class Test
{ public void finalize()
{ System.out.println("object destroyed");
}
public static void main(String[] args)
{ Test t1 = new Test();
System.out.println(t1);
t1 = null;
Runtime r = Runtime.getRuntime();
r.gc();
}
}
Q53. Though interface is a pure abstract class then why interfaces are needed?(OR)
What if you had an Abstract class with only abstract methods? How would
that be different from an interface? (OR)What are the difference between an
abstract class and an interface?
Ans:
Abstract class:
The abstract classes may contain state (data members) and/or
implementation (methods).
Can contains non final & non static variables i.e., abstract class may
have state.
Only abstract methods are good enough to implement in subclass.
Does not supports multiple inheritance using abstract classes.
Can contains any number of constructors.
Interface:
Interfaces can have no state or implementation.
All variables must be static and final. Hence there is no state in
interface.
The subclass of an interface must provide an implementation of all the
methods of that interface.
Interfaces supports multiple inheritance.
Never contains constructors at all.
Q57. What are the possible ways to handle the multiple exceptions in java?
Ans: Below all cases can handle multiple exceptions using single catch,
1. catch(Exception e){}
2. using pipe symbol, catch(ArithmeticException |
ClassCastException a)
3. using multiple catch blocks we can handle.
(when we write the multiple catch block the catch block order should be child
to parent,If we write the parent to child we will get error.)
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
DURGASOFT
Q58. What is the purpose of try-with resources concept?
Ans: a.When we declare the resources using try block, once the try block is
completed the resource is automatically released.
syntax: try(Resource-1;resource-2;.....resource-n){
}
b. How it is release automatically means,every resource internally
implemeting the AutoCloseable & it contains close() method to close the resources.
public interface java.lang.AutoCloseable {
public abstract void close() throws
java.lang.Exception;
}
c. The close() method is invoked automatically on objects managed by the try-
with-resources statement.
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ try(Scanner s = new Scanner(System.in))
{ System.out.println("enter id");
int a = s.nextInt();
System.out.println("input value="+a);
}
}
}
Note: using throw keyword we can throw predefined exceptions & user defined
exception.
But throwing predefined exceptions are not recommended because
predefined exceptions are having fixed meaning.
equals() method present in object class used for reference comparison it return
Boolean value.
If two reference variables are pointing to same object returns true otherwise
false.
String is child class of Object and it is overriding equals() methods used to
perform data comparison. If two objects data is same then returns true otherwise
false.
StringBuffer class there is no equals() method it uses parent class(Object)
equals() method used for reference comparison.
String s1 = new String("ratan");
String s2 = new String("ratan");
System.out.println(s1.equals(s2));
If the application requirment is to store the fixed data then use String class.
2. Two ways to create object
a. without using new operator
String str = "ratan"
b. by using new operator
String str = new String("ratan");
3. If the application requirement is to perform Data comparision use String class.
StringBuffer:
1. StringBuffer is mutable modifications are allowed.
If the applcation requirement to store the data with flexibility of modification then
use StringBuffer class.
2. One way to create the StringBuffer using new
StringBuffer sb = new StringBuffer("ratan");
3. If the application requirement is reference-comparision then use StringBuffer class.
data comparision not possible.
StringBuilder :
A mutable sequence of characters. But with no guarantee of
synchronization(StringBuilder methods can be accessed by multiple threads at a
time).
This class is designed for use as a drop-in replacement for StringBuffer in
places where the string buffer was being used by a single thread. Where possible, it is
recommended that this class be used in preference to StringBuffer as it will be faster
under most implementations.
Before enum
class Week
{ public static final Week MON;
public static final Week TUE;
public static final Week WED;
}
java code with enum:
enum Week
{ MON,TUE,WED; //public static final
}
Q70. How to perform read & write operations on text files & images?
Ans:
To perform IO operations we need classes & interfaces these are present in java.io
package.
Using java.io package classes & interfaces it is possible to work with only text files.
Java Application can read the data from text file & write the data to text file.
Channel is a communication medium to transfer the data.
Every Channel can do two operations,
a. read operations
b. write operations.
Q72. How to create & remove the files & directories in java?
Ans:
boolean java.io.File.createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract path name if and
only if a file with this name does not yet exist.
true if the named file does not exist and was successfully created;
false if the named file already exists
File file = new File("ratan.txt");
System.out.println(file.exists());
boolean status = file.createNewFile();
boolean java.io.File.mkdir()
Creates the directory named by this abstract pathname.
true if and only if the directory wascreated; false otherwise.
File f = new File("usman");
boolean b = f.mkdir();
Note: To create the file under the directory the directory should be present.
File ff = new File("usman","ratan.txt");
ff.createNewFile();
To delete the file use delete() method.
File file = new File("ramu.txt");
boolean bb = file.delete();
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
36 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
DURGASOFT
Q73. what are the advantages of nested classes in java?
Ans:Declaring the class inside the another class is called nested class.
Nested classes are introduced in java1.2 version
There are two types of nested classes
1. Static nested classes
2. Non-static nested classes(Inner classes)
a. Normal inner.
b. Method local inner.
c. Anonymous inner.
Collections.sort(students,Comparator.comparing(Student::getRollno));
To get the information about Demo class load the class first. The loaded class
information stored in Class object.
Class c = Class.forName("Demo");
Daemon Thread:
In Java, daemon threads are basically referred to as a service provider that
provides services and support to user threads.
The threads are executing at back group to give the support to foreground
threads.
ex: garbage Collector. (while JVM running Garbage Collector running)
Once the main/user thread completes execution all daemon threads are
automatically stopped.
To set the daemon nature use setDaemon() method.
thread.setDaemon(true);
The assert statements are by default desable.To enable the assert statemetns
use -ea (enable assertion)
if the assert condition is true then applcation is normal execution
if the assert is false we will get AssertionError with message.
When we get AssertionError think that we are putting some condition but it is fail.
b. Map : used to store the data two objects format in the form of key:value
{"ratan":5,"anu":2,"sravya":10,"that":5}
Map implementation classes : HashMap , LinkedHashMap ,
TreeMap , Hashtable
Collections:
store the group of objects : homogenous & heterogenous
Collections are growable in nature : size will increase & decrease
memory wise it is good
collections support methods operations are easy.
collections can store only object data.
Q91. What are the Differeent ways to read the data from collection classes?
Ans: we can read the data from collection classes in different way,
1. using for-each loop.
2. using get method.
3. using cursors
a. Enumeration
b. Iterator
c. ListIterator
4. using forEach() method.
Q93. What are the conditions we need to fallow while sorting Collection data?
Ans: if we want to perform sorting data it must satisfies the below conditions,
a. The data must be homogenous.
b. Must implements Comparable interface.
In java String,all wrapper classes are implementing comparable interface by default.
The Collection class methods internally fallows compareTo() method to
perform sorting.
Different ways to perform sorting,
Collections.sort();
list.sort()
stream.sort()
case 1: if we are trying to perform sorting of heterogeneous data ,while
performing comparison by using comapreTo() method JVM will
generate java.lang.ClassCastException.
Using compareTo() not possible to compare two different objects.
ArrayList al = new ArrayList();
al.add("ratan");
al.add(10);
Collections.sort(al);
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
46 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: [email protected]
DURGASOFT
case 2: when we perform sorting of data, if the data contains null value while
performing comparison by using compareTo() method JVM will
generate java.lang.NullPointerException.
Any object with comparision of null, you will get NullPointerException.
ArrayList al = new ArrayList();
al.add("ratan");
al.add(null);
Collections.sort(al);
Q94. what is the purpose of serialization & Desrialization process? How to prevent
serialization?
Ans: with in the JVM instance just public modifier is sufficient to get the permission.
JVM1 :module-1 module-2
If the project is running multiple JVM instances then public modifier is not sufficient to
access the data, in this case use serialization & desrialization.
JVM-1 n/w JVM-2
m1 file m2
Serialization:
The process of converting java object into network supported form or file
supported form is called serialization. (OR) The process of saving an object to a file is
called serialization.
(OR)The process of writing the object to file is called serialization.
To do the serialization we required fallowing classes
1. FileOutputStream
2. ObjectOutputStream
Deserialization:
The process of reading the object from file is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
java.lang.Comparable:
To perform default natural sorting we will use Comparable, only String &
wrapper classes are implements Comparable Interface.
It gives compareTo() method technique to sort elements.
If you want to sort the elements as per the default natural sorting order, you
must choose the Comparable interface.
java.util.Comparator:
It is used to perform the sorting of userdefiend classes like Emp,Student....etc.
The predefiend classes are not implementing this interface.
It gives compare() method technique to sort elements.
c. The key value pair is known as entry, the map contains group of entries.
d. In the map the keys must be unique but values we can duplicate.
3. ip no of hits
10.5.6.4 ----- 5
10.5.4.2 ----- 10
78.90.45.4 ----- 5
Streams don’t change the original data structure, they only provide the result
as per the pipelined methods.
map: The map method is used to returns a stream consisting of the results of
applying the given function to the elements of this stream.
Collections generics are non polymorphic because the generic data remmoves at
compile time.
void addAnimals(List<Animal> animals){
}
List<Dog> dogs = new ArrayList<Dog>();
addAnimals(dogs);//C.E