Java Programming

Java Programming Interview Questions and Answer

Q. Can we Override static methods in java?

A.

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is 'No'. Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).

Q. Can we overload static methods?

A.

The answer is 'Yes'. We can have two ore more static methods with same name, but differences in input parameters.

Q. What is blank final variable?

A.

A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later.

 final int i = 10;
 i = 30; // Error because i is final.

A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final.

    // A simple blank final example 
    final int i;
    i = 30;

Q. Can we override private methods in Java?

A.

No, a private method cannot be overridden since it is not visible from any other class.

Q. Why method overloading is not possible by changing the return type in java?

A.

In C++ and Java, functions can not be overloaded if they differ only in the return type . The return type of functions is not a part of the mangled name which is generated by the compiler for uniquely identifying each function. The No of arguments, Type of arguments & Sequence of arguments are the parameters which are used to generate the unique mangled name for each function. It is on the basis of these unique mangled names that compiler can understand which function to call even if the names are same(overloading).

Q. Can we overload main() method?

A.

The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded in a similar manner, JVM always looks for the method signature to launch the program.

  • The normal main method acts as an entry point for the JVM to start the execution of program.
  • We can overload the main method in Java. But the program doesn’t execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only.

Q. Which class is the superclass for every class ?

A.

Object class

Q. What happens if you remove static modifier from the main method?

A.

Program compiles successfully . But at runtime throws an error "NoSuchMethodError".

Q. What is JAVA?

A.

Java is a high-level programming language and is platform independent.

Java is a collection of objects. It was developed by Sun Microsystems. There are a lot of applications, websites and Games that are developed using Java.

For more details please visit here

Q. How does Java enable high performance?

A.

Java uses Just In Time compiler to enable high performance. JIT is used to convert the instructions into bytecodes.

Q. What are the Java IDE’s?

A.

Eclipse and NetBeans are the IDE’s of JAVA.

Q. What do you mean by Constructor?

A.

The points given below explain what a Constructor is in detail:

  • When a new object is created in a program a constructor gets invoked corresponding to the class.
  • The constructor is a method which has the same name as class name.
  • If a user doesn’t create a constructor implicitly a default constructor will be created.
  • The constructor can be overloaded.
  • If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter.

Q. What is meant by Local variable and Instance variable?

A.

Local variables are defined in the method and scope of the variables that have existed inside the method itself.

An instance variable is defined inside the class and outside the method and scope of the variables exist throughout the class.

Q. What is a Class?

A.

All Java codes are defined in a class. A Class has variables and methods.

Variables are attributes which define the state of a class.

Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement.

public class Addition{ //Class name declaration
int a = 5; //Variable declaration
int b= 5;
public void add(){ //Method declaration
int c = a+b;
}
}

Q. What is an Object?

A.

An instance of a class is called object. The object has state and behavior.

Whenever the JVM reads the "new()" keyword then it will create an instance of that class.

public class Addition{
public static void main(String[] args){
Addion add = new Addition();//Object creation
}
}

The above code creates the object for the Addition class.

Q. What are the Oops concepts?

A.

Oops concepts include:

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Interface

Q. What is Encapsulation?

A.

Purpose of Encapsulation:

  • Protects the code from others.
  • Code maintainability.

We are declaring 'a' as an integer variable and it should not be negative.

public class Addition(){
int a=5;
}

If someone changes the exact variable as "a = -5" then it is bad.

In order to overcome the problem we need to follow the below steps:

  • We can make the variable as private or protected one.
  • Use public accessor methods such as set and get.

So that the above code can be modified as:

public class Addition(){
private int a = 5; //Here the variable is marked as private
}

Below code shows the getter and setter.

Conditions can be provided while setting the variable.

get A(){
}
set A(int a){
if(a>0){// Here condition is applied
.........
}
}

For encapsulation, we need to make all the instance variables as private and create setter and getter for those variables. Which in turn will force others to call the setters rather than access the data directly.

Q. What is Polymorphism?

A.

A single object can refer the super class or sub-class depending on the reference type which is called polymorphism.

Public class Manipulation(){ //Super class
public void add(){
}
}
public class Addition extends Manipulation(){ // Sub class
public void add(){
}
public static void main(String args[]){
Manipulation addition = new Addition();//Manipulation is reference type and Addition is reference type
addition.add();
}
}

Using Manipulation reference type we can call the Addition class "add()" method. This ability is known as Polymorphism.

Polymorphism is applicable for overriding and not for overloading.

Q. What is meant by Method Overriding?

A.

Method overriding happens if the sub class method satisfies the below conditions with the Super class method:

  • Method name should be same
  • Argument should be same
  • Return type also should be same

The key benefit of overriding is that the Sub class can provide some specific information about that sub class type than the super class.

public class Manipulation{ //Super class
public void add(){
………………
}
}

Public class Addition extends Manipulation(){
Public void add(){
………..
}
Public static void main(String args[]){
Manipulation addition = new Addition(); //Polimorphism is applied
addition.add(); // It calls the Sub class add() method
}
}

addition.add() method calls the add() method in the Sub class and not the parent class. So it overrides the Super class method and is known as Method Overriding.

Q. What is meant by Overloading?

A.

Method overloading happens for different classes or within the same class.

For method overloading, subclass method should satisfy the below conditions with the Super class method (or) methods in the same class itself:

  • Same method name
  • Different argument type May have different return types

public class Manipulation{ //Super class
public void add(String name){ //String parameter
………………
}
}

Public class Addition extends Manipulation(){
Public void add(){//No Parameter
………..
}
Public void add(int a){ //integer parameter

}
Public static void main(String args[]){
Addition addition = new Addition(); 
addition.add(); 
}
}

Here the add() method having different parameters in the Addition class is overloaded in the same class as well as with the super class.

Note − Polymorphism is not applicable for method overloading.

Q. What is meant by Abstract class?

A.

We can create the Abstract class by using "Abstract" keyword before the class name. An abstract class can have both "Abstract" methods and "Non-abstract" methods that are a concrete class.

Abstract method:

The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called "abstract". Declarations are the ends with a semicolon.

public abstract class Manupulation{
public abstract void add();//Abstract method declaration
Public void subtract(){
}
}

  • An abstract class may have a Non- abstract method also.
  • The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods.

Q. Explain about Public and Private access specifiers.

A.

Methods and instance variables are known as members.

Public:

Public members are visible in the same package as well as the outside package that is for other packages.

Private:

Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside packages.

Q. Difference between Default and Protected access specifiers.

A.

Default: Methods and variables declared in a class without any access specifiers are called default.

Default members are visible to the other classes which are inside the package and invisible to the classes which are outside the package.

Protected: Protected is same as Default but if a class extends then it is visible even if it is outside the package.

Q. Explain about Map and their types.

A.

Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses equals ( ) method to determine whether two keys are same or different.

Hash Map:

  • Unordered and unsorted map.
  • Hashmap is a good choice when we don?t care about the order.
  • It allows one null key and multiple null values.

Public class Fruit{
Public static void main(String[ ] args){
HashMap names =new HashMap( );
names.put(?key1?,?cherry?);
names.put (?key2?,?banana?);
names.put (?key3?,?apple?);
names.put (?key4?,?kiwi?);
names.put (?key1?,?cherry?);
System.out.println(names);
}
 }

Output:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}
Duplicate keys are not allowed in Map.
Doesn?t maintain any insertion order and is unsorted.

Hash Table:

  • Like vector key, methods of the class are synchronized.
  • Thread safety and therefore slows the performance.
  • Doesn?t allow anything that is null.

public class Fruit{
public static void main(String[ ]args){
Hashtable names =new Hashtable( );
names.put(?key1?,?cherry?);
names.put(?key2?,?apple?);
names.put(?key3?,?banana?);
names.put(?key4?,?kiwi?);
names.put(?key2?,?orange?);
System.out.println(names);
}
 }

Output:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}
Duplicate keys are not allowed.

TreeMap:

  • Sorted Map.
  • Like Tree set, we can construct a sort order with the constructor.

public class Fruit{
public static void main(String[ ]args){
TreeMap names =new TreeMap( );
names.put(?key1?,?cherry?);
names.put(?key2?,?banana?);
names.put(?key3?,?apple?);
names.put(?key4?,?kiwi?);
names.put(?key2?,?orange?);
System.out.println(names);
}
}

Output:
{key1=cherry, key2=banana, key3 =apple, key4=kiwi}
It is sorted in ascending order based on the key. Duplicate keys are not allowed..

Q. What is mean by Exception?

A.

An Exception is a problem that can occur during the normal flow of an execution. A method can throw an exception when something wails at runtime. If that exception couldn?t be handled, then the execution gets terminated before it completes the task.

If we handled the exception, then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception.

try{
//Risky codes are surrounded by this block
}catch(Exception e){
//Exceptions are caught in catch block
}

Q. What are Exception handling keywords in Java?

A.

try:

When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.

catch:

This is followed by try block. Exceptions are caught here.

finally:

This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.

Q. What is the final keyword in Java?

A.

Final variable:

Once a variable is declared as final, then the value of the variable could not be changed. It is like a constant.

final int = 12;

Final method:

A final keyword in a method that couldn’t be overridden. If a method is marked as a final, then it can’t be overridden by the subclass.

Final class:

If a class is declared as final, then the class couldn’t be subclassed. No class can extend the final class.

Q. What is a Thread?

A.

In Java, the flow of a execution is called Thread. Every java program has at least one thread called main thread, the Main thread is created by JVM. The user can define their own threads by extending Thread class (or) by implementing Runnable interface. Threads are executed concurrently.

public static void main(String[] args){//main thread starts here
}

Q. How to stop a thread in java? Explain about sleep () method in a thread?

A.

We can stop a thread by using the following thread methods.

  • Sleeping
  • Waiting
  • Blocked

Sleep:

sleep () method is used to sleep the currently executing thread for the given amount of time. Once the thread is wake up it can move to the runnable state. So sleep () method is used to delay the execution for some period.

It is a static method.

eg. Thread. Sleep (2000)

So it delays the thread to sleep 2 milliseconds. sleep () method throws an uninterrupted exception, hence we need to surround the block with try/catch.

public class ExampleThread implements Runnable{
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
}
}

Q. When to use Runnable interface Vs Thread class in Java?

A.

If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class.

If we are not going to extend any class then we can extend the thread class.

Q. Difference between start() and run() method of thread class.

A.

start() method creates new thread and the code inside the run() method is executed in the new thread. If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.

Q. Explain thread life cycle in Java.

A.

Thread has the following states:

  • New
  • Runnable
  • Running
  • Non-runnable (Blocked)
  • Terminated

Thread has the following states:

  • New:
    In New state, Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.
  • Runnable:
    The Thread is in runnable state after invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state the thread is considered alive.
  • Running:
    The thread is in running state after it calls the run () method. Now the thread begins the execution.
  • Non-runnable (Blocked):

    The thread is alive but it is not eligible to run. It is not in runnable state but also, it will return to runnable state after some time.

    eg. wait, sleep, block.
  • Terminated:
    Once the run method is completed then it is terminated. Now the thread is not alive.

Q. What is the purpose of a Volatile Variable?

A.

Volatile variable values are always read from the main memory and not from thread’s cache memory. This is used mainly during synchronization. It is applicable only for variables.

volatile int number;

Q. Is String a Primitive data type ?

A.

No.

For more details visit here



Python if , elif and else

Python Conditions and If statements

  • 0
Python for beginners

Learning Python Part 1

  • 3
Struct Alignment and Padding

Struct Alignment and Padding in C++ And C

  • 0
Friend function

Friend function C++

  • 0
The diamond problem Solution C++

Solving the Diamond Problem with Virtual Inheritance

  • 0
Pointers

C++ Pointers

  • 0
Structures

C++ Structures

  • 0
Types of Inheritance in C++

Inheritance and access specifiers C++

  • 0
Java date pattern

Java Date Pattern Syntax

  • 0
Java Date and Calendar

Java Date formats

  • 0
JAVA Data Type

Data types in Java

  • 0
Java unreachable code

Unreachable Code Error in Java

  • 0
INTERVIEW EXPERIENCES

Articles

09

FEB

×

Forgot Password

Please enter your email address below and we will send you information to change your password.