The Talent500 Blog
Tricky Java Interview questions and answers 1

Tricky Java Interview questions and answers

Java remains a fundamental programming language that continues to adapt to technological changes in software engineering. With this evolution, facing a Java interview can be challenging because you may be asked tricky questions.

The software development market is competitive, and you will want to win even if you cannot navigate some tricky Java interview questions. This is why we have compiled a list of some commonly asked tricky Java interview questions and answers.

Let’s get started.

 

1.What will be the output of the given Java code?

 

public class Test { public static void main(String[] args) {

  method(null);

 }

 public static void method(Object o) {

 

System.out.println(“Object method”);

 }

 public static void method(String s) {

 

System.out.println(“String method”);

 }}

The output will be “String method.”

There is no object ‘null’ in Java. Still, we can assign null to any object as a reference type in Java code. Here the Java String is also an object of the class java.lang.String which is why the Java compiler calls the overloaded method with the most specific parameters. Therefore, we get the said output because, in Java, a String class is more detailed than an Object class.

2.How can you reverse a string in Java with minimum lines of code? 

As there is no built-in reverse() utility method in the String class in Java, several other methods exist to reverse a string. The easiest way is to create a character array from the string and then iterate it from the end to the start for reversal. To return the reversed string, we can append the characters to a string builder and return it.

Here’s the code to implement this method:

public class StringPrograms {

 

       public static void main(String[] args) {

               String str = “123”;

 

               System.out.println(reverse(str));

       }

       public static String reverse(String in) {

               if (in == null)

                      throw new IllegalArgumentException(“Null is not valid input”);

 

               StringBuilder out = new StringBuilder();

 

               char[] chars = in.toCharArray();

 

               for (int i = chars.length – 1; i>= 0; i–)

                     out.append(chars[i]);

 

               return out.toString();

       }

 

}

Here we have used a null check in the method and StringBuilder to append characters that optimize the performance of the code. Notice chars.length – 1 in the loop is used because Java starts indexing from 0.

 

3.What is a deadlock in Java, and how can you create one programmatically? 

 

Deadlock is one of the most complex errors in Java. It is a scenario in a multi-threaded Java environment where two or more threads are blocked forever. A code that uses two or more threads can face deadlock issues, rendering the application dysfunctional for a long time.

 

Here is a code that creates a deadlock scenario:

 

public class ThreadDeadlock {

   public static void main(String[] args) throws InterruptedException {

     Object obj1 = new Object();

     Object obj2 = new Object();

     Object obj3 = new Object();

   

     Thread t1 = new Thread(new SyncThread(obj1, obj2), “t1”);

     Thread t2 = new Thread(new SyncThread(obj2, obj3), “t2”);

     Thread t3 = new Thread(new SyncThread(obj3, obj1), “t3”);

     

     t1.start();

    

Thread.sleep(5000);

     t2.start();

    

Thread.sleep(5000);

    

t3.start();     

   }

 

}

 

class SyncThread implements Runnable {

 

   private Object obj1;

   private Object obj2;

 

   public SyncThread(Object o1, Object o2) {

     this.obj1 = o1;

     this.obj2 = o2;

   }

 

   @Override

   public void run() {

     String name = Thread.currentThread().getName();

 

    

System.out.println(name + ” acquiring lock on ” + obj1);

     synchronized (obj1) {

      

System.out.println(name + ” acquired lock on ” + obj1);

       work();

      

System.out.println(name + ” acquiring lock on ” + obj2);

      

synchronized (obj2) {

        

System.out.println(name + ” acquired lock on ” + obj2);

        

work();

       }

      

System.out.println(name + ” released lock on ” + obj2);

     }

    

System.out.println(name + ” released lock on ” + obj1);

    

System.out.println(name + ” finished execution.”);

   }

 

   private void work() {

     try {

      

Thread.sleep(30000);

     } catch (InterruptedException e) {

      

e.printStackTrace();

     }

   }

 

}

All three threads can access the first object in the code. But, these threads are written in a way that they use shared resources and keep waiting indefinitely to acquire the lock on the second object. It will keep the code running forever without ever executing thoroughly.

To void deadlocks in Java, we can use Java thread dump.

4.Will the ‘finally’ block execute if you put the return statement or System.exit () on the ‘try‘ or ‘catch‘ block?

A common misconception among Java programmers is that the ‘finally’ block will always execute. But this is proved wrong by putting a return statement in the ‘try’ or ‘catch’ block of the code or calling System.exit() from the ‘try’ or ‘catch’ block.

Keep in mind that in Java code, the ‘finally’ block will execute successfully, even if you put a return statement in the ‘try’ or ‘catch’ block. However, when you try to call System.exit() from the ‘try’ or ‘catch’ block, the ‘finally’ block will fail to execute.

Conclusion

These mind-bending Java interview questions are devised to check your understanding of the core concepts of Java. A proficient Java developer understands the importance of learning the fundamentals and best practices to write scalable, maintainable, high-quality code.

 

Talent500 is a remote team-building platform for Fortune 500 companies, enterprises, and fast-growing startups to hire talent. Sign up here to learn more.

0
Anand Thati

Anand Thati

Lead Software Engineer at Talent500. Works majorly on the backend development and SaaS architecture design. Always hunts for optimised solutions to make the product faster and secure.

Add comment