Skip to main content

Basic Java Interview Questions


    Show answers
  1. What is the difference between Java and C++?
    JavaC++
    Memory managed (or garbage collected) languageProgrammer has to manage the heap memory.
    Compiled java code is platform independentC++ binary code is platform specific.
    Compiled and Interpreted languageCompiled language
    Pure object orientedFunctions can be disassociated from any class
    Supports multilevel inheritanceSupports multiple and multilevel inheritance
    Supports function overloadingSupports function and operator overloading
    Supports only signed numeric data typesSupports both signed and unsigned data types
    Supports unicode characters and char type takes 2 bytes in memoryDoesn't support unicode characters by default
  2. Is Java a compiled language or an interpreted language?
    Java is both compiled (to byte code) and interpreted language.
  3. What is byte code?
    Source java file is compiled into a intermediate code before interpreted by JVM. This intermediate code is called byte code.
    This is similar to MSIL in .Net
  4. What is JVM/JRE?
    JVM stands for Java Virtual Machine and JRE stands for Java Runtime Environment. Both (in most cases) used interchangeably. They represent the run time system for Java without which java code can not run.
  5. How does Java achieve platform independence?
    Java achieves platform independence by means of JVM. JVM differs from platform (Windows, Linux, Mac, Solaris, Unix) to platform. Since JVM converts the byte code to the underlying platform binary code, byte code remains platform independent and there by Java.
  6. Does Java support multiple/multilevel inheritance?
    Java does not support multiple inheritance but it supports multilevel inheritance.
  7. What is the difference between c++ and Java array?
    C++ array is created in stack where as Java array is created in heap.
    C++ array is a contiguous normal memory. Java array is an Object and it has run time boundary checking feature and a read only attribute called length to indicate the length of the array.
  8. Describe final/finally/finalize.
    final - similar to const in C/C++.
    finally - used to cleanup the resource after try/catch block is executed.
    finalize - similar to destructor in C++.
  9. Why should the main method be static?
    So that the JVM can call the main method without creating object for the class in which the main method is declared.
  10. Where are the equals() and hashcode() methods defined?
    They are defined in Object class and available to any java object as all java classes are children of Object class.
  11. Do you need to override equals() method when overriding hashcode() or vice versa?
    Yes. They are complementary to each other to represent the object equality. Hence it will give unpredictable behavior when one of them is not overridden.
  12. Is there anything wrong with the following code?
    void test() {
     try{
         BufferedReader in = new BufferedReader(new FileReader("sample.txt"));
         String line = null;
         while((line=in.readLine())!=null) {
             ...
         }
     } catch(IOException e) {
         ...
     } catch(FileNotFoundException e) {
         ...
     }
    }
    The catch chain should be such that the child most exception class is at the top and the parent exception class is at the bottom. Otherwise compiler will throw unreachable code exception.
  13. What are checked and unchecked exception?
    Any exception class that extends java.lang.RuntimeException or its children is called unchecked exception. These exceptions are checked at the compile time so you dont have to catch or declare to be thrown.
    eg. NullPointerException, ArrayIndexOutOfBoundException
    All other exceptions are called checked exceptions and you need to handle them in your code.
    eg. IOException, FileNotFoundException
  14. What do a method and a class mean when are qualified with final keyword?
    The final class can not be extended and the final method can not be overridden.
  15. What is nested class? what are their types?
    A class declared inside another class is called nested class. It has two types namely, static nested class and inner class.
  16. How to create an instance for an inner class outside of the enclosing class?
    You need to have the instance of the outer class to create the instance of the inner class.
    e.g OuterClass var = outerClassObject.new InnerClass();
  17. Is virtual supported in Java?
    Yes, all the non final methods are virtual by default. Hence you dont have to qualify them as virtual; in fact there is no virtual keyword in Java.
  18. Is operator over loading supported in Java?
    No. However the Java system itself has overloaded '+' operator for String concatenation.
  19. What is an abstract method?
    A method without a body is called abstract method. It is generally qualified with the keyword abstract.
  20. What is an abstract class?
    A class qualified with abstract keyword is called abstract class. It may or may not have abstract methods.
  21. Can an abstracted class be instantiated?
    No. However it can be extended and instance for the subclass can be created.
  22. What is a default constructor?
    When there is no user defined constructor, the java system provides a no-arg constructor and this constructor is called default constructor.
  23. Is there a destructor in Java?
    There is a finalize method used to cleanup any resource. Remember this method will be called when the object is garbage collected and NOT when the object goes out of scope.
  24. How do you define a singleton class?
    By making the constructor as private and providing a static accessor method to create and return the object of the singleton class. However the code should ensure that there is only one instance at any time.
  25. Can an interface have variables?
    Yes, they are public static final by default.
  26. Can a class be defined as abstract class without having any abstract method?
    Yes.
  27. Can a concrete class have any abstract method?
    No.
  28. Can an abstract class be private or final?
    No.
  29. Can a class be defined as private or protected?
    Yes, only the nested class can take private or protected access specifiers. The top level class, however, can take only the public access specifier.
  30. What are the different access specifiers available?
    public, protected, private and package (no keyword)
  31. Can a class access the protected members of another class without subclassing it?
    Yes if it is in the same package of the class which defines the protected member.
  32. What are all the mechanisms available for handling exception in Java?
    1. Handle using try-catch block 2. Declare it to be thrown
  33. Is JVM same for all the platforms?
    No. It is platform dependent.
  34. What are the different types of parameter passing in Java?
    Pass-by-value and Pass-by-reference. Primitive types are passed by value and all the objects are passed by reference.
  35. Does Java support pointers?
    No.
  36. What is WORA?
    Write Once; Run Anywhere.
  37. What is Garbage collection?
    GC is a task/feature built into JVM for collecting all (or required) free memory (which is occupied by objects with no reference)
  38. Can you run the garbage collection?
    No. But you can instruct JVM to run the GC using System.gc(). But there is no guarantee that it will run.
  39. What is static import?
    You can use static import to import the static members of a class. For example, if you are using Math.min(...) method very often in your code, you can simply say min(...) instead of that, by saying import static java.util.Math.min;
  40. If a class does not have any explicit package declaration, what package the class will belong to?
    It belongs to default package and is directly placed under src directory.
  41. What is serialization?
    A mechanism to send the object over internet or to store in a file/database. For an object to be serialized the class of that object must implement java.io.Serializable interface.
  42. What is thread?
    It is a construct to run any task concurrently. Java provide java.lang.Thread class to enable multi-tasking.
  43. What are the different ways available for creating threads?
    Extending java.lang.Thread class or implementing java.lang.Runnable interface
  44. By default how many threads will be available in a java program?
    Only one thread, the main thread. In the case GUI/Swing program it will be more, such as main, EDT, AWT, etc.
  45. What is jar file?
    A Java archive file (basically in zip format) containing all the source and resource file of a package/program/module.
  46. What is the difference between notify() and notifyAll()?
    notify() sends wakeup signal to one of the awaiting thread where as notifyAll() send this signal to all the threads awaiting on the same monitor object.
  47. What is volatile variable?
    'volatile' is a qualifier to mark any variable such that this variable is expected to be updated outside the thread that is reading it, i.e., more than one thread can/will modify the variable which is qualified with 'volatile'. e.g. one thread runs a loop with a conditional flag and this flag will be update by another thread
  48. Does Java support unsigned numeric types?
    No
  49. What are primitive wrapper classes?
    Each primitive types (byte, short, int, long, float, double, char) have their corresponding immutable objects and those object classes (Byte, Short, Integer, Long, Float, Double, Character) are called wrapper classes
  50. What is auto boxing and auto unboxing?
    Whenever a primitive value is assigned to its wrapper variable either directly or indirectly (through method call) then a corresponding wrapper object is created and assigned automatically with the primitive value given. This is called auto boxing. The reverse of this is called auto unboxing. Caution:when you try to unbox a null value, NullPointerException is thrown.
  51. What is enum? how it is different from C++ enum?
    Enums in Java are special classes for which you can't create objects at run time. They are similar to C++ enum and differ in the following ways.
    • Type safe: You can't assign any other value to a enum varialbe (except null)
    • Name space: it is not an int any more; it is fully qualified.e.g org.season.Season season, rather than int season as in C++;
    • Brittleness: If a method expects season value, it can't take any arbitrary values such as 25 or 26 unlike C++ enum
    • Informative printed values: when you print an enum, you get the enum name itself instead of numeric value (unlike C++)
  52. What is var-arg?
    Like printf method in C language, java methods (1.5 or above) can now take variable arguments.e.g.
    void argTest(String format, Integer... args){...}
    Here the method call looks like,
    • argTest("sample numbers");
    • argTest("sample numbers", 2);
    • argTest("sample numbers", 2, 3);
    • argTest("sample numbers", new Integer[]{2, 3});
    You can access the args variable as if it is an array.
  53. What is annotation? What is the usage of annotation?
    Annotations provide meta data about the Type they are annotating. They are used by compilers(@override), IDEs, and containers such as EJB, servlet (@EJB, @Stateless, @WebServlet etc)
  54. What do you mean by a deprecated class/method?
    Deprecated class/method is no longer supported and may be removed in the future release
  55. What is the difference between an instance member and class member?
    You need object of the class to access the instance member. But class members can be accessed by using the class itself.
  56. Can a class be member of another class?
    Yes. They are called nested classes. They are of two types viz static nested class and inner class
  57. What is anonymous class?
    An inner class with out a name.
  58. Can a class extend any one class and implement an interface at the same time?
    Yes
  59. Can an anonymous class extend any one class and implement an interface at the same time?
    No. It can either implement an interface or extend a class.
  60. How do you pass any parameter to an anonymous class constructor?
    No, you can't.
  61. How do you carry out post creation operation in anonymous class?
    Use object initializers.
  62. What is a static block?
    A block which will be executed at the time of class loading to initialize the class members. This is executed only once in the lifetime of a class.
  63. Can a final variable be initialized anywhere other than at the declaration statement?
    Yes. If it is not initialized along with the declaration, then it can be initialized once in the constructor.
  64. Can a static variable be final?
    Yes.
  65. Are primitive wrapper class objects mutable?
    Yes, they can't be modified.
  66. Is String a mutable class?
    No. It is immutable.
  67. What does Clonable interface do?
    It is a marker interface to let the object of a class to be colend.
  68. What are the rules for a class to be serializable?
    • Must have a public no-arg constructor.
    • All the members of the class must be serializable or they have to be marked as transient.

Comments

Popular posts from this blog

Installing GoDaddy certificate in Wildfly/Keycloak

In the previous post we saw how to set up Keycloak . Here we will see how to generate and install GoDaddy.com certificate in Keycloak. The steps are similar for Wildfly as well. Step 1: Generate CSR file Run the following commands in your terminal. <mydomain.com> has to be replaced with your actual domain name. keytool -genkey -alias mydomain_com -keyalg RSA -keysize 2048 -keystore mydomain_com.jks keytool -certreq -alias mydomain_com -file mydomain_com.csr -keystore mydomain_com.jks Step 2: Generate certificate Upload  mydomain_com . csr  file content into GoDaddy.com, generate and download certificate for tomcat server (steps to generating SSL certificate is beyond the scope of this article). If you unzip the file, you will see the following files. gd_bundle-g2-g1.crt ..5f8c...3a89.crt   #some file with alphanumeric name gdig2.crt Files 1 and 2 are of our interest. Third file is not required. Step 3: Import certificate to key store Download r

Using Nginx as proxy server for Keycloak

I have used Keycloak  in its very early stage ( when it is was in 2.x version). But now it has come a long way (at this time of writing it is in 21.x) In this article let's configure Keycloak behind Nginx. Here are the points to consider.  If you want to configure Apache2 as a proxy server for your java application, please check  this article . We are going to use a domain name other than localhost Anything other than localhost will require Keycloak to run in production mode which requires SSL configurations etc. Or it requires a proxy server. Lets begin. Requirements Keycloak distribution Ubuntu 22.04 server Configuring Keycloak 1. Download Keycloak from here . 2. Extract it using tar -xvzf  keycloak-21.0.1.tar.gz 3. Create a script file called keycloak.sh with the following contents #!/bin/bash export KEYCLOAK_ADMIN=<admin-username-here> export KEYCLOAK_ADMIN_PASSWORD=<admin-password-here> nohup keycloak-21.0.0/bin/kc.sh start-dev --proxy edge --hostname-strict=fa

Hibernate & Postgresql

If you are using Hibernate 3.5 or above to talk to Postgresql database, have you ever tried to store a byte array? Let's take an example. Here is the mapping which will store and read byte[] from the database. @Lob @Column(name = "image") private byte[] image; Here is the JPA mapping file configuration. <persistence version="2.0"  xmlns="http://java.sun.com/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">   <persistence-unit name="testPU" transaction-type="JTA">     <provider>org.hibernate.ejb.HibernatePersistence</provider>     <jta-data-source>test</jta-data-source>     <properties>     </properties>   </persistence-unit> </persistence> When you try to save your entity you will get t

Dynamic SOAP Service Client

If you have written SOAP service client, you might know that you need the WSDL file; need to generate Java code for that,compile that Java classes and add it as dependency for your module. What would you do if you have to incorporate your code with a new SOAP service every now and then? What would you do if all you need is to consume the service and do a little processing on the output, i.e., you need the data in XML format? What would you do if you don't have a complete WSDL? What would you do if your service is in .NET whose WSDL is having problem while generating Java classes? Is there a way to write a dynamic client which can consume any SOAP service? .... YES!... there is a way. Let's quickly write a web (SOAP) service. Software used: Java 7 NetBeans IDE 7.4 GlassFish 4.0 Maven Create a web project and choose Glassfish as server. Now add web service (not a rest service) as below. Edit the SimpleService.java as follows. package com.mycom

How to retry a method call in Spring or Quarkus?

Have you ever come across a situation where you wanted to retry a method invocation automatically? Let's say you are calling a stock ticker service for a given stock and get a transient error. Since it is a transient error, you will try again and it may work in second attempt. But what if it doesn't? Well, you will try third time. But how many times can you try like that? More importantly after how much time will you retry? Imagine if you have a handful of methods like this. Your code will become convoluted with retry logic. Is there a better way? Well, if you are using spring/spring boot, you are in luck. Here is how you can do that using spring. Let's write our business service as follows. import java.time.LocalDateTime; import java.util.concurrent.CompletableFuture; import lombok.extern.slf4j.Slf4j; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Retryable; import org.springframework.scheduling.annotation.Async; import