Thursday, April 18, 2024

Java Coding Interview Questions For Experienced Professionals

Don't Miss

Why Would It Be More Secure To Store Sensitive Data In A Character Array Rather Than In A String

Java interview questions and answers for experienced | Live Mock | coding interview

A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get or set method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread . The example below, from the ThreadLocal Javadoc, generates unique identifiers local to each thread. A threads id is assigned the first time it invokes ThreadId.get and remains unchanged on subsequent calls.

public class ThreadId     }     // Returns the current thread's unique ID, assigning it if necessary    public static int get }

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible after a thread goes away, all of its copies of thread-local instances are subject to garbage collection .

In Java, each thread has its own stack, including its own copy of variables it can access.When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM Warning, this variable may be modified in another Thread.

In all versions of Java, the volatile keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variables current value instead of using a cached value.

What Is The Output Of The Following Java Program

The output of the above code will be

30JavatpointJavatpoint1020

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020.

Q 2 List The Features Of The Java Programming Language

A few of the significant features of Java Programming Language are:

Easy: Java is a language that is considered easy to learn. One fundamental concept of OOP Java has a catch to understand.

Secured Feature: Java has a secured feature that helps develop a virus-free and tamper-free system for the users.

OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in Java, everything is considered an object.

Independent Platform: Java is not compiled into a platform-specific machine instead, it is compiled into platform-independent bytecode. This code is interpreted by the Virtual Machine on which the platform runs.

Full Stack Java Developer Course

Don’t Miss: Assistant Property Manager Interview Questions

The Most Trending Findings

Browse our collection of the most thorough Online Learning Platform related articles, guides & tutorials. Always be in the know & make informed decisions!

Question 1: Give The Simplest Way To Find Out The Time A Method Takes For Execution Without Using Any Profiling Tool

Java Cheat Sheet For Interview

Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a plan for execution.

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for performance. Try it on a method which is big enough, in a sense the one which is doing a considerable amount of processing

Also Check: How To Win A Job Interview

Write A Program To Show A Single Thread In Java

Java Program to show Single Thread

publicclassMain}

Output

When the sentence is a palindrome

Input: 2 Race, e cAr 2Output: true

When the sentence is not a palindrome

Input: 2 Race, a cAr 2Output: false
  • Corner cases, You Might Miss: It is very important to convert all the alphabets in the String to lowercase. If this is not done, our answer will not be correct. Also, the special case of the string being empty is not handled separately as the program automatically covers this test case by not including any character of the string. So, according to our program, an empty string will be a palindrome.
  • If you want that the answer should be false in the case of an empty string, you can apply this condition in the isStrPalindrome function.
  • Time Complexity: O where N is the length of the input string.Auxiliary Space: O as we have not used any extra space.

Why Is Java Coding Popular Among Employers

One of the biggest reasons Java is popular among employers is because of its independence. As long as your computer has the Java Runtime Environment, you can execute a Java program on your computer. Most computers can handle a JRE, including Macintosh, Linux, Unix, Windows and selective mobile phones.

Features that make Java programming popular include:

  • It’s easy to learn and implement.

  • Any code written with Java can run on virtually any computing platform.

  • The code is robust enough to independently run Java programs without any external dependencies.

  • Java has experienced consistent development.

  • It’s a memory management and multithreaded programming language.

Related:12 Tough Interview Questions and Answers

You May Like: What Are The Interview Questions For Hr Recruiter

Q13 What Do You Mean By Aggregation

An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Lets take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not destroy.

Show Examples Of Overloading And Overriding In Java

Java 8 coding/programming Interview questions for freshers and Experienced | Code Decode | Examples

When a class has two or more methods with the same name, they are called overloaded methods. The following example code shows as overloaded method called print:

classFoovoidprint}}

When a superclass method is also implemented in the child class, itâs called overriding. The following example code shows how to annotate the printname method thatâs implemented in both classes:

classBase}classChildextendsBase}

Test yourself by guessing the output of the following code snippets.

String s1 ="abc" String s2 ="abc" System.out.println 
false

The output of the given statement is false because the + operator has a higher precedence than the == operator. So the given expression is evaluated to âs1 == s2 is:abcâ == âabcâ, which is false.

String s3 ="JournalDev" int start =1 char end =5 System.out.println) 
ourn

The output of the given statement is ourn. The first character is automatically type cast to int. Then, since the first character index is 0, it will start from o and print until n. Note that the String substring method creates a substring that begins at index start and extends to the character at index end – 1.

HashSet shortSet =newHashSet forSystem.out.println) 
100
try}else}finally

No output. This code results in an infinite loop if the flag is true and the program exists if the flag is false. The finally block will never be reached.

String str =null String str1="abc" System.out.println| str.equals) 
String x ="abc" String y ="abc" x.concat System.out.print 
abc

Also Check: How To Send An After Interview Email

Question 2: Find Subarrays With Given Sum In An Array

Given an Array of non negative Integers and a number. You need to print all the starting and ending indices of Subarrays having their sum equal to the given integer.For example :

Input-intarr= intnum=9starting index:1,Ending index:2starting index:5,Ending index:5starting index:5,Ending index:6

Solution :

Q37 What Are The Two Ways Of Implementing Multi

Ans: Multi threaded applications can be developed in Java by using any of the following two methodologies:

1) By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run method in this interface which is implemented.

2) By writing a class that extend Java.Lang.Thread class.

Read Also: How To Prepare For Your First Interview

Q41 How We Can Execute Any Code Even Before Main Method

Ans: If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.

What Are The Different Types Of Variables In Java

Top Array Interview Questions (2022)

There are mainly three different types of variables available in Java, and they are:

  • Static Variables
  • Local Variables
  • Instance Variables

Static Variables: A variable that is declared with the static keyword is called a static variable. A static variable cannot be a local variable, and the memory is allocated only once for these variables.

Local Variables: A variable that is declared inside the body of the method within the class is called a local variable. A local variable cannot be declared using the static keyword.

Instance Variables: The variable declared inside the class but outside the body of the method is called the instance variable. This variable cannot be declared as static and its value is instance-specific and cannot be shared among others.

Example:

class A  }//end of class 

Don’t Miss: How To Interview A Realtor When Buying

How Can You Use The Hibernate Framework In Your Everyday Tasks

The interviewer may ask this question to test your knowledge of the Hibernate Framework. Your response can include a brief explanation of Hibernate Framework and its uses.

Example answer:”The Hibernate Framework is a Java framework that you can use to simplify Java application development and database interactions. As an open-source, object-relational mapping tool, it enables data creation, manipulation and access. It maps the object to the database data and internally uses the Java Database Connectivity API to interact with the data.

With the Hibernate Framework, you can automatically create tables in the database and gather data from multiple tables. It implements specifications of the Java Persistence API for data persistence. Since the Hibernate Framework internally uses a default first-level cache and a second-level cache, it performs fast. You can use the object-oriented Hibernate Query Language to generate database-independent queries. By using HQL, you do not need to change the SQL query and write database-specific queries to make any database changes.”

Related:Important Hibernate Interview Questions and Answers to Them

How Do You Reverse A String In Java

There is no reverse utility method in the String class. However, you can create a character array from the string and then iterate it from the end to the start. You can append the characters to a string builder and finally return the reversed string.

The following example code shows one way to reverse a string:

publicclassStringProgramspublicstaticStringreverse}

Bonus points for adding null check in the method and using StringBuilder for appending the characters. Note that the indexing in Java starts from 0, so you need to start at chars.length – 1 in the for loop.

Read Also: What To Ask When Interviewing Someone

What Is The Usage Of This Keyword In Java

The following are the usage provided by this keyword in Java, and they are:

  • It is used to refer to the current class instance variable.
  • This is also used to invoke the current class constructor
  • It is used to invoke the current class method
  • It can be passed as an argument in the method call and in the constructor call

Q18 What Is A Constructor Overloading In Java

Java Interview Questions and Answers for 3 to 10 years of Experienced Developers|Part-1|Code Decode

In Java, constructor overloading is a technique of adding any number of constructors to a class each having a different parameter list. The compiler uses the number of parameters and their types in the list to differentiate the overloaded constructors.

class Demopublic Demo}

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below. Apart from this Java Interview Questions Blog, if you want to get trained from professionals on this technology, you can opt for a structured training from edureka!

Recommended Reading: How To Master Interview Questions

Question : What Is Difference Between Executorsubmit And Executerexecute Method

This Java interview question is from my list of Top 50 Java multi-threading question answers Its getting popular day by day because of the huge demand of a Java developer with good concurrency skills.

This Java interview question answers that former returns an object of Future which can be used to find the result from a worker thread)

There is a difference when looking at exception handling. If your tasks throw an exception and if it was submitted with executing this exception, will go to the uncaught exception handler .

If you submitted the task with submit the method any thrown exception, checked exception or not, is the part of the tasks return status.

For a task that was submitted with submitting and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

If you want to learn more about Future, Callable, and Asynchronous computing and take your Java Concurrency skills to the next level, I suggest you check out Java Concurrency Practice in Bundle course by Java Champion Heinz Kabutz.

Its an advanced course, which is based upon the classic Java Concurrency Practice book by none other than Brian Goetz, which is considered as a bible for Java Developers. The course is definitely worth your time and money. Since Concurrency is a robust and tricky topic, a combination of this book and class is the best way to learn it.

Question : Can You Write A Critical Section Code For The Singleton

This core Java question is another common question and expecting the candidate to write Java singleton using double-checked locking.

Remember to use a volatile variable to make Singleton thread-safe.

Here is the code for a critical section of a thread-safe Singleton pattern using double-checked locking idiom:

public class Singleton }}return _instance  }}

On the same note, its good to know about classical design patterns likes Singleton, Factory, Decorator, etc. If you are interested in this, then this Design Pattern library is an excellent collection of that.

Also Check: How To Create A Digital Portfolio For An Interview

What Is The Major Difference Between Object

An object-based programming language provides the most effective way to follow all the features of OOPs concepts except inheritance. VBScript and JavaScript are examples of Object-based programming languages. Whereas Object-oriented programming language supports all the features of OOPs concepts and examples of Object-oriented programming language is Java, Python, and so on.

Consider Using Star Interview Method

How to answer coding interview questions

The STAR interview technique is a method of developing in-depth responses that thoroughly answer a hiring manager’s questions. You can provide a comprehensive approach by following these steps:

  • Situation: Describe an environment where you faced a challenge or where you handled a project. For instance, you could describe how you managed a team of programmers.

  • Task: Next, describe the roles you had during the event. Perhaps you had a deadline and had to lead the team to finish the project by the deadline.

  • Action: Describe how you completed the task. Focus on how you influenced the result as opposed to what your team did to overcome the challenge.

  • Result: Finally, describe the outcome of your approach to the task. You can also relate what you learned in the role.

You won’t need to answer every question using the STAR interview technique. Many Java coding interview questions are technical and require a more direct answer, but it’s usually best to use the STAR method when faced with a behavioral-based question.

Related:How To Use the STAR Interview Response

Nonverbal communication is one of many tools that can help you make a good impression in interviews and in your professional life. However, candidate assessments should be based on skills and qualifications, and workplaces should strive to be inclusive and understanding of individual differences in communication styles.

Don’t Miss: How To Interview For A Recruiter Position

Tell Me About A Time When Composition Was A Clear Benefit Over Inheritance

With this question, the interviewer is trying to learn more about your and specific level of knowledge using different Java resources. In addition to clearly defining the difference between composition and inheritance, it is important to apply it to your specific work experience when using Java.

Example:”I was working on a project, creating a new software program for a point of sale system using inheritance, when we noticed we were not in the same logical domain. I suggested changing to composition and, after receiving approval, I changed directions. We solved a lot of the errors and improved the security of the program.”

Related: 25 of the Top Java Developer Skills for IT Professionals

Making Java Easy To Learn

In this article, We will discuss about Java Coding Interview Questions and their Answers. Moreover, we will try to provide multiple approaches to solve a coding problem. Additionally, related concepts to a particular coding problem will also be discussed. Our primary focus of this article is to provide all kinds of Java Coding Interview Questions with their Answers. However, for theoretical questions & answers of Java Interview, kindly visit our another article Java Interview Questions.

Read Also: Healthcare Data Analyst Interview Questions

Questions 1: How Do You Avoid Deadlock In Java

If you know, a deadlock occurs when two threads try to access two resources which are held by each other, but to that happen the following four conditions need to match:

  • Mutual exclusion
  • Circular WaitThere must exist a set of processes
  • You can avoid deadlock by breaking the circular wait condition. To do that, you can make arrangements in the code to impose the ordering on the acquisition and release of locks.

    If lock were acquired in a logical order and released in just opposite order, there would not be a situation where one thread is holding a lock that is received by others and vice-versa.

    You can further see my post, how to avoid deadlock in Java for the code example, and a more detailed explanation.

    I also recommend, Applying Concurrency and Multi-threading to Common Java Patterns By José Paumard on Pluralsight for a better understanding of concurrency patterns for Java developers.

    More articles

    Popular Articles