Java Interview Questions and Answers
Java Interview Questions and Answers
Are Looking for Java Training? Learn Advanced Java training in Besant Technologies – Only Institute with Oracle Authorized Java Training Center. For More Details Call Now!
Java Interview Questions and Answers for beginners and experts. List of frequently asked Java Interview Questions with answers by Besant Technologies. 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 Chennai and Java Training in Bangalore
Best Java Interview Questions and Answers
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 Gangboard medium. These are top Java interview questions and answers, prepared by our institute experienced trainers.
Java interview questions and answers for the job placements
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.
Java interview questions and answers for Freshers and Experienced
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:
- byte
- int
- short
- long
- float
- double
- char
- boolean
- Object-Oriented language– First and foremost feature of Java. By object-oriented means here the state and behavior of an object is described by the class and the methods.
- Platform independent language – Java runs on the WORA principle. WORA means “Write Once Run Anywhere”. Java was mainly designed to support platform independency. Thereby Java supports multiple platforms like Windows, Mac, Linux, Sun Solaris, etc.
- Portable – It means Java byte code can be run on any hardware that is JVM compliant.
- Robust – It is a highly supported language. It has a strong memory management and the reason is that there are no pointer allocations.
- Prohibits Memory Leaks – Java is having automatic garbage collection feature that stops the memory leakage.
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.
- It eliminates the duplicate entries and it makes use of hashing for storage.
- Hashing is the mapping between a key value and a data item. This way it provides the efficient searching of data.
- TreeSet Class – It implements java.util.Set interface.
- It provides an ordered set and this class uses tree for storage purpose.
- Like Hashset class, this also eliminates the duplicate entries.
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.
- An ArrayList Class implements java.util.List interface and for storage it uses arrays, while a LinkedList class also implements java.util.List interface but uses linked list for storage.
- Storage in arrays is faster than List.
- The insertion and deletion of elements can’t be done in the middle of an ArrayList. To achieve this, a new array needs to be constructed. But in case of LinkedList, elements can be added and deleted from anywhere in the list.
- JVM stands for Java Virtual Machine. JVM is a process execution machine that provides the runtime environment in which the java byte code can be executed.
- It is platform dependent because JVMs are available for almost all hardware and software platforms.
- JDK stands for Java Development Kit. It so physically exists. It is for writing Java applets and applications The runtime environment of JDK sits on the top of the operating system.
- JRE is an acronym for Java Runtime Environment. It is also known as Java Runtime. It is a part of JDK. It is a set of programming tools used for developing the Java applications.
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.
- StringBuffer is thread safe, which means it is synchronized. Two methods at the same time can’t call the methods of StringBuffer. On the other hand, StringBuilder is non-synchronized. So two methods can simultaneously call the methods of StringBuilder.
- StringBuffer is less efficient when compared to StringBuilder.
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:
- Public – Class, Methods and Fields are accessible from anywhere.
- Private – Methods and Fields can be accessed only from the same class to which they actually belong.
- Protected – Methods and Fields can be accessed from the same class to which they belong, from the sub-classes and also from the classes of same package. But they are not accessible from outside.
- Default – Methods, Fields, classes can only be accessible from the same package, not from outside.
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
- Where an abstract class have a limit to extent only one class or abstract class at a time, Interface has no such limits. It can extend n numbers of interfaces at the same time.
- Abstract classes can have both abstract as well concrete methods. On the other hand, interface can only have abstract methods.
- Abstract class can provide complete code, but interface can only provide signature, not the code.
- Speed wise Abstract classes are faster than interfaces.
- An abstract class can have public and protected abstract methods while Interface, by default, can have only public abstract methods.
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:
- First is by the use of Java.Lang.Runnable Interface.
- Another ways is to write a class that extends the Java.Lang.Thread class.
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:
- Improves program speed and quality
- helps in storing & processing the data efficiently
- Decreases the programming effort and increases the reusability chances of a software.
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.
- ArrayList is faster than Vector.
- ArrayList is introduced in JDK 1.2. It is therefore not a legacy class, but Vector is.
- To traverse the elements, an ArrayList uses Iterator interface while Vector can use Iterator as well as Enumeration interface.
- Unlike ArrayList, Vector is synchronized.
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.
- When it comes to traversing the elements, Enumeration can do only legacy elements unlike Iterator that can traverse both legacy as well as non-legacy elements.
- Enumeration interface don’t have remove() method which is there in Iterator.
- Enumeration is less safer than Iterator.
- Enumeration is fail-safe while Iterator is fail-fast.
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:
- Ready: When a thread is created, it is said to be in the Ready state.
- Running: The thread that is currently being executed is said to be in running state.
- Waiting: Awaiting state is a state when a thread that is waiting for another thread to free certain resources so that it can acquire those resources.
- Dead: A thread whose run() method exits is in dead or terminated state.
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!:
- The throw is used for throwing an exception while Throws used for declaring an exception.
- Throw followed by an instance, whereas throws followed by a class.
- With throw, one cannot throw multiple exceptions, but with Throws, multiple exceptions can be declared.
- Throw is used in method body, but Throws is used in the method declaration which is signature.
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.
- JVMs are available for many hardware and software platforms (so JVM is platform dependent).
- JRE stands for Java Runtime Environment. It is the implementation of JVM.
- JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
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.
- In below example, a constant with the name const_val is declared and assigned a value
- Private Final int const_val=100
- When a method is declared as final, it can NOT be overridden by the subclasses.This method is faster than any other method because they are resolved at the compiled time.
- When a class is declared as final, it cannot be subclassed. Example String, Integer, and other wrapper classes.
- lang.object
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.
- A static method belongs to the class rather than an object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- A static method can access static data member and can change the value of it.
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
- By using Java.Lang.Runnable Interface. Classes implement this interface to enable multithreading. There is a Run() method in this interface which is implemented.
- By writing a class that extends Java.Lang.Thread class.
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.
- Final is a modifier which you can apply to variable, methods, and classes. If you create a variable final, this me its value cannot be changed once initialized.
- Finalize is a method, which is called just before an object is a garbage collected, allowing it a final chance to save itself, but the call to finalize is not definite.
- Finally is a keyword which is used in exception handling, along with try and catch. The finally block is always implemented regardless of whether an exception is thrown from try block or not.
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
- Array
- It is fixed size
- Arraylist
- Its not fixed size, dynamically grows and shrinks.
- Array
- Does not provide built in methods
- Arraylist
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
- Arithmetic Operator
- Logical Operator
- Relational Operator
- Assignment Operator
- Increment or decrement Operator
- bitwise Operator
- ternary or conditional operator
conditional statement are:
- if
- if-else
- nested if-else
- else-if ladder
- switch-case
un conditional statement are:
- break
- continue
- goto
- exit()
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:
- while
- do-while
- for
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:
- bubble sort
- selcstion sort
- insertion sort
- quick sort
- merge sort
searching is a technique through which we can search a particular elements.
Some searching techniques are:
- linear search
- binary serch
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 without parameter without return type.
- function without parameter with return type.
- function with parameter without return type.
- function with parameter with return type.
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.
It is collection of node and each node divided in two part, first part called as info part and second part called as address part which hold the address of next node.
Syntax,
Struct Node
{
Int info;
Struct Node Add;
}
Its is collection of node and each node can have maximum two child node.
spanning tree are that type of tree in which we cover all nodes using minimum number of edges.
oops stand for object oriented programming language.if any language following oops concept that means they have following property
- class
- object
- inheritence
- polymorphism
- Abstraction
- Encpasulation
- databinding
Ability to perform different different task is called as polymorphism. Example –function overloading, Operator overloading in C++.
if we use feature of system without knowing background detail is called abstraction.
It’s a process through which we can access the property of one class into another class
- single inheritance
- multiple inheritanc
- multilevel inheritance
- hybrid inheritance
- hierarchal inheritance
constructor: it is special type of function which have the same name as a class name. constructor does not return any value even void.
Destructor:-it’s a same like constructer presided with ~.it is use to de allocate memory which has allocated by constructor .
we can declared variable and function as a static.
Static function can have only static variable.
Static function and variable can call directly without help of object.
Friend functions are that type of function which are not member of class.
Since they are not member of class, we can call directly.
Friends function is use to access private member of classes.
Function does not have function body is call virtual function
Syntax,
Returntypre function_name(agruments)=0;
if we declared a object,and at the same time we initialised is called as copy constructor
Ex. Class o1;
Class o2=o1;//copy constructor
it is pure object oriented and platform independent language.
final is keyword in java
If we declared any variable as a final, the value of variable cant be change.
If we declared any method as a final, That method can not override.
If we declared any class as a final, That class cant be inherit.
super keyword is use to call Super class variable, super class constructor and super class method.
abstract-it is the collection of abstract method and concrete method. we cant perform multiple inheritance using abstract class.
Interface-it is the collection of abstract method and final variable. we can perform multiple inheritance using interface.
applet program can run on web browser as well as on console window.
Its have life cyle-
Init()->start()->paint()->stop()->destroy()
it’s a advance version of awt. All component of swing are pure java component. we use package
Import javax.swing.*;
A thread is small part of program, which work independently.
if multiple thread seeking a chance of same resource. once a tread has achieved resource other thread do not interrupt,is called as synchronisation
the way of handing exception is called exception handling.
Exceptional handling uses
- try
- catch
- finally
- throw
- throws
JDBC stands for java data base connectivity which is use to establish connection between Java Application and database.
there are for types of driver
- JDBC-ODBC bridge driver
- Native API driver
- Network driver->handle multiple data base
- pure java driver or protocol driver
Step1: import package
Import java.sql.*;
Step2:load the driver
Class.forName(sun.jdbc.odbc);
Step3:establish connection
Connection corn=DriverMangaer.getConnection(“sun:jdbc:odbc:”,”usr”,”pass”);
Step4: create statement object
Statement st=cor.CreateStatement();
Step5: proses the query
St.executequery(“sql statement”);
Step6: close connection
Corn.close();
Servlet is java program store on server. its store web container. Once a request has sent by user to server ,the appropriate response send back by server to user.
life cycle of servlet are
Init()àservice()àdestroy()
Import javax.servlet.*;
Public class Hello extend HttpServlet
{
Public void doGet(HttpServletRequest req, HttpServletResponse res)
{
PrintWriter pw=req.getWriter();
pw.print(“<body bgcolor=lightyellow><h1> welcome in servlet</body>”);
}
Jsp stands for java server page. Its written in form of tag. starting tag <% and closing tag %>
- While loop is called as pre condition checking loop whereas do-while loop is called as post condition checking.
- While loop works depend on condition where as do-while loop works at least one time.
All the java program execution begins with the main method () because the JVM is hard coded.
The filename of the snippet will be checked by the compiler to compile the code.
The JVM will check for the Classname for interpreting the code to byte code.
Yes, the programmer can save the filename and classname as different name because the compiler will check for the file name for compiling and the JVM will check for the class name for converting the code to machine code, but it is good naming convention to have file name and class name as same name.
Multiple operators and operands in the same line are called Expressions.
The relational operators in Java are 6 in number and they are (<, >, <=, >=, ==, ! =) . The result is always in Boolean (Yes/No).
Bitwise operators are used for masking the date in encryption and decryption process. They are encoded along with the data.
Memory management is spiltted- into 4 sections and the local variables are managed in stack.
Object can be created by 4 ways they are: by new, by cloning, by reflection, by de-serialization.
When there is no reference or when the object is nowhere used then the object becomes unreachable and they are called unreachable objects, the JVM will call the garbage collector to destroy the same.
Memory management in Java is spiltted- into 4 sections namely: Heap, stack, String pool, Miscellaneous and the Reference variables are managed in Heap.
Arrays are created as Objects in java. Arrays can contain any type of elements value (primitive or objects) but the storage of both data is not possible in a single array.
The size occupied by primitive datatype, object or array is managed and hence there is no need of sizeof operator in java.
The ability of JVM to pick one method from several methods that exist in a hierarchy is called Runtime Polymorphism.
When we try to access the Instance methods and variables, when there is a null reference to them.
When the heap memory if full and we try to over load the memory with the reference variables then the Out of memory error will be generated.
Yes, exceptions can occur in catch block. The exceptions in java are handled in try{} and catch{} block. The try{} contains the code which can r
aise an exception and the catch{} block contains the code to catch and handle the exceptions.
Throws keyword should be used only in the header and if we use the keyword in body it will result in the compile time error.
Checked Exceptions are used to represent the business/environmental failure
Ex: Business failure: ATM cash withdrawal, trying to withdraw money with low balance
Environmental failure: Network issue.
When both the extended classes have the same method name, during the runtime ambiguity can occur and it can lead to compile time error.
The multithreading is implemented as JVM feature, which allows to run more than one thread at a time. Here the threads uses a shared memory area so saves memory and context-switching between the threads takes less time than the process
Java multithreading is used in games and animation.
Native methods in the thread class allows the execution of the thread by invoking the start() method. When a thread is created it is assigned with the priority.
No, because we can’t start a thread which is already started.
When the stack memory if full with the local variables and we try to over load the memory with the local variables then the Out of stack error will occur.
Memory management in Java is spilted- into 4 sections namely: Heap, stack, String pool, Miscellaneous and the String literals are managed in String pool .
When we have 2 start() method in thread, it will result in Illegal state exception. We cannot have 2 start() method in a program because the JVM is hardcoded to start the execution of program from the start() method.
JVM Thread Scheduler will manages the lifecycle of thread based on state transition (NEW, RUNNABLE, BLOCKED, WAITING, TERMINATED).
When the thread is created, every thread is assigned with the default priority 5.
The garbage collector is assigned with the low priority as 1, because the gc() method should not run in-between the execution of main program. The JVM will invoke the gc() method once the memory is filled with unreachable objects.
TreeSet will give the result in sorted order. It is the most important implementation of interface in java. Objects in Treeset are stored in a sorted and ascending order.
Comparator need to be explicitly linked to treeset via constructor. They are used to order the objects of user-defined classes and they are capable of comparing two objects of different classes.
Workspace manages the jar files, Artifacts & runtime libraries.
Artifacts will interacts with hard disk and automates the interaction.
Access specifiers like Default, private, public and protected can be applied to class, methods, variables, Innerclass, constructor
We cannot access the members inside the class if we specify the access specifiers, either we should leave without specifying or we should specify as public.
We will use final class only when we need Immutable classes. Immutable – the user cannot create any objects.
If the author doesn’t want the user to create an object then the class id marked as abstract, it indirectly means that some implementation is missing in the code.
Abstract methods will provide only design not implementation and the class which extends the abstract will have the implementation part.
In Java, class can be used to create an object and define data types. It acts as a compilation of Java language based computers.
Standard class loading is a class loading method that generates objects and events using new words, while class name is not known at the time of the compilation.
Multi-threading is a programming concept that can be used to run multiple tasks simultaneously on a single program.
Java was created by James Coscough in Sun Microsystem in 1995.
- Java Virtual Machine has JVM
- JRR
- JDK has Java development kit
No java notes can be used. This is a serious security. Instead of markers, they are used in Java as safe and secure as compared to markers.
Action to connect to a database of Java:
- Registration of driver class
- Creating Link
- Creating Report
- Complete the questions
- Close link
JVM provides an operating environment to enable Java byte codes. The JRE contains JVM files that need JVM during the JRM movement.
The default size is 0.75, and the default capability is calculated:
Initial capacity * Attributes
A package is a set of relevant classes and interfaces.
Java.lang.Throwable is a superclass of all exception classes, and all exception classes are derived from this basic class.
When internal classes are in the same file, subclasses may be in another file. In turn, when subclasses have their parent class methods, the inner classes get the methods they want.
Java has its own garbage collection, which should define any destructors. The destruction of the goods is automatically carried out by the garbage collection machine.
JSON is an abbreviation for the JavaScript Object Code. It uses JavaScript syntax, and the design is only text.
Java is an independent language on a platform.
A new class is defined as anonymous class without a name in a row of code.
JVM is a Java Virtual Machine, which is the operating system for compiled Java class files.
No, a dead book can not start again.
In Java, the rows are items.
In Java, the code set used to start a product.
In Java, an object can no longer be used or specified, garbage collection is called and the material is automatically erased.
The difference between the stack and the line is that Stay is based on the Last In First Out (LIFO) policy and is based on the principle of FIFO (First, First Out).
Statistical methods can be called directly without creating an example (class) of the class. A stable method is directly accessible to all variables’ variables of a class, but it can not access standard variables without creating an example of class.
Super important tips for the parent class. There are many uses of the super key:
- It is used to call the Super Class (Parent Class) Constructor.
- It may be used to access the super class system hidden by the supplier (inviting parent class version, by applying the method).
- Invite the parent class constructor.
Final methods – These methods can not be violated any way.
Final variable – Constants, the value of this variable can not be altered.
Final Class – Such classes can not be obtained by other classes. The use of this type of classes can be used when security or someone does not want that particular class. Java’s final phase
This is a special class defined by Java; Other classes are subdivisions of the subject class. The subject class is superclass of other classes. The subject class consists of the following steps
- Object-maternal () – means the object of creating a new object.
- Objject Obj – determines whether an object is equal to another.
- Final decision () – The garbage collector invites the garbage collection on a subject when it determines that the material does not exist. The subset system violates the final method for removing system resources or performing other cleansing actions.
- toString () – The object returns a string representation.
A set of relevant categories (classes, interfaces, techniques, and references) are defined as a group. See: Package in Java.
Star form (java.util. *) Includes all types of packages, and packages can increase the time – especially if you import multiple packages. However, this is not a run-time performance at any time.
See: Fixed import in Java.
By using the new operator, Java automatically handles the de-reservation of memory, as things are allocated. This whole process is called garbage collection.
The final method () method is used to release the reserved resources.
The trash collector’s final object () method only calls once for an object.
No, it’s not possible. You can not force garbage collection. You can call system.gc () method for garbage collection but there is no guarantee that garbage collection will be made.
Exceptions Unusual conditions during program program. This may be due to an incorrect logic written by an incorrect user input or programmer.
Java.lang.Exception
There are definitions for this set exceptions.
There are two types of exceptions: the exceptions and the exceptions that are not deleted.
Verified Exceptions: These exceptions should be handled by the programmer, otherwise the program will reject the errata.
Unselected Exceptions: It is a programmer until you write the code to avoid unchecked exceptions. If you do not handle these exceptions, you can not get a compilation. These exceptions will occur in turn.
Error: Mostly complicated system. This occurs occasionally at run time and needs to be resolved to continue.
Exception: Most often an input data problem or wrong logic on the index. Compilation may occur in time or run times.
Throwing is used by throwing the main user defined or pre-defined exception.
If once you have not checked a validated exception once, it should be reported using the throwskeyword. The key looks at the end of a hand signature.
Read the difference here: java – blowing blows.
Yes, a standard set of exceptions can be thrown out. It has its own limits: it runners exceptions (unselected exceptions).
Finally, the module always runs the code that is not an exception. The block to catch volume or effort to finally block the block follows.
1) ClassNotFoundException Class can not load the required class on the track.
2) No error occured when loaded on NoClassDefFoundError class, but one or more of the class required by other classes can not be removed or packaged.
No, you can not try without it or finally stop it. One or both of them should be.
Yes, we can have multiple capture blocks to handle more than one exception.
Yes, if we try to catch, we can use the black blade without catching the clasp.
If the last volume was not executed?
If called System.exit () or if JVM is disabled first, it will not be finalized at the same time.
Yes, we are using something else but it can not be considered a good practice. For an exception we must have a catch block.
A Java Bean is the Java class, which follows some simple steps, in which the traditions are titled as the names and traditions of some of the methods. This is because the conventions are as follows, making it easy to process as a software tool that connects beans into the operating system. JavaBeans reusable software components.
Sun Microsystems originally developed the high-level programming language “JAVA” and got released in the year 1995. Various platforms like Mac OS, Windows, and different UNIX versions are used to run Java.
Java is intended to acclimate to a developing environment. Java programs can carry a wide-ranging quantity of run-time data which can be utilized to validate and solve contacts to objects during run-time.
Below are the four (4) different types of access specifiers:
- Protected
- Public
- Private
- Default
Loops in Java programming is to execute or block a statement frequently
Three types of loops in Java
- While Loops
- Do While Loops
- For Loops
Parameterized and Default are the two constructors in Java
Following are the Oops concepts:
- Interface
- Polymorphism
- Abstraction
- Encapsulation
- Inheritance
There are few conditions to be satisfied by subclass with super class to make Method overriding happen. The conditions are method name, argument and return type should be same.
In Java, multiple inheritances is not possible. To solve these issues and get an option, Interface concept is presented in Java.
Packages in Java evade the name clashes, afford simpler access control, and make easy to locate the associated classes.
Yes, the constructor in Java returns the current instance of the class.
No, it is not possible to make a constructor final
Yes, it is possible to overload the constructors in Java by changing the arguments count which the constructor accepted.
You can use the static block to initialize the static data member. While classloading, the static block is executed before the main method.
The keyword “this” in Java is a variable which is referring to the current object. You can pass this keyword as an argument into constructors or methods.
In Java, object class is the superclass for the entire classes.
Aggregation – said to be a relationship between two (2) classes.
The keyword “Super” is a reference variable which is for referring to the immediate parent class object.
The keyword “Super” is used to raise the immediate parent class method and immediate parent class constructor.
No, it is not possible to use both “this()” and “super()” in a constructor.
Yes, we can overload the main() method with the use of method overloading.
Final variable in Java is for restricting the user from updating it. When initializing the final variable, it is not possible to change the value. To be very clear, when the final variable is allotted to value, they can never be modified. If you find a final variable not assigned to any value, they can be assigned via a class constructor.
We cannot declare a constructor as final as it is never inborn. It is very clear that constructors are not normal approach, hence it is of no use in declaring the constructors as final. If trying to declare so, you will receive an error from the compiler.
It is necessary to override the abstract method in the subclass to provides its definition and hence the abstract method cannot be declared as final.
Encapsulation maintains and protects the code from others.
Any kind of forms is said to be polymorphism. Based on the reference type, a single object can refer to the sub-class or super class. This method is known as polymorphism.
Java Collection is a framework which is intended to store the objects and operate the pattern to stockpile the objects.
Following are the operations performed by collections in Jav
- Insertion
- Manipulation
- Searching
- Deletion
- Sorting
Interface available in Java collections are Sorted Set, Collection, Map, Set” open=”no” style=”default” icon=”plus” anchor=”” class=””], Sorted Map, List, and Queue.
Classes available in Java collections are Array List, Linked List, Lists and Vector.
Treemap, Hash Table, Hash Map, and Linked Hashed Map are the four (4) maps available in Java collections
We cannot use pointers as there is no a concept called pointers in Java.
Hashtable is synchronized and thread-safety. Hashtable enumerator is helpful to iterate the values and do not allow anything which is null. Performance of Hashtable is always slow.
Inserted elements of HashSet are listed in random order and it can easily store null objects. Performance of HashSet is always high.
TreeSet performance is always slow.
There are two (2) types of exceptions in Java
Unchecked Exception and Checked Exception are the two (2) type of exceptions in Java.
Declaring throws keyword and Using try/catch are the two (2) methods available in Java to handle exceptions.
When handling the exception, the standard execution flow will never be terminated. With the use of catch declaration, it is useful to recognize the issues.
There are three (3) exception handling keywords available in Java which are try, catch and finally.
The execution flow in Java is called ‘Thread’. Java will always have the main thread, which is created by JVM (Java Virtual Machine). By executing a runnable interface or spreading thread class, users can describe their individual threads.
To enable the thread to wait in the waiting pool, we can use the method wait (). Wait () method intimates the thread to pause for a provided quantity of time. When called using notify () or notify all () method, the thread wakes up.
notify (): To enable a single thread to wake up from the waiting pool, notify () method is used.
notify all (): To enable all the threads to wake up from the waiting pool, notify all () method is used.
Blocked, Sleeping and Waiting are the three (3) thread methods to stop a thread in Java
The thread life cycle of Java is given below:
New -> Runnable -> Running -> Non-runnable -> Terminated
Users can convert a file into a byte stream and this process is known as Serialization. The conversion is performed for safety purpose. To achieve this process, java.io.Serializable interface must be implemented.
The values which are constantly recited from the main memory, but not from thread’s cache memory are said to be the Volatile Variable. Volatile Variable is useful at the time of synchronization.
In Java, byte datatype default value is zero (0).
There are many Java programs and one among them is applet which runs in the Web browser. Applet has the whole Java API at its clearance.
Use cases are the vital part of the program analysis, defining a state for us which a program might come across and the program behavior that needs to be revealed in that condition.
The executable file for .java (source code) is the compiled .class file (also called byte code).
The byte code can run on any platform-dependant JVM. (The architecture dependancy is taken care by the JVM- virtual machine that utilises the resources of the base OS)
Abstraction is the process of highlighting the key features and ignoring the unnecessary features based on the problem domain. It occurs at the design level and is a requirement gathering phase in SDLC.
Example:
Patient necessary details : name, age, blood group medical history Patient ignored details : account number, qualification
Encapsulation is binding of data members and member functions into a single unit called as class. It is used to achieve data hiding and implementation hiding.
It occurs at the implementation level. Data hiding is achieved by allowing only authorised users to access private data via public methods. Implementation hiding is achieved as internal changes within a method is hidden from user , as user can only call/invoke methods.
Example:
Access private balance of Account class via public getBalance() method.
Just In Time (JIT) Compiler is a part of the Execution Engine of JVM architecture. The interpreter translates the byte code line by line into native OS understandable language. There may be lines of code that may execute many times, like a function that finds if prime or not (the scenario is to find the prime numbers between 1- 10000). Since the prime function executes many times interpreter will have to translate the code to native code several times.
Instead in Hotspot(TM) JVM, this sequence of code that executes frequently (called a hotspot) and profiled by a profiler and upgraded to compilation level 1, 2 3 and 4. When the 4th level threshold is reached the JIT Compiler stores the already translated native code to a local cache. The next time the hotspot is executed , instead of converting to native code again, the cached version is executed. Thus using JIT Compiler improves the performance of the system.
Compile-time polymorphism example is method overloading.Here the method resolution (call resolved to the definition of the method) occurs at compile-time ( If no matching call, then a compile time error occurs ) . It is also called static polymorphism or early-binding.
Runtime polymorphism example is method over-riding. Here which method will be called is resolved at runtime ( as which method is called is based on which object is created and object creation always occurs at runtime in java ) and hence it is called runtime polymorphism. It is also called dynamic binding or late-binding.
The native hashCode() method of the Object class returns a unique integer value for different objects. This integer value is generated as an internal representation of the address of an object and not the actual actual address of object in java. This unique integer is used in data structures like HashMap to find out the bucket to store key-value pairs.
The hashCode method has to be overridden as the contract between equals and hashCode.This contract is maintained to avoid duplicate keys to be entered in a HashMap.
The contract states that if two objects are equal on the basis of equals method, then their hashCode values should be same.
The primitive == is an operator and is used to compare the values of both primitives and reference variables.
The equals() method of Object class is same as primitive ==
The equals() method when overridden as per the performance specification by Joshua Bloch, cannot be used on primitives and is used to compare the content within objects ( equality of content within an object )
String is an immutable class since JDK 1.5. Immutability concept involves that if the content of object of immutable class is not altered then existing object in memory (SCP in String case) is returned. If content of object of immutable class is altered, then new object is created and returned. It helps for efficient utilisation of memory as String is the most frequently used class.
StringBuffer is introduced in 1.0v of java and is the mutable version of String. The methods of StringBuffer is synchronised and thus thread-safe. It is used in slower applications
StringBuilder is introduced in 1.5v of java and is the mutable version of String. The methods of StringBuilder is non-synchronised and thus not thread-safe. It is used in faster applications.
The toString() method is implicitly invoked (except in case of null value) when a reference variable is being printed. It is used to convert object to String type.
The toString() method of Object class returns a String indicating the fully qualified name of class+ @ + HashCode value in Hex String representation.
toString method can be overridden if want to customise the output as per derived class specifications.
All exceptions occur at runtime.
Checked exceptions are those exceptions that are forced by the compiler to handle it (either by using try-catch or using throws). The program cannot be executed unless checked executions are handled. Usually scenarios where the exception is quite frequent and compiler will force you to provide an alternate execution flow checked exceptions are configured.
All user-defined exceptions are checked exceptions. Ex : SQLException, FileNotFoundException
Unchecked exceptions are those exceptions where the compiler will not force to handle the exception. The program can be run without exception handling.
Example: ArithmeticException, ArrayOutOfBoundsException
throw keyword is used to manually throw the object of exception. It is used to create user-defined exception.
throws keyword is used to delegate the handling of the Exception to the calling function. It is used along with constructor or method signature.
Born state/New State : When object of Thread is created the thread is said to be in the born state. Using new keyword.
Runnable State : When the start method is invoked on the thread, the thread enters the Runnable State. It is in ready queue waiting for CPU core to be allocated.
Running State: When thread scheduler, assigns CPU core to the thread, the run() method is invoked and the thread is said to be in running state.
Blocked State: When the wait(), sleep() method is invoked, the thread enters the blocked state.
Dead State: After the thread completes its task, i.e end of run() method, then thread enters dead state.
wait() method is a non-static method that is present in the Object class.
It is always called within a synchronised block as lock is released before going to waiting set.
sleep() is a static method that is present in the Thread class.
It need not be called within synchronised method/block as it doesn’t involve release of lock to go to blocked state.
wait() method is called within a synchronised method/block and involves the release of lock to go to the wait set. Locking/Unlocking is related to/applied on all objects in java and hence the wait() method is kept in Object class even though it is used for inter-thread communication.
ArrayList is not a legacy class and initial size is 10 of the internal data structure which is a growable array. When the 11th element is added, then the array grows by approx. 50% of original sizeArrayList methods are non-synchronised and hence is not thread-safe
Vector is a legacy class and its internal array grows by 100% of original capacity when exceeds limit. The methods of Vector are synchronised and hence is thread-safe.
The internal data structure of HashMap is a HashTable where values are stored as key value pairs. HashMap involves an associative array clubbed with linked lists.
HashMap hm=new HashMap(); hm.put(“abc”, 1289);
On the key, the hashCode is calculated and provided the hashCode() method is overridden, based on the content the unique integer value is generated. Since the size of the HashMap array is only
After the bucket number is calculated, then the corresponding bucket is searched using equals() method for any duplicate key. If no duplicate key then the new< Key Value > is inserted at the end of the linked list as a node with <hashCode,Key,Value, next pointer>.
If duplicate key exists then the old value is replaced with new value and the old value is returned. hm.get(“abc”);
When retrieving a value based on the key, the following is calculation is done to retrieve the bucket number
Bucket number = HashFunction(hashCode(key))
At that bucket, the equals() method is used to check if a key with same as given key exists, if yes then its corresponding value is returned , else null returned.
HashSet internal data structure is a HashMap. Hence duplicate elements are not allowed for entry in a HashSet
HashSet hs=new HashSet(); hs.add(“abc”);
hs.add(“pqr”); —> returns true hs.add(“abc”); —> returns false
When HashSet constructor invoked internally a HashMap is created HashMap hm=new HashMap();
When the add method is called on HashSet , internally in the add method, a put operation takes place as follows
public boolean add(Object o){
return hm.put(o, PRESENT)==NULL;
<—- here PRESENT is a reference variable to an empty Object
}
If no duplicate key then the value is added and returns null so add return boolean true value.
If duplicate key exists then put returns the odd value i.e PRESENT which is not equal to NULL and the add returns a boolean false value.
A class with abstract keyword is called an abstract class. Its object cannot be created. A class which has at least one abstract method will be an abstract class.
Abstract method is a method declaration that is used to specify an idea/hypothesis
Once a class already extends another class, it can’t extend from abstract class as no class-level multiple inheritance in java
If two classes that are not related in hierarchy and want to have them follow standards/rules , then interfaces are used. The implementors of the interface need or need not be related in hierarchy. Interfaces are used to achieve loosely coupled applications.
They are used to achieve standardisation amount classes that are related/unrelated.
It is used to inspect the class and acquire information of the class at runtime. The class name, constructors used, methods used, fields , access specifiers can also be retrieved at runtime using Reflection API. The class called Class object is created within the heap space when the class binary information is loaded into memory. This Class contains methods like getDeclaredMethods() that give back information regarding the class. Every .class file that is loaded into the Method Area has a corresponding class called Class object created in heap space for it.
Reflection API can be used to make your own compilers or frameworks.
You can get a reference to the class called Class in one of the following ways:
- Class c=Employee.class
- Class c= Class.forName(“Employee”)
- Employee e =new Employee(); Class c=e.getClass();
This is because Map involves dealing with key-value pairs and it doesn’t need the methods declared in Collection interface (as Collection interface deals with addition, removal of single objects to a collection ) hence doesn’t implement Collection interface.
No static methods can’t be overridden, as overriding is runtime polymorphism where the method call is based on the object that is created at runtime. And since static method is not not related to any object, as it belongs to class. Hence static method can’t be overridden.
It is called as method hiding , as the method of Parent class is hidden from the derived class.
There is no programmatic support for pointers in java. All programming languages internally to read and write from memory make use of pointers. Pointers support arithmetic operation like
int* p; p++;
The above is not allowed in java. In Java references are created on which no arithmetic operations can be performed, hence called reference.
String s; <—- a reference variable s s++; <—- gives error
Yes , from java 5 onwards the concept of Co-variant return type is introduced. In this, the overriding method(in derived class) return type if is a subclass of return type of overridden method (in base class) then it is a valid override.
In java, it is pass by value only, as even the reference is considered a value that is passed to local variable of function. ( work on copy and not on original value). Hence in java only pass by value is supported.
It is used for better readability and maintenance of code. An anonymous inner class can be a sub- class of a named Class or an implementor of a named interface.
At time of object creation itself the definition of the inner class is mentioned and this provides for better readability of the code.
The .class file is generated as OuterClass$1 where 1 indicated first anonymous class specified in the OuterClass
Center JAVA is the principal of Java Programming language that is broadly used to create fundamental java applications .Core JAVA is the base for any high level JAVA ideas.
J2EE is an augmentation of the Java SE dependent on the Java programming language utilized for creating also, conveying online undertaking applications. It comprises of a bunch of APIs, administrations, and conventions that give the usefulness to create multi-layered electronic applications.
It incorporates a few advances that broaden the usefulness of the Java SE APIs, for example, Servlets, Connectors, Enterprise JavaBeans, and so forth
JVM is the JAVA Virtual Machine. The JVM is a particular that is introduced in your framework and the utilization of JVM is to run a java program in your framework. It changes over or incorporates your java source code into a bytecode and calls the fundamental technique to run the java code.
Java Virtual Machine(JVM) is a stage autonomous dynamic machine which is utilized to run the java code that is actualized in your PC and Java Runtime Environment(JRE) is the usage of JVM that gives the runtime climate for creating and executing java applications. The JRE comprises of a bunch of libraries, records of JVM and a bunch of programming devices that are useful in building up the java applications. Java Development Kit(JDK) is the usage of any of the Java stages like Java SE, Java EE or Java ME of the Oracle Corporation. The JDK contains the JRE and the advancement devices needed for creating java applications.
Compartments give the runtime backing to J2EE application parts. The holder gives an execution climate on top of the JVM. The J2EE applications are conveyed in various compartments before execution. A portion of the sorts of compartments in J2EE are application customer compartment, an applet holder, a Web compartment, and an EJB compartment.
Classes and items are the two primary parts of article arranged programming. Java is an Object arranged programming language that utilizes the idea of classes and articles. A
class is a format for objects, and an item is an occurrence of a class. A portion of the article – situated ideas are Encapsulation, Polymorphism, Inheritance, and so on.
An EAR record is a JAR document with an .ear expansion. A J2EE application with the entirety of its modules is conveyed in an EAR document.
MVC stands Model-View-Controller.
Model – The model class is a java bean class additionally called the POJO class which is utilized to store the condition of the java beans.
View – The view layer is the UI part of the application that is presented for use to the end client. The view layer is created utilizing JSP, JSTL, HTML,etc
Regulator – the regulator layer goes about as the interface between the view layer and the backend of the application. The regulator class is utilized to get the solicitations from the
customer, measure into a reaction at the worker side segments and divert to the customer side. The regulator is generally composed utilizing java servlet class.
The existence pattern of a servlet comprises of the accompanying stages:
- Servlet class stacking
- Servlet launch
- the init technique
- Request taking care of (call the assistance strategy)
- Removal from administration (call the annihilate strategy)
The kinds of constructors utilized in java are default constructor and parameterised constructor. The default constructor is considered when the client doesn’t determine an unequivocal
constructor to the class. The default constructor likewise helps in making objects for a class. The parameterised constructor is utilized to characterize or initialise the estimations of example factors inside the constructor. The parameterised constructor ought to contain at least one boundaries for which the qualities are alloted.
Legacy is an instrument by which one article obtains all the properties and conduct of another object of another class. It is utilized for Code Reusability and Method Superseding. There are five sorts of legacy in Java.
- Single-level legacy
- Multi-level legacy
- Multiple Inheritance
- Hierarchical Inheritance and Hybrid Inheritance
- super can be utilized to allude to the prompt parent class occasion variable.
- super can be utilized to conjure the quick parent class strategy.
- super() can be utilized to summon quick parent class constructor.
Strategy Overloading utilizes the idea of Polymorphism, ie) we can make different techniques with same name yet extraordinary mark performing various activities. The techniques that are over-burden contrasts either in the quantity of contentions or the bring type back of the techniques.
Strategy abrogating is a procedure wherein a particular technique is actualized in an unexpected way in the subclass which is as of now gave in the parent class. It is utilized for Runtime polymorphism.
Rules for Method abrogating
- The technique should have a similar name as in the parent class.
- The strategy should have a similar signature as in the parent class.
- Two classes should have an IS-A connection between them.
The fundamental contrast between the last technique and dynamic strategy is that the dynamic strategy can’t be last as we need to abrogate them in the subclass to give its definition while last strategy can’t be abrogate.
- The Collection is an interface though Collections is a class.
- The Collection interface is utilized to make functionalities of information design to Rundown, Set, and Queue. Be that as it may, Collections class is to sort and synchronize theassortment components.
- The Collection interface gives the strategies that can be utilized for information structure though Collections class gives the static strategies which can be utilized for different procedure on an assortment.
Java Server Pages innovation (JSP) is a worker side programming language used to make a powerful site page as Hyper Text Markup Language (HTML). It is an
expansion to the servlet innovation.
- By incorporate mandate
- By incorporate activity
JSP Standard Tag Library is a library of predefined labels that facilitate the advancement of JSP.
Five sorts of JSTL labels are : center labels, sql labels, xml labels, internationalization labels and capacities labels.
Exemptions are the mistakes that may happen in a java program. The Exception Handling is a strategy utilized in java to produce blunder messages for the client dependent on various
mistakes/exemptions as information yield special case, and so on The two primary kinds of special cases in Java are Checked exemptions and Unchecked special cases.
Java Server Faces (JSF) is a system utilized for planning UI to create Java web applications. It depends on MVC plan.
Activity structures are java beans which are the relationship of at least one Action Mapping. Activity structures helps in keeping a meeting state all through the web application.
Java DataBase Connectivity (JDBC) is a Java API used to collaborate between a java application and the data set. The JDBC is utilized for executing questions of an information base in a java application.
JDBC driver contains classes and interfaces that help Java application and data set.
There are 4 kinds of JDBC drivers.
1. Type 1 driver or JDBC-ODBC connect driver.
2. Type 2 driver or Native-API, incompletely Java driver.
3. Type 3 driver or Network Protocol, unadulterated Java driver.
4. Type 4 driver or Native-convention, unadulterated Java driver.
There are 3 kinds of JDBC Statements, as given beneath:
1. Explanation: It will execute SQL question (static SQL inquiry) against the data set.
2. Arranged Statement: Used when we need to execute SQL explanation
consistently. Info information is dynamic and taken contribution at the run time.
3. Callable Statement: Used when we need to execute put away systems.
There are four kinds of exemptions in JDBC
1. batch Update Exception
2. Information Truncation
3. SQL Exception
4. SQL Warning
Ans: 4
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MyIteratorElement {
public static void main(String a[]){
String removeElem = “Bob”;
List<String> myArrayList = new ArrayList<String>();
myArrayList.add(“Alex”);
myArrayList.add(“Mark”);
myArrayList.add(“Steve”);
myArrayList.add(“Bob”);
myArrayList.add(“Max”);
System.out.println(“Before Changes:”);
System.out.println(myArrayList);
Iterator<String> itr = myArrayList.iterator();
while(itr.hasNext()){
if(removeElem.equals(itr.next())){
itr.remove();
}
}
System.out.println(“After Changes:”);
System.out.println(myArrayList);
}
}
public class MyThreadExample extends Thread{
public void run(){
System.out.println(“I’m in Run Method”);
}
public static void main(String b[]){
Thread myThread = new Thread(new MyThreadExample());
myThread.start();
myThread.start();
}
}
I’m in Run Method, I’m in Run Method.
I’m in Run Method. Thread Exception
I’m in Run Method.
Error in the code.
Ans: 2
There are four kinds of exemptions in JDBC
1. batch Update Exception
2. Information Truncation
3. SQL Exception
4. SQL Warning
Ans: 4
True
False
Ans: 2
JIT
Byte Code Loader
Class Loader.
Ans: 3
public class OperatorsExample {
public static void main (String args []){
int x=3;
int y=6;
(a<b)? System.out.println(x): System.out.println(y);
}}
3
6
Error in statement
None of the above
Ans: 3
StringSplit
StringTokenizer
None of the above
Ans: 2
import java.util.*;
public class SortList {
public static void main(String[] a) {
String[] ar={“we”,”ride”,”alone”,”in”,”the”,”streets”};
List<String> listA = Arrays.asList(ar);
Collections.sort(listA);
System.out.println(listA);
}
}
Copy ()
Clone ()
None of the above
Ans: 2
Notify ()
Equals ()
Wait ()
Copy ()
Ans: 2
Synchronization
Semaphores
Volatile
None of the above.
Ans: 2
public class Main1 {
public static void main(String args[]) {
System.out.println(fucntion());
}
int fucntion()
{
return 15;
}
}
15
compiler error
0
garbage value
Ans: 2
public void myFun(String myStr)
{
String[] arr = myStr.split(“;”);
for (String s : arr)
{
System.out.println(s);
}}
public static void main(String[] args)
{
char myChar[] = {‘b’, ‘c’, ‘ ‘, ‘d’, ‘e’, ‘;’, ‘f’, ‘g’, ‘ ‘,’h’, ‘i’, ‘;’, ‘j’, ‘k’, ‘ ‘, ‘l’, ‘m’};
String myStr = new String(myChar);
myFun(myStr);
}}
bc de
fg hi
jk lm
bc
de;fg
hi;jk
lm
Compilation error
Ans: 1
class Main
{
public static void main(String[] args)
{
StringBuffer c = new StringBuffer(“hello”);
StringBuffer d = new StringBuffer(“world”);
c.delete(1,3);
c.append(d);
System.out.println(c);
}
}
hlloworld
hloworld
heoworld
Compilation error
Ans: 2
There are four kinds of exemptions in JDBC
1. batch Update Exception
2. Information Truncation
3. SQL Exception
4. SQL Warning
Ans: 4
String object1 = new String(“besant”);
String object2 = new String(“besant”);
if(object1.hashCode() == object2.hashCode())
System.out.println(“The hashCode is equal”);
if(object1 == object2)
System.out.println(“The memory address is same”);
if(object1.equals(object2))
System.out.println(“The value is equal”);
The hashCode is equal
The value is equal
The hashCode is equal
The memory address is same
The value is equal
The memory address is same
The value is equal
Ans: 1
String myStr = “besant”;
myStr.toUpperCase();
myStr += “technologies”;
String string = myStr.substring(2,13);
string = string + myStr.charAt(4);;
System.out.println(string);
santtechno
santtechnolo
santtechnoln
esantechnoa
Ans: 3
Java is being always the best and trending course for over 20 years. Our Java training in Chennai by Besant Technologies is ranked as best training institute by many people who got trained under this course. There are lots of job openings for Java developer and also there for many mobile applications development companies. In this blog, we are posting the best and top 100 Java interview questions and answers.
These Java interview questions and answers were prepared by the experienced and talented trainers and tutors from our institute and also by the Java developer those who are having 5+ years of experience.
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 and answers.
As a Java professional, it is essential to know the right buzzwords, learn the right technologies and prepare the right answers to common Java Interview Questions and answers. Learn and study this Java interview questions and answers, move your carrier to the next level.