Sunday, April 2, 2017

Java Interview Questions for freshers

In this post i am sharing Java Interview Questions which are frequently ask for freshers and experienced developers.

1) What is difference between Java and C++?
A) (i) Java does not support pointers. Pointers are inherently insecure and troublesome. Since pointers do not exist in Java. (ii) Java does not support operator overloading. (iii) Java does not perform any automatic type conversions that result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. Therefore, Java does not have global variables or global functions. (v) Java does not support multiple inheritance.

2) What are local variables in Java?

Ans: In Java all variables which are declared inside a block,a method or a constructor are called local variables. These variables must be initialized before using them.

Example:
class Test{
public void age()

{
int age=0;

age=age+30;
System.out.println("my age is:"+age);
}
public static void main(String args[])
{
Test t=new Test();
t.age();
}
}

In the above example,age is local variable. This is declared inside age()method and its scope is limited to this method only.

3) What are instance variable in Java?

Ans: In Java,variables which are declared at class level outside a method or constructor or any block are called instance variables. These variables need not initialize before using them,instance variables are automatically initialized to their default value.Each instance of a class has their own copy of instance variables.

Example:
class Test{
int age;
public void myAge()
{
age=age+30;
System.out.println("my age is:"+age);
}
public static void main(String args[])
{
Test t=new Test();
t.age();
}
}


In the ave program age is instance variable since it is declared outside myAge() method.

4) Why main method is static in Java?

Ans:  main method is static since Java Virtual Machine can call it without creating any instance of class which contains main method. If main method were not declared static then JVM has to create instance of main class and since constructor can be overloaded and can have arguments there would be any certain and consistent way for JVM to find main method in java.

5) What is Encapsulation?

Ans: Wrapping of data and function into a single unit called encapsulation. 
Example: all java programs.
(Or)
Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Or Hiding the information from others is called as Encapsulation. Or Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

6) What is STACK in Java?

Ans: During method calls, objects are created for method arguments and method variables. These objects are created on stack.

7) What is Memory Heap?

Ans: Generally the objects are created using the new keyword. Some heap memory is allocated to this newly created object. This memory remains allocated throughout the life cycle of the object. When the object is no more referred, the memory allocated to the object is eligible to be back on the heap. 

8)Does Java supports Multiple inheritance?

Ans: When a class extends more than one classes then it is called multiple inheritance. Java Doesn't support multiple inheritance directly but by using interface is supported. Whereas C++ supports multiple inheritance.

9) What is abstract class?

Ans: An abstract class is class which can not be create the object of abstract class. We can only extended such classes.We can achieve partial abstraction using abstract classes,to achieve full abstraction we use interface.

10) Difference between transient and volatile variables?

Ans: The transient modifier applies to variables only, the object are variable will not persist. Transient variables are not serialized. Whereas volatile value will be changed unexpectedly by the other part of the program, "it tells the compiler a variable    may change asynchronously due to threads"

11) Difference between parameters and arguments?

Ans: While defining method, variable passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

12)Can an application have multiple classes having main() method?

Ans: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method

13)What is Garbage Collection in java?

Ans: In Java,destruction of object from memory is done automatically by the JVM. When there is no reference to an object then that object is assumed to be no longer needed and the memory occurred by the object are released. This mechanism is called Garbage Collection. This is accomplished by the JVM.

The Garbage Collection cannot be force explicitly. We may request JVM for garbage collection by calling System.gc() method. But there is no guarantee that JVM will perform the garbage collection.

14) What is method overloading in Java?

Ans: If two or more methods in a class have same name but different parameters it is known as method overloading. It is one of the way through which java supports polymorphism. Method overloading can be done by changing number of arguments or by changing the data type of arguments.

15) What is method overriding in Java?

Ans: If subclass(child class)has the same method as declared in the parent class,it is known as method overriding in java. In other words,if subclass provides specific implemention of the method that has been provided by one of its parent class,it is known as method overriding.

16)Can I have multiple main methods in the same class?

Ans: No the program fails to compile. The compiler says that the main method is already defined in the class.

17)Can we declare abstract method in final class?

Ans:  It indicates an error to declare abstract method in final class. Because of final class never allows any class to inherit it.

18)Can we declare final method in abstract class?

Ans: If a method is defined as final then we can’t provide the reimplementation for that final method in it’s derived classes i.e overriding is not possible for that method. We can declare final method in abstract class suppose of it is abstract too, then there is no used to declare like that. 

19) What is static block?

Ans: Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to  the main method the static block will execute.

20) Can you override private or static method in Java?

Ans: You can not override private or static method in java. If you create similar method with same return type and same method arguments that's called method hiding.

21) What is this keyword?

Ans: 'this' is a keyword in java. Which can be used inside method or constructor of class.'this' works as a reference to current object whose method or constructor is being invoked.'this' keyword can be used to refer any member of current object from within an instance method of a constructor.

22) What is difference between final,finally and finalize in java?

Ans: 
final: It is a keyword. The variable declared as final should be initialized only once and can not be changed. Java classes declared as final cannot be extended.Methods declared as final cannot be overridden

finally: It is a block. The finally block always executes when the try block exists. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling. It allows the programmer to avoid having clean up code accidentally bypassed by a return,continue,or break.Putting clean up code in a finally block is always good practice,even when no exceptions are anticipated.

finalize: It is a method. The finalize()method of a java class is useful during garbage collection.

23) Why static methods can not access instance variables?

Ans: Static methods can be invoked before the object is created; Instance variables are created only when the new object is created. Since there is no possibility to the static method to access the instance variables. Instance variables are called as non-static variables

24) What is difference between String and StringBuffer?

Ans: String is a fixed length of sequence of characters, String is immutable.
StringBuffer represent growable and writeable character sequence, StringBuffer is mutable which means that its value can be changed. It allocates room for 16-addition character space when no specific length is specified. Java.lang.StringBuffer is also a final class hence it cannot be sub classed. StringBuffer cannot be overridden the equals() method.

25) What is Synchronization?

Ans: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. (Or) When two or more threads need to access the shared resources they need to some way ensure that the resources will be used by only one thread at a time. This process which is achieved is called synchronization.

26) What is System class?

Ans: System class hold a collection of static methods and variables. The standard input, output, error output of the java run time are stored in the in, out, err variables.

27)How does a Hashtable internally maintain the key-value pairs?

Ans: The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

28)If hash table is so fast, why don't we use it for everything? 

Ans:  One reason is that in a hash table the relations among keys disappear, so that certain operations (other than search, insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the order of the key. Another reason is that when no good hash function can be found for a certain application, the time and space cost is even higher than other data structures (array, linked list, or tree). 
Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.
If many entries are to be put into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

29)What are the Difference between Iterator & Enumeration & List Iterator ?

Ans: Iterator is not synchronized and enumeration is synchronized. Both are interface, Iterator is collection interface that extends from ‘List’ interface. 

Enumeration is a legacy interface, Enumeration having 2 methods 'Boolean hasMoreElements()'& 'Object NextElement()'. Iterator having 3 methods 'boolean hasNext()', 'object next()', 'void remove()'. Iterator also has an extra feature not present in the older Enumeration interface - the ability to remove elements there is one method "void remove()".
List Iterator
It is an interface, List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Methods are 'hasNext()', 'hasPrevious()'.

30) How can we sore an array?

Ans: Arrays class provides a series of sort() methods for sorting arrays. If the array is an array of primitives (or) an array of a class that implements Comparable then you can just call the method directly:
Arrays.sort(theArray);
  If, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.
Arrays.sort(theArray, theComparator);

31) What happens if an exception is not caught?

Ans: An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

32) What is try,catch,throw and throws?

Ans:
 try :This is used to fix up the error, to prevent the program from automatically terminating, 
try-catch is used to catching an exception that are thrown by the java runtime system. 
Throw :is used to throw an exception explicitly.
Throws :A Throws clause list the type of exceptions that a methods might through.

33) Difference between checked & unchecked exceptions in Java?

Ans: Checked exception is some subclass of Exception. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. 

Exampls: IOException thrown by java.io.FileInputStream's read() method•
             
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. 

Example:StringIndexOutOfBoundsException thrown by String's charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

34)What is difference between ClassNotFoundException and NoClassDefFoundError?

Ans: Though both of these errors are related to missing classes in the classpath,the main difference between them is their root cause.

ClassNotFoundException comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath. While in case of NoClassDefFoundError requested class was present at compile time but not available at runtime. Sometimes due to an exception during class initialization. Example is exception from static block causes NoClassDefFoundError when a failed to load class was later referenced by the run time.

35)What is difference between an Exception and an error?

Ans: Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program.

Examples:
  • Memory error
  • Hardware error
  • JVM error
Exceptions are conditions within the code. Developer takes responsibility to handle such conditions and take necessary corrective actions.

Example:

NullpointerException
ArithmeticException

Read Also:













No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...