186 Java Interview Questions You Ne
186 Java Interview Questions You Ne
Java is the most widely used programming language in the current IT industry. One
major reason for the vast number of beginners and professionals in the field of
programming is the career potential that Java knowledge comes with. This article is
dedicated to the same purpose. Here is a complete guide on how to help you crack
the most frequently asked Core Java Interview questions.
What is Java?
Why is Java a platform independent language?
What are the differences between C++ and Java?
Why is Java not a pure object oriented language?
List the features of the Java Programming language?
What do you get in the Java download file?
Explain JVM, JRE, and JDK.
What is a ClassLoader?
What are the Memory Allocations available in JavaJava?
What are the differences between Heap and Stack Memory in Java?
Now, let's discuss the key Java interview questions for freshers and their answers.
In contrast, because the byte code generated by the Java compiler is platform-
independent, it can run on any machine, Java programs are written once and run
everywhere.
Languages Compatibility.
C++ is a programming language that is based on the C programming language. Most
other high-level languages are compatible with C++.
Most of the languages of Java are incompatible. Java is comparable to those of C
and C++.
Java’s native libraries do not provide direct call support. You can use Java Native
Interface or access the libraries.
Characteristics.
C++ distinguishes itself by having features that are similar to procedural and
object-oriented languages. The characteristic that sets Java apart is automatic
garbage collection. Java doesn’t support destructors at the moment.
In C++, the source program is compiled into an object code that is further executed
to produce an output.
Easy: Java is a language that is considered easy to learn. One fundamental concept
of OOP Java has a catch to understand.
Secured Feature: Java has a secured feature that helps develop a virus-free and
tamper-free system for the users.
OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in
Java, everything is considered an object.
JDK
JRE
Abbreviation for JavaDevelopment Kit
JRE is a set of software and library designed for executing Java Programs
JRE Package is one that only supports files and libraries for a runtime environment
JRE Package does not get an installer but has only a runtime environment
4. What is a ClassLoader?
A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading
class files when a program is executed; Class Loader is the first to load the
executable file.
Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?
Class Memory
Heap Memory
Stack Memory
Program Counter-Memory
Native Method Stack Memory
6. What are the differences between Heap and Stack Memory in Java?
Stack memory in data structures is the amount of memory allocated to each
individual programme. It is a fixed memory space. Heap memory, in contrast, is the
portion that was not assigned to the Java code but will be available for use by the
Java code when it is required, which is generally during the program's runtime.
18. What is a singleton class in Java? And How to implement a singleton class?
A class that can possess only one object at a time is called a singleton class. To
implement a singleton class given steps are to be followed:
A local variable can be anywhere inside a method or a specific block of code. Also,
the scope is limited to the code segment where the variable is declared.
28. What part of memory - Stack or Heap - is cleaned in the garbage collection
process?
On Heap memory, garbage collection is employed to release the memory used by
objects with no references. Every object created in the Heap space has access to
the entire application and may be referred to from anywhere.
29. What is the difference between the program and the process?
A programme is a non-active entity that includes the collection of codes necessary
to carry out a specific operation. When a programme is run, an active instance of
the programme called a process is launched. A process is begun by a programme once
it has been run. The process carries out the program's specified instructions.
30. What are the differences between constructor and method of a class in Java?
Initializing the state of the object is done by constructors. A function Object ()
{ [native code] }, like methods, contains a group of statements (or instructions)
that are carried out when an object is created. A method is a group of statements
that work together to complete a certain task and return the outcome to the caller.
A method has the option of working without returning anything.
31. Which among String or String Buffer should be preferred when there are a lot of
updates required to be done in the data?
Because StringBuilder is quicker than StringBuffer, it is advised to utilize it
wherever possible. However, StringBuffer objects are the best choice if thread
safety is required.
32. What happens if the static modifier is not included in the main method
signature in Java?
The main function is called by the JVM even before the objects are created, thus
even if the code correctly compiles, there will still be an error at runtime.
34. What happens if there are multiple main methods inside one class in Java?
There is no limit to the number of major approaches you can use. Overloading is the
ability to have main methods with different signatures than main (String []), and
the JVM will disregard those main methods.
41. Why is the remove method faster in the linked list than in an array?
Because there is no background scaling of an array, insertion, addition, and
removal operations are quicker with a LinkedList. Only references in adjacent items
need to update when a new item is added in the middle of the list.
42. How many overloaded add() and addAll() methods are available in the List
interface? Describe the need and uses.
List is an interface in the Java Collections Framework. The add() and addAll()
methods are the main methods at the List interface. The add() method is used
to add an element to the list, while the addAll() method is used to add a
collection of elements to the list.
The List interface contains two overloaded versions of the add() method: The
first add() method accepts a single argument of type E, the element to be added to
the list.
The second add() method accepts a variable number of arguments of type E, which are
the elements to be added to the list.
The List interface also contains two overloaded versions of the addAll() method:
The first addAll() method accepts a single argument of type Collection<? Extends
E>, which is the collection of elements to be added to the list.
The second addAll() method accepts a variable number of arguments of type E, which
are the elements to be added to the list.
43. How does the size of ArrayList grow dynamically? And also state how it is
implemented internally?
A resizable array implementation in Java is called ArrayList. Dynamically expanding
array lists make it possible to add new elements at any time. The underlying data
structure of the ArrayList is an array of the Object class. The ArrayList class in
Java has three constructors. There are available readObject and writeObject methods
specific to it. The Object Array in an ArrayList is temporary. There are
implemented and Serialization-capable versions of RandomAccess, Cloneable, and
java.io (that are Marker Interface in Java).
Master Java programming and elevate your career with the Java Certification Course
by Simplilearn. Gain in-demand skills and become job-ready. Enroll now and
transform your future!
46. How is the creation of a String using new() different from that of a literal?
The new () operator always produces a new object in heap memory when creating a
String object. The String pool may return an existing object if we build an object
using the String literal syntax, such as "Baeldung," on the other hand.
47. How is the ‘new' operator different from the ‘newInstance()' operator in java?
Both the new operator and the newInstance() method are used to create objects in
Java. If we already know the kind of object to create, we can use the new operator;
however, if the type of object to create is supplied to us at runtime, we must use
the newInstance() function.
48. Is exceeding the memory limit possible in a program despite having a garbage
collector?
Yes, even with a garbage collector in place, the programme could still run out of
memory. Garbage collection aids in identifying and removing programme objects that
are no longer needed in order to release the resources they use. When an object in
a programme cannot be reached, trash collection is executed with respect to that
object. If there is not enough memory available to create new objects, a garbage
collector is used to free up memory for things that have been removed from the
scope. When the amount of memory released is insufficient for the creation of new
objects, the program's memory limit is exceeded.
49. Why is synchronization necessary? Explain with the help of a relevant example.
Multiple threads trying to access the same resources in a multi-threaded software
may frequently result in unexpected and incorrect outcomes. Therefore, it must be
ensured through some form of synchronization that only one thread can access the
resource at any given time. Java offers a method for setting up threads and
synchronizing their operations with the aid of synchronized blocks. The
synchronized keyword in Java is used to identify synchronized blocks. In Java, a
synchronized block is one that is tied to an object. Only one thread can be running
at a time inside synchronized blocks since they are all synchronized on the same
object. Until the thread inside the synchronized block exits the block, all other
threads trying to enter the block are blocked.
New: A new thread is always in the new state when it is first formed. The function
hasn't been run yet, thus it hasn't started to execute for a thread in the new
state.
Active: A thread switches from the new state to the active state when it calls the
start() method. The runnable state and the running state are both contained within
the active state.
Blocked or Waiting: A thread is either in the blocked state or the waiting state
when it is inactive for a while (but not indefinitely).
Timed waiting: When we use the sleep () method on a particular thread, we are
actually engaging in timed waiting. The thread enters the timed wait state using
the sleep () function. The thread awakens when the allotted time has passed and
resumes execution where it left off.
Termination: A thread that has been terminated means it is no longer active in the
system. In other words, the thread is inactive and cannot be revived (made active
again after being killed).
52. What could be the tradeoff between the usage of an unordered array versus the
usage of an ordered array?
When opposed to an unordered array, which has a time complexity of O, an ordered
array's search times have a time complexity of O(log n) (n). Due to the need to
shift the elements with higher values to create room for the new member, an ordered
array has a temporal complexity of O(n) during the insertion process. Instead, an
unordered array's insertion operation requires a constant O amount of time (1).
53. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?
The same package or class may be imported more than once. Neither the JVM nor the
compiler raise an objection. Even if you import the same class several times, the
JVM will only internally load it once.
54. In case a package has sub packages, will it suffice to import only the main
package? e.g. Does importing of com.myMainPackage.* also import
com.myMainPackage.mySubPackage.*?
Sub-packages won't be imported when a package is imported. When you import a
package, all of its classes and interfaces—with the exception of those from its
sub-packages—are imported.
55. Will the final block be executed if the code System.exit(0) is written at the
end of the try block?
The system is established as the last line to be run, after which nothing will
happen, therefore both the catch and finally blocks are essentially ignored.
57. Why is it said that the length() method of String class doesn't return accurate
results?
Since this char [] array is used by the Java String class internally, the length
variable cannot be made public.
58. What are the possible ways of making objects eligible for garbage collection
(GC) in Java?
If a reference variable for an object is removed from the programme while it is
running, the object may be trash collected. They are also referred to as
inaccessible objects occasionally. The new operator returns a reference to an
object after dynamically allocating memory for it.
59. In the below Java Program, how many objects are eligible for garbage
collection?
I don't know about the program, but generally, three objects are eligible for
garbage collection.
The first object is created when the program is started and is no longer needed
when the program ends.
The second object is created when the user inputs their name and is no longer
required when the program ends.
The third object is created when the user inputs their address and is no longer
needed when the program ends.
60. What is the best way to inject dependency? Also, state the reason.
Constructor injection. A class requesting its dependencies through its function
Object() { [native code] } is the most typical instance of dependency injection.
Since the client cannot be constructed without the required dependencies, this
guarantees that it is always in a correct state.
The singleton scope creates a single instance of a bean, which is shared by all
objects that request it.
The prototype scope creates a new instance of a bean for each object that requests
it.
The request and session scopes are only available in a web-based context. The
request scope creates a new bean instance for each HTTP request, and the session
scope creates a single instance of a bean shared by all objects in a single HTTP
session.
64. Assume a thread has a lock on it, calling the sleep() method on that thread
will release the lock?
No, the thread might release the locks using notify, notifyAll(), and wait()
methods.
5! = 5*4*3*2*1 = 120
Output: 5
69. Write a Java Program to check if any number is a magic number or not. A number
is said to be a magic number if after doing the sum of digits in each step and in
turn doing the sum of digits of that sum, the ultimate result (when there is only
one digit left) is 1.
// Java program to check if
// a number is Magic number.
class GFG
{
public static boolean isMagic(int n)
{
int sum = 0;
// Note that the loop continues
// if n is 0 and sum is non-zero.
// It stops when n becomes 0 and
// sum becomes single digit.
while (n > 0 || sum > 9)
{
if (n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
else
System.out.println("Not a magic Number");
}
}
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
70. Write a Java program to create and throw custom exceptions.
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
if (isPossible(n))
printf("%s", "Yes");
else
printf("%s", "No");
return 0;
}
73. Write a Java program for solving the Tower of Hanoi Problem.
// Java recursive program to solve tower of hanoi puzzle
class GFG
{
// Java recursive function to solve tower of hanoi puzzle
static void towerOfHanoi(int n, char from_rod, char to_rod, char
aux_rod)
{
if (n == 1)
{
System.out.println("Move disk 1 from rod
" + from_rod + " to rod " +to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " +
from_rod + " to rod " +to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
// Driver method
public static void main(String args[])
{
int n = 4; // Number of disks
towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are
names of rods
}
}
74. Implement Binary Search in Java using recursion.
// Java Program to Illustrate Recursive Binary Search
// Importing required classes
import java.util.*;
// Main class
class GFG {
// Method 1
// Recursive binary search
// Returns index of x if it is present
// in arr[l..r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
// Restrict the boundary of right index
// and the left index to prevent
// overflow of indices
if (r >= l && l <= arr.length - 1) {
int mid = l + (r - l) / 2;
// If the element is present
// at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
it can
// only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l,
mid - 1, x);
// Length of array
int n = arr.length;
// Custom element to be checked
// whether present or not
int x = 10;
// Calling above method
int result = ob.binarySearch(arr, 0, n - 1, x);
// Element present
if (result == -1)
// Print statement
System.out.println("Element not
present");
+ result);
}
}
75. Is delete, next, main, exit or null keyword in java?
No, these keywords do not exist in Java. Delete, Next, Exit are the operations
performed in the Java program, Main is the predefined method, and Null is the
default String type.
With this we are done with the first section that is Basic Java Interview Question,
Now, lets move on to our next section of Intermediate Java Interview Questions.
JRE has class libraries and other JVM supporting files. But it doesn’t have any
tool for java development such as compiler or debugger.
JDK has tools that are required to write Java Programs and uses JRE to execute
them. It has a compiler, Java application launcher, and an applet viewer.
79. What are Brief Access Specifiers and Types of Access Specifiers?
Access Specifiers are predefined keywords used to help JVM understand the scope of
a variable, method, and class. We have four access specifiers.
88. Why is the delete function faster in the linked list than an array?
Delete Function is faster in linked lists in Java as the user needs to make a minor
update to the pointer value so that the node can point to the next successor in the
list
>> operator does the job of right shifting the sign bits
>>> operator is used in shifting out the zero-filled bits
91. Brief the life cycle of an applet.
The life cycle of an applet involves the following.
Initialization
Start
Stop
Destroy
Paint
92. Why are generics used in Java Programming?
Compile-time type safety is provided by using generics. Compile-time type safety
allows users to catch unnecessary invalid types at compile time. Generic methods
and classes help programmers specify a single method declaration, a set of related
methods, or related types with an available class declaration.
97. Can you run a code before executing the main method?
Yes, we can execute any code, even before the main method. We will be using a
static block of code when creating the objects at the class's load time. Any
statements within this static block of code will get executed at once while loading
the class, even before creating objects in the main method.
Frontend Developer
Python
Java 8
Node.js
JavaScript
Angular
ReactJS
Spring Boot
Static Data
JSP elements
101. What is JDBC?
JDBC is an abbreviation for Java Database Connector.
start with "< %@" and then end with "% >"
Include directive
It includes a file and combines the content of the whole file with the currently
active pages.
Page directive
Page Directive defines specific attributes in the JSP page, like the buffer and
error page.
Taglib
Taglib declares a custom tag library, which is used on the page.
When an Observable object gets upgraded, it calls the update() method of each of
its observers.
After that, it notifies all the observers that there is a change of state.
The Observer interface gets implemented by objects that observe Observable objects.
Exception handler method: In this kind of exception handling, the user will get the
@ExceptionHandler annotation type used to annotate a method to handle exceptions.
XML Configuration: The user can use the SimpleMappingExceptionResolver bean in
Spring’s application file and map the exception.
107. What is JCA in Java?
Java Cryptography Architecture gives a platform and provides architecture and
application programming interfaces that enable decryption and encryption.
Developers use Java Cryptography Architecture to combine the application with the
security applications. Java Cryptography Architecture helps in implementing third
party security rules and regulations.
Java Cryptography Architecture uses the hash table, encryption message digest, etc.
to implement the security.
Basic Authentication:
Usernames and passwords are given by the client to authenticate the user.
Form-based authentication:
In this, the login form is made by the programmer by using HTML.
Digest Authentication:
It is similar to basic authentication, but the passwords are encrypted using the
Hash formula. Hash Formula makes digest more secure.
110. Explain FailFast iterator and FailSafe iterator along with examples for each.
FailFast iterators and FailSafe iterators are used in Java Collections.
Ex: CopyOnWriteArrayList
package simplilearnJava;
public class StringReverse {
public static void main(String args[]) {
String str = "Simplilearn";
String reverse = new StringBuffer(str).reverse().toString();
System.out.printf("Actual Word: %s, Word after reversing %s", str, reverse);
}
public static String reverse(String source) {
if (source == null || source.isEmpty()) {
return source;
}
String reverse = "";
for (int i = source.length() - 1; i >= 0; i--) {
reverse = reverse + source.charAt(i);
}
return reverse;
}
}
Expected Output:
package simplilearnJava;
import java.util.Scanner;
public class SRoot {
public static void main(String args[]) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Input a number to find square root: ");
double square = sc.nextDouble();
double squareRoot = Math.sqrt(square);
System.out.printf("The square root is: %f ", squareRoot);
}
}
}
Expected Output:
25
package simplilearnJava;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FindDuplicate {
public static void main(String args[]) {
printDuplicateCharacters("Simplilearn");
}
public static void printDuplicateCharacters(String word) {
char[] characters = word.toCharArray();
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
for (Character ch : characters) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}
Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
System.out.printf("List of duplicate characters in String '%s' %n", word);
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("%s: %d %n", entry.getKey(), entry.getValue());
}
}
}
}
Expected output:
i: 2
l: 2
package simplilearnJava;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class ArrayDuplicate {
public static void main(String args[]) {
List<Integer> num = new ArrayList<Integer>();
num.add(1);
num.add(2);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
System.out.println("Your list of elements in ArrayList : " + num);
Set<Integer> primesWithoutDuplicates = new LinkedHashSet<Integer>(num);
num.clear();
num.addAll(primesWithoutDuplicates);
System.out.println("list of original numbers without duplication: " + num);
}
}
Expected Output:
package simplilearnJava;
import java.util.HashMap;
public class WordCount {
public static void main(String[] args) {
String str = "Hello World, Welcome to Simplilearn";
String[] split = str.split(" ");
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < split.length; i++) {
if (map.containsKey(split[i])) {
int count = map.get(split[i]);
map.put(split[i], count + 1);
} else {
map.put(split[i], 1);
}
}
System.out.println(map);
}
}
Expected Output:
package simplilearnJava;
public class NextHighest {
public static void main(String[] args)
{
int array[] = { 1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32};
int high = 0;
int nextHigh = 0;
System.out.println("The given array is:");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + "\t");
}
for (int i = 0; i < array.length; i++)
{
if (array[i] > high)
{
nextHigh = high;
high = array[i];
}
else if (array[i] > nextHigh)
{
nextHigh = array[i];
}
}
System.out.println("Second Highest is:" + nextHigh);
System.out.println("Highest Number is: " +high);
}
}
Expected Output:
1 2 3 4 11 12 13 14 21 22 23 24 31 32
118. Could you provide some implementation of a Dictionary having a large number of
words?
The simplest implementation that can be given is that of a List wherein one can
place ordered words and perform a Binary search. The other implementation with a
better search performance is HashMap where the key is used as the first character
of the word and the value as a LinkedList.
hashmap {
119. How would you tackle it if you might have to encounter pattern programs in
Java?
To tackle pattern programs in Java, you need a strong understanding of loops (for,
while) and nested loops. Pattern programs generally involve printing shapes like
triangles, pyramids, or grids using characters or numbers, which can be achieved by
controlling row and column iterations with loops. By carefully managing loop
conditions, you can manipulate spaces, characters, or numbers to create the desired
patterns.
//Local Variable
import Java.io.*;
class Main {
public static void main(String[] args)
{
int var = 145;
System.out.println("Local Variable: " + var);
}
}
//Instance variable
import Java.io.*;
class Main {
public int value = 12;
public static void main(String[] args)
{
Main va = new Main();
System.out.println("My value is: " + va.value);
}
}
121. Can the main method be overloaded?
Yes, the main method can be overloaded as many times as we want. Nevertheless, JVM
prefers to call the main method with the help of its predefined calling method.
Example:
class Main {
public static void main(String args[]) {
System.out.println(" Main Method");
}
public static void main(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
public static void main(char[] args){
System.out.println("Overloaded Character array Main Method");
}
public static int main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
122. Comment on method overloading and overriding by citing relevant examples.
Method overloading occurs during the compile time, whereas method overriding occurs
during the run time. Static binding is used during overloading, whereas dynamic
binding is used during methods overriding.
//Function overloading
#function1
void addPodium(int a, int b)
{
System.out.println(a + b);
}
#function2
float addPodium(float a, float b, float c)
{
System.out.println(a + b + c);
}
//Function overriding
class Parent {
void show()
{
System.out.println("I am Parent");
}
}
class Child extends Parent {
void show()
{
System.out.println("I am Child");
}
}
class Main {
public static void main(String[] args)
{
Parent obja = new Parent();
obja.show();
Parent objb = new Child();
objb.show();
}
}
123. A single try block and multiple catch blocks can co-exist in a Java Program.
Explain.
One or more catch blocks can follow a try block. Each catch block must have a
unique exception handler. So, if you want to perform multiple tasks in response to
various exceptions, use the Java multi-catch block.
124. Do final, finally and finalize keywords have the same function?
No, final, finally and finalize keywords have different functionalities.
Finally is used to execute the code written inside the block without handling any
exceptions.
Finalize is used to call the function of the implementation of cleaning the garbage
collection of an object.
127. Using relevant properties highlight the differences between interfaces and
abstract classes.
An abstract class can have a combination of both abstract and non-abstract methods,
whereas an interface has only abstract methods in it.
The start() method creates a separate call stack for thread execution. Once the
call stack is created, the JVM calls the run() method to execute the thread in that
call stack.
129. What is the difference between the ‘throw' and ‘throws' keyword in Java?
The throw keyword is often used to explicitly throw an exception. It can only throw
one exception at a time whereas throws can be used to declare multiple exceptions.
130. Identify the output of the below Java program and Justify your answer.
class Main {
public static void main(String args[]) {
Simplilearn s = new Simplilearn(5);
}
}
class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class Simplilearn extends InterviewBit{
Simplilearn(){
System.out.println(" Welcome to Simplilearn ");
}
Simplilearn(int x){
this();
super();
System.out.println(" Welcome to Simplilearn 2");
}
}
The above code will throw the compilation error. It is because the super() is used
to call the parent class constructor. But there is the condition that super() must
be the first statement in the block. Now, in this case, if we replace this() with
super(), it will also throw a compilation error. Because this() also must be the
block's first statement. So, in conclusion, we can say that we cannot use this()
and super() keywords in the same block.
133. What are the default values assigned to variables and instances in Java?
By default, for a numerical value it is 0, for the boolean value it is false and
for objects it is NULL.
135. Can you tell the difference between equals() method and equality operator (==)
in Java?
The equality operator (= =) is used to check the equality condition between two
variables, but the equals() method is used to check the equality condition between
two objects.
Become job-ready by opting for the decade's hottest career option. Score your dream
job in no time by enrolling in our Full Stack Java Developer Program Today!
136. How is an infinite loop declared in Java?
An infinite loop can be declared in Java by breaking the logic in the instruction
block. For example,
138. Explain the use of the final keyword in variable, method and class.
In Java, one can apply the final keyword to a variable, methods, and class. With
the help of the final keyword, the variable turns out to be a constant, the method
cannot be inherited and the class cannot be overridden.
139. Is it possible that the ‘finally' block will not be executed? If yes then list
the case.
Yes, there is a possibility that the ‘finally’ block cannot get executed. Here are
some of the cases where the above situation occurs.
During the time of fatal errors such as memory exhaustion, memory access error,
etc.
During the time of using System.exit()
140. Difference between static methods, static variables, and static classes in
Java.
A variable, method, or class can be made static by using the static keyword. A
static class cannot be instantiated. When both objects or instances of a class
share the same variables, this is referred to as static variables. Static methods
are simply methods that refer to the class in which they are written.
142. Apart from the security aspect, what are the reasons behind making strings
immutable in Java?
Because of security, synchronization, concurrency, caching, and class loading, the
String is immutable in Java. The reason for making string final would be to destroy
its immutability and help stop others from trying to extend it. String objects are
cached in the String pool, making them immutable.
143. Which of the below generates a compile-time error? State the reason.
int[] n1 = new int[0];
boolean[] n2 = new boolean[-200];
double[] n3 = new double[2241423798];
char[] ch = new char[20];
We get a compile-time error in line 3. The error we will get in Line 3 is - the
integer number too large. It is because the array requires size as an integer. And
Integer takes 4 Bytes in the memory. And the number (2241423798) is beyond the
capacity of the integer. The maximum array size we can declare is - (2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4)
will give a compile-time error. The program will compile fine. But we get the
runtime exception in line 2. The exception is - NegativeArraySizeException.
Here what will happen is - At the time when JVM will allocate the required memory
during runtime then it will find that the size is negative. And the array size
can’t be negative. So the JVM will throw the exception.
148. Why is the character array preferred over string for storing confidential
information?
Because Strings are immutable, any change will result in the creation of a new
String, whereas char[] allows you to set all of the elements to blank or zero. So
storing a password in a character array clearly reduces the security risk of
password theft.
149. What are the differences between HashMap and HashTable in Java?
HashMap
HashTable
1. Asynchronous in nature
1. Synchronous in nature
2. Not thread-safe
2. Thread safe
151. What are the different types of Thread Priorities in Java? And what is the
default priority of a thread assigned by JVM?
There are different types of thread properties in Java. They are MIN_PRIORITY,
MAX_PRIORITY, and NORM_PRIORITY. By default, the thread is assigned NORM_PRIORITY.
158. What gives Java its 'write once and run anywhere' nature?
Java's 'write once and run anywhere' nature is achieved by using Java Virtual
Machine (JVM) and bytecode. Java code is compiled into bytecode, which can be
executed on any platform that has a JVM installed.
+----------+
Example | count=0 |
+----------+
| |
Instance1 | |
+----------+
| |
Instance2 | |
+----------+
166. Why is method overloading not possible by changing the return type in Java?
It is not possible by changing the return type in Java because the return type of a
method is not part of its signature.
168. Can we change the scope of the overridden method in the subclass?
No, we cannot change the scope of the overridden method in the subclass.
175. Difference between the final method and the abstract method
The main difference between a final method and an abstract method in Java is that a
final method cannot be overridden in a subclass, while an abstract method must be
overridden in a subclass.
177. What do you understand about an instance variable and a local variable?
Instance variables and local variables are two types of variables in Java. Instance
variables are declared inside a class but outside any method. They are used to
store data that is specific to an object. Local variables, on the other hand, are
declared inside a method and are used to store temporary data that is required only
within that method.
One of the main differences between instance variables and local variables is their
scope. Instance variables have a larger scope than local variables. The second
difference between instance variables and local variables is their initialization.
Instance variables are initialized automatically by default values if not
initialized explicitly, while local variables must be initialized explicitly before
they can be used.
179. Can you tell the difference between the equals() method and equality operator
(==) in Java?
Equals() method and equality operator (==) are used for comparing objects in Java.
However, they differ in their functionality. Equals() method is used to compare the
contents of two objects, while the equality operator (==) is used to compare the
references of two objects.
When we use the equality operator (==) to compare two objects, it checks if both
objects refer to the same memory location. On the other hand, when we use the
Equals() method, it checks if the contents of the two objects are equal.
equals() method
Deep copy
The New State represents a thread that has been created but not started yet. The
Runnable state represents a thread that is ready to run but may not be scheduled to
run by the operating System. The Blocked state represents a thread that is waiting
for a monitor lock to be released. The Waiting state represents a thread that is
waiting for another thread to perform a specific action. The Timed Waiting state
represents a thread that is waiting for a specific amount of time to elapse. The
Terminated state represents a thread that has completed its execution.
184. What are the possible ways of making objects eligible for garbage collection
(GC) in Java?
In Java, objects are automatically garbage collected when they are no longer
referenced. However, we can also make objects eligible for garbage collection
manually using the System.gc() method or by setting the object reference to null.
Creational patterns are used for creating objects. Some examples of Creational
patterns are Singleton, Factory, and Abstract Factory.
Structural patterns are used for assembling objects and creating relationships
between them. Some examples of Structural patterns are Adapters, bridges, and
Composites.
Platform Independence: Java code can run on any platform that has a JVM installed.
Object-Oriented: Java is an object-oriented programming language that supports
encapsulation, inheritance, and polymorphism.
Memory Management: Java has automatic memory management, which means that it
manages memory allocation and deallocation automatically.
Multithreading: Java supports multithreading, which allows multiple threads to run
concurrently.
Security: Java has built-in security features that protect the System from
malicious attacks.
Exception Handling: Java has a robust exception-handling mechanism that allows
developers to handle errors and exceptions effectively.
Garbage Collection: Java has automatic garbage collection, which means that it
automatically frees the memory.
It was in the year 1991; Sun Microsystems made history. The quest was to design a
programming language for the Television set-top box. James Gosling (father of Java)
himself would have never predicted that he was about to lay the foundations for the
IT industry's future.
Java follows the simplest and readable form of writing code with the most
sophisticated syntax of an object-oriented programming language. Not only these,
but Java claims to have multiple advantages that give it a strong edge over other
programming languages.
The first important reason out of the ten to Learn Java is Java's beginner-friendly
and competitive edge nature.
Unlike its predecessors, Java comes with advanced memory management tools. Runtime
Environment takes care of memory allocation, reallocation, and deallocation
automatically via an in-built software tool called the Garbage collector.
Moving ahead, we will learn the dramatic and updated features of the Java
programming language that makes it a dominant competitor to its allies.
2. Updated features
It is found that beginners these days are in a dilemma if they want to learn Java.
Such a dilemma is because beginners still believe the myth that says Java is an
old, outdated, and obsolete programming language.
But in reality, Java is going through an unthinkable evolution that brought up many
remarkable changes and add-ons to the programming language. The latest commercial
version of Java from the oracle corporations is the Oracle Java 15
Java 15 comprises the latest text blocks, a foreign-memory access API, hidden
classes, Z Garbage Collector, and the sealed classes previews, pattern matching,
and records. Java 15, for now, is treated as a short-term release, as it is
supposed to be operational for six months with Oracle Premier Support until JDK 16
arrives.
Up next, we will learn the most important reasons out of the ten, and the only
reason for Java to become the industry leader. That is the code portability
(platform independence) and versatility.
The primary objective of JVM is to convert the code written in the user's language
into machine level language (ByteCode), and then the interpreter will compile and
execute the code. The same protocol is followed regardless of the type of the host
operating system.
Next, the language's object-oriented nature makes Java-capable bind the data
members and data manipulating methods together. Data binding makes the data to be
more secure. Not just security, Java is also capable of working with various
resources and working over the network.
Data binding and security features make Java a most versatile programming language.
Followed by platform independence and the versatile nature of Java, we have the
open-source library support of Java.
Java has the support of libraries such as Apache Commons, Google Guava, Maven, and
so on.
Apart from Java EE, the API support in Java took the programming language to the
next level. The developers in Java can integrate back-end, front-end, and
supporting libraries to create a new application. The best part is, the developers
do not have to worry about the complex internal code implementations.
Apart from this, there are numerous communities and groups on the internet and
social media, respectively. The fellow developers in the communities are
enthusiastic about assisting and resolving the issues faced by other developers and
beginners.
The reason for this is that they also develop a variety of software development
tools for assistance. To name a few, we have
IntelliJ
Eclipse
Android Studio
Netbeans
Etc
Advancing to the next level, we have a major dependency on Java.
Multiple Applications are dependent on Java, to name a few; we have the following:
Banking Sectors
Information Technology Sectors
Software Development Sectors
Stock Markets
Financial Services
Social Media
And much more
Up next, we have the never-ending demand for Java Developers.
Dominant-against-allies-Learn-Java-2
So with that, we have reached the end of this "10 Reasons That Explain Why You Need
to Learn Java" article.
==========================================
What is Java: A Beginners Guide To Java
Lesson 2 of 43By Rahul Arun
What is Java?
Java is an object-oriented programming language used in distributed environments on
the internet. It is a high-level language that is also easy to read and understand.
With it, developers can “write once, run anywhere” (WORA), meaning that the
compiled Java code will run on all Java-compatible platforms without the need for
recompilation.
History of Java
James Gosling and Sun Microsystems invented the Java programming language in 1991.
He had a single motto while creating the language: “Write once; run anywhere.” They
first named this language Oak because of the oak tree outside Gosling’s office.
Later, the name changed to Green, then to Java Coffee, which was named after the
coffee from Indonesia, and eventually shortened to Java in 1995.
Editions in Java
There are three editions in Java. Programmers can learn any of these editions based
on the application they want to make.
Java Standard Edition - Contains core libraries, like java.lang, java.util, etc.
Java Enterprise Edition - Includes Java APIs, like JMS, EJB, JSPs/servlets, etc.
Java Micro Edition - This edition is used to program Java in cell phones, set-top
boxes, handhelds, and so on.
The most widely used edition in Java is Java SE (Standard Edition). Java SE
encompasses the basics of Java—most applications require Standard Edition.
Object: Object is an element or an entity that has a state and behavior. For
example, a dog can be considered an object with a color, a breed, and a name. It
has behaviors such as barking and eating.
Class: A class is a collection of multiple objects. It is a blueprint that can be
used to create as many objects as you like. Classes are used to organize code, just
like how fruits, vegetables, and clinical products are divided into different
sections in a supermarket.
Constructor: Constructor may look like a method, but it is not one. Its name is the
same as the class name, and it does not return any value.
Inheritance: Inheritance is the concept where one class acquires the properties and
the behaviors of the parent class.
Polymorphism: Polymorphism is the process of performing the same task in different
ways. It lets programmers use the same word to mean different things in different
contexts.
Abstraction: Abstraction in Java is used to hide internal details and show only the
relevant essential details.
Encapsulation: Binding or wrapping code and data together into a single unit (like
a capsule) are known as encapsulation. A Java class is an example of encapsulation.
Want a Top Software Development Job? Start Here!
Full Stack Developer - MERN StackExplore ProgramWant a Top Software Development
Job? Start Here!
Java Features
Java has several qualities and features, including:
Components of Java
There are three main components of the Java programming language, including:
JVM: The Java Virtual Machine or JVM is a platform-independent Java component that
provides an environment for executing Java programs. So, JVM loads the code,
validates the code, executes the code, and provides a runtime environment.
JRE: The Java Runtime Environment or JRE builds an environment in which the Java
files can be run and executed. It is a software package that contains JVM along
with Java class libraries and Java class loader.
JDK: The Java Development Kit or JDK is a superset of JRE and is a software
development environment used to develop Java applications and applets. The JDK
includes a private JVM and a few other resources to finish the development of a
Java application.
Java OOPs Concepts
There are four main concepts of object-oriented programming (OOP), including:
1. Abstraction
Abstraction means showing the relevant details and hiding all the backend or
internal details. In the example below, for a student to be admitted into the
college, the relevant details asked will be the name, address, parent’s name, and
high school marks. Details like favorite sports, food, or movies are not relevant.
oops-command
2. Encapsulation
Encapsulation is similar to a capsule. The entire code and all of the data are
bound together in a single unit. All the methods and variables are stored under one
class name, and the same class object can use it.
encapsulation
3. Polymorphism
Polymorphism means one task is performed in different ways. One function is used
for different tasks. In the example below, Method draw() can be used in different
places to draw different shapes, like a triangle, rectangle, or circle.
polymorphism
4. Inheritance
When one class inherits certain properties and attributes of other classes, it is
known as inheritance. There is always a superclass and a subclass. The subclass
inherits attributes from the superclass. In the example below, the animal is a
superclass that has attributes eat() and sleep(). Subclasses reptile, mammal, and
human inherit these attributes.
inheritence
Start with the basics of Java programming (variables, data types, conditional
statements, arrays, loops, functions)
Read a book on Java Programming to understand the basic concepts
Learn the advanced topics (object-oriented programming, inheritance, abstract
class, Java interface, collections, abstract classes, exceptional handling, wrapper
classes)
Practice coding regularly to know to learn from experience
Read articles and new documentation on Java to stay up to date
Developers often ask themselves a question at some point in their career—Do I need
a Java certification?
Some employers do value certifications a lot. Earning a certification will help you
grow in your career and earn more.
There are four types of certification levels mentioned within Oracle’s Java
certification path:
Become job-ready and get complete job assistance by opting for the decade's hottest
career option. Score your dream job in no time by enrolling in our Full Stack Java
Developer Job Guarantee Program Today!
Hello World Program in Java
hello world
Output:
javac
temp-variable
Output:
javac-output
Conclusion
Almost everything we use in our day-to-day life is now connected to Java. Java
programming language continues to be one of the top technologies in the industries,
and the job demand is significantly high. If you want to learn Java and start your
career in it, do refer to the following playlist link: Java Tutorials.