Wednesday, August 10, 2022

Simple Java Coding Interview Questions

Don't Miss

Q6 How Does An Exception Propagate In The Code

Java Interview Questions and Answers | Java Tutorial | Java Online Training | Edureka

If an exception is not caught, it is thrown from the top of the stack and falls down the call stack to the previous procedure. If the exception isnt caught there, it falls back to the previous function, and so on, until its caught or the call stack reaches the bottom. The term for this is Exception propagation.

Q The Difference Between Serial And Parallel Garbage Collector

Serial Garbage Collector

Serial garbage collector works by holding all the application threads. It is designed for the single-threaded environments. It uses just a single thread for garbage collection. The way it works by freezing all the application threads while doing garbage collection may not be suitable for a server environment. It is best suited for simple command-line programs.

Turn on the -XX:+UseSerialGC JVM argument to use the serial garbage collector.

Parallel Garbage Collector

Parallel garbage collector is also called as throughput collector. It is the default garbage collector of the JVM. Unlike serial garbage collector, this uses multiple threads for garbage collection. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection.

back to top

Sample Technical Interview Questions: Java

    If youre looking for a job in software development or any other role that is highly technical, chances are you will be asked to participate in a technical interview. In this interview youll be given questions that test your technical subject-matter knowledge and ability to apply your skills. You can learn all about technical interviews and how to prepare for them from our Guide to Acing the Technical Interview.

    Some technical interviews are generic and ask a wide range of programming questions, but interviews for more specific roles may focus on a single language, like Java. Here weve compiled a list of technical interview questions you may be asked in a Java interview. To learn more about Java and its applications, check out our ultimate guide to Java.

    You May Like: How To Sell Yourself In An Interview

    Q1: What Is The Method To Serialize An Object In Java

    Ans: To convert an object into a byte stream by serialization in Java, the class executes an interface with the name Serializable. All the class objects executing serializable interface are serialized, and their state is retained in the byte stream.

    If you are going for the interview, it is one of the essential Java technical interview questions that you should know.

    How Is Jsp Better Than Servlet Technology

    Java Interview Questions By Pankaj Panjwani

    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: What Questions Are Asked In A Customer Service Interview

    What Are The Different Types Of Control Statements In Java

    Java has 3 different types of control statements:

    • Selection statements: These statements give the option of choosing a different path of execution of a program depending on the result of a test condition. The expressions in this group are if, if-else and switch statement.

    • Iteration statements: These statements allow repeated evaluation of a statement or a block of statements if the test condition is satisfied. This group contains a statement such as a while, do-while, for and for-each.

    • Jump statements: These statements make the program control jump to another part of the program forward or backward directions with or without a test condition. The statements in this group are break, break label, continue.

    Common Java Code Interview Questions

    Interviewers usually ask basic Java code questions in interviews along with some theoretical aspects. You might be asked questions or tasks like these:

  • Write a Java program to swap two numbers using the third variable.

  • Write a Java program to swap two numbers without using the third variable.

  • Write a Java program to find whether a number is prime or not.

  • Write a Java program to find the duplicate characters in a string.

  • Write a Selenium code to switch to the previous tab.

  • What is an abstract class? How are abstract classes similar or different in Java from C++?

  • How is inheritance in C++ different from Java?

  • What is object cloning?

  • What are the differences between HashMap and HashTable in Java?

  • Can you overload or override static methods in Java?

  • Recommended Reading: How To Give A Mock Interview

    Q1: Can A Class Have More Than One Constructor

    Ans: Yes. A class can have more than one constructor with various parameters. The usage of the constructor for the object depends on the arguments passed wh8ile establishing the objects.

    When you go for the interview, remember it is one of the essential Java interview questions interviewers can ask.

    Q What Is Difference Between String Stringbuffer And Stringbuilder

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

    Mutability Difference:String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.

    Thread-Safety Difference: The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

    Example: StringBuffer

    publicclassBufferTest  }  

    Example: StringBuilder

    back to top

    Read Also: How To Prepare For A Cyber Security Interview

    Q9 What Are The Differences Between Throw And Throws

    throw keyword
    Throw is used to explicitly throw an exception.Throws is used to declare an exception.
    Checked exceptions can not be propagated with throw only.Checked exception can be propagated with throws.
    Throw is followed by an instance.Throws is followed by class.
    Throw is used within the method.Throws is used with the method signature.
    You cannot throw multiple exceptionYou can declare multiple exception e.g. public void methodthrows IOException,SQLException.

    In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.

    What Are The Differences Between Static And Non

    This question is to test your understanding of using static and non-static methods. Your answer can include the use of keywords, compile-time and runtime.

    Example answer:”For creating the static method in Java, you must use the static keyword before the method name. With the non-static method, using the static keyword before the name of the method is not necessary. In Java, a static method is part of the class, and a non-static method is part of the object of a class. You do not need to create an instance of the class to access the static method, but creating an instance of the class is essential for accessing the non-static method.

    A static method can call only other static methods, not a non-static method, and it can access only static variables, not a non-static variable. A non-static method, on the other hand, can call a static method and access a static variable. The syntax to call a static method using the class is className.methodName. You can call it a non-static method like any method.”

    Recommended Reading: How To Prepare For Us Citizenship Interview

    Java Basic Interview Questions With Answers

    If you are discussing Java basics in your interview, you can expect to face questions that give you the opportunity to show off your knowledge. Below are 10 Java interview questions with answers to serve as examples for possible interview situations:

  • What platforms are supported by Java programming language?

  • Explain Java Architectural Neutral.

  • What are the features of an interface?

  • Why would you use a package in Java?

  • Define JAR file and WAR file.

  • What is a final class?

  • What Are Various Access Specifiers Present In Java

    Java Interview Questions

    There are four access specifiers present in Java, and they are:

  • Public: The methods, classes, and variables that are defined as the public can be accessed by any class or method.
  • Private: The methods or classes which are declared as private can be accessible within the same class only.
  • Protected: The variables, methods, and classes which are defined as private can be accessed within the same class of the same package or by the subclass of the same class.
  • Default: By default, all the classes, variables, and methods are of default scope. The default is accessible within the package only.
  • Read Also: What To Ask In A Job Interview Employer

    Q How Garbage Collector Algorithm Works

    Garbage collection works on and Sweep algorithm. In Mark phase it detects all the unreachable objects and Sweep phase it reclaim the heap space used by the garbage objects and make the space available again to the program.

    There are methods like System.gc and Runtime.gc which is used to send request of Garbage collection to JVM but its not guaranteed that garbage collection will happen. If there is no memory space for creating a new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space

    back to top

    Define For Each Loop In Java

    For-each is another kind of array traversing technique in Java which is the same as that of for loop, while loop. It is most commonly used to iterate over a collection or an array such as ArrayList. An example for for-each loop is as follows:

    class ForEachPro      //traversing the array with for-each loop   for   }   } 

    Output:

    12121444

    Don’t Miss: What Is A Technical Interview

    Why The Main Method Is Static In Java

    Java main method is always static, so the compiler can call it without the creation of an object or before the creation of an object of the class. In any Java program, the main method is the starting point from where the compiler starts program execution. So, the compiler needs to call the main method.

    Q Java Program To Implement Singly Linked List

    Python String Coding Interview Questions In Simple Way

    The singly linked list is a linear data structure in which each element of the list contains a pointer which points to the next element in the list. Each element in the singly linked list is called a node. Each node has two components: data and a pointer next which points to the next node in the list.

    Example:

    publicclassSinglyLinkedList         }    // Represent the head and tail of the singly linked list    publicNodehead = null     publicNodetail = null     // addNode will add a new node to the list    publicvoidaddNode     else         }    // display will display all the nodes present in the list    publicvoiddisplay     System.out.println     while     System.out.println         }    publicstaticvoidmain     }  

    Output:

    back to top

    Read Also: How To Write A Good Interview Thank You Note

    Get Ready For Your Upcoming Technical Interview

    If youâve begun preparing for your next technical interview, register for Interview Kickstartâs technical interview webinar and get ahead by understanding foolproof and advanced strategies from industry experts. These reviews from our alums will tell you exactly how weâve helped thousands of students to scallop their professional careers by helping them crack technical interviews at the biggest companies.

    Tricky Java Interview Questions

    Here are some tricky interview questions on Java to boost the inner coding interview ninja are listed below.

  • How would a large number of unused import statements affect the performance?
  • Mention a scenario where a hotspot will be able to optimize your code?
  • Tell us how a decorator design pattern works in I/O classes?
  • How can one call one constructor to another constructor in a class?
  • Mention the purpose of the intern method in the String class?
  • What happens when an exception is thrown from a finally block?
  • Why is it more preferable to use hibernate than JDBC for database interaction?
  • How can you make your web application use HTTPS protocol?
  • Also Check: How To Ask About Work Culture In An Interview

    Q Do You Know Generics How Did You Used In Your Coding

    Generics allows type to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well.

    Advantages

    • Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
    • Type Casting: There is no need to typecast the object.
    • Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.

    Example:

    /** * A Simple Java program to show multiple * type parameters in Java Generics ** We use < >  to specify Parameter type***/classGenericClass< T, U>   // To print objects of T and U publicvoidprint  } // Driver class to test above classMainClass  }

    Output:

    back to top

    Array Of Products Of All Elements Except Itself

    20 most important java programming interview questions

    Problem Statement:

    Implement the int findProduct method which will modify arr in such a way that in the output, each index i will contain the product of all elements present in arr except the element stored on that index i.

    Solution and Explanation:

    class ProductArray       // Initializing temp to 1 for product on right side    temp = 1      // Product of elements on right side excluding arr     for           return result    }   public static String arrayToString      return result     }    else   }  public static void main      System.out.println)     int prodArray = findProduct     System.out.println)   }}

    The algorithm for this solution is to first create a new array with products of all elements to the left of each element, as done on lines 17-20.

    Then on lines 27-30, multiply each element in that array to the product of all the elements to the right of the array by traversing it in reverse.

    Also Check: What Channel Is The Oprah Interview On

    What Is Synchronization In Java

    Synchronization is a process of handling resource accessibility by multiple thread requests. The main purpose of synchronization is to avoid thread interference. At times when more than one thread tries to access a shared resource, we need to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. The synchronization keyword in java creates a block of code referred to as a critical section.

    Q4 Explain Bean In Spring And List The Different Scopes Of Spring Bean

    Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

    There are five Scopes defined in Spring beans.

    • Singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesnt have shared instance variables otherwise it might lead to data inconsistency issues because its not thread-safe.
    • Prototype: A new instance will be created every time the bean is requested.
    • Request: This is same as prototype scope, however its meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
    • Session: A new bean will be created for each HTTP session by the container.
    • Global-session: This is used to create global session beans for Portlet applications.

    In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.

    Also Check: What To Answer In A Job Interview

    General Java Interview Questions For Freshers

    Your interviewer might ask you general questions about Java and its use during your interview for a fresher role. Here are some general Java interview questions they might ask:

    • Explain wrapper classes in Java.

    • What is autoboxing?

    • Explain the advantages of object cloning.

    • Describe the disadvantages of object cloning.

    • What is the strictfp keyword and why is it important?

    • Explain the importance of the System class.

    • Describe the singleton class.

    • Describe the static method and its restrictions.

    • Explain the difference between the static method and the instance method.

    • How do you use the “this” keyword in Java?

    • Describe constructor chaining using the “this” keyword in Java.

    • Explain the Inheritance and its use in Java.

    • What is a superclass, and what is the Java superclass?

    • Define aggregation and its importance in Java.

    • Explain the difference between composition and aggregation in Java.

    • What is the “super” keyword and how is it used in Java?

    • Explain method overloading in Java.

    Related: JavaScript Vs. Java: What Are The Fundamental Differences?

    What Is A Comparator In Java

    Coding Interview Questions And Answers | Programming Interview Questions And Answers | Simplilearn

    Consider the example where we have an ArrayList of employees like, etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort method. We need to provide something to the sort function depending on what values we have to perform sorting. Then in that case a comparator is used.

    Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values.

    Read Also: How To Set Up A Phone Interview

    What Is Object In Java

    An object is a software bundle of variables and related methods. You can represent real-world objects using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as a software object within an electronic exercise bike. However, you can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.

    Question : Edit Distance Problem In Java

    Given two strings string1 and string2, String1 is to be converted into String2 with the given operations available in the minimum number of steps. Using any one of the given operations contributes to the increment of steps by one.

    Allowed Operations are : Remove : This operation allows the Removal any one character from String. Insert : This operation allows the Insertion of one character at any spot in the String. Replace : This operation allows the replacement of any one character in the string withany other character.

    Solution: Edit distance problem in java.

    Read Also: How To Send A Thank You Email For An Interview

    More articles

    Popular Articles