Real turing java quiz questions Flashcards

1
Q

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

A

Answer: a
The ASCII value of ‘l’ is 108 and the ASCII value of ‘o’ is 111.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

which among them doesn’t have index based structure?
1. Set
2. Map
3. TreeMap
4. List
5. None of the above

A

answer: 1, 2, 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

For the given function, which of the following is a valid lambda expression?
Interface easy {
String method (int a);
}

A

Easy c = d -> {return d;};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Differences Between Lock and Synchronized Block

A

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:

  1. A synchronizedblock is fully contained within a method. We can have Lock APIs lock() and unlock() operation in separate methods.
  2. A synchronized block doesn’t support the fairness. Any thread can acquire the lock once released, and no preference can be specified.
  3. We can achieve fairness within the Lock APIs by specifying the fairness property. It makes sure that the longest waiting thread is given access to the lock.
  4. A thread gets blocked if it can’t get an access to the synchronized block. The Lock API provides tryLock() method. The thread acquires lock only if it’s available and not held by any other thread. This reduces blocking time of thread waiting for the lock.
  5. A thread that is in “waiting” state to acquire the access to synchronized block can’t be interrupted. The Lock API provides a method lockInterruptibly() that can be used to interrupt the thread when it’s waiting for the lock.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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");
    }
}
  1. old world
  2. new world
  3. compile time error
  4. world
  5. run time error
A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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)

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Not real question

what is hashCode() method in java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Not real question

why hashCode() method is used in java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Not real question

how hashCode() method works?

A

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:

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode() must consistently return the same value, provided no information used in equals comparisons on the object is modified. This value doesn’t need to stay consistent from one execution of an application to another execution of the same application.
  2. If two objects are equal according to the equals(Object) method, calling the hashCode() method on each of the two objects must produce the same value.
  3. If two objects are unequal according to the equals(java.lang.Object) method, calling the hashCode method on each of the two objects doesn’t need to produce distinct integer results. However, developers should be aware that producing distinct integer results for unequal objects improves the performance of hash tables.
  4. “As much as is reasonably practical, the hashCode() method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Not real question

How hash collisions are resolved in java?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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?

  1. Implement a cache to store frequently accessed data and reduce
    the number of database queries.
  2. Use a profiling tool to identify other performance issues and
    optimize the code further.
  3. Increase the database connection pool size to improve
    performance.
  4. None of the options are correct.
  5. Modify the code to close the database connection after each query is executed.
A

The best course of action to resolve the performance issue caused by unclosed database connections is:

  1. Modify the code to close the database connection after each query is executed.
    This will ensure that resources are properly released, preventing resource leaks and improving performance. Additionally, it’s a good practice to use connection pooling to manage database connections efficiently, but closing connections after each use is essential to prevent resource leakage.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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.

A

Let’s evaluate each statement:

  1. None of the options are correct: This statement suggests that none of the given options are true. If any of the following options are true, then this statement would be incorrect.
  2. Dynamic binding takes place using normal functions: Dynamic binding occurs in Java through method overriding, where the appropriate method to call is determined at runtime based on the object’s type rather than the reference type. So, this statement is incorrect.
  3. For virtual methods binding is done during compile time: In Java, virtual methods (methods that can be overridden by subclasses) are bound at runtime based on the actual type of the object. Therefore, this statement is incorrect.
  4. Static binding uses Objects to resolve to bind while Dynamic binding uses Type information for binding: Static binding occurs at compile time, where the method call is resolved based on the reference type. Dynamic binding occurs at runtime, where the method call is resolved based on the actual object type. So, this statement is incorrect.
  5. Static binding is better performance-wise than dynamic binding for static, final, and private methods: Static binding is generally faster because it is resolved at compile time, whereas dynamic binding incurs the overhead of determining the appropriate method at runtime. This is particularly true for static, final, and private methods. So, this statement is true.
    Therefore, option 5 is the correct statement.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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.

A

since the threads are running concurrently and there’s no synchronization mechanism in place, the output might vary due to race conditions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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 above
A

Answer: d

17
Q

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);
        }
    }
}
  1. Output is Caught an exception
  2. The file name is medium question and the output is medium level question
  3. Error occurred
  4. The file name is medium level question and the output is medium question
  5. None of the above options is correct
A

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.

18
Q

Not a real question

Write a program to illustrate how FileInputStream and FileOutputStream works in java

A
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);
        }
    }
}
19
Q

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;
}
~~~
1. Field a is accessible in all classes in other packages
2. Field d is accessible in subclasses only in other packages.
3. Field c is accessible in all classes in other packages
4. Field d is accessible in all classes in other packages
5. Field b is accessible in all classes in other packages

A

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.

20
Q

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

A

answer: d

21
Q
A