Tuesday, June 11, 2024

Java Interview Programming Questions And Answers

Don't Miss

Can We Modify The Throws Clause Of The Superclass Method While Overriding It In The Subclass

Java Interview Questions And Answers | Java Programming Interview Questions And Answers |Simplilearn

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

How To Reverse A String In Java

It might be surprising, but there is no reverse utility method in the String class. But, itâs a very simple task. We can create a character array from the string and then iterate it from the end to start. We can append the characters to a string builder and finally return the reversed string.

public class StringPrograms public static String reverse }

Bonus Points: Adding null check in the method and using StringBuilder for appending the characters. Easy to Miss: The indexing in Java starts from 0. So, we have to start at âchars.length – 1â in the for loop.

Find 5 Mistakes In The Following Code Snippet

package com.journaldev.programming-interviews public class String Programs }
  • Package name canât have hyphens.
  • Class name canât have whitespaces.
  • The main method is not public, so it wonât run.
  • The main method argument shouldnât specify the size.
  • The semicolon is missing in the string definition.
  • Recommended Reading: How To Nail A Zoom Interview

    Difference Between Method Overloading And Overriding

    Method Overloading Method Overriding
    1) Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its superclass.
    2) Method overloading occurs within the class. Method overriding occurs in two classes that have IS-A relationship between them.
    3) In this case, the parameters must be different. In this case, the parameters must be the same.

    Write A Program To Show A Single Thread In Java

    Data Structure and algorithm interview questions in java

    Java Program to show Single Thread



    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.

    Read Also: How To Answer Nursing Interview Questions

    Write A Program In Java To Calculate Pow Using Recursion The Expected Time Complexity Is O Where N Is The Power You Cannot Use Any Extra Space Apart From The Recursion Call Stack Space

    We have seen how we can calculate the pow in linear time. We can optimize our approach by changing the recurrence relation. Let us understand this with the help of an example shown below:

    So, we can see that if the power is even, we can divide the power by 2 and can multiply x to the power n/2 by itself to get our answer. What if the power of the number is odd?

    In that case, we multiply the number x once to the term x to the power n/2 multiplied by itself. Here, n/2 will be the floor value of . You can verify this for any pair of x and n.

    So, doing this will reduce the time complexity from O to O. This happens because of the change in recurrence relation and the recursion tree as shown below.

    Solving these recurrence relations gives us the respective time complexities. So, the code for O approach is shown below

    Java Code for in Logarithmic Time Complexity

    import java.util.* classMainpublicstaticdoublepowreturn power     }publicstaticvoidmain}

    Sample Output:

    Input: 1.103Output: 1.3676310000000003
    • For negative Power
    • Corner Cases, You Might Miss: The power of a number can be negative too. So, we know that x-n = . In this way, we can handle the corner test case of a power being negative.
    • Time Complexity: As already discussed, Time Complexity is O.
    • Auxiliary Space: The auxiliary space is O as we have not used any extra space.

    What Is A Multi

    There could be a scenario where a single piece of code can cause multiple exceptions. You can handle this situation by creating several catch clauses, each catching a different exception. When the program throws an exception, it inspects the catch statements in the order in which they appear. The first catch whose type matches the type of exception is executed. Below is an exception handling program in Java to understand the multi-catch block.

    // Multi-catch block // Code taken from Edureka.com public class SampleMultipleCatchBlock  catch    catch   catch   System.out.println  } } 

    Also Check: How To Interview Job Candidates

    Q 25 What Happens When The Main Isn’t Declared As Static

    When the main method is not declared as static, then the program may be compiled correctly but ends up with a severe ambiguity and throws a run time error that reads “NoSuchMethodError.”

    With this we are done with the first section that is Basic Java Interview Question, Now, lets move on to our next section of Intermediate Java Interview Questions.

    What Are The Differences Between Constructor And Method Of A Class In Java

    Java 8 coding/programming Interview questions for freshers and Experienced | Code Decode | Examples
    Constructor is used for initializing the object state. Method is used for exposing the object’s behavior.
    Constructor has no return type. Method should have a return type. Even if it does not return anything, return type is void.
    Constructor gets invoked implicitly. Method has to be invoked on the object explicitly.
    If the constructor is not defined, then a default constructor is provided by the java compiler. If a method is not defined, then the compiler does not provide it.
    The constructor name should be equal to the class name. The name of the method can have any name or have a class name too.
    A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn’t make sense. Java throws compilation error saying – modifier final not allowed here A method can be defined as final but it cannot be overridden in its subclasses.
    Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects. A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.

    You May Like: A Follow Up Email After 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 java.io.* 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.

    How Is Jsp Better Than Servlet Technology

    JSP is a technology on the servers side to make content generation simple. They are document-centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside an HTML template file. It provides the framework for the development of a Web Application.

    You May Like: How To Crack Devops Interview

    What Is The Difference Between Concurrent Collections And Synchronized Collections

    Concurrent collection and synchronized collection are used for thread safety. The difference between them is how they achieve thread-safety by their scalability, performance. The performance of concurrent collection is better than synchronized collection because it holds a single part of the map to achieve concurrency.

    Can We Change The Scope Of The Overridden Method In The Subclass

    Top 21 Java Inheritance Interview Questions and Answers

    Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

    • The private can be changed to protected, public, or default.
    • The protected can be changed to public or default.
    • The default can be changed to public.
    • The public will always remain public.

    You May Like: How To Prepare For An Interview Manager Position

    Q 67 What Is The Difference Between Systemout Systemerr And Systemin

    System.out and System.err represent the monitor by default and thus can be used to send data or results to the monitor. System.out is used to display normal messages and results. System.eerr is used to display error messages. System.in represents InputStream object which by default represents standard input device, i.e., keyboard.

    Q8 What Purpose Do The Keywords Final Finally And Finalize Fulfill


    Final is used to apply restrictions on class, method, and variable. A final class cant be inherited, final method cant be overridden and final variable value cant be changed. Lets take a look at the example below to understand it better.

    class FinalVarExample 


    Finally is used to place important code, it will be executed whether the exception is handled or not. Lets take a look at the example below to understand it better.

    class FinallyExample catch finally }}}


    Finalize is used to perform clean up processing just before the object is garbage collected. Lets take a look at the example below to understand it better.

    class FinalizeExample public static void main}

    Recommended Reading: Financial Analyst Interview Case Study

    What Are The Advantages Of Hibernate Over Jdbc

    Some of the important advantages of Hibernate framework over JDBC are:

  • Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  • Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
  • Hibernate implicitly provides transaction management, in fact, most of the queries cant be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback.
  • JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times its redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we dont need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  • Hibernate Query Language is more object-oriented and close to Java programming language. For JDBC, we need to write native SQL queries.
  • Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  • Hibernate provides option through which we can create database tables too, for JDBC tables must exist in the database.
  • Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
  • Q 30 How Many Types Of Constructors Are Used In Java

    Top 20 Java 8 Interview Questions & Answers [Most Important] | JavaTechie

    There are two types of constructors that are used in Java.

    Parameterized Constructors: Parameterized constructor accepts the parameters with which users can initialize the instance variables. Users can initialize the class variables dynamically at the time of instantiating the class.

    Default constructors: This type doesnt accept any parameters rather, it instantiates the class variables with their default values. It is used mainly for object creation.

    Read Also: How To Answer Typical Interview Questions

    Can You Tell The Difference Between Equals Method And Equality Operator In Java

    This is a method defined in the Object class. It is a binary operator in Java.
    This method is used for checking the equality of contents between two objects as per the specified business logic. This operator is used for comparing addresses , i.e checks if both the objects are pointing to the same memory location.


    • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
    • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

    Q 42 Why Are Generics Used In Java Programming

    Compile-time type safety is provided by using generics. Compile-time type safety allows users to catch unnecessary invalid types at compile time. Generic methods and classes help programmers specify a single method declaration, a set of related methods, or related types with an available class declaration.

    Also Check: What Should A Thank You Letter Say After An Interview

    Describe The Spring Framework

    The Spring framework is used to make enterprise applications using Java. Its central features can work with essentially any Java application.

    Spring is an application framework and container that facilitates the inversion of control . With inversion of control, a generic network sends the flow of control to customized portions of a program.

    What Are The Different Ways Of Threads Usage

    133 Core Java Interview Questions Answers From Last 5 Years
    • We can define and implement a thread in java using two ways:
    • Extending the Thread class
    classInterviewBitThreadExampleextendsThread  publicstaticvoidmain  }
    • Implementing the Runnable interface
    classInterviewBitThreadExampleimplementsRunnable  publicstaticvoidmain  }
    • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
    • start method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run method for executing the thread in that call stack.

    You May Like: Robin Roberts Kardashian Full Interview

    Question : How To Find Duplicate Characters In String In Java

    Solution: Here is a solution to find duplicate characters in String.

  • Create a HashMap and character of String will be inserted as key and its count as value.
  • If Hashamap already contains char,increase its count by 1, else put char in HashMap.
  • If value of Char is more than 1, that means it is duplicate character in that String.
  • How Do You Reverse A String In Java

    There is no reverse utility provided in Java. Hiring managers might ask this question to determine your knowledge of Java and your problem-solving skills. You can create a character array from the string and iterate it from the end to the beginning. You can append the characters to a string builder and finally return the reversed string.

    Example answer:

    You May Like: Interview Questions For Call Center Managers

    Q 3 What Do You Get In The Java Download File How Do They Differ From One Another

    We get two major things along with the Java Download file.

    Abbreviation for Java Runtime Environment

    JDK is a dedicated kit for solely software development

    JRE is a set of software and library designed for executing Java Programs

    Unlike JVM, JDK is Platform Dependent

    Unlike JVM, JRE is also Platform Dependent

    JDK package is a set of tools for debugging and Developing

    JRE Package is one that only supports files and libraries for a runtime environment

    JDK package will be provided with an installer file

    JRE Package does not get an installer but has only a runtime environment

    How To Find If A String Is Present In A Text File

    Top 10 Java Interview Questions | Java Interview Questions And Answers | Simplilearn

    We can use Scanner class to read the file contents line by line. Then use String contains method to check if the string is present in the file or not.

    boolean findStringInFile throws FileNotFoundException }scanner.close return false }

    The above code assumes that the string we are searching for in the file doesnât contain newline characters.

    Recommended Reading: How To Write An Interview Rejection Letter

    What Is The Difference Between Assert And Verify Statements In Selenium


    • We can check whether an element is on the page or not.
    • The test fails and gets terminated whenever there is a fail in the check. That is the program control flow stops.


    • Its only to specify whether the given condition is true or false.
    • The program control flow does not stop due to this.

    Overall, the Verify statement does not halt the program execution whereas the Assert statement does halt the execution.

    Also Check: What Are Some Common Interview Questions

    What Is The Difference Between Static Method And Instance Method

    static or class method
    1)A method that is declared as static is known as the static method. A method that is not declared as static is known as the instance method.
    2)We don’t need to create the objects to call the static methods. The object is required to call the instance methods.
    3)Non-static members cannot be accessed in the static context directly. Static and non-static variables both can be accessed in instance methods.
    4)For example: public static int cube For example: public void msg.

    You May Like: Is An Interview With God Based On A True Story

    More articles

    Popular Articles