Output of the code:
public static void main(String args[]) {
String c = "Hello I am practicing Java";
if (c.startsWith("H")) {
c = c.trim();
c = c.replaceAll("am", "was");
c = c.substring(3, 5);
byte[] b = c.getBytes();
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
System.out.println(c);
}a. 108
111
lo
b. None of the options
c. 141
121
lo
d. 175
151
lo
Answer: a
The ASCII value of ‘l’ is 108 and the ASCII value of ‘o’ is 111.
which among them doesn’t have index based structure?
1. Set
2. Map
3. TreeMap
4. List
5. None of the above
answer: 1, 2, 3
For the given function, which of the following is a valid lambda expression?
Interface easy {
String method (int a);
}
Easy c = d -> {return d;};
Differences Between Lock and Synchronized Block
Simply put, a lock is a more flexible and sophisticated thread synchronization mechanism than the standard synchronized block.
The Lock interface has been around since Java 1.5. It’s defined inside the java.util.concurrent.lock package, and it provides extensive operations for locking.
There are a few differences between the use of synchronized block and using Lock APIs:
Output of this program:
class TestA implements Runnable {
TestB testB = TestB.test;
@Override
public void run() {
testB.notify();
}
}
class TestB implements Runnable {
private String str = "old";
public static TestB test;
@Override
public void run() {
test = new TestB();
test.wait();
test.str = "New ";
System.out.println(test.str);
}
public static void main(String[] args) {
Thread t1 = new Thread(new TestA());
Thread t2 = new Thread(new TestB());
t1.start();
t2.start();
System.out.println("world");
}
}Answer: world
Output:
world
Exception in thread “Thread-0” Exception in thread “Thread-1” java.lang.NullPointerException: Cannot invoke “Object.notify()” because “this.threadNotifyExample2” is null
at org.example.ThreadNotifyExample.run(ThreadNotifyExample.java:8)
at java.base/java.lang.Thread.run(Thread.java:840)
java.lang.IllegalMonitorStateException: current thread is not owner
at java.base/java.lang.Object.wait(Native Method)
at java.base/java.lang.Object.wait(Object.java:338)
at org.example.ThreadNotifyExample2.run(ThreadNotifyExample.java:21)
at java.base/java.lang.Thread.run(Thread.java:840)
We have overridden the hashCode() function of an Object with a function that always returns the same value
and put the Object as a key of a Hashmap. What is the complexity of the get() function of this HashMap?
1. O(n)
2. O(n2)
3. O(logn)
4. O(1)
If the hashCode() function always returns the same value for all objects, it essentially means that all objects will be mapped to the same hash bucket in the HashMap. When you call get() on this HashMap, it will still have to iterate over the elements in the same bucket to find the correct key (using equals()).
In the worst-case scenario, where all objects end up in the same bucket, the time complexity of get() would degrade to O(n), where n is the number of elements in that bucket. However, typically, HashMap implementations use linked lists or balanced trees to handle collisions in the same bucket, so the worst-case scenario is mitigated.
In Java’s HashMap implementation, if there are multiple entries in the same bucket, it uses a linked list (or in more recent versions, a balanced tree for large lists) to handle collisions, so the time complexity for get() becomes O(1) on average, assuming a good implementation of hashCode() and equals().
So, the correct answer would be:
O(1)
Not real question
what is hashCode() method in java?
A hash code is an integer value that is associated with each object in Java. Its main purpose is to facilitate hashing in hash tables, which are used by data structures like HashMap.
The hashCode() method
In Java, the hash code value of an object is returned by calling the hashCode() method, on that object. This method is implemented, by default, in the Object class and is, therefore, inherited by user-defined classes as well.
This method returns the same integer value (when called on the same object during the same instance of a Java application), provided that no data used by the equals() method is modified.
When hashCode() is called on two separate objects (which are equal according to the equals() method) it returns the same hash code value. However, if it is called on two unequal objects, it will not necessarily return different integer values.
source
Not real question
why hashCode() method is used in java?
The simplest operations on collections can be inefficient in certain situations.
To illustrate, this triggers a linear search, which is highly ineffective for huge lists:
List<String> words = Arrays.asList("Welcome", "to", "Baeldung");
if (words.contains("Baeldung")) {
System.out.println("Baeldung is in the list");
}Java provides a number of data structures for dealing with this issue specifically. For example, several Map interface implementations are hash tables.
When using a hash table, these collections calculate the hash value for a given key using the hashCode() method. Then they use this value internally to store the data so that access operations are much more efficient.
source
Not real question
how hashCode() method works?
Simply put, hashCode() returns an integer value, generated by a hashing algorithm.
Objects that are equal (according to their equals()) must return the same hash code. Different objects do not need to return different hash codes.
The general contract of hashCode() states:
Not real question
How hash collisions are resolved in java?
The intrinsic behavior of hash tables brings up a relevant aspect of these data structures: Even with an efficient hashing algorithm, two or more objects might have the same hash code even if they’re unequal. So, their hash codes would point to the same bucket even though they would have different hash table keys.
This situation is commonly known as a hash collision, and various methods exist for handling it, with each one having their pros and cons. Java’s HashMap uses the separate chaining method for handling collisions:
“When two or more objects point to the same bucket, they’re simply stored in a linked list. In such a case, the hash table is an array of linked lists, and each object with the same hash is appended to the linked list at the bucket index in the array.
In the worst case, several buckets would have a linked list bound to it, and the retrieval of an object in the list would be performed linearly.”
Hash collision methodologies show in a nutshell why it’s so important to implement hashCode() efficiently.
Java 8 brought an interesting enhancement to HashMap implementation. If a bucket size goes beyond the certain threshold, a tree map replaces the linked list. This allows achieving O(logn) lookup instead of pessimistic O(n).
source
which one of these is an invalid statement about static keyword in java?
1. The static block in a class is executed everytime an object is created from that class
2. None of the statements are invalid
3. All the statements are invalid
4. we can have static blocks in a class
5. we can have static method implementations in a interface
The invalid statement about the static keyword in Java is:
The static block in a class is executed every time an object is created from that class.
Static blocks in Java are executed only once when the class is loaded into memory, not every time an object is created. So, option 1 is incorrect.
You are working on a complex Java application that processes data from multiple sources and produces a
final report for a client. The application is experiencing performance issues, with some reports taking several
minutes to generate.
After analyzing the code and running tests, you have identified a section of the code that is causing the
performance bottleneck.
Upon further investigation, you discover that the code is making several database calls to retrieve data, but
the database connection is not being closed properly, leading to resource leaks and degraded performance.
What is the best course of action to resolve the issue?
The best course of action to resolve the performance issue caused by unclosed database connections is:
what is the difference between stack and heap memory in java?
1. The stack is used for static data and method calls, while the heap is used for dynamic data.
2. The stack is used for objects and method calls, while the heap is
used for primitive data types.
3. The stack is used for primitive data types and method calls, while
the heap is used for objects.
4. The stack is used for local variables and method calls, while the
5. heap is used for global variables.
6. None of the options is correct
The correct difference between stack and heap memory in Java is:
The stack is used for primitive data types and method calls, while the heap is used for objects.
Explanation:
Stack memory is used for storing primitive data types (e.g., int, float, char) and method calls.
Heap memory is used for dynamically allocated objects, such as instances of classes created with the new keyword.
Options 1, 2, 4, and 5 either incorrectly characterize the usage of stack and heap memory or provide incomplete information. Therefore, option 6, “None of the options is correct,” is incorrect as well.
which of the following are true in java?
1. None of the options are correct.
2. Dynamic binding takes place using normal functions.
3. For virtual methods binding is done during compile time.
4. Static binding uses Objects to resolve to bind while Dynamic
binding uses Type information for binding.
5. Static binding is better performance-wise than dynamic binding for static, final, and private methods.
Let’s evaluate each statement:
Output of this code:
class ThreadExample implements Runnable {
int a = 0, b = 0;
int incrementA() {
return ++a;
}
int incrementB() {
return ++b;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(incrementA() + " " + incrementB());
}
}
public static void main(String[] args) {
ThreadExample test1 = new ThreadExample();
ThreadExample test2 = new ThreadExample();
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
t2.start();
t1.start();
}
}a. 11 22 33 11 22 33
b. compile time error
c. runtime error
d. 11 11 22 22 33 33
e. output is not guaranteed.
since the threads are running concurrently and there’s no synchronization mechanism in place, the output might vary due to race conditions.
How many objects are eligible for garbage collection, after line A is executed?
~~~
static class Garbage {
public Garbage g;
public static void main(String[] args) {
Garbage g2 = new Garbage();
Garbage g3 = new Garbage();
g2.g = g3;
g3.g = g2;
g2 = new Garbage();
g3 = g2; // line A
garbageCollection();
}
}
```
a. 1
b. 2
c. 3
d. None of the aboveAnswer: d
Output of this code:
public class StreamExample {
public static void main(String[] args) {
try {
String s = "Medium level question";
byte[] b = s.getBytes();
FileOutputStream fileOutputStream = new FileOutputStream("medium question");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.write(b);
objectOutputStream.flush();
objectOutputStream.close();
} catch (Exception e) {
System.out.println("Caught an exception " + e);
System.exit(0);
}
try {
FileInputStream fileInputStream = new FileInputStream("medium topic");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
objectInputStream.close();
System.out.println(objectInputStream.available());
} catch (Exception e) {
System.exit(0);
}
}
}The correct answer is: Error occurred
The reason is that FileInputStream is trying to read from a file named “medium topic”, while the file that was created earlier in the code is named “medium question”. Therefore, when trying to read from “medium topic”, a FileNotFoundException will be thrown, causing the catch block to execute and the program to exit without printing any additional information.
Not a real question
Write a program to illustrate how FileInputStream and FileOutputStream works in java
public class StreamExample {
public static void main(String[] args) {
try {
String s = "Medium level question";
byte[] b = s.getBytes();
FileOutputStream fileOutputStream = new FileOutputStream("file.txt");
fileOutputStream.write(b);
fileOutputStream.close();
} catch (IOException e) {
System.out.println("Caught an exception " + e);
System.exit(0);
}
try {
FileInputStream fileInputStream = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int bytesRead;
StringBuilder content = new StringBuilder();
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
content.append(new String(buffer, 0, bytesRead));
}
fileInputStream.close();
System.out.println(content);
} catch (IOException e) {
System.exit(0);
}
}
}which fields are accessible from outside the package com.turing?
~~~
package com.turing
public class Test {
int a;
public int b;
protected int c;
private int d;
}
~~~
The correct answer is:
Field b is accessible in all classes in other packages.
Explanation:
Field a: It has default (package-private) access, meaning it is accessible only within the package com.turing.
Field b: It has public access, meaning it is accessible from anywhere, including other packages.
Field c: It has protected access, meaning it is accessible within the package com.turing and by subclasses of Test regardless of the package they are in.
Field d: It has private access, meaning it is accessible only within the class Test itself.
Therefore, only Field b is accessible from outside the package com.turing.
Output of this code:
public class ExceptionTest {
public Integer divide(int a, int b) {
try {
return a/b;
} finally {
System.out.println("finally");
}
}
public static void main(String[] args) {
ExceptionTest exceptionTest = new ExceptionTest();
try {
System.out.println(exceptionTest.divide(10, 0));
} catch (Exception e) {
System.out.println("Division by 0!");
}
}
}a. finally
b. compilation error
c. None of the option
d. finally division by 0!
e. division by 0! finally
answer: d