JAVA (What is what)
JAVA (What is what)
Java language was developed in such a way that it does not depend on any hardware or
software due to the fact that the compiler compiles the code and then converts it to
platform-independent byte code which can be run on multiple systems.
The only condition to run that byte code is for the machine to have a runtime
environment (JRE) installed in it
Java supports primitive data types - byte, boolean, char, short, int, float, long, and double
and hence it is not a pure object oriented language.
3. Difference between Heap and Stack Memory in java. And how java
utilizes this.
Stack memory is the portion of memory that was assigned to every individual program.
And it was fixed. On the other hand, Heap memory is the portion that was not allocated to
the java program but it will be available for use by the java program when it is required,
mostly during the runtime of the program.
When we write a java program then all the variables, methods, etc are stored in the
stack memory.
And when we create any object in the java program then that object was created in
the heap memory. And it was referenced from the stack memory.
It is not wrong if we claim that java is the complete object-oriented programming language.
Because Everything in Java is under the classes. And we can access that by creating the
objects.
But also if we say that java is not a completely object-oriented programming language
because it has the support of primitive data types like int, float, char, boolean, double, etc.
C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java
internally uses pointers.
C++ supports the concept of Multiple inheritances whereas Java doesn't support
this. And it is due to avoiding the complexity of name ambiguity that causes the
diamond problem.
6. Pointers are used in C/ C++. Why does Java not make use of pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on
code simplicity, and the usage of pointers can make it challenging. Pointer utilization can
also cause potential errors. Moreover, security is also compromised if pointers are used
because the users can directly access memory with the help of pointers.
Instance variables are those variables that are accessible by all the methods in the class.
They are declared outside the methods and inside the class. These variables describe the
properties of an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables for utilization. If any
modification is done on these variables, then only that instance will be impacted by it, and
all other class instances continue to remain unaffected.
Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
Local variables are those variables present within a block, function, or constructor and can
be accessed only inside them. The utilization of the variable is restricted to the block scope.
Whenever a local variable is declared inside a method, the other class methods don’t have
any knowledge about the local variable.
Example:
There are no default values assigned to the variables in java. We need to initialize
the value before using it. Otherwise, it will throw a compilation error of ( Variable
might not be initialized).
But for instance, if we create the object, then the default value will be initialized by
the default constructor depending on the data type.
If it is a reference, then it will be assigned to null.
If it is numeric, then it will assign to 0.
If it is a boolean, then it will be assigned to false. Etc.
JIT stands for Just-In-Time and it is used for improving the performance during run
time. It does the task of compiling parts of byte code having similar functionality at
the same time thereby reducing the amount of compilation time for the code to run.
The compiler is nothing but a translator of source code to machine-executable code.
But what is special about the JIT compiler? Let us see how it works:
o First, the Java source code (.java) conversion to byte code (.class) occurs
with the help of the javac compiler.
o Then, the .class files are loaded at run time by JVM and with the help of an
interpreter, these are converted to machine understandable code.
o JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM
analyzes the method calls in the .class files and compiles them to get more
efficient and native code. It also ensures that the prioritized method calls are
optimized.
o Once the above step is done, the JVM executes the optimized code directly
instead of interpreting the code again. This increases the performance and
speed of the execution.
11. Can you tell the difference between equals() method and equality
operator (==) in Java?
We are already aware of the (==) equals operator. That we have used this to compare the
equality of the values. But when we talk about the terms of object-oriented programming,
we deal with the values in the form of objects. And this object may contain multiple types
of data. So using the (==) operator does not work in this case. So we need to go with
the .equals() method.
Both [(==) and .equals()] primary functionalities are to compare the values, but the
secondary functionality is different.
Infinite loops are those loops that run infinitely without any breaking conditions. Some
examples of consciously declaring infinite loop is:
for (;;)
{
// Business logic
// Any break logic
}
while(true){
// Business logic
// Any break logic
}
do{
// Business logic
// Any break logic
}while(true);
class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses) {
variable1 = doctors;
variable2 = nurses;
}
public Hospital(int doctors) {
variable1 = doctors;
}
public Hospital(double salaries) {
variable3 = salaries
}
}
Three constructors are defined here but they differ on the basis of parameter type and their
numbers.
Copy Constructor is the constructor used when we want to initialize the value to the new
object from the old object of the same class.
class InterviewBit{
String department;
String service;
InterviewBit(InterviewBit ib){
this.departments = ib.departments;
this.services = ib.services;
}
}
Here we are initializing the new object value from the old object value in the constructor.
Although, this can also be achieved with the help of object cloning.
Yes, It is possible to overload the main method. We can create as many overloaded main
methods we want. However, JVM has a predefined calling method that JVM will only call
the main method with the definition of -
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 void main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
The only difference in the return type of the method does not promote method overloading.
The following example will furnish you with a clear picture of it.
class OverloadingHelp {
public int findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
public int findarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The first
method calculates the area of the rectangle, whereas the second method calculates the area
of a cuboid.
Method overriding is the concept in which two methods having the same method signature
are present in two different classes in which an inheritance relationship is present. A
particular method implementation (already present in the base class) is possible for the
derived class by using method overriding.
Let’s give a look at this example:
class HumanBeing {
public int walk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
class Athlete extends HumanBeing {
public int walk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and time. If the
derived class method is called, then the base class method walk gets overridden by that of
the derived class.
17. A single try block and multiple catch blocks can co-exist in a Java
Program. Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the
general approach because only the first catch block satisfying the catch condition is
executed. The given code illustrates the same:
Here, the second catch block will be executed because of division by 0 (i / x). In case x was
greater than 0 then the first catch block will execute because for loop runs till i = n and
array index are till n-1.
18. Explain the use of final keyword in variable, method and class.
In Java, the final keyword is used as defining something as constant /final and represents
the non-access modifier.
final variable:
o When a variable is declared as final in Java, the value can’t be modified once
it has been assigned.
o If any value has not been assigned to that variable, then it can be assigned
only by the constructor of the class.
final method:
o A method declared as final cannot be overridden by its children's classes.
o A constructor cannot be marked as final because whenever a class is
inherited, the constructors are not inherited. Hence, marking it final doesn't
make sense. Java throws compilation error saying - modifier final not allowed
here
final class:
o No classes can be inherited from the class declared as final. But that final
class can extend other classes for its usage.
19. Do final, finally and finalize keywords have the same function?
Final: If any restriction is required for classes, variables, or methods, the final keyword
comes in handy. Inheritance of a final class and overriding of a final method is restricted by
the use of the final keyword. The variable value becomes fixed after incorporating the final
keyword. Example:
Finally: It is the block present in a program where all the codes written inside it get
executed irrespective of handling of exceptions. Example:
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so that
the clean-up activity is implemented. Example:
20. Is it possible that the ‘finally’ block will not be executed? If yes then list
the case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
21. Identify the output of the java program and state the reason.
1. public class InterviewBit
2. {
3. public static void main(String[] args) {
4. final int i;
5. i = 20;
6. int j = i+20;
7. i = j+30;
8. System.out.println(i + " " + j);
9. }
10. }
The above code will generate a compile-time error at Line 7 saying - [error: variable i
might already have been initialized]. It is because variable ‘i’ is the final variable. And
final variables are allowed to be initialized only once, and that was already done on line no
5.
The super keyword is used to access hidden fields and overridden methods or
attributes of the parent class.
Following are the cases when this keyword can be used:
o Accessing data members of parent class when the member names of the class
and its child subclasses are same.
o To call the default and parameterized constructor of the parent class inside
the child class.
o Accessing the parent class methods when the child classes have overridden
them.
Yes! There can be two or more static methods in a class with the same name but differing
input parameters.
The main method is always static because static members are those methods that belong to
the classes, not to an individual object. So if the main method will not be static then for
every object, It is available. And that is not acceptable by JVM. JVM calls the main method
based on the class name itself. Not by creating the object.
Because there must be only 1 main method in the java program as the execution starts from
the main method. So for this reason the main method is static.
No! Declaration of static methods having the same signature can be done in the
subclass but run time polymorphism can not take place in such cases.
Overriding or dynamic polymorphism occurs during the runtime, but the static
methods are loaded and looked up at the compile time statically. Hence, these
methods cant be overridden.
26. Difference between static methods, static variables, and static classes in
java.
Static Methods and Static variables are those methods and variables that belong to
the class of the java program, not to the object of the class. This gets memory where
the class is loaded. And these can directly be called with the help of class names.
o For example - We have used mathematical functions in the java program like
- max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find
that we call it directly with the class name. Like - Math.max(), Math.min(),
etc. So that is a static method. And Similarly static variables we have used
like (length) for the array to get the length. So that is the static method.
Static classes - A class in the java program cannot be static except if it is the inner
class. If it is an inner static class, then it exactly works like other static members of
the class.
The main objective of this process is to free up the memory space occupied by the
unnecessary and unreachable objects during the Java program execution by deleting those
unreachable objects.
This ensures that the memory resource is used efficiently, but it provides no
guarantee that there would be sufficient memory for the program execution.
Java Classloader is the program that belongs to JRE (Java Runtime Environment).
The task of ClassLoader is to load the required classes and interfaces to the JVM
when required.
Example- To get input from the console, we require the scanner class. And the
Scanner class is loaded by the ClassLoader.
Heap.
To copy the object's data, we have several methods like deep copy and shallow copy.
Example -
class Rectangle{
int length = 5;
int breadth = 3;
}
Now by doing this what will happen is the new reference is created with the name obj2 and
that will point to the same memory location.
Deep Copy - In a deep copy, we create a new object and copy the old object value
to the new object. Example -
Both these objects will point to the memory location as stated below -
33. Which of the below generates a compile-time error? State the reason.
We get a compile-time error in line 3. The error we will get in Line 3 is - 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.
Storage area: In string, the String pool serves as the storage area. For StringBuilder
and StringBuffer, heap memory is the storage area.
Mutability: A String is immutable, whereas both the StringBuilder and
StringBuffer are mutable.
Efficiency: It is quite slow to work with a String. However, StringBuilder is the
fastest in performing operations. The speed of a StringBuffer is more than a String
and less than a StringBuilder. (For example appending a character is fastest in
StringBuilder and very slow in String because a new memory is required for the
new String with appended character.)
Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer
are used whereas a String is not used. However, StringBuilder is suitable for an
environment with a single thread, and a StringBuffer is suitable for multiple threads.
Syntax:
// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");
Interface example:
Consider the example where we have an ArrayList of employees like( EId, Ename, Salary),
etc. Now if we want to sort this list of employees based on the names of employees. Then
that is not possible to sort using the Collections.sort() method. We need to provide
something to the sort() function depending on what values we have to perform sorting.
Then in that case a comparator is used.
Comparator is the interface in java that contains the compare method. And by overloading
the compare method, we can define that on what basis we need to compare the values.
38. In Java, static as well as private method overriding is possible. Comment
on the statement.
The statement in the context is completely False. The static methods have no relevance
with the objects, and these methods are of the class level. In the case of a child class, a
static method with a method signature exactly like that of the parent class can exist without
even throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and overriding is
certainly not possible. Private method overriding is unimaginable because the visibility of
the private method is restricted to the parent class only. As a result, only hiding can be
facilitated and not overriding.
Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not
present, there are certain properties that distinguish a HashSet from a TreeSet.
Implementation: For a HashSet, the hash table is utilized for storing the elements
in an unordered manner. However, TreeSet makes use of the red-black tree to store
the elements in a sorted manner.
Complexity/ Performance: For adding, retrieving, and deleting elements, the time
amortized complexity is O(1) for a HashSet. The time complexity for performing
the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the
performance of HashSet is faster in comparison to TreeSet.
Methods: hashCode() and equals() are the methods utilized by HashSet for making
comparisons between the objects. Conversely, compareTo() and compare() methods
are utilized by TreeSet to facilitate object comparisons.
Objects type: Heterogeneous and null objects can be stored with the help of
HashSet. In the case of a TreeSet, runtime exception occurs while inserting
heterogeneous objects or null objects.
JDK- For making java programs, we need some tools that are provided by JDK
(Java Development Kit). JDK is the package that contains various tools, Compiler,
Java Runtime Environment, etc.
JRE - To execute the java program we need an environment. (Java Runtime
Environment) JRE contains a library of Java classes + JVM. What are JAVA
Classes? It contains some predefined methods that help Java programs to use that
feature, build and execute. For example - there is a system class in java that
contains the print-stream method, and with the help of this, we can print something
on the console.
JVM - (Java Virtual Machine) JVM is a part of JRE that executes the Java program
at the end. Actually, it is part of JRE, but it is software that converts bytecode into
machine-executable code to execute on hardware.
42. What are the differences between JVM, JRE and JDK in Java?
43. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
HashMap is not synchronized thereby making it HashTable is synchronized and hence it is
better for non-threaded applications. suitable for threaded applications.
Allows only one null key but any number of null This does not allow null in both keys or
in the values. values.
Supports order of insertion by making use of its Order of insertion is not guaranteed in
subclass LinkedHashMap. HashTable.
46. What are the different types of Thread Priorities in Java? And what is
the default priority of a thread assigned by JVM?
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default
priority for any thread is NORM_PRIORITY assigned by JVM.
47. What is the difference between the program and the process?
48. What is the difference between the ‘throw’ and ‘throws’ keyword in
java?
The ‘throw’ keyword is used to manually throw the exception to the calling
method.
And the ‘throws’ keyword is used in the function definition to inform the calling
method that this method throws the exception. So if you are calling, then you have
to handle the exception.
Example -
class Main {
public static int testExceptionDivide(int a, int b) throws ArithmeticException{
if(a == 0 || b == 0)
throw new ArithmeticException();
return a/b;
}
public static void main(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handle the exception
}
}
}
Here in the above snippet, the method testExceptionDivide throws an exception. So if the
main method is calling it then it must have handled the exception. Otherwise, the main
method can also throw the exception to JVM.
And the method testExceptionDivide 'throws’ the exception based on the condition.
49. What are the differences between constructor and method of a class in
Java?
Constructor Method
Method is used for exposing the
Constructor is used for initializing the object state.
object's behavior.
Method should have a return type.
Constructor has no return type. Even if it does not return anything,
return type is void.
Method has to be invoked on the
Constructor gets invoked implicitly.
object explicitly.
If the constructor is not defined, then a default If a method is not defined, then the
constructor is provided by the java compiler. compiler does not provide it.
The name of the method can have
The constructor name should be equal to the class name.
any name or have a class name too.
A constructor cannot be marked as final because
whenever a class is inherited, the constructors are not A method can be defined as final
inherited. Hence, marking it final doesn't make sense. but it cannot be overridden in its
Java throws compilation error saying - modifier final not subclasses.
allowed here
A final variable if initialised inside
Final variable instantiations are possible inside a
a method ensures that the variable
constructor and the scope of this applies to the whole
cant be changed only within the
class and its objects.
scope of that method.
Example - Consider a Television (Typical CRT TV). Now another Smart TV that is
inherited from television class. So we can say that the Smart iv is also a TV. Because CRT
TV things can also be done in the Smart TV.
53. Which among String or String Buffer should be preferred when there
are lot of updates required to be done in the data?
In order to achieve this, the attribute can be declared along with the usage
of transient keyword as shown below:
In the above example, all the fields except someInfo can be serialized.
55. What happens if the static modifier is not included in the main method
signature in Java?
There wouldn't be any compilation error. But then the program is run, since the JVM cant
map the main method signature, the code throws “NoSuchMethodError” error at the
runtime.
In java multithreading, the main() threads are always non-daemon threads. And there is no
way we can change the nature of the non-daemon thread to the daemon thread.
58. What happens if there are multiple main methods inside one class in
Java?
The program can't compile as the compiler says that the method has been already defined
inside the class.
59. What do you understand by Object Cloning and how do you achieve it in
Java?
It is the process of creating an exact copy of any object. In order to support this, a
java class has to implement the Cloneable interface of java.lang package and
override the clone() method provided by the Object class the syntax of which is:
In case the Cloneable interface is not implemented and just the method is
overridden, it results in CloneNotSupportedException in Java.
When an exception occurs, first it searches to locate the matching catch block. In case, the
matching catch block is located, then that block would be executed. Else, the exception
propagates through the method call stack and goes into the caller method where the process
of matching the catch block is performed. This propagation happens until the matching
catch block is found. If the match is not found, then the program gets terminated in the
main method.
Exceptions are runtime errors. Suppose we are making an android application with java.
And it all works fine but there is an exceptional case when the application tries to get the
file from storage and the file doesn’t exist (This is the case of exception in java). And if this
case is not handled properly then the application will crash. This will be a bad experience
for users. This is the type of error that cannot be controlled by the programmer. But
programmers can take some steps to avoid this so that the application won’t crash. The
proper action can be taken at this step.
No, it is not necessary for a catch block to be present after a try block. - A try block should
be followed either by a catch block or by a finally block. If the exceptions likelihood is
more, then they should be declared using the throws clause of the method.
63. Will the finally block get executed when the return statement is written
at the end of try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}
finally block will be executed irrespective of the exception or not. The only case where
finally block is not executed is when it encounters ‘System.exit()’ method anywhere in
try/catch block.
64. Can you call a constructor of a class inside the another constructor?
Yes, the concept can be termed as constructor chaining and can be achieved using this().
65. Contiguous memory locations are usually used for storing actual values
in an array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.)
is not possible. The data members/objects present in the ArrayList have references to the
objects which are located at various sites in the memory. Thus, storing of actual objects or
non-primitive data types (like Integer, Double, etc.) takes place in various memory
locations.
It is because the 0 index array avoids the extra arithmetic operation to calculate the memory
address.
Example - Consider the array and assume each element takes 4-byte memory space. Then
the address will be like this -
Now if we want to access index 4. Then internally java calculates the address using the
formula-
[Base Address + (index * no_of_bytes)]. So according to this. The starting address of the
index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is calculated.
Now consider the same with 1 index Array -
Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th
index. Which is wrong. Then we need to apply formula - [Base Address + ((index-1) *
no_of_bytes)].
And for calculating this, an extra arithmetic operation has to be performed. And consider
the case where millions of addresses need to be calculated, this causes complexity. So to
avoid this, ) the index array is supported by java.
67. Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete the element
from either end or the front of the linked list. But in the array, indexes are used. So to
manage proper indexing, we need to adjust the values from the array So this adjustment of
value is costlier than the adjustment of references.
68. How many overloaded add() and addAll() methods are available in the
List interface? Describe the need and uses.
There are a total of 4 overloaded methods for add() and addAll() methods available in List
Interface. The below table states the description of all.
Multiple-inheritance is not possible in Java. Classes can only extend from one
superclass. In cases where multiple functionalities are required, for example - to
read and write information into the file, the pattern of composition is preferred. The
writer, as well as reader functionalities, can be made use of by considering them as
the private members.
Composition assists in attaining high flexibility and prevents breaking of
encapsulation.
Unit testing is possible with composition and not inheritance. When a developer
wants to test a class composing a different class, then Mock Object can be created
for signifying the composed class to facilitate testing. This technique is not possible
with the help of inheritance as the derived class cannot be tested without the help of
the superclass in inheritance.
The loosely coupled nature of composition is preferable over the tightly coupled
nature of inheritance.
71. What is the difference between ‘>>’ and ‘>>>’ operators in java?
These 2 are the bitwise right shift operators. Although both operators look similar. But
there is a minimal difference between these two right shift operators.
‘>>’ Bitwise Right Shift Operator- This operator shifts each bit to its right
position. And this maintains the signed bit.
‘>>>’ Bitwise Right Shift Operator with trailing zero- This operator also shifts
each bit to its right. But this doesn’t maintain the signed bit. This operator makes
the Most significant bit to 0.
Consider the University as a class that has some departments in it. So the university
will be the container object. And departments in it will contain objects. Now in this
case, if the container object destroys then the contained objects will also get
destroyed automatically. So here we can say that there is a strong association
between the objects. So this Strong Association is called Composition.
Now consider one more example. Suppose we have a class department and there are
several professors' objects there in the department. Now if the department class is
destroyed then the professor's object will become free to bind with other objects.
Because container objects (Department) only hold the references of contained
objects (Professor’s). So here is the weak association between the objects. And this
weak association is called Aggregation.
73. How is the creation of a String using new() different from that of a
literal?
When a String is formed as a literal with the assistance of an assignment operator, it makes
its way into the String constant pool so that String Interning can take place. This same
object in the heap will be referenced by a different String if the content is the same for both
of them.
74. How is the ‘new’ operator different from the ‘newInstance()’ operator in
java?
Both ‘new’ and ‘newInstance()’ operators are used to creating objects. The difference is-
that when we already know the class name for which we have to create the object then we
use a new operator. But suppose we don’t know the class name for which we need to create
the object, Or we get the class name from the command line argument, or the database, or
the file. Then in that case we use the ‘newInstance()’ operator.
Yes, it is possible for the program to go out of memory in spite of the presence of a garbage
collector. Garbage collection assists in recognizing and eliminating those objects which are
not required in the program anymore, in order to free up the resources used by them.
Synchronization assists in resolving the issue and the resource is shared by a single thread
at a time. Let’s take an example to understand it more clearly. For example, you have a
URL and you have to find out the number of requests made to it. Two simultaneous
requests can make the count erratic.
No synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if
another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus,
inconsistency in count values takes place because the expected final value is 12 but the
actual final value we get will be 11.
Now, the function increase() is made synchronized so that simultaneous accessing cannot
take place.
With synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public synchronized int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread
Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in
count values takes place.
New – When the instance of the thread is created and the start() method has not
been invoked, the thread is considered to be alive and hence in the NEW state.
Runnable – Once the start() method is invoked, before the run() method is called by
JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also
be entered from the Waiting or Sleeping state of the thread.
Running – When the run() method has been invoked and the thread starts its
execution, the thread is said to be in a RUNNING state.
Non-Runnable (Blocked/Waiting) – When the thread is not able to run despite the
fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally,
after some time of its aliveness, the thread should go to a runnable state.
o A thread is said to be in a Blocked state if it wants to enter synchronized
code but it is unable to as another thread is operating in that synchronized
block on the same object. The first thread has to wait until the other thread
exits the synchronized block.
o A thread is said to be in a Waiting state if it is waiting for the signal to
execute from another thread, i.e it waits for work until the signal is received.
Terminated – Once the run() method execution is completed, the thread is said to
enter the TERMINATED step and is considered to not be alive.
The following flowchart clearly explains the lifecycle of the thread in Java.
81. What could be the tradeoff between the usage of an unordered array
versus the usage of an ordered array?
The main advantage of having an ordered array is the reduced search time
complexity of O(log n) whereas the time complexity in an unordered array is O(n).
The main drawback of the ordered array is its increased insertion time which is O(n)
due to the fact that its element has to reordered to maintain the order of array during
every insertion whereas the time complexity in the unordered array is only O(1).
Considering the above 2 key points and depending on what kind of scenario a
developer requires, the appropriate data structure can be used for implementation.
82. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?
It is possible to import a class or package more than once, however, it is redundant because
the JVM internally loads the package or class only once.
83. 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.*?
This is a big NO. We need to understand that the importing of the sub-packages of a
package needs to be done explicitly. Importing the parent package only results in the import
of the classes within it and not the contents of its child/sub-packages.
84. Will the finally block be executed if the code System.exit(0) is written at
the end of try block?
NO. The control of the program post System.exit(0) is immediately gone and the program
gets terminated which is why the finally block never gets executed.
Marker interfaces, also known as tagging interfaces are those interfaces that have no
methods and constants defined in them. They are there for helping the compiler and JVM to
get run time-related information regarding the objects.
87. Why is it said that the length() method of String class doesn't return
accurate results?
The length method returns the number of Unicode units of the String. Let's
understand what Unicode units are and what is the confusion below.
We know that Java uses UTF-16 for String representation. With this Unicode, we
need to understand the below two Unicode related terms:
o Code Point: This represents an integer denoting a character in the code
space.
o Code Unit: This is a bit sequence used for encoding the code points. In order
to do this, one or more units might be required for representing a code point.
Under the UTF-16 scheme, the code points were divided logically into 17 planes
and the first plane was called the Basic Multilingual Plane (BMP). The BMP has
classic characters - U+0000 to U+FFFF. The rest of the characters- U+10000 to
U+10FFFF were termed as the supplementary characters as they were contained in
the remaining planes.
o The code points from the first plane are encoded using one 16-bit code unit
o The code points from the remaining planes are encoded using two code
units.
Now if a string contained supplementary characters, the length function would count that as
2 units and the result of the length() function would not be as per what is expected.
In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE
character is considered to be TWO - Notice the inaccuracy here? As per the java
documentation, it is expected, but as per the real logic, it is inaccurate.
92. How we can set the spring bean scope. And what supported scopes does it
have?
A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute
in an XML configuration file. Spring Bean supports the following five scopes:
Singleton
Prototype
Request
Session
Global-session
The Java Garbage Collector (GC) typically removes unused objects when they are no
longer required, but when they are still referenced, the unused objects cannot be removed.
So this causes the memory leak problem.
95. Assume a thread has a lock on it, calling the sleep() method on that
thread will release the lock?
A thread that has a lock won't be released even after it calls sleep(). Despite the thread
sleeping for a specified period of time, the lock will not be released.