Are Looking for Java Training? Learn Advanced Java training in Innovitt Global – . For More Details Call Now!
Java Interview Questions and Answers for beginners and experts. List of frequently asked Java Interview Questions with answers by Innovitt Global. We hope these Java interview questions and answers are useful and will help you to get the best job in the networking industry. These Java interview questions and answers are prepared by Java Professionals based on MNC Companies’ expectations. Stay tuned we will update New Java Interview questions with Answers Frequently. If you want to learn Practical Java Training then please go through this Java Training in Lucknow and Java Training in Uttar Pradesh
Besant Technologies supports the students by providing Java interview questions and answers for job placements and job purposes. Java is the leading important course in the present situation because more job openings and the high salary pay for this Java and more related jobs. We provide Java online training also for all students around the world through the Online medium. These are top Java interview questions and answers, prepared by our institute experienced trainers.
Here is the list of most frequently asked Java Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level. The questions are for intermediate to somewhat advanced Java professionals, but even if you are just a beginner or fresher you should be able to understand the answers and explanations here we give.
Here I am providing some of the important core java interview questions with answers that you should know. You can bookmark this post to brush up your knowledge before heading for an interview. Whether you are a fresher or highly experienced professional, java plays a vital role in any Java/JEE interview. Java is the favorite area in most of the interviews and plays a crucial role in deciding the outcome of your interview. This post is about java interview questions that come directly from 10+ years of experienced Professionals of Java programming and lots of interviewing experience.
As a Java professional, it is essential to know the right buzzwords, learn the right technologies and prepare the right answers to commonly asked Java Interview Questions. Here’s a definitive list of top Java Interview Questions that will guarantee a breeze-through to the next level.
The ease of executing the code on any platform makes this language a Platform Independent Programming Language. Just by installing JDK software on a system, JVM also gets installed automatically. This JVM (Java virtual machine) is the one that can execute Java bytecode. Each Java source file is compiled into a bytecode file, which is later executed by the JVM. Java was designed with a motto to allow the programs to be run on any platform, without the need of rewriting or compiling them each time recompile for different platforms.
There are 8 primitive data types that are supported by Java:
Autoboxing is an automatic conversion which is made by the Java compiler. The conversion of a primitive type to the equivalent reference type is termed as Autoboxing. Conversion of a double to a Double, an int to an Integer, etc are examples of Autoboxing. We can simply call it boxing too. Unboxing is the opposite of Boxing, i.e., conversion of the reference type to the corresponding primitive type such as Byte to byte.
Overloading: When two or more methods in the same class having exactly the same name, but parameters are different then it is called Method overloading. It is a compile-time concept. Overriding: When a child class redefines the same method as that of in a parent class, then it is called Method overriding. Polymorphism is applicable for overriding, and not for overloading. It is a run-time concept.
HashSet Class – It implements java.util.Set interface.
List is a collection of non-duplicate objects which are in an order. One can access the elements of a list in a specific order.
WORA means Write Once Run Anywhere. Java is compiled to a bytecode which does not platform specific. This bytecode is the intermediate language between the source code and the machine code. As the bytecode is not platforming specific, so it can be used to any platform. Sometimes, it is also called WORE – Write Once Run Everywhere.
We can override hashcode and equals whenever necessary. Especially the case when one wants to do equality check or to use one’s object as a key in HashMap. If we don’t override hashcode() method, we’ll not be able to recover our object from hashMap (if that is used as a key in HashMap).
An Immutable class is a Java class whose objects cannot be modified once created. Any alteration in the Immutable object results into a new object. All the java.lang package wrapper classes are immutable. Examples are: Short, Long, Boolean, String, etc.
Access specifiers are defined as the keywords that are used before a class name which defines the scope of accessing. The types of access specifiers are:
Singleton is a class with only one instance in the whole Java application. For an example java.lang.Runtime is a Singleton class. The prime objective of Singleton is to control the object creation by keeping the private constructor.
Yes, Try block either needs to be followed by Catch block or by Finally block or sometimes by both. The reason is that any exception that will be thrown from a try block needs to be caught in a catch block, and even if no exception is there then also use of Finally block should be there so as to specify any specific tasks that need to be performed before code ends.
In Java, Final the keyword is used to declare a constant. A value can be assigned only once to a constant. Later, the value can’t be changed. Example: Private Final int const_val=50 Here constant is assigned the value 50. The method here is resolved at complied time, thus are faster than any other code.
Yes, this case is possible. We can create an abstract class by using the abstract keyword before the class name. Also, even if a class has one or more abstract methods, then also, it must be declared as abstract, else it will throw error
Serialization – It is a way of writing an object’s state into a byte stream. This converted byte stream is transferred on the network and the object is then re-created at the destination. Implementation of java.io.Serializable the interface is must if you want to serialize a class’ object. Serialization is basically used when data needs to be transmitted over the network. This traveling of state of an object on the network is known as marshaling.
Multithreading is a concept of running multiple tasks in a concurrent manner in a single program. The threads
shares the same process stack and thus runs in parallel. This process helps in improving the performance of a program. Multi-threading can be implemented in two ways:
Collection: A collection is an object for grouping multiple elements into a single unit. It can hold other objects’ references. Collections are also termed as the container
Collections Framework: It provides an architecture that stores, manipulates and represents collections. It is a collection of classes and interfaces. Advantages of Collections Framework:
It implements the java.util.Queue interface and supports the operations that wait for space availability in the queue while storing an element. Blocking queues are mainly designed keeping the consumer-producer problems in mind. BlockingQueue does not accept the null elements. Also they are used in inter-thread communications.
Constructor – It gets invoked automatically when a new object is created. Every class has a constructor, so even if one forgot to mention it, the Java compiler itself creates a default constructor for that class. Constructor is like a method that doesn’t return the type. Constructor overloading – It is same as method overloading. Same constructor with different parameters can be declared in the same class. Then it’s the role of compiler to differentiate which constructor needs to be called depending upon the parameters and the sequence of data types.
Break is used in a switch so that code breaks after the valid case and thus prevents the flowing of code in the cases too. If break isn’t used after each case (except the last one), a wrong result will generate as it will execute all the proceeding cases after the valid case.
An independent path of execution in a program is called as Thread. There are several states of a thread:
No this is not a true case. Automatic garbage collection can help in reducing the chances but can’t eradicates the possibility fully. It doesn’t ensure that a Java program will never go out of memory. There is a possibility that objects are created at a faster pace than that of garbage collection. This results into the filling of all the available memory resources, thus memory goes out of leak.
Creating an exact copy of an object is known as the object cloning. clone() method of object class and java.lang.Cloneable interface are used for this purpose. If we don’t use mentioned interface(Cloneable interface), the clone() method will generate the CloneNotSupportedException. Cloning is a fastest way to copy the arrays. Also cloning takes less lines of code.
No, these two are different keywords, thus can’t be used interchangeably. Following are the differences between the two!:
JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification.
An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.
A sub-class is a class which inherits from another class called superclass. Sub-class can access all public and protected methods and fields of its superclass.
In Java, a constant is declared using the keyword Final. Value can be assigned only once and after assignment, a value of a constant can’t be changed.
The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private etc) with or without concrete implementation.
Another key difference in the use of abstract classes and interfaces is that a class which implements an interface [su_spoiler title=”must implement all the methods of the interface while a class which inherits from an abstract class doesn’t require implementation of all the methods of its superclass.
A class can implement multiple interfaces but it can extend only one abstract class.
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides the software-based platform.
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.
Yes, a class can have multiple constructors with different parameters. Which constructor gets used for object creation depends on the arguments passed while creating the objects.
An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.
Multi-threaded applications can be developed in Java by using any of the following two methodologies
If we want to execute any statements before the even creation of objects at load time of class, 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.
Key the benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.
Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.
Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.
String is not a primitive data type in java. When a string is created in java, it’s actually an object of Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String class can be used on the string object.
Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded
In Java, string objects are called immutable as once the value has been assigned to a string, it can’t be changed and if changed, a new object is created. In below example, reference str refers to a string object having value“Value one”.
An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.
It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.
wait() method should always be called in loop. It is likely that, until thread gets CPU to start running again, the condition may not hold. Therefore, it is always advised to check condition in loop before continuing.
By using kill -3 PID in Linux, where PID is the process id of Java process, you are able to take a thread dump of Java application. In Windows, you can press Ctrl + Break.
Both are used to pause thread that is currently running, however, sleep() is meant for short pause because it does not release lock, while wait() is meant for conditional wait.This is why it releasesm lock, which can then be developed by a different thread to alter the condition of which it is waiting.
++ is not thread-safe in Java because it involves multiple commands such as reading a value, implicating it, and then storing it back into memory.
Constructor chaining in Java is when you call one constructor from another. This generally occurs when you have multiple, overloaded constructor in the class.
When a Java process has started using Java command, memory is distributed to it. Part of this memory is used to build heap space, which is used to assign memory to objects every time they are formed in the program.
Part of this memory is used to build heap space, which is used to assign memory to objects every time they are formed in the program.
Garbage collection is the procedure inside JVM which reclaims memory from dead objects for future distribution.
Both poll() and remove() take out the object from the Queue but if poll() fails, then it returns null. However, if remove() fails, it throws exception.
A class consists of the Local variable, instance variables, and class variables.
ingleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.
An Object is first declared, then instantiated and then it is initialized.
This data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has
package or default accessibility when no accessibility modifier is specified.
This method is used to get the primitive data type of a certain String.
The String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.
An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread’s method invocation stack.
An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.
If the method overrides one of its superclass’s methods, overridden the method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.
Runnable interface is used in java for implementing multi-threaded applications. Java.Lang. Runnable the interface is implemented by a class to support multi-threading.
Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.
If we want to execute any statements before even creation of objects at load time of class, 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 creation of objects in the main method.
We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.
We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object. lone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies. 45. In Java, how we can disallow serialization of variables? If we want certain variables of a class not to be serialized, we can use the keyword trient while declaring them.
Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using
try-catch block in the code in order to successfully compile the code.
Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and the developer can use only those constructors which are defined in the class.
The basic condition of method overriding is that method name, arguments, as well are turn type must be exactly same as is that of the method being overridden. Hence using a different return type doesn’t override a method.
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java zPI at its disposal.
It is used to sort collections and arrays of objects using the Collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.
In Java application first, java compiler convert our java source code to bytecode. This bytecode sends or through any OS or hard disk or something, it’s accepted directly in using of JVM.Each JVM worked based on own platform, but all JVM accept machine language(of byte stream) easily.so only java application called platform independent.
1.Loader-it performed to collect the codes anywhere(hard disk or software or ide)to given JVM.
2.Compiler-to converts source code to bytecode.
3.Jit-to covert bytecode to a high-level language.
4.Execution-finally program starts to run and execute the output.
JDK-java development kit current version is 1.8.
No, its present primitive(old datatypes).so java not fully based on OOPS.
Wrapper class means typecasting (to convert one data type to another data type).this class used to data objects(Integer, Float, Char, Byte, Short, Long, Double, Boolean).
Once create the value of class cannot be modified, that class called immutable class.immutable class present 9 classes and there are 8 wrapper class and string class, totally present 9 immutable class.
Array means collection of similar data types.its present two types.
1.single dimension-stored multiple value in single variable.
ex: int a[]={1,2,3,4};
2.multi dimension-values stored based on rows and columns.
ex: int a[][]={{1,2,3},{1,2,3},{1,2,3}};
String means a collection of characters.It’s used to get any data type values(Like int, char, float,etc..).so string act as strong media.
String value once creates cannot be modified so only we prepared next level of StringBuilder and StrinngBuffer.
StringBuilder-it’s a non-synchronized method so it’s acting very fast and no thread safe.
StrinngBuffer-it’s a synchronized method so it’s acting slow and thread safe.
Function means member function and smallest multiple blocks of class.the function only can be access to provide calling function, otherwise cannot be accessed.
It’s a templet or blueprint or collection of objects .its describe state and behaviors .state means-data, behavior means-method.
It’s a runtime or real-time entities.each object gets own properties and response.objects are used to access the class properties.
One object or message functioned different actions called polymorphism.
Using a number of same method name and different parameters in a single class to achieve this process polymorphism its known as function overloading.
Using same method name and same parameters in inheritance method to override parent on child class details, it is called function overriding.
this keyword means-current or represent a class.its used to read current class properties.
super keyword means-super or parent class.its used to read immediate parent class properties.
One class of data or properties collected or send in another class is called inheritance.
1.single-one parent to one child class.
2.multilevel-one parent to child, after that child act as a parent, to send another child.
3.hierarchical-one parent to any child.
4.multiple-two parent send at a time one child.
5.hybrid-combination of hierarchical and multiple.
scope means storage capacity or level of variable and methods.
1.package scope-this variable or method storage present within a package otherwise its destroyed.
2.class scope-its present within the class otherwise, it’s destroyed.
3.method scope-its present the method otherwise, it’s destroyed.
4.block scope-its present within the block otherwise, it’s destroyed.
1.public-its global value, accessed package to package.
2.private-its private value, accessed only within the class.
3.protected- its used inheritance class, its possible only hierarchical inheritance.
4.default- its normal type, its used within the package.
Binding or warping to the data and method within a class is called encapsulation.
Hiding the background details and show only essential features or functions.this is advance of an interface.
Different network performed a different task called multitasking.to achieve this process using two concepts
1.multi threading
2.multi processing
A single core of sequential process called thread.
ex: single desktop application.
Multiple actions performed sequentially at a time is called multithreading.
ex: atm process
Multi processing-no allocation of the common memory in a set of process, so speed low, high cost.
Multi threading-multi threading allocates common memory in a set of threading, so high speed, low cost.
The interface in java is a mechanism to achieve abstraction.There can be only abstract methods in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritances in Java. and also a blueprint of class.
Abstraction-using abstract keyword must.itsused to not achieve multiple and hybrid inheritance.
Interface-abstract keyword not must.its used to achieve multiple and hybrid inheritance.
* The abstract class cannot implement one interface, but one interface implements to one abstract class.
In our source code converted into a byte stream(machine understanding language) this process called Serialization.it’s means to write the objects (of data) in the needed destination.so we are using output streams of write objects.
In our byte stream convert into a high-level language(human being understanding language) this process called deSerialization.its mean read the objects (of data) in a needed platform.so we are using input streams of reading objects.
The exception is an abnormal condition.In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
types
1.error-its irrecoverable.
2.checked exception-compile time error.
3.un checked exception-run time error.
Any exception occurred in our source code the compiler terminated or skip the process, so that place we are using Exception Handling.
it means to catch and handle the exception, to maintain the flow of process normally.some methods
1.Try-it used to catch the exception.
2.Catch-it used to handle the exception.
3.Finally-finally block executes always.
4.throw-it used to create exception explicitly.
5.throws-its indicate signature of methods for handling the exception.
Java is a programming language used to create programs that is used to perform the tasks.
Main() thread will start first
By using synchronized keyword you can achieve lock.
By using Thread.currentThread() method
Provides built in methods to add,delete
Collections.sort() method we can use to sort
Set internally uses map data structure.
Yes
Set with sorted elements.
For searching Arraylist is will be used and for modification linkedlist will be used.
Key will remain same, It will override the value.
Yes hashmap allows only one null key
It uses Linkedlist data structure.
Yes. By using lambda expressions.
Java 8 interface allows one method implementation as default by using default keyword.
Stringbuffer is a synchronized
Stringbuilder is not synchronized.
Small individual units of program call token.
Keywords: Its reserved which have special meaning provided by compiler.
Data type: Its define the type of variable. There are four fundamental data type in c
Int->integer value
Float-> Float value
Char->character value
Double->for double value
Constant: its means fixed. Once a variable has declared as a constant,the value of variable can not change through out the program. const keywords use to declare variable as contant.
Variable: it’s a identifier which use to hold the value in program.
there are seven fundamental data type in c
conditional statement are:
un conditional statement are:
in if—else statement either if block will work or else block will wor, both cant work together. If condition is true if block will work other wise else block will work.
Syntax:
if(condition)
{
//statement;
}
else
{
//statement;
}
its is use for multiple value checking.
Syntax:
Switch(expression)
{
Case 1: //statement
break;
Case 2: //statement
break;
Case 3: //statement
break;
.
.
default:
}
its shortest form of if-else.its is called as ternary operator.
Syntax:
Expression?value1: value2;
If expression is true it return value1 otherwise vlaue2.
Iterative statement are:
Array is the collection of homogenous data elements.
Syntax:
int Array_name(size);
sorting is technique in which we arrange dtata in either ascending or descending order.
Some techniques are:
searching is a technique through which we can search a particular elements.
Some searching techniques are:
it’s a set of statement to perform specific task.
Syntax of user define function:
Returntype function_name(datatype1 param1,datetype2 param2,….)
{
//set of statements
return(value);
}
there are four type of user define function
function call itself again and again is called recursive function
Syntax:
Function_name
{
//statements
Function_name();
}
it is the collection of non-homogenous data element.
Syntax:
stuct structure_name
{
Datatype1 varaiable1;
Datatype2 varaiable2;
.
.
};
struct structure_name Variable_name;
the major difference between structure and union is
In structure each member variables have individual memory allocation where as in union member variable share memory allocation.
pre-processor directive start with # and it work before compilation
Example:#include,#define,#if,#prgma,#error etc
micro can be define before main() function
Syntax:
#define x 6
it is collection of data or information, store permanently in our system.
if we want to write or retrieve data from the file that is possible only with help of file pointer.file pointer can be declared as
File *File_pointer_name;
it’s a sequence of data through which we can easily perform operation like insert, search and delete
its is non-primitive linear data structure work on LIFO(last in first out) technology.it is use in conversion of expression, scientific calculation etc.
its is non-primitive linear data structure work on FIFO(First in first out) technology.it is use in Railway reservation system, online ordersystem etc.