Java Interview Questions

 

Hey Shouters!! In this tutorial, we will discuss the most important java interview questions of Java Language.

These questions are simple and easy to remember. Read the answers carefully.

:: Some Basic Definitions in Programming ::

  1. Problem: A Problem can be apparently defined as a question raised for inquiry, consideration, or solution.
  2. Instruction: A specific task in a computer processor can be done via Instruction.
  3. Statement: An instruction written in a high-level language. A statement directs the computer to perform a specified action.
  4. Program: A computer program is a collection of instructions that can be executed by a computer to perform a specific task.
  5. Task: In computing, a task is a unit of execution or a unit of work.
  6. Process: In computing, a process is the instance of a computer program that is being executed by one or many threads. It contains the program code and its activity
  7. Thread: Threads are a way for a program to divide (termed "split") itself into two or more simultaneously (or pseudo-simultaneously) running tasks.

:: Main Features of Java Language ::

Java is one of the most popular and used programming language, the features of java are:

  1. Platform Independent
  2. Multi-Threaded
  3. High Performance
  4. Secure

1. Is Java both Interpreted and Compiled language ?

Yes, a java program is first compiled into bytecode which JRE can understand. ByteCode is then interpreted by the JVM making it an interpreted language.

2. Is variable be used without initialization ?

There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
But, Instance variables have default values.

3. Do Class/Static variables are initialized in Constructors?

If you declare an instance variable static and final Java compiler will not initialize it in the default constructor, therefore, it is mandatory to initialize static and final variables. If you don't a compile-time error is generated.

4. When main method is checked ?

In Java, Almost one class has the main method. If we do not declare any main method then in Runtime, a Runtime exception is generated. JVM is responsible for check the main method.

5. How many types of variables are used?

There are 3 types of variables i.e. LOCAL, INSTANCE, AND CLASS/STATIC variable.

6. Data types :

Each data type in java has a specific type, which determines the size of memory, the range of values that can be stored, and the set of operations that can be applied to the variables.

1.Primitive Datatype- There are 8 major primitive data types such as; byte, short, int, long, float, double, char, boolean.

Syntax-
DataType variable = value;

2.Non Primitive Datatype-

Reference variables are created using defined constructors of the classes.

There are 4 types of Non Primitive datatypes i.e.
Array, String, Class, and interface because those are declared by a programmer.

7. Wrapper Classes :

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class.

8. Difference between equals() method and == operator.

The "equals()" method is used for checking the equality of two objects. Or, we can say that "values" are equal or not is checked by this operator.

whereas, “==” or equality operator is a binary operator used to compare primitives and objects. Or, we can say that it is used for reference or address comparison.

9. Difference between constructor and method.

Following are the differences between constructor and methods in Java.


ConstructorMethod
Return type:No return type.Must have a return type.
Implicitly Invoked:Yes (default constructor).No.
Name:Name must always be the same as the class name.May be Same.
Overloading:Possible.Possible.
Overriding: Not possible.Possible.
Call:Call once when an object is created.Directly call (May be multiple times).
Super:Used to invoke immediate parent class constructor.Used to invoke immediate parent class method.
Check 'this()' method is used or not.

10. Difference between Overloading and Overriding.


OverloadingOverriding
Signature:Name of the functions are same, return-type and parameter-list should be different.Name, Return type, parameter-list should be same.
Polymorphism:Compile-time polymorphism.Run-time polymorphism.
Inheritance:No need to inherit.Must be inherited.
Static Methods:Can be overloaded.Cannot be overriden.
Final Methods:Can be overloaded.Cannot be overriden.
Constructor:Can be overloaded.Cannot be overriden.

11. What is Polymorphism?

"Poly" means "many" and "morphism" means "forms". Thus, Polymorphism means many forms. A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism.

12. Discuss the types of inheritance?

Interface and Class and Abstract Class is called "template".

According to parent and child both are "class" template, there are four types of inheritance which are:

  1. Single: Only one parent as well as one child class.
  2. Multi-level: A child class having more than one parent class but at different levels.
  3. Hierarchical: More than one child classes having the same parent class.
  4. Hybrid: A combination of two or more types of inheritance.

According to parent have an "interface" template and child have a "class" template, Java supports one more inheritance i.e. Multiple Inheritance.

Multiple: One subclass is inherited from more than one base interface class.

13. Explain Get and Post method.


Get MethodPost Method
Data sent:Limited amount of data can be sent because data is in header.Large amount of data can be sent because data is sent in body.
Secured:Not secured, data is exposed in URL bar.Secured, Data is not exposed in URL bar.
Bookmark:Can be bookmark.Cannot be bookmark.
Idempotent:Idempotent.Non-Idempotent.
Efficient:More efficient.Less efficient.
If methods are written in such a way that repeated calls to the same method do not cause duplicate updates, the method is said to be "idempotent."

14. What is data encapsulation?

It is a concept for combining properties and methods in a single unit. It helps to understand how many methods and variables an object has. It also serves for data hiding purposes.

15. What is continue, break, and return-

The 'break', 'continue', and 'return' are three important keywords used in Loops and functions. When a break keyword is used in a loop, the loop is broken instantly while when continue keyword is used, the current iteration is broken and the loop continues with the next iteration and when the return keyword is used, execution returns to the function calling portion.

16. Final keyword in Java:

An interesting thing is that, In Java, the Main method can also be declared as final.

Another one is, Default Constructor cannot initialize final instance variables. A compile-time error is generated.

A constructor cannot be declared as static or final. A final variable can only be initialized once.

If we cannot provide an initial value to final variables then this variable is called a "blank final" variable and must be initialized in every constructor.

Final is a non-access modifier is for prevent overriding .

Final modifier can be applied on class, blocks, methods and variables.

17. An abstract class without having any abstract method?

Yes, we can create an abstract class by using abstract keyword before class name even if it doesn't have any abstract method.
However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.

18. String datatype :

The string is not a primitive data type in java.

"String[]" is used in command line argument.

"String…" is an array of parameters of type String, whereas "String[]" is a single parameter.

"String…" provides more readability. The string class is present at "java.Lang.String" package.

The java.lang.String class implements Serializable, Comparable, and CharSequence interfaces.

We use String with some predefined functions, such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

19. Multi threading :

In Java "main" method is known as Main Thread. When java program starts Main Thread comes in action.

A thread is a process that utilized the memory, runs in a very short time, has a run method, the program will either extend Thread or implement the Runnable interface.

Multithreading is a specialized form of multitasking.

Thread life cycle has 5 states, "New" "Runnable" "Running" "Blocked" "Terminate". A thread is present in one of the five states.

Use try-catch block when unsign multi-threading.

Threads are sometimes called lightweight processes because they have their own stack but can access shared data.

20. Can execute any code even before main method?

Yes, it is possible to execute any code even before the main method. We can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before the creation of objects in the main method.

Can we call Constructor more than once for an Object:
class cs
{
cs()
{
System.out.println("INITIALIZED");
}
}
class D
{ 
public static void mainx()
{
cs a=new cs();
cs a=new cs();
}
}

OUTPUT:
error: variable a is already defined in method main
()

It's called only once for an object at the time of object creation and hence, we can't invoke the constructor again for an object after its creation.

21.Is JDK required on each machine to run Java?

JDK is a development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn't required. Only JRE is required.

22. Difference between Array and arrayList ?

ARRAY-
Size should be given at the time of array declaration.

To put an object into an array we need to specify the index. ( e.g. name[1] = “book”)

Array is not type parameterized.

ArrayList-
Size may not be required. It changes the size dynamically.

No index required. (e.g. name.add(“book”)) ArrayList in java 5.0 are parameterized.

23. What is COPY CONSTRUCTOR?

A copy constructor is a member function that is used to initialize an object using another object of the same class. Though there is no need for copy constructor in Java since all objects are passed by reference. Moreover, Java does not even support automatic pass-by-value.

24. Different types of declaration of main method?

The main method can be declared in 4 different types i.e.
The order of modifiers is not important. i.e. "public static" we can take "static public" also.

  1. We can declare "String[]" in any acceptable form.
  2. We can take any valid java identifier instead of 'args'.
  3. We can replace "String[]" with var arg parameter i.e. 3 dots(…).

Some valid modifiers can be added in the main() declaration i.e. final, synchronized, strict.

So, A valid main() method declaration is as follows, i.e.

public class Shout_coders
{
public static final synchronized strictfp void main(String[] args) {}
}

25. What is RUNTIME ERROR AND COMPILATION ERROR?

Compile-time error is any type of error that prevents a java program compile like a syntax error, a class not found, a bad file name for the defined class, Misspelled variable name or method names, a possible loss of precision when you are mixing different java data types and so on.

A runtime error means an error that happens, while the program is running. To deal with this kind of error java define Exceptions. Some Runtime errors are ArithmeticException, ArrayIndexOutOfBoundsException, ClassNotFoundException, FileNotFoundException, IOException and so on.

26. Non access modifiers-

There are 4 types of non-access modifiers:

  1. The static modifier for creating class methods and variables
  2. .The final modifier for finalizing the implementations of classes, methods, and variables.
  3. The abstract modifier for creating abstract classes and methods.
  4. The synchronized and volatile modifiers, which are used for threads. Synchronized keyword in Java is used to provide mutually exclusive access to a shared resource with multiple threads in Java.
  5. Volatile does not acquire any lock on variables or objects. synchronized statement acquires lock on method or block in which it is used.

If you have any doubt regarding any question. Feel Free to comment below and if you to add any questions. Write your suggestion below in the comment box.

Recommended Posts-

  1. Program to add two numbers in Java
  2. Java Program to Calculate the Factorial of a number.
  3. Java Program to Swap two numbers
  4. Java Program to Check Whether a Number is an Even or Odd
  5. Java Program to find HCF of two numbers

Comments

Popular posts from this blog

ArrayList

Java Collection Framework