java_300
java_300
JRE: JRE stands for the Java Runtime Environment. It provides the runtime
environment for the program and is the actual interpretation of the JVM. It
contains libraries and other files that JVM can use.
JVM: JVM does not physically exist; instead, it is a virtual machine. It converts
bytecode into machine-readable code to execute the program. Overall, it provides
the specifications required to run the program.
8. What is inheritance?
Inheritance is the feature of Java by which the class obtains all the attributes
and the behavior of another class, mainly called the parent class. This helps to
save a lot of time and enables the reuse of methods and fields.
9. What is polymorphism?
Practically speaking, polymorphism means to exist in many forms. You can create an
abstract or an interface and implement it in any class you want. Polymorphism
mainly can used for method overloading (compile-time polymorphism) and method
overriding (runtime polymorphism)
Abstract class
It cannot be instantiated
It cannot have both abstract and non-abstract methods.
Other classes can implement only one abstract class.
All types of access modifiers can be used – public, private, and protected.
Interface
It can be instantiated
It can have only abstract methods by default.
Multiple implementations of interfaces are possible.
All the variables have to be ‘static’ or ‘final’.
21. What is the purpose of the static keyword?
The main purpose of static keywords in Java is memory management. Using static
keywords helps to use the memory more efficiently by creating a single copy of our
input variable or method instead of repeating them individually. This is quite
useful, especially when dealing with a massive database.
In the beginning, the constructor was made private. After that, a private static
instance of the class needs to be created. Finally, a public static method is
provided to return the instance.
However, as the ArrayList uses less memory it makes it suitable for data storage,
unlike LinkedList which is better to manipulate lists.
For instance, when the user wants to add given numbers, but the number of arguments
is not fixed. In such cases, if methods are written individually it will make the
work more difficult. Here, method overloading helps to figure out the program
quickly.
25. Explain the concept of method overriding.
Method overloading is a quite useful feature in Java that helps to assign multiple
methods with the same name yet having different parameters for a specific class.
For instance, we want to create a new class or subclass, from the superclass, using
the same method. Now, method overriding will allow the subclass’s method to
override the method of the superclass.
When this keyword is added to the variable, JVM ignores the variable’s value and
stores a default value. Most of the time, it is done when the program needs to
accept the user’s login details and password.
To handle the exceptions, the ‘try’ and ‘catch’ block can be used.
int sum = 0;
int count = 0;
if (num < 0) {
throw new IllegalArgumentException("Input positive integer
only");
}
sum += num;
count++;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
scanner.nextLine();
}
}
OOP Concepts
31. Explain the concept of object-oriented programming (OOP).
Object-oriented programming is related to the objects rather than just the values
or logic of simple programming. Precisely, the object is a data field that has a
set of attributes and features.
This programming model simplifies complex and lengthy software developments using
the concepts of abstraction, encapsulation, inheritance, and polymorphism.
This programming model simplifies complex and lengthy software developments using
the concepts of abstraction, encapsulation, inheritance, and polymorphism.
35. What is the use of the ‘protected’ access modifier while dealing with
inheritance?
The access modifier ‘protected’ is used for the attributes and the methods that
need to be made accessible only by the classes of the same package. However, even
after locating in different packages, the subclasses can access these variables and
methods. This not only helps to achieve proper inheritance but is also useful in
preventing access from irrelevant classes.
38. What is the difference between shallow copy and deep copy in the context of
object-oriented programming?
Shallow copy happens when the user copies the references only into the objects or
variables. In this case, new memory is not allocated. However, the new memory is
allocated in deep copy, but the reference is not copied.
44. What are the advantages and disadvantages of using inheritance in object-
oriented programming?
In Java, inheritance allows the user to reuse the code by transferring all the
attributes to the subclass from the superclass. This also helps with method
overriding, saving time, and simplifying maintenance.
Apart from this, inheritance also has a major drawback, restricting the extension
of subclasses from more than one superclass. This can sometimes reduce the
efficiency of the projects.
47. Can you describe the difference between method overloading and method
overriding?
Method overloading means having the same name of methods but with different data
types or parameters or even both. For example, the methods below have different
parameters and data types.
Some of the access modifiers are public, private, default, and protected
int num=10;
77. How do you initialize a variable?
Initializing a variable is the same as declaring a value. However, in order to
initialize the variable, the value must be assigned, unlike the declaration. A
simple example can solve the confusion.
int num=10;
Double num1;
Here, the first variable is declared and initialized as the value is assigned to
it. While the second one, ‘num1’, is only declared; it is not yet initialized as
there is no value given to the variable.
int num=10;
79. What is a type conversion?
Type conversion is another name for typecasting in Java. It is used to convert one
data type to another data type. It is necessary when one type of data needs to be
stored in another variable. The type conversion must be done by mentioning the
variable that makes the program more readable.
84. Explain the difference between local variables, instance variables, and class
variables in Java.
The local variables are the ones that are declared within the method block,
conditions, or loops. They are only recognized by that part of the program and can
not be interacted with or invoked from another part.
The instance variable is the opposite of this. They are declared outside these
methods or conditionals, usually at the beginning of the class. That’s why all the
parts of the program recognize them.
Lastly, the class variables are the general variables present inside a class. They
can be both local or instance.
89. How does the final keyword affect variables in Java, and what are its
implications for the program?
The final keywords make the value of the variable unchangeable. Hence, they are
fixed and can not be modified. This is done to fix and make the variables constant
so that the work related to them can be done efficiently.
double num;
Control Flow Statements
91. What are control flow statements?
To control the flow of the code, Java has specialized control flow statements to
help the user to make the decision to provide a smooth program flow. The common
control flow statements are ‘if’, ‘loop’, and the ‘jump’ statements.
if (num > 0) {
num=num*2;
);
}
This example shows a basic if-statement. Here, if the number the user has input is
bigger than 0, then the number will be multiplied by 2. When the conditions are not
met, the program will not function.
if (num > 0) {
num=num*2;
);
if else(num<0){
num=num/2;
}
else{
num=0;
}
This example shows that if the num variable is greater than 0, it will be
multiplied by 2. If the first condition is not fulfilled, and the num variable is
less than 0, it will be divided by 2. If none of the above conditions are
satisfied, the value of num will be 0.
case '+':
return operand1+operand2;
case '-':
return operand1+operand2;
case '*':
return operand1*operand2;
case '/':
eturn operand1/operand2;
}
default:
System.out.println("Result: Invalid”);
}
This is a simple calculator that takes the user input in characters and based on
the symbol it decides if the operands need to be added, subtracted, multiplied, or
divided. When the conditions are met, it does not check the rest of the blocks.
However, if none is correctly aligned, it goes to the default option and executes
the code inside it.
for(int i: array ){
System.out.println(i)
}
101. What is a while loop?
The while loop is also similar to the for loop, but it is used to iterate until a
specific condition is fulfilled. When the user does not know how many times the
task shall be repeated, using a while loop is the best practice.
while (i=!10){
i++;
}
Here until the value of variable i becomes 10, the while loop will be repeated and
the task inside will also be repeated. Here the task is to increase the value of
the i by one.
107. What's the difference between a while loop and a do-while loop, and when would
you use each?
The while loop and do-while loop functions are similar – they are used to iterate
the code block until a specific condition is fulfilled. However, do-while is
especially used when the user wants to iterate at least once even if the conditions
are satisfied.
109. When do you choose a switch statement over if-else, and vice versa?
Switch statements are often used when the conditions are neither true nor false
(boolean value) but relatively certain specific values, like the calculator
example. When the operator is the symbol ‘+,’ the program should add, and so on.
On the other hand, the switch statement is better when a faster and easier approach
is needed with few values. For instance, the operation is performed if the number
is greater than 0. Otherwise, it is excluded.
122. What are the main interfaces of the Java Collections Framework?
The Java Collections Framework comprises five major interfaces, which include List,
Set, Map, Queue, and Deque.
Lists maintain ordered collections and permits duplicates, while Sets ensure unique
elements. Maps manage key-value pairs and each key is unique. Queues follow the
FIFO (First-In-First-Out) principle, and Deques support insertion and removal from
both ends.
186. What is the difference between byte streams and character streams?
Byte streams deal with raw binary data, reading, and writing data byte by byte. On
the other hand, character streams handle textual data to read and write characters
and strings.
Java Concurrency
213. What is concurrency in Java?
In Java, concurrency allows the users to perform multiple tasks simultaneously and
in parallel. The ‘Concurrency’ package covers the multithreading, parallelism, and
concurrency platforms, enabling the development of concurrent applications. Using ‘
java.util.concurrent’, this package can be imported to any class to give a
multithreaded feature.
However, Java allows multiple threads to perform many concurrent works at a time.
For example, while writing a document, the user input is taken in one thread, while
the formatting of the document is another.
Runnable Interface
Methods like aliveCoreThreadTimeOut() can be used to terminate the core thread when
no task arrives within the alive time.
The ForkJoinPool class is a type of Executor Class that divides the larger tasks
into smaller divisions to handle them efficiently. Forks refer to the steps
required to split the tasks whereas Join is used to join the subtasks into one
result after their execution.
It allows one to re-enter the lock on a resource more than one time. Each time the
thread enters the lock, its value is incremented by one, and with every unlock
request it is decremented by one. When the value reaches zero, the resource is
unlocked.
The methods of readLock() and writeLock() are needed to achieve this concurrency.
However, an object of the Lock class needs to be created beforehand.
No caching of the volatile variables happens. Rather, they are read from the main
memory. This informs the compiler to prevent it from any optimization.
Java Networking
243. What is Java networking?
Java networking allows the connection of two or more devices together so that they
can share the resources. This feature also allows a centralized software management
option.
However, the URL class can point to anything from simple file locations to
complicated database queries in search engines.
The communication between the server and the client is done by reading and writing.
Methods like getInputStream() and getOutputStream() are used to return the streams
of the sockets.
Here’s a simple example of which IP address can be accessed by just the URL.
import java.net;
public class example {
public static void main (Strings[]args){
InetAddress ip1 = InetAddress.getByName(“www.facebook.com”);
System.out.println(ip1.getHostAddress());
}
}
257. How do you get the hostname of an IP address?
To get the hostname, the InetAddress class has predefined methods. The
getHostName() should be included after the name of the object. With this, by giving
the URL simply, the hostname and the IP address can be retrieved.
From joining and leaving the multicast group, this class also ensures the proper
sending and receiving of the multicast datagrams. For this, the multicast group
address and the port number should be specified.
Serial garbage collection, parallel garbage collection, concurrent mark, and sweep
collection are some of the commonly used ones.
Once the method is used, the garbage collector permanently destroys the object.
This process is known as finalization.
280. What are strong references?
Strong references are not accessible to garbage collections. Following is an
example of a strong reference.
286. What is the difference between heap memory and non-heap memory?
The unrequired objects are often stored in the heap memory before they are
collected by the garbage collectors. On the other hand, the non-heap memory is used
to store the information like loaded classes.
Several methods can be followed to analyze memory usage in Java. Monitoring the CPU
usage, analyzing the garbage collection, and checking the executable methods,
classes, and threads are essential.
At first, the work might seem complex. Thus, often users hire Java developers who
are specialized to effectively analyze the memory usage of the applications.
It can be done simply by changing the heap size. Again, garbage collection
strategies and IAC solutions are some of the high-end processes that can be used.
290. What is the difference between the young generation and the old generation in
JVM?
Young generations are the memory where the newly created objects are stored. As the
objects are created in the Eden space, they are collected by the garbage collector
when they are not reachable anymore.
Contrastingly, the old generation is used to store long-lived objects. The objects
that are left in the garbage collection of the young generation, are prompted to
the old generation’s memory. Here, they are deleted which are of no use and are
occupying space for too long.
However, a single detector is not enough for this. Multiple diagnosing is required
for different cases to find all the memory leaks.
To determine the liveness of the object, G1 knows the global marking phase. After
the completion of the marking phase, G1 identifies the empty spaces which are
garbage collected.