java interview questions

Java has been a perennial contributor to the software development domain. It is not only necessary to learn and master Java skills but also to practice these skills in real-time. In this article, we bring you, some of the most sought after Java Interview Questions that will help you ace major interview processes and help test your skills and knowledge at its absolute. You can access various programming and technical courses on Great Learning Academy and get your free certificates.

Java Interview Questions are Divided into Three Categories:

Basic Java Interview Questions and Answers for Freshers/Beginners

  • Why is Java Platform Independent?
  • What is Constructor Overloading?
  • What is Method overriding? What’s the use of it in Java?
  • What is Method overloading? Why is it used in Java?
  • Why is Java Robust?
  • How many types of Inheritance are possible in Java?
  • Why is Java Secure?
  • What is the difference between JDK, JRE, and JVM?
  • What are the features of Java?
  • Does Java Support Pointers?
  • 1. Why is Java Platform Independent?

    At the time of compilation, the java compiler converts the source code into a JVM interpretable set of intermediate form, which is termed as byte code. This is unlike the compiled code generated by other compilers and is non-executable. The java virtual machine interpreter processes the non-executable code and executes it on any specific machine. Hence the platform dependency is removed.

    2. What is Constructor Overloading?

    When a class has multiple constructors with different function definitions or different parameters it is called constructor overloading.

    import java.io.*; 
    import java.lang.*; 
    public class constructor_overloading { 
        double sum; 
        constructor_overloading(){ 
            sum=0; 
        } 
        constructor_overloading(int x,int y){ 
            sum=x+y; 
        } 
        constructor_overloading(double x,double y){ 
            sum=x+y; 
        } 
        void print_sum(){ 
            System.out.println(sum); 
        } 
        public static void main(String args[]){ 
            constructor_overloading c=new constructor_overloading(); 
            c.print_sum(); 
            constructor_overloading c1=new constructor_overloading(10,20); 
            c1.print_sum(); 
            constructor_overloading c2=new constructor_overloading(10.11,20.11); 
            c2.print_sum(); 
        } 
    } 

    3. What is Method overriding? What’s the use of it in Java?

    Method overriding is a process in which methods inherited by child classes from parent classes are modified as per requirement by the child class. It’s helpful in hierarchical system design where objects share common properties.

    Example: Animal class has properties like fur colour, sound. Now dog and cat class inherit these properties and assign values specific to them to the properties.

    class Animal { 
        void sound(){ 
        } 
    } 
     class Cat extends Animal{ 
         void sound(){ 
             System.out.println("Meow"); 
         } 
    } 
    
    class Dog extends Animal{ 
        void sound(){ 
            System.out.println("Bark"); 
        } 
    } 
    
    public class OverRide{ 
        public static void main(String args[]){ 
            Cat c=new Cat(); 
            c.sound(); 
    
            Dog d=new Dog(); 
            d.sound(); 
        } 
    } 

    4. What is Method overloading? Why is it used in Java?

    If multiple functions in a class have the same name but different function definitions it is called method overloading.
    It is used to make a java function serve multiple purposes making the code cleaner and API less complex.
    Example:

    println() prints any data type passed to it as a string. 
    
    public class Add_Overload { 
        void add(int x, int y){ 
            System.out.println(x+y); 
        } 
        void add(double x, double y){ 
            System.out.println(x+y); 
        } 
        void add(double x, int y){ 
            System.out.println(x+y); 
        } 
        public static void main(String args[]){ 
            Add_Overload a= new Add_Overload(); 
            a.add(10,20); 
            a.add(20.11,11.22); 
            a.add(20.11,2); 
    
        } 

    5. Why is Java Robust?

    Java is termed as robust because of the following features:
    – Lack of pointers: Java does not have pointers which make it secure
    – Garbage Collection: Java automatically clears out unused objects from memory which are unused
    – Java has strong memory management.
    – Java supports dynamic linking.

    6. How many types of Inheritance are possible in Java?

    Single, multiple, multilevel, hybrid and hierarchical inheritance are possible in java. Hybrid inheritance and hierarchical inheritance are only possible through interfaces.

    7. Why is Java Secure?

    Java does not allow pointers. Pointers give access to actual locations of variables in a system. Also, java programs are bytecode executables that can run only in a JVM. Hence java programs do not have access to the host systems on which they are executing, making it more secure. Java has its own memory management system, which adds to the security feature as well.

    8. What is the difference between JDK, JRE, and JVM?

    JDK is a software environment used for the development of Java programs. It’s a collection of libraries that can be used to develop various applications. JRE (Java Runtime Environment) is a software environment that allows Java programs to run. All java applications run inside the JRE. JVM (java virtual machine) is an environment that is responsible for the conversion of java programs into bytecode executables. JDK and JRE are platform-dependent whereas JVM is platform-independent.

    9. What is a singleton class in Java? What’s the benefit of making a class singleton?

    A singleton class is a class in Java that can at most have one instance of it in an application. If new instances are created for the same class they point to the first instance created and thus have the same values for all attributes and properties.
    Singleton classes are created to create global points of access to objects. Singleton classes find their primary usages in caching, logging, device drivers which are all entities for universal access.

    10. What are the features of Java?

    Java is a pure Object Oriented Programming Language with the following features:
    – High Performance
    – Platform Independent
    – Robust
    – Multi-threaded
    – Simple
    – Secure

    11. Does Java Support Pointers?

    Pointers are not supported in java to make it more secure.

    You can also go through this Java Tutorial to understand better

    12. Why are static variables used in Java?

    Static methods and variables are used in java to maintain a single copy of the entity across all objects. When a variable is declared as static it is shared by all instances of the class. Changes made by an instance to the variable reflect across all instances.

    public class static_variable {
    
        static int a;
        static int b;
        static_variable(){
            a=10;
        }
        int calc_b(){
            b=a+10;
            return b;
        }
    void print_val(){
        System.out.println(this.b);
    }
    public static void main(String args[]){
        static_variable v=new static_variable();
        v.calc_b();
        v.print_val();
        static_variable v1=new static_variable();
        v1.print_val();
    }
    }

    13. Explain the exception handling mechanism of Java?

    Exception class inherits from the Throwable class in java. Java has a try-catch mechanism for handling exceptions without them being generated as errors.

    public class Exception_Handling { 
        String gender; 
        Exception_Handling(String s){ 
            gender=s; 
        } 
         void Check_Gender(String s) throws GenderException{ 
            if (gender!="Male" || gender!="Female") 
                throw new GenderException("Gender Invalid"); 
            else 
            System.out.println("Gender valid"); 
            } 
        public static void main(String args[]){ 
            Exception_Handling n=new Exception_Handling("None"); 
            try{ 
                n.Check_Gender("Female"); 
            }catch (Exception e){ 
                System.out.println("Exception : "+e); 
            } 
        } 
        } 
    class GenderException extends Exception{ 
        GenderException(String s){ 
            super(s); 
        } 
    } 

    14. How many types of constructor does Java support?

    Java supports the following types of constructors:
    – Non-Parameterized or Default Constructors
    – Parameterized Constructors
    – Copy constructor

    15. What is the role of finalize()?

    Finalize() is used for garbage collection. It’s called by the Java run environment by default to clear out unused objects. This is done for memory management and clearing out the heap.

    16. Explain encapsulation in Java.

    Encapsulation is the process of wrapping variables and functions together into a single unit in order to hide the unnecessary details. The wrapped up entities are called classes in java. Encapsulation is also known as data hiding because it hides the underlying intricacies.

    17. Explain abstraction in Java.

    Abstraction is the process of revealing the essential information and hiding the trivial details across units in java. Java has abstract classes and methods through which it does data abstraction.

    18. If a child class inherits base class then are the constructor of the base class also inherited by the child class?

    Constructors are not properties of a class. Hence they cannot be inherited. If one can inherit constructors then it would also mean that a child class can be created with the constructor of a parent class which can later cause referencing error when the child class is instantiated. Hence in order to avoid such complications, constructors cannot be inherited. The child class can invoke the parent class constructor by using the super keyword.

    19. What are static methods, static variables, and static blocks?

    Static methods are methods that can be called directly inside a class without the use of an object.
    Static variables are variables that are shared between all instances of a class.
    Static blocks are code blocks that are loaded as the class is loaded in memory.

    20. What’s the use of static methods?

    Static methods are used when there is no requirement of instantiating a class. If a method is not going to change or overridden then it can be made static.

    21. What’s the use of static variables?

    Static variables are used for maintaining a common state of certain data which is modifiable and accessible by all instances of a class.

    22. What is the use of super?

    super() is used to invoke the superclass constructor by the subclass constructor. In this way, we do not have to create different objects for super and subclasses.

    23. What are the interfaces?

    An interface is a collection of constants, static methods, abstract methods, and default methods. Methods in an interface do not have a body.

    24. How is abstraction achieved in Java?

    Abstraction is achieved in Java by the use of abstract class and abstract methods.

    25. How is encapsulation achieved in Java?

    Encapsulation is achieved by wrapping up data and code into simple wrappers called classes. Objects instantiate the class to get a copy of the class data.

    26. What is an abstract class in Java?

    An abstract class is a class that can only be inherited and it cannot be used for object creation. It’s a type of restricted class with limited functionality.

    27. How is polymorphism achieved in Java?

    An example of polymorphism is the == operator which can be used to compare both numerics and strings.

    28. Can the main method be declared as private in Java?

    Yes, the main method can be declared as private.

    29. Why are strings immutable in Java?

    Strings in java are frequently used for hashmap keys. Now if someone changes the value of the string it will cause severe discrepancies. Hence strings are made immutable.

    30. What are wrapper classes in Java?

    Wrapper classes are a functionality supported by java to accept primitive data types as inputs and then later convert those into string objects so that they can be compared to other objects.

    31. Can interfaces in Java be inherited?

    Yes, interfaces can be inherited in java. Hybrid inheritance and hierarchical inheritance are supported by java through inheritable interfaces.

    32. Are static methods allowed in a Java interface?

    Yes, static methods are allowed in java interfaces. They are treated as default methods so they need not be implemented.

    33. When do we use the Array list?

    Whenever there is a need for random access of elements in java we use ArrayList. Get and set methods provide really fast access to the elements using the array list.

    34. What is the use of generics in Java?

    Generics allow classes and interfaces to be a type for the definition of new classes in java which enables stronger type checking. It also nullifies the probability of type mismatch of data while insertion.

    35. What is an object in Java?

    An object is an instance of a class in java. It shares all attributes and properties of a class.

    36. What happens if we make the constructor final?

    If we make the constructors final then the class variables initialized inside the constructor will become unusable. Their state cannot be changed.

    37. What is an iterator?

    An iterator is a collection framework functionality which enables sequential access of elements. The access can be done in one direction only. Java supports two types of iterators:
    1. Enumeration Iterator
    2. List Iterator

    38. What is a hashmap?

    Hashmap is a collection framework functionality which is used for storing data into key-value pairs. To access data we need the key. A hashmap uses linked lists internally for supporting the storage functionality.

    39. What is a stack?

    A stack is a data structure that supports LAST IN FIRST OUT methodology. The element pushed last is at the top of the stack. A stack supports the following functionality:

    • Push-operation to push an element into the stack
    • Pop-operation to push an element out of the stack
    • Peek-An option to check the top element

    40. How is garbage collection done in Java?

    Java has an automatic built-in garbage collection mechanism in place. Apart from the built-in mechanism, manual initiation of garbage collection can also be done by using the gc() of system class.

    41. If we clone objects using the assignment operator does the references differ?

    When objects are cloned using the assignment operator, both objects share the same reference. Changes made to the data by one object would also be reflected in the other object.

    42. Can static methods reference non-static variables?

    Yes, static methods can reference non-static variables. It can be done by creating an object of the class the variable belongs to.

    43. How do static blocks get executed if there are multiple static blocks?

    Multiple static blocks are executed in the sequence in which they are written in a top-down manner. The top block gets executed first, then the subsequent blocks are executed.

    44. Can there be two main methods in a class?

    Yes, there can be two main methods. This also means that the main method is overloaded. But at the time of execution, JVM only calls the original main method and not the overloaded main method.

    45. Can private variables be inherited?

    Private variables have a class-specific scope of availability. They can only be accessed by the methods of the class in which they are present. Hence when the class is inherited, private variables are not inherited by the subclass.

    46. Can we override static methods?

    Static methods cannot be overridden because they are not dispatched to the object instance at run time. In their case, the compiler decides which method gets called.

    47. Which class do all classes inherit from in java?

    All classes in java inherit from the Object class which is the superclass of all classes.

    48. What is classloader?

    ClassLoader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

    • Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
    • Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
    • System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using “-cp” or “-classpath” switch. It is thus also known as Application classloader.

    49. What is a treemap?

    Treemap is a navigable map interpretation in java which is built around the concepts of red and black trees. The keys of a treemap are sorted in ascending order by their keys.

    50. What is a vector?

    A vector is an ArrayList like data structure in java whose size increases as per the demands. Moreover, it also supports some legacy functions not supported by collections.
    You should also know that a vector is more suitable to work with threads, unlike collection objects.

    51. What is the difference between ArrayList and vector?

    An ArrayList is not suitable for working in a thread based environment. A vector is built for thread-based executions. ArrayList does not support legacy functions whereas a vector has support for legacy functions.

    Intermediate Java Interview Questions and Answers 2020

    52. Write a program to calculate the factorial of a number in java.

    import java.util.Scanner; 
    
    public class star { 
         public static void main(String[] args) { 
             Scanner sc=new Scanner(System.in); 
             int fact=1; 
             int n=sc.nextInt(); 
    
             for (int i=1;i<=n;i++) 
             fact=fact*i; 
    
             System.out.println(fact); 
    
    
            } 
    
    } 

    53. Write a program to check if a number is prime.

    import java.util.Scanner; 
    public class star { 
         public static void main(String[] args) { 
             Scanner sc=new Scanner(System.in); 
             int n=sc.nextInt(); 
             int count=0; 
             for (int i=1;i<=n;i++) 
             { 
                 if (n%i==0) 
                 count++; 
             } 
             if (count==2) 
             System.out.println("Prime"); 
             else 
             System.out.println("Not Prime"); 
            } 
    } 

    54. Write a program to convert decimal numbers to binary.

    import java.util.Scanner; 
    
    class star 
    { 
    public static void main(String arg[])    
    {    
        Scanner sc=new Scanner(System.in); 
        System.out.println("Enter a decimal number"); 
        int n=sc.nextInt(); 
        int  bin[]=new int[100]; 
        int i = 0; 
        while(n > 0) 
        { 
        bin[i++] = n%2; 
           n = n/2; 
        } 
       System.out.print("Binary number is : "); 
        for(int j = i-1;j >= 0;j--) 
       { 
           System.out.print(bin[j]); 
       } 
    } 
    } 

    55. Write a program to convert decimal numbers to octal.

    import java.util.Scanner; 
    class star 
    { 
      public static void main(String args[]) 
      { 
        Scanner sc = new Scanner( System.in ); 
        System.out.print("Enter a decimal number : "); 
        int num =sc.nextInt(); 
        String octal = Integer.toOctalString(num); 
        System.out.println("Decimal to octal: " + octal); 
      } 
    } 

    56. Which utility function can be used to extract characters at a specific location in a string?

    The charAt() utility function can be used to achieve the above-written functionality.

    57. How to get the length of a string in java?

    Length of string in java can be found using the .length() utility.

    58. Which of the following syntax for defining an array is correct?
    – Int []=new int[];
    – int a[]=new int[];
    – int a[] =new int [32];

    int a[]=new int[32] is the correct method.

    59. Can the size of an array be increased after declaration?

    The size of a java array cannot be increased after declaration. This is a limitation of Java arrays.

    60. What is the size of the below array in memory?
    int a[]=new int[10];

    Each int block takes a size of 4 bytes and there are 10 such blocks in the array. Hence, the size the array takes in memory is 40 bytes.

    61. How many data types does java support?

    Java supports 8 primitive data types, namely byte, short, int, long, float, double, char, boolean.

    62. How to find out the ASCII value of a character in java?

    int c=char(‘A’) would give the ASCII value of A in java.

    63. How to get a string as user input from the console?

    We have to instantiate an input reader class first. There are quite a few options available, some of which are BufferedReader, InputStreamReader Scanner.
    Then the relative functionality of the class can be used. One of the most prevalently used is nextLine() of Scanner class.

    64. How to check the size of strings?

    The size of strings in java can be checked by using the length() function.

    65. How can we sort a list of elements in Java?

    The built-in sorting utility sort() can be used to sort the elements. We can also write our custom functions but it’s advisable to use the built-in function as its highly optimized.

    66. If we sort a list of strings how would be the strings arranged? The strings would be arranged alphabetically in ascending order.

    67. What is a Thread?

    A thread is a lightweight program that allows multiple processes to run concurrently. Every java program has at least one thread called the main thread, the main thread is created by JVM. The user can define their own threads by extending the Thread class (or) by implementing the Runnable interface. Threads are executed concurrently.

    public static void main(String[] args){//main thread starts here 
    } 

    68. The difference between Serializable and Externalizable in Java?

    Serializable interface is used to make Java classes serializable so that they can be transferred over a network or their state can be saved on disk, but it leverages default serialization built-in JVM, which is expensive, fragile and not secure. Externalizable allows you to fully control the Serialization process, specify a custom binary format and add more security measure.

    69. What will this return 3*0.1 == 0.3? true or false?

    This is one of the really tricky questions and can be answered only if your concepts are very clear. The short answer is false because some floating-point numbers can not be represented exactly.

    70. Can we use String in the switch case?

    We can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. See the detailed answer for more explanation and discussion.

    71. What are object serialization and deserialization?

    The use of java.io.Serializable to convert an object into a sequence of bytes is known as object serialization. Deserialization is the process of recovering back the state of the object from the byte stream.

    72. Write a program to do bubble sort on an array in java.

    import java.util.Scanner; 
    class star 
    { 
      public static void main(String args[]) 
      { 
        int arr[] =new int [10]; 
        Scanner sc = new Scanner( System.in ); 
        System.out.println("Enter size of array"); 
        int n=sc.nextInt(); 
        System.out.print("Enter an arry : "); 
        for (int i=0;i<n;i++) 
            arr[i]=sc.nextInt(); 
        for (int i=0;i<n;i++) 
        { 
            for (int j=0;j<n-i-1;j++) 
            { 
                if (arr[j]>arr[j+1]) 
                { 
                    int t=arr[j]; 
                    arr[j]=arr[j+1]; 
                    arr[j+1]=t; 
                } 
            } 
        } 
     for (int i=0;i<n;i++) 
        { 
            System.out.println(arr[i]); 
        } 
      } 
    } 

    73. Can we start a thread twice in java?

    Once a thread is started, it can never be started again. Doing so will throw an IllegalThreadStateException

    Advanced Java Interview Questions and Answers 2020

    74. The difference between checked and unchecked exception in Java?

    A checked exception is checked by the compiler at compile time. It’s mandatory for a method to either handle the checked exception or declare them in their throws clause. These are the ones which are a subclass of Exception but doesn’t descend from RuntimeException. The unchecked exception is the descendant of RuntimeException and not checked by the compiler at compile time. This question is now becoming less popular and you would only find this with interviews with small companies, both investment banks and startups are moved on from this question.

    75. The difference between throw and throws in Java?

    throw is used to actually throw an instance of java.lang.Throwable class, which means you can throw both Error and Exception using throw keyword e.g.

    throw new IllegalArgumentException("size must be multiple of 2") 


    On the other hand, throws is used as part of method declaration and signals which kind of exceptions are thrown by this method so that its caller can handle them. It’s mandatory to declare any unhandled checked exception in throws clause in Java. Like the previous question, this is another frequently asked Java interview question from errors and exception topic but too easy to answer.

    76. Can we make an array volatile in Java?

    Yes, you can make an array volatile in Java but only the reference which is pointing to an array, not the whole array. What I mean, if one thread changes the reference variable to points to another array, that will provide a volatile guarantee, but if multiple threads are changing individual array elements they won’t be having happens before guarantee provided by the volatile modifier.

    77. Is ++ operator is thread-safe in Java?

    No, it’s not a thread safe operator because it involves multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.

    78. Which class contains the clone method? Cloneable or Object?

    java.lang.Cloneable is a marker interface and doesn’t contain any method clone method is defined in the object class. It is also knowing that clone() is a native method means it’s implemented in C or C++ or any other native language.

    79. Can I store a double value in a long variable without casting?

    No, you cannot store a double value into a long variable without casting because the range of double is more than long and we need to type cast. It’s not difficult to answer this question but many developer get it wrong due to confusion on which one is bigger between double and long in Java.

    80. Which one will take more memory, an int or Integer?

    An Integer object will take more memory as Integer is an object and it stores metadata overhead about the object but int is a primitive type, so it takes less space.

    81. The difference between nested static class and top level class?

    A public top level class must have the same name as the name of the source file, there is no such requirement for a nested static class. A nested class is always inside a top level class and you need to use the name of the top-level class to refer nested static class e.g. HashMap.Entry is a nested static class, where HashMap is a top level class and Entry is nested static class.

    82. What is the use of the final keyword?

    The final keyword is used to declare the final state of an entity in java. The value of the entity cannot be modified at a later stage in the application. The entity can be a variable, class, object, etc.
    It is used to prevent unnecessary modifications in a java application.

    83. What’s the difference between deep copy and shallow copy?

    Shallow copy in java copies all values and attributes of an object to another object and both objects reference the same memory locations.

    Deep copy is the creation of an object with the same values and attributes of the object being copied but both objects reference different memory locations.

    84. What’s the use of default constructor?

    The default constructor is a constructor that gets called as soon as the object of a class is declared. The default constructor is un-parametrized. The generic use of default constructors is in the initialization of class variables.

    class ABC{ 
        int i,j; 
        ABC(){ 
            i=0; 
            j=0; 
        } 
    } 

    Here ABC() is a default constructor.

    85. What is object cloning?

    Object cloning is the process of creating an exact copy of an object of a class. The state of the newly created object is the same as the object used for cloning.
    The clone() method is used to clone objects. The cloning done using the clone method is an example of a deep copy.

    86. Why are static blocks used?

    They serve the primary function of initializing the static variables. If multiple static blocks are there they are executed in the sequence in which they are written in a top-down manner.

    87. What is constructor chaining?

    constructor chaining is the process of invoking constructors of the same class or different classes inside a constructor. In this way multiple objects are not required for constructor invocation with constructors having different parameters.

    88. What is the use of this keyword in java?

    This keyword is used to reference an entity using the current object in java. It’s a multi-purpose keyword which serves various functionalities

    89. What’s the difference between String and String Builder class in java?

    Strings are immutable while string Builder class is mutable. The string builder class is also synchronized.

    90. How to calculate the size of an object?

    The size of an object can be calculated by summing the size of the variables of the class the object is instantiated from.
    If a class has an integer, a double variable defined in it then the size of the object of the class is size(int)+size(double).
    If there is an array, then the size of the object would be the length of array*size of data type of array.

    91. What’s the difference between == and .equals()?

    “==” is an operator, whereas .equals() is a function.
    “==” checks if the references share the same location, whereas .equals() checks if both object values are the same on evaluation.

    92. Write a program to generate the following output in java?
    *
    **
    ****
    *****
    ******

    public class star { 
         public static void main(String[] args) { 
             int i; 
             int count=1; 
            for (i=1;i<=5;i++){ 
                for (int j=1;j<=i;j++) 
                    System.out.print("*"); 
                System.out.println(" "); 
    
            } 
    
    } 
    } 

    93. Write a program to generate the following output.
    ****
    ***
    **
    *

    public class star { 
         public static void main(String[] args) { 
             int i; 
             int count=1; 
            for (i=5;i>=1;i--){ 
                for (int j=1;j<=i;j++) 
                    System.out.print("*"); 
                System.out.println(" "); 
    
            } 
    
    } 
    } 

    94. Write a program in java to remove all vowels from a string.

    import java.util.Scanner; 
    
    public class star { 
         public static void main(String[] args) { 
             Scanner sc=new Scanner(System.in); 
             String n=sc.nextLine(); 
             String n1=n.replaceAll("[AEIOUaeiou]", ""); 
             System.out.println(n1); 
    
             } 
            } 

    95. Write a program in java to check for palindromes.

    String str, rev = ""; 
          Scanner sc = new Scanner(System.in); 
    
          System.out.println("Enter a string:"); 
          str = sc.nextLine(); 
    
          int length = str.length(); 
    
          for ( int i = length - 1; i >= 0; i-- ) 
             rev = rev + str.charAt(i); 
    
          if (str.equals(rev)) 
             System.out.println(str+" is a palindrome"); 
          else 
             System.out.println(str+" is not a palindrome"); 

    96. How can java threads be created?

    Threads can be created by implementing the runnable interface.
    Threads can also be created by extending the thread class

    97. What is the underlying mechanism in java’s built-in sort?

    Java’s built-in sort function utilizes the two pivot quicksort mechanism. Quicksort works best in most real-life scenarios and has no extra space requirements.

    98. Which utility function is used to check the presence of elements in an ArrayList?

    hasNext() is used for the presence of the next element in an ArrayList.

    99. How to remove an element from an array?

    To remove an element from an array we have to delete the element first and then the array elements lying to the right of the element are shifted left by one place.

    100. Difference between a = a + b and a += b ?

    The += operator implicitly cast the result of addition into the type of the variable used to hold the result. When you add two integral variables e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens. If the result of the addition is more than the maximum value of a then a + b will give compile time error but a += b will be ok as shown below
    byte a = 127;
    byte b = 127;
    b = a + b; // error : cannot convert from int to byte
    b += a; // ok

    This brings us to the end of the Java Interview Questions. Glad to see you are now better equipped to face an interview. 

    You can enroll to these JAVA courses on Great Learning Academy and get certificates for free:

    Java Programming

    Java Programming in Hindi

    Data Structures and Algorithms in Java

    Wondering where to learn the highly coveted in demand skills for free? Check out the courses on Great Learning Academy. Enrol in any course, learn the in-demand skill and get your free certificate. Hurry!

    2

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here

    8 + 3 =