Friday, March 1, 2024

Java Coding Interview Questions For 4 Years Experience

Don't Miss

If You Were Training Someone In Java What Would You Tell Them About Wrapper Classes

TCS Java coding questions | 4.5 Years of Experience | Selected

Give an accurate answer that shows your technical knowledge of Java and also your interpersonal skills and ability to share information with others.

Example answer:”If I were training someone in wrapper classes, I would first make sure they understood all eight primitive types and how they can use them. I think the most important thing to convey is that assigning a wrapper class is final and immutable. Knowing this will save that person a lot of time.”

Related:6 Qualities That Make a Great Team Player

Write A Program In Java To Show Isalive And Join Operations In Multithreading

The isAlive method tells whether a thread is alive or terminated. These alive and terminated are the states of a thread in Java. Also, the join operation joins a thread to another. This means that the thread will wait for the complete execution of the thread to which it is joined even if its own work is completed. Then, they both will terminate together.

Java Code to show isAlive and join operations

classDemoThreadextendsThread}classDemoThread2extendsThread catch   } }}publicclassMain catch   t2.setDaemon  t2.start // t2.interrupt  Thread mainThread = Thread.currentThread try  catch     }} 



Q 93 Which Of The Below Generates A Compile

int n1 = new int

boolean n2 = new boolean

double n3 = new double

char ch = new char

We get a compile-time error in line 3. The error we will get in Line 3 is – the 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 is beyond the capacity of the integer. The maximum array size we can declare is – .

Because the array requires the size in integer, none of the lines 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 cant be negative. So the JVM will throw the exception.

Don’t Miss: How To Ask For Interview Feedback

Whats The Difference Between Stack And Array



Stack follows a Last In First Out pattern. What this means is that data access necessarily follows a particular sequence where the last data to be stored is the first one that will be extracted.

On the other hand, Arrays do not follow a specific order, but instead can be accessed or called by referring to the indexed element within the array.

Boost Your Coding Skills. Nail Your Next Interview

Can We Declare The Static Variables And Methods In An Abstract Class

Java Coding Interview Questions For 10 Years Experience ...

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.


hi !! I am good !!i = 102

Also Check: What To Do To Prepare For An Interview

Java Interview Questions For 2 Years Experience

Can An Interface Implement Another Interface? Can An Interface Extend Another Interface? Can A Class Extend More Than One Class? Why Is An Interface Be Able To Extend More Than One Interface But A Class Cant Extend More Than One Class? Can An Interface Be Final? Can A Class Be Defined Inside An Interface? Can An Interface Be Defined Inside A Class? What Is A Marker Interface? Which Oo Concept Is Achieved By Using Overloading And Overriding? If I Only Change The Return Type, Does The Method Become Overloaded? Why Does Java Not Support Operator Overloading? Can We Define Private And Protected Modifiers For Variables In Interfaces? What Is Externalizable? What Modifiers Are Allowed For Methods In An Interface? What Is A Local, Member And A Class Variable? What Is An Abstract Method? What Value Does Read Return When It Has Reached The End Of A File? Can A Byte Object Be Cast To A Double Value? What Is The Difference Between A Static And A Non-static Inner Class? A non-static inner class may have object instances that are associated with instances of the classs outer class. A static inner class does not have any object instances. What Is An Objects Lock And Which Objects Have Locks? What Is The % Operator? When Can An Object Reference Be Cast To An Interface Reference? Which Class Is Extended By All Other Classes? Which Non-unicode Letter Characters May Be Used As The First Character Of An Identifier? What Restrictions Are Placed On Method Overloading? What Is Downcasting ?

Q44 What Is A Map In Java

In Java, Map is an interface of Util package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface:

  • Map doesnt contain duplicate keys.
  • Each key can map at max one value.

  • Also Check: How To Interview A Housekeeper

    Write Java Program That Checks If Two Arrays Contain The Same Elements

    To check if two arrays contain the same elements, you need to first create a set of elements from both the arrays, and then compare the elements in these sets to find if there is an element that is not present in both sets. The following example code shows how to check if two arrays only contain common elements:

    importjava.util.Arrays importjava.util.HashSet importjava.util.Set publicclassArraySameElements Integer a2 = Integer a3 = System.out.println) System.out.println) }staticbooleansameElementsreturntrue }}

    What Does It Mean For A Collection To Be Backed By Another Give An Example Of When This Property Is Useful

    Accenture java interview questions and answers| 4+ years experience

    If a collection backs another, it means that changes in one are reflected in the other and vice-versa.

    For example, suppose we wanted to create a whitelist function that removes invalid keys from a Map. This is made far easier with Map.keySet, which returns a set of keys that is backed by the original map. When we remove keys from the key set, they are also removed from the backing map:

            public static < K, V>  Map< K, V>  whitelist 

    retainAll writes through to the backing map, and allows us to easily implement something that would otherwise require iterating over the entries in the input map, comparing them against allowedKey, etcetera.

    Note, it is important to consult the documentation of the backing collection to see which modifications will successfully write through. In the example above, map.keySet.add would fail, because we cannot add a key to the backing map without a value.

    Reflection allows programmatic access to information about a Java programs types. Commonly used information includes: methods and fields available on a class, interfaces implemented by a class, and the runtime-retained annotations on classes, fields and methods.

    Examples given are likely to include:

    A concrete code example could be something simple, like copying an objects fields into a map:

            Person person = new Person         Map< String, Object>  values = new HashMap< >         for .getDeclaredFields)         // prints         System.out.println 

    Read Also: How To Do Great In A Job Interview

    Q What Is The Purpose Of The Runtime Class And System Class

    Runtime Class: The purpose of the Runtime class is to provide access to the Java runtime system. The runtime information like memory availability, invoking the garbage collector, etc.

    System Class: The purpose of the System class is to provide access to system resources. It contains accessibility to standard input, standart output, error output streams, current time in millis, terminating the application, etc.

    Read Also: What Questions To Ask When You Are Interviewing Someone

    Q5 Explain The Role Of Dispatcherservlet And Contextloaderlistener

    DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

    ContextLoaderListener, on the other hand, is the listener to start up and shut down the WebApplicationContext in Spring root. Some of its important functions includes tying up the lifecycle of Application Context to the lifecycle of the ServletContext and automating the creation of ApplicationContext.

    Also Check: What To Ask After An Interview

    You Have To Search The Element In O Time Complexity Without Using Any Extra Space Print True If The Element Exists In The Matrix Else Print False

    The normal searching technique will take O time complexity as we will search every element in the matrix and see if it matches our target or not. The other approach uses the fact that the elements are sorted row-wise. We can apply binary search on every row. Hence, the time complexity will be OSince we want the solution in O, this approach is not the one we will use. We will use the Staircase Search Algorithm. See, we know that the elements are sorted column-wise and row-wise. So, we start from the last element of the first row as shown below

    Let us say we want to search for 21. We know that 21 is larger than 15. Since the matrix is row-wise sorted, element 15 is the largest element of this row. So, we are not going to find 21 in this row. So, we move directly to the last element of the next row. The Same is the case here as well. So, we move to the next row. Here, the element is 22. So, 21 might be present in this row. So, we move one step backwards in this row only.

    On moving one step backwards, we see that we reach 16. Since this number is smaller than our target of 21, we know that we will not find our target in this row. Hence, we move to the last element of the next row and the same happens here too. Now, we are in the last row. We know that element might exist in this row. So, we keep on moving back in this row and find element 21.

    So, we will implement this same algorithm. This is called staircase search.

    Java Code for Staircase Search

    Sample Output

    What Is The Inheritance

    Top 20 Java interview questions for 5 to 6 years experience

    Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

    There are five types of inheritance in Java.

    • Single-level inheritance

    Recommended Reading: Healthcare Data Analyst Interview Questions

    Don’t Miss: How To Develop Interview Skills

    Q9 Can You Override A Private Or Static Method In Java

    You cannot override a private or static method in Java. If you create a similar method with the same return type and same method arguments in child class then it will hide the superclass method this is known as method hiding. Similarly, you cannot override a private method in subclass because its not accessible there. What you can do is create another private method with the same name in the child class. Lets take a look at the example below to understand it better.

    class Base public void print class Derived extends Base public void print public class test }

    Q18 Whats The Difference Between An Abstract Class And Interface In Java

    Ans: The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers with or without concrete implementation.

    Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesnt require implementation of all the methods of its super class.

    A class can implement multiple interfaces but it can extend only one abstract class.

    Don’t Miss: What Are Some Interview Questions For Customer Service

    Compare The Sleep And Wait Methods In Java Including When And Why You Would Use One Vs The Other

    sleep is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

    wait, on the other hand, simply pauses the thread until either the specified number of milliseconds have elapsed or it receives a desired notification from another thread , without keeping a hold on the monitor/lock of the shared object.

    sleep is most commonly used for polling, or to check for certain results, at a regular interval. wait is generally used in multithreaded applications, in conjunction with notify / notifyAll, to achieve synchronization and avoid race conditions.

    Q1 What Is The Difference Between Error And Exception

    Real time Java Interview Questions for 4 years Experienced

    An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.

    While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving the user feedback for entering proper values etc.

    You May Like:

    Read Also: How To Interview For A Leadership Position

    How Would You Implement The Insertion Sort Algorithm

    • We assume the first element in the array to be sorted. The second element is stored separately in the key. This sorts the first two elements. You can then take the third element and do a comparison with the ones on the left of it. This process will go on until a point where we sort the array.

    int a =

    for {

    int n = m

    while {

    int k = a

    a = a

    a = k

    Some More Sample Java Interview Questions For Developers With 5 Years Of Experience

  • Explain method overloading Java.
  • Letâs talk about the equals methods.
  • Explain the concept of a catch block.
  • Describe what it’s like working with threads in Java.
  • How will you attain thread safety in Java?
  • Explain if it is possible to call a run method of a Thread class.
  • How is a programâs Java Thread Dump found?
  • Describe the process of multithreading in Java.
  • What is the one thing you would keep in mind when multithreading in Java?
  • What is context-switching?
  • What will be the output of the program given below?
  • class A

    synchronized void m1




    void m2




    Recommended Reading: How To Prepare For An Interview Manager Position

    What Is The Final Blank Variable

    A final variable, not initialized at the time of declaration, is known as the final blank variable. We can’t initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

    Java Coding Interview Questions: 35+ Most Asked Java Coding

    Top 20 Java interview questions for 5 to 6 years experience

    It is challenging for freshers to find most asked Java coding interview questions that commonly asked in interviews.

    Here We have collected 35+ Most asked Java coding Interview Questions that are recommended by Engineers of MNCs.

    Here we have covered both easy and tricky questions. Because of some time, easy questions are also not solved by many candidates.

    This coding question of Java Programming will help you to crack the coding interview rounds.

    Along with the coding questions, you should also prepare pattern programming in Java because the interviewer may ask some time pattern questions.

    Coding Programs are like you have given some operations to perform on numbers, strings, arrays, or on linked lists.

    Below are the Java programs which mostly asked in a coding round, which are categorized in section wise. Prepare each variety of coding questions, which is very important and will help you crack your coding rounds.

    Also Check: What Questions To Ask In An Administrative Assistant Interview

    Write A Program In Java To Print The Elements Of The Matrix In Wave Order As Shown Below

    It is clear from the image itself that we are traversing column-wise. Now, when we traverse an even column, we traverse it from top to bottom and when we traverse an odd column, we traverse it from bottom to top direction.

    Code for Wave Print a Matrix in Java

    import* import java.util.* publicclassMain    } for         } else         }        System.out.println     }  }}

    Sample Output

    Input: 123456789Output:147852369
    • Time Complexity: O where N is the number of rows and M is the number of columns.
    • Auxiliary Space: O as we have not used any extra space to solve this problem.

    Java Program To Check If The Given Number Is Prime

    We can write a simple program to divide the given number ânâ from 2 to n/2 and check the remainder. If the remainder is 0, then itâs not a prime number.

    public class PrimeNumberCheck public static boolean isPrime if  for  }return true }}

    But, this is not very memory and time-efficient. For a given number N, if there is a prime number M between 2 to âN that evenly divides it, then N is not a prime number.

    You May Like: How To Answer It Interview Questions

    More articles

    Popular Articles