Top Java Interview Questions with Answers..






Hello Visitors! I have posted this post to help with Some Java questions which can or will be asked in the Interview for Automation testing.


Q. What is JAVA?
A: - Java is a high-level programming language and is platform-independent.
Java is a collection of objects. It was developed by Sun Microsystems. There are a lot of applications, websites, and Games that are developed using Java.

Q. What do you mean by platform independence of Java?
A: - Platform independence means that you can run the same Java Program in any Operating System. For example, you can write a java program in Windows and run it in Mac OS.

Q. Is Java a value-based or reference-based?
A: - Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

Q. JVM is a dependent or independent platform?
A: - JVM is platform dependent because it takes java byte code and generates byte code for the current operating system. So Java software is platform dependent but Java language is platform-independent because the different operating system has different JVMs.

Q. Why Java is not pure Object Oriented language?
A: - Java is not said to be pure object-oriented because it supports primitive types such as int, byte, short, long, etc. I believe it brings simplicity to the language while writing our code. Obviously, java could have wrapper objects for the primitive types but just for the representation, they would not have provided any benefit.
As we know, for all the primitive types we have wrapper classes such as Integer, Long, etc that provide some additional methods.

Q. What is Object class?
A: - The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. The Object class is beneficial if you want to refer to any object whose type you don't know. Notice that the parent class reference variable can refer to the child class object, known as upcasting.

Q. What is the parent or base class of all the classes in Java?
A: - Object class is the super base class of all Java classes. Every other Java classes descend from Object.

Q. Which class is the superclass of all classes?
A: - java.lang.Object is the root class for all the java classes and we don’t need to extend it.

Q. What is a Class?
A: - Class is a blueprint. It is the structure where we can define variables and methods to utilize by objects.




Q. What is Keyword in Java?
A: - Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are predefined words by Java so it cannot be used as a variable or object name.
  • List of Java Keywords
A list of Java keywords or reserved words are given below:
  1. package: Java package keyword is used to declare a Java package that includes the classes.
  2. class: Java class keyword is used to declare a class.
  3. import: Java import keyword makes classes and interfaces available and accessible to the current source code.
  4. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It can have abstract and non-abstract methods.
  5. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
  6. public: Java the public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
  7. private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
  8. protected: Java protected keyword is an access modifier. It can be accessible within package and outside the package but through inheritance only. It can't be applied on the class.
  9. default: Java default keyword is used to specify the default block of code in a switch statement.
  10. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
  11. char : Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters.
  12. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
  13. byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
  14. double: Java double keyword is used to declare a variable that can hold a 64-bit floating-point numbers.
  15. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
  16. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
  17. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
  18. new: Java new keyword is used to create new objects.
  19. void: Java void keyword is used to specify that a method does not have a return value.
  20. return: Java return keyword is used to return from a method when its execution is complete.
  21. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
  22. static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is used for memory management mainly.
  23. this: Java this keyword can be used to refer to the current object in a method or constructor.
  24.  super: Java super keyword is a reference variable that is used to refer to the parent class object. It can be used to invoke immediate parent class method.
  25. extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
  26. implements: Java implements keyword is used to implement an interface.
  27. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exception. It is followed by an instance.
  28.  throws: The Java throws keyword is used to declare an exception. Checked exception can be propagated with throws.
  29. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
  30. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
  31. if: Java if keyword tests the condition. It executes the if block if condition is true.
  32. else: Java else keyword is used to indicate the alternative branches in an if statement.
  33. do: Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several times.
  34. while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
  35. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.
  36. break: Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at specified condition.
  37. continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
  38. switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
  39. case: Java case keyword is used to with the switch statements to mark blocks of text.
  40. final: Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It is used to restrict the user.
  41.  finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether exception is handled or not.
  42. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
  43.  instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
  44.  native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
  45.  strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
  46.  synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
  47.  transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
  48.  volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
Q. What is the difference between equals() and == operator?
A: - equals() is a method and == is an operator

Q. Difference between == and =.?
A: - == denotes comparison and returns true/false,
        = denotes assigning the value.

Q. What is the importance of main method in Java?
A: - main() method is the entry point of any standalone java application. The syntax of main method is public static void main(String args[]).
main method is public and static so that java can access it without initializing the class. The input parameter is an array of String through which we can pass runtime arguments to the java program.

Q. Can we execute java code without main()?
A: - Yes, You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

Q. What will happen, if main() is declared as private?
A: - main() method must be public, if you declared main as a private, complier returns an error “main() method not public.”

Q. Can we overload a main() method in Java?
A: - Yes, we can overload main method in Java. But the program doesn’t execute the overload main method when you run your program, you have to call the overloaded main method from the actual main method.

Q. What will happen, if static modifier removed from the signature of main()?
A: - Program compiles, but at the run time, it returns an error “NoSuchMethodError”.

Q. What happens when exception is thrown by main method?
A: - When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

Q. What is Java Package and which package is imported by default?
A: - Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.
                java.lang package is imported by default and we don’t need to import any class from this package explicitly.

Q. What is the default package in java?
A: -The default package is an unnamed package. The unnamed package contains java classes whose source files did not contain a package declaration. The purpose of default package is for convenience when developing small or temporary applications or when just beginning development.

Q. What is access modifiers in Java?
A: -Access modifiers are the keywords in Java by which we can set the level of access for class, methods, variables and constructors. There are 4 different access modifiers in Java: -
1.       Public: - The public access modifier is accessible everywhere.
2.       Private: - The private access modifier  is accessible only within class. We cannot access it from other classes or subclasses or even in same package.
3.       Protected: - The protected access modifier can be accessed from classes of same package or sub classes of that class.
4.       Default: - If you don’t use any modifiers, it is treated as default access modifier. The default access modifier is accessible only within package.

Q. What is the difference b/ w extend and implement keyword?
A: -1. The extends keyword is used to create a subclass using features of a super class. Where The implements keyword is used for the implementation of an interface.
2.The extends keyword may not override all the methods of a super class. Whereas The implements keyword has to implement all the methods of an implemented interface.
3. A class can extend only one super class. Where A class can implement multiple interfaces.

Q. Is null a keyword?
A: -Null is a reserved word for literal values. It seems like a keyword, but actually, it is a similar to true or false.

Q. What is a Variable in Java?
A: -A variable is a name which is associated with a value that can be changed. For example when I write int i=10; here variable name is i which is associated with value 10, int is a data type that represents that this variable can hold integer values.

Q. Types of Variables?
A: -Instance Variable, Local Variable and Static Variable.

Q. What is the difference between instance variable and a local variable?
A: - Local Variables
– A variable which is declared inside the method is called a local variable.
Instance Variables
– A variable which is declared inside the Class but outside the method is called Instance Variable.

Q. What is static keyword?
A: - static keyword can be used with class level variables to make it global i.e. all the objects will share the same variable.
static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.

Q. Why we use Static in java. Tell me something different which is not there in theory?
A: -The static keyword in Java is used mainly for memory management. It is used with variables, methods, blocks and nested classes. It is a keyword that is used to share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class.

Q. What are static variables?
A: -Static variables are class level variable where all instances of the class refer same variable. When an instance update its value, all the other objects will see the new value. They are loaded at run time when the respective Class is loaded.

Q. What are static and non-static methods?
A: -1) static methods
* We must use static keywords to declare or define static methods.
* Static methods are associated with the class that means these methods can be called with the class name or with objects or without objects(Direct call) there is no need to declare any objects for static methods.
* Static methods can access only static member and static methods are of the same class or different class that means static method can’t access non-static member or methods.
Static methods create only one copy of the whole program and share it with other member or methods.
2) Non-Static methods
* We must not have static keywords before method name to declare or define static methods.
* Non-static methods are not associated with the class that means these methods cannot be called with the class name and it is mandatory to declare objects and non-static methods can be called with the object name.
* Non-static methods can access static member and static methods and non-static member and non-static methods are of the same class or different class but non-static can’t modify static member or methods values.
* For non-static methods create an individual copy of all the objects or in other words create a separate copy of all the objects.

Q. Can static methods be overloaded?
A: -Static methods can be overloaded (meaning that you can have the same method name for several methods as long as they have different parameter types).
Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.

Q. What is a Static block?
A: -In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.

Q. What is the use of static Block?
A: -Static block is used for initializing the static variables. This block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.

Q. Can we declare a class as static?
A: - We can’t declare a top-level class as static however an inner class can be declared as static. If inner class is declared as static, it’s called static nested class. Static nested class is same as any other top-level class and is nested for only packaging convenience.

Q. Explain the difference between static and instance methods in Java?
A: - Static Method
·         Static methods are the methods in Java that can be called without creating an object of class.
·         Static method is actually declared with static keyword.
·         Static method means which will exist as a single copy for a class.
·         Static methods can’t access instance methods and instance variables directly.
Instance Method
·         Instance methods is called when an object of its class is created.
·         Instance methods is not created with static keyword.
·         Instance methods exist as multiple copies depending on the number of instances created for that class.
·         Instance method can access static variables and static methods directly.

Q. What purpose does the keyword final, finally, and finalize fulfill?
A: - Final: - Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden, and final variable can’t be changed.
     Finally: - Finally is used to place to place important code, it will be executed whether exception is handled or not
     Finalize - Finalize is used to perform clean up processing just before object is garbage collected.

Q. Can we have Finally block without Try & Catch blocks?
A: - If an exception is thrown prior to the try block, the finally code will not execute. The finally block always executes when the try block exits. So you can use finally without catch but you must use try.

Q. What’s the difference between plugins and dependencies?
A: -Both plugins and dependencies are Jar files. But the difference between them is, most of the work in maven is done using plugins; whereas dependency is just a Jar file which will be added to the classpath while executing the tasks. For example, you use a compiler-plugin to compile the java files.

Q. Can final methods be overloaded?
A: -private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class.

Q. Can we have try without catch block?
A: -Yes, we can have try-finally statement and hence avoiding catch block.

Q. What is Interface?
A: -An interface in java is an abstract type that is used to specify a behavior of that class must implement. An interface also contains method and variables just like class but method declared in interface are by default abstract.
                In selenium WebDriver driver = new ChromeDriver();
In this case webdriver itself is an interface, so based on this webdriver driver = new ChromeDriver(); we are initializing chrome browser using selenium webdriver. It means we are creating reference variable of the interface and creating an object. Here WebDriver is an interface and ChromeDriver() is a class.

Q. Can we create an object for an interface?
A: -NO, we can’t create an object of an Interface ,we use an Interface to hide the implementations from user. Interface contains only abstract methods and as abstract methods do not have a body (of implementation code) we cannot create an object without constructor also.

Q. Can an interface implement or extend another interface?
A: -Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method implementations, there is no issue of diamond problem. That’s why we have multiple inheritance in interfaces i.e. an interface can extend multiple interfaces.

Q. What is Abstract class?
A: -A class which is declare with the abstract keyword is known as an Abstract class in Java. It can have abstract and non-abstract methods.
                Points to remember:
1.       An abstract class must be declared with an abstract keyword.
2.       It can have abstract and non-abstract methods.
3.       It can have constructors and static methods also.

Q. What is the difference between Abstract class and Interface?
A: -Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.
1. The abstract keyword is used to declare abstract class. Where The interface keyword is used to declare interface.
2. Abstract class can have abstract and non-abstract methods. Where Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
3. Abstract class doesn't support multiple inheritance. Whereas Interface supports multiple inheritance.
4. Abstract class can have final, non-final, static and non-static variables. Where Interface has only static and final variables.
5. An abstract class can extend another Java class and implement multiple Java interfaces. Whereas An interface can extend another Java interface only.
6. An abstract class can be extended using keyword "extends". Where An interface can be implemented using keyword "implements".
7. A Java abstract class can have class members like private, protected, etc. whereas Members of a Java interface are public by default.  

Q. Can we create an object for an abstract class?
A: -If we will create an object of the abstract class and calls the method having no body (as the method is pure virtual) it will give an error. That is why we can’t.

Q. What’s Singleton class?
A: - In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.

Q. To exit the system from the current execution what command is used in java?
A: - The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination.
exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination.
Note : This method does not return any value.
The following example shows the usage of java.lang.System.exit() method.

// A Java program to demonstrate working of exit() 
import java.util.*;
import java.lang.*;
  
class Demo
{
    public static void main(String[] args)
    {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
  
        for (int i = 0; i < arr.length; i++)
        {
            if (arr[i] >= 5)
            {
                System.out.println("exit...");
  
                // Terminate JVM
                System.exit(0);
            }
            else
                System.out.println("arr["+i+"] = " +
                                  arr[i]);
        }
        System.out.println("End of Program");
    }
}

Output:
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
exit...

Q. What are the OOP’s features/concepts?
A: -inheritance, Abstraction, Encapsulation, polymorphism, Interface.

Q. Inheritance?
A: -It is the process where one class inherits the properties of the other class.
Let’s say we have two classes, Parent class and child class. As per definition, the child class inherits the properties of the properties class. The purpose of inheritance is to obtain code reusability.
                When we create a Base class in our automation framework to initialize webdriver Interface, waits, logger, reports and when we extend this base class in our other classes such as test and utility classes. In this case extending one class into another class, is example of implementing Inheritance.

Q. What are the different types of inheritance in Java?
A: -Below are the different types of inheritance which is supported by Java
Single Inheritance
Multiple Inheritance (Through Interface)
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance (Through Interface)

Q. Abstraction?
A: -Abstraction is the methodology of hiding the implementation of internal details and showing only the functionality to the user.
Example. Mobile Phone- A man does not know how the phone works internally but he can make a call.
                In Automation framework whenever we use page object model we write all the locators in page class and use this locators in our test. It means we are hiding our implementation from the user. This is a simple example of abstraction in our framework.

Q. Encapsulation?
A: -Encapsulation is a process of wrapping code and data (variables) together into a single unit.
Example. In a page object model classes, In which we declare WebElement’s locator using @Findby and initializing of this data members will be done using Constructor to utilize these in test methods.

Q. What is Polymorphism?
A: -Polymorphism is a concept by which we can perform a single action in different ways. There are 2 types of polymorphism in Java, 1) Compile time and 2) Runtime polymorphism.

Q. What is overloading and overriding in java?
A: -* Method Overloading is a compile time polymorphism where the method name is same with different arguments or input parameters with different data types within a same class then it is called as method overloading / compile time polymorphism.
      * Method overriding is a Runtime polymorphism where the same method is present is parent class as well as in child class with the same name and same number of arguments then it is called as method overriding / Runtime polymorphism.

Q. What are primitive data types in Java?
A: -Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double.

Q. What is the purpose of using Wrapper classes in Java?
A: -Wrapper classes are used to convert any data type into an object. The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.

Q. What is Association in Java?
A: -Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Q. Why use Association in Java?
A: -Association is used to establish a relation between objects of two separate classes that can be two entirely different entities. This relationship indicates that a particular class is aware of another class and holds a reference to that class.

Q. When to use Association in Java?
A: -Association is applied when two classes need to interact with each other through their objects to achieve a certain result. It establishes a way to connect one or more objects with the objects of other classes.
These multidirectional connections are performed successfully through two of Association’s forms:
·         Composition
·         Aggregation.

Q. What is Aggregation in java?
A: - Aggregation is a special form of association. It is a relationship between two classes like association, however it is a directional association, which means it is strictly a one way association. It represents a HAS-A relationship.

Q. Why use Aggregation in Java?
A: -We use aggregation when want to reuse the code in our program. For example, Object A1 has a reference to another object called Object A2. They have a HAS-A relationship between them. As the Object A1 has reference to Object A2, the functionalities of Object A2 can be used by Object A1. Similarly, any class having a reference to Object A2 can utilize its methods.

Q. When to use Aggregation in Java?
A: - Aggregation is primarily used to connect two classes where the aggregate class has a reference to another class. This class has the ownership of the other class. When we want to avoid having cyclic references between the relationships of the two classes, we use this form of association.

Q. What is Composition in Java
A: - A Composition is a restricted form of aggregation where the two objects are highly dependent on each other. When a composition exists between two objects, the composed object cannot exist independently.

Q. Why Use Composition in Java?
A: - Composition is used when we want to establish a PART-OF relationship between two objects and one must be dependent on the other.

Q. When to use Composition in Java?
A: - Composition in Java is used to make the code reusable but the code is preserved and encapsulation is not hampered. In addition, composition also allows better testing of classes, such as unit testing. In test-driven development, composition is often chosen over inheritance because of its usability.

Q. What is Composition vs. Aggregation?
A: -
Composition
Aggregation
Here, the two objects are highly dependent on each other. The child class cannot work without the parent class.
Here, two objects can exist independently. A child class can work freely without the parent class.
It is a form of strong association.
It is a form of weak association.
It has a PART-OF relationship between two objects.
It is a HAS-A relationship between two objects.

Q. What is inner class in java?
A: -We can define a class inside a class and they are called nested classes. Any non-static nested class is known as inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with instance, we can’t have any static variables in them.

Q. What is THIS Keyword in Java?
A: -Keyword THIS is a reference variable in Java that refers to the current object.
The various usages of 'THIS' keyword in Java are as follows:
·         It can be used to refer instance variable of current class
·         It can be used to invoke or initiate current class constructor
·         It can be passed as an argument in the method call
·         It can be passed as argument in the constructor call
·         It can be used to return the current class instance

Q. What is Super keyword in JAVA?
A: -The super keyword in Java is a reference variable, which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.
Usage of Java super Keyword:
·         super can be used to refer immediate parent class instance variable.
·          super can be used to invoke immediate parent class method.
·          super() can be used to invoke immediate parent class constructor.

Q. Difference between Break and Continue?
A: -Break is used for immediate termination of loop while Continue terminates the current iteration and resumes the control to the next iteration of the loop.

Q. What do you mean by Constructor?
A: -The constructor is a method which has the same name as a class name.
If the user created a constructor with a parameter then he should create another explicitly without a parameter constructor can be overloaded.

Q. What is default constructor?
A: -No argument constructor of a class is known as default constructor. When we don’t define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won’t create default constructor for us.

Q. What is the value returned by Constructor in Java?
A: -When we call a constructor in Java, it returns the object created by it. That is how we create new objects in Java.

Q. Can we overload a Constructor?
A: -Yes, we can overload a Constructor.

Q. Can we inherit a Constructor?
A: -No, Java does not support inheritance of constructor.

Q. Why constructors cannot be final, static, or abstract in Java?
A: -If we set a method as final it means we do not want any class to override it. But the constructor (as per Java Language Specification) cannot be overridden. So there is no use of marking it final.
If we set a method as abstract it means that it has no body and it should be implemented in a child class. But the constructor is called implicitly when the new keyword is used. Therefore it needs a body.
If we set a method as static it means that it belongs to the class, but not a particular object. The constructor is always called to initialize an object. Therefore, there is no use of marking constructor static.

Q. Is it possible to use this() and super() both in same constructor?
A: -No, Java does not allow using both super() and this() in same constructor. As per Java specification, super() or this() must be the first statement in a constructor.

Q. What is Garbage Collection in Java and how  exactly it is done?
A: -Garbage means unreferenced objects. Garbage collection is the process of reclaiming the runtime unused memory automatically. In other words, it is  a way to destroy unused objects.

Q. What is the difference between Heap and Stack?
A: -Stack is used for static memory allocation and Heap is used for dynamic memory allocation.
     Stack memory is used to store local variable and functions unlike Heap memory is used to store objects in Java.

Q. What is String in Java?
A: -String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and can cannot be changed once it has been created.

Q. Is String a wrapper class?
A: -String is a class but not a wrapper class.

Q. Why String is non primitive?
A: -String is a class in java . Not A primitive data type . That’s why there are various String methods for manipulation , modification of String defined in String Class . Java is beautiful .

Q. What is String tokenizer?
A: -StringTokenizer class in Java is used to break a string into tokens. Example: A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.

Q. How can we make String upper case or lower case?
A: -We can use String class toUpperCase and toLowerCase methods to get the String in all upper case or lower case. These methods have a variant that accepts Locale argument and use that locale rules to convert String to upper or lower case.

Q. Difference between String, StringBuilder and StringBuffer?
A: -String vs StringBuffer vs StringBuilder
• String is immutable whereas StringBuffer and StringBuider are mutable classes.
• StringBuffer is thread safe and synchronized whereas StringBuilder is not, that’s why StringBuilder is more faster than StringBuffer.
• String concat + operator internally uses StringBuffer or StringBuilder class.
• For String manipulations in non-multi-threaded environment, we should use StringBuilder else use StringBuffer class.

Q. What is the difference between String and StringBuffer?
A: -Strings in Java are immutable (i.e. cannot be changed once created), whereas StringBuffer is mutable.

Q. Why String is immutable or final in Java?
A: -There are several benefits of String because it’s immutable and final.
·         String Pool is possible because String is immutable in java.
·          It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password etc.
·          Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.
·          Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.

Q. Addition features in Java 8?
A: - Some of the important Java 8 features are;
·         forEach() method in Iterable interface.
·         default and static methods in Interfaces.
·         Functional Interfaces and Lambda Expressions.
·          Java Stream API for Bulk Data Operations on Collections.
·          Java Time API.
·          Collection API improvements.
·          Concurrency API improvements.
·          Java IO improvements.

Q. What is the difference between collection and collections?
A: -Differences between Collection and Collections are as follows:
I. Collection is an interface in Java. But Collections is a class in Java.
II. Collection is a base interface. Collections is a utility class in Java.
III. Collection defines methods that are used for data structures that contain the objects. Collections defines the methods that are used for operations like access, find etc. on a Collection.



Q. What is Collection in Java?
A: -A Collection is a group of individual objects represent as a single unit. Java provides collection framework which defines several classes and interfaces to represent a group of objects as a single unit.
                The collection interface and Map interface are the two main “root” interface of java collection classes.

Q. What are the types of Collections?
A: -HashSet class, TreeSet class, ArrayList class, Linklist class, HashMap class, TreeMap class, Priority Queue class.

Q. What is generics?
A: -“Java Generics are a language feature that allows for definition and use of generic types and methods.” Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like LinkedList<E> is a generic type that has a type parameter E.

Q. What are the basic interfaces of Java Collections Framework?
A: -Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.
Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.
List is an ordered collection and can contain duplicate elements. You can access any element from its index. List is more like array with dynamic length.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

Q. Why Map interface doesn’t extend Collection interface?
A: -Although Map interface and its implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.
If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.

Q. What is an Iterator?
A: -Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration.

Q. What is List?
A: -The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by the classes of ArrayList, LinkedList, Vector and Stack.
List interfaces implement ArrayList, LinkedList, Vector, Stack.

Q. What are the Java Collection classes that implement List interface?
A: -Java classes that implement List interface are:
·         ArrayList
·         LinkedList
·         Vector
·         Stack

Q. How will you reverse a List in Java?
A: -In Collections class, Java provides a method reverse(List list) that can be used to reverse a List.
E.g. Collections.reverse(myList);

Q, What is Set?
A: -* Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
* Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
* Set has various methods to add, remove clear, size etc. to enhance the usage of this interface

Q. What are the Java Collection classes that implement Set interface?
A: -Java classes that implement Set interface are:
·         AbstractSet
·         HashSet
·         LinkedHashSet
·         TreeSet

Q. What is the difference between List and Set?
A: -List and Set both are the interface belongs to the Collection framework. Both interfaces extend the collection of Objects as a single unit.
List is a type of ordered collection that maintains the elements in insertion order while Set is a type of unordered collection so elements are not maintained any order.
List allows duplicate elements where Set doesn’t allow duplicate elements.

Q. What is the difference between a Set and a Map in Java?
A: -Main differences between a Set and a Map in Java are:
1.       Duplicate Elements: A Set does not allow inserting duplicate elements. A Map does not allow using duplicate keys, but it allows inserting duplicate values for unique keys.
2.        Null values: A Set allows inserting maximum one null value. In a Map we can have single null key at most and any number of null values.
3.       Ordering: A Set does not maintain any order of elements. Some of sub-classes of a Set can sort the elements in an order like LinkedHashSet. A Map does not maintain any order of its elements. Some of its sub-classes like TreeMap store elements of the map in ascending order of keys.

Q. What is Vector?
A: -Vector implements List Interface. Like ArrayList it also maintains insertion order but it is rarely used in non-thread environment as it is synchronized and due to which it gives poor performance in searching, adding, delete and update of its elements.

Q. What is Stack?
A: -Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

Q. What is HashSet?
A: -Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
·         HashSet stores the elements by using a mechanism called hashing.
·         HashSet contains unique elements only.
·         HashSet allows null value.
·         HashSet class is non synchronized.
·         HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
·         HashSet is the best approach for search operations.

Q. What are the differences between a HashSet and TreeSet collection in Java?
A: -Main differences between a HashSet and TreeSet are:
4.       Ordering: In a HashSet elements are stored in a random order. In a TreeSet, elements are stored according to natural ordering.
5.       Null Value Element: We can store null value object in a HashSet. A TreeSet does not allow to add a null value object.
6.       Performance: HashSet performs basic operations like add(), remove(), contains(), size() etc in a constant size time. A TreeSet performs these operations at the order of log(n) time.
7.       Speed: A HashSet is better than a TreeSet in performance for most of operations like add(), remove(), contains(), size() etc.
8.       Internal Structure: a HashMap in Java internally backs a HashSet. A NavigableMap backs a TreeSet internally.
9.       Features: A TreeSet has more features compared to a HashSet. It has methods like pollFirst(), pollLast(), first(), last(), ceiling(), lower() etc.
10.   Element Comparison: A HashSet uses equals() method for comparison. A TreeSet uses compareTo() method for comparison to maintain ordering of elements.

Q. In Java, how will you decide when to use a List, Set or a Map collection?
A: -1. If we want a Collection that does not store duplicate values, then we use a Set based collection.
2. If we want to frequently access elements operations based on an index value then we use a List based collection. E.g. ArrayList
3. If we want to maintain the insertion order of elements in a collection then we use a List based collection.
4. For fast search operation based on a key, value pair, we use a HashMap based collection.
5. If we want to maintain the elements in a sorted order, then we use a TreeSet based collection.

Q. What is LinkedHashSet?
A: -LinkedHashSet is also an implementation of Set interface.
                LinkedHashSet maintains the insertion order. Elements gets sorted in the same sequence in which they have been added to the Set.

Q. What is SortedSet?
A: -SortedSet , is a subtype of the java. util. Set interface. The Java SortedSet interface behaves like a normal Set with the exception that the elements it contains are sorted internally. This means that when you iterate the elements of a SortedSet the elements are iterated in the sorted order.

Q. Difference between TreeSet and SortedSet?
A: -SortedSet is an interface which TreeSet implements. That’ it !!

Q. What is Queue?
A: -The Java Queue interface, java.util.Queue represents a data structure designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue. This is similar to how a queue in a supermarket works.
The Java Queue interface is a subtype of the Java Collection interface. It represents an ordered sequence of objects just like a Java List, but its intended use is slightly different.

(( Queue – PriorityQueue, Dequeue – implements LinkedList ))

Q. PriorityQueue?
A: -A priority queue in Java is a particular type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.
Some useful points for PriorityQueue to be remembered.
·         It never permits NULL values
·         It is an unbounded queue
·         The front of PriorityQueue contains the least elements according to the specific ordering, and the rare of the priority queue contains the most significant elements.

Q. Dequeue?
A: -The dequeue is a double ended queue and data elements can be added or removed from either end. The dequeue in Java is implemented using the java.util.Deque interface which is a subtype of the java.util.Queue interface

Q. What are similarities and difference between ArrayList and Vector?
A: -ArrayList and Vector are similar classes in many ways.
1. Both are index based and backed up by an array internally.
 2. Both maintains the order of insertion and we can get the elements in the order of insertion.
 3. The iterator implementations of ArrayList and Vector both are fail-fast by design.
4. ArrayList and Vector both allows null values and random access to element using index number.
These are the differences between ArrayList and Vector.
`               1. Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList.
 2. ArrayList is faster than Vector because it doesn’t have any overhead because of synchronization.
3. ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class.

Q. What is an Array in Java?
A: -Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
* Array is index-based, the first element of the array is stored at the 0 index.
To declare an array, define the variable type with square brackets:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};

Q. What is the disadvantage of Array?
A: -Arrays are fixed in size i.e. After creating an Array, we cannot change its size at later point of the program.
The solution for this is ArrayList which can grow in size at a later point of the program

Q. What is the difference between Array and ArrayList?
A: -                         Array                                                     ArrayList
1. Size should be given at the time of             1. Size may not require. It changes the size directly.
Array deceleration.
2. Array is not type parameterized.                 2. ArrayList in java 5.0 are parameterized.
3. String [] name = new String[2]                      3. ArrayList name = new ArrayList
4. To put an object into array we need           4. No index required. name.add(“book”)                      
to specify the index name[i] = “Book”;

Q. What is the difference between ArrayList and LinkedList?
A: -1. ArrayList internally uses a dynamic array to store the elements. Where LinkedList internally uses a doubly linked list to store the elements.
2. Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory. Where Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3. An ArrayList class can act as a list only because it implements List only. Where LinkedList class can act as a list and queue both because it implements List and Dequeue interfaces.
4. ArrayList is better for storing and accessing data. Where LinkedList is better for manipulating data.

Q. What is the difference between Set and HashSet?
A: -A Set is a generic set of values with no duplicate elements.
A HashSet is a set where the elements are not sorted or ordered. HashSet is an implementation of a Set.


Q. Why we use Map interface? What are main classes implementing Map interface?
A: -Map interface is a special type of collection which is used to store key-value pairs. It does not extend Collection interface for this reason. This interface provides methods to add, remove, search or iterate over various views of Map.
Main classes implementing Map interface are: HashMap, Hashtable, EnumMap, IdentityHashMap, LinkedHashMap and Properties.

Q. How HashMap works in Java?
A: -HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method input and get methods.
When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.
When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. Below image will explain these detail clearly.

Q. What is difference between HashMap and Hashtable?
A: -HashMap and Hashtable both implements Map interface and looks similar, however there are following difference between HashMap and Hashtable.
1. HashMap allows null key and values whereas Hashtable doesn’t allow null key and values.
2. Hashtable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, Hashtable is suitable for multi-threaded environment.
3. LinkedHashMap was introduced in Java 1.4 as a subclass of HashMap, so in case you want iteration order, you can easily switch from HashMap to LinkedHashMap but that is not the case with Hashtable whose iteration order is unpredictable.
4. HashMap provides Set of keys to iterate and hence it’s fail-fast but Hashtable provides Enumeration of keys that doesn’t support this feature.
5. Hashtable is considered to be legacy class and if you are looking for modifications of Map while iterating, you should use ConcurrentHashMap.

Q. Why HashTable doesn’t allow null and HashMap does?
A: -To successfully store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode method and the equals method. Since null is not an object, it can’t implement these methods. HashMap is an advanced version and improvement on the Hashtable. HashMap was created later.

Q. Can we have duplicate key value in HashMap?
A: -HashMap doesn't allow duplicate keys but allows duplicate values. That means A single key can't contain more than 1 value but more than 1 key can contain a single value. HashMap allows null key also but only once and multiple null values.

Q. How to fetch values from a HashMap?
A: -Syntax:
Hash_Map.values()
Return Value: The method is used to return a collection view containing all the values of the map.

Q. What is the difference between HashMap and TreeMap in java ?
A: -1. HashMap does not maintain any ordering guarantee. TreeMap elements are sorted according to the natural ordering of the elements.
2. HashMap implementation internally uses hashing. TreeMap internally uses Red-black tree implementation.
3. HashMap can contain any number of null values and one null key. TreeMap cannot contain null keys but may contain null values.

Q. Difference between HashMap and HashSet?
A: -The main difference between a HashSet and a HashMap are:
1.       Base class: A HashSet class implements the Set interface. Whereas a HashMap class implements the Map interface.
2.       Storage: A HashSet is used to store distinct objects. A HashMap is used for storing key & value pairs, so that these can be retrieved by key later on.
3.       Duplicate Elements: A HashSet does not allow storing duplicate elements. A HashMap also does not allow duplicate keys. But we can store duplicate values in a HashMap.
4.       Null Elements: In a HashSet we can store a single null value. In a HashMap we can store single null key, but any number of null values.
5.       Element Type: A HashSet contains only values of objects as its elements. Whereas a HashMap contains entries(key value pairs).
6.       Iteration: By using an Iterator we can iterate a HashSet. But a HashMap has to be converted into Set for iteration.

Q. What are the similarities between a HashSet and a HashMap in Java?
A: -As the name suggests, HashSet and HashMap are Hashing based collections. Similarities between HashSet and HashMap are:
1.       Thread Safety: Both HashMap and HashSet are not synchronized collections. Therefore they are not good for thread-safe operations. To make these thread-safe we need to explicitly use synchronized versions.
2.       Order of Elements: None of these classes guarantee the order of elements. These are unordered collections.
3.       Internal Implementation: A HashMap backs up a HashSet internally. So HashSet uses a HashMap for performing its operations.
4.       Performance: Both of these collections provide constant time performance for basic operations such as insertion and removal of elements.

Q. Comparable vs Comparator in Java?
A: -Comparable and Comparator both are interfaces and can be used to sort collection elements.
  • Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. Whereas The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.
  • Comparable affects the original class, i.e., the actual class is modified. Where Comparator doesn't affect the original class, i.e., the actual class is not modified.
  • Comparable provides compareTo() method to sort elements. Where Comparator provides compare() method to sort elements.
  • Comparable is present in java.lang package. Where A Comparator is present in the java.util packaged.

 Q. What is threading
A:- Thread in a program is an exception path. Threading is creating additional independent execution paths in your program.

Q. How does multi-threading is achieved?
A: -Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Q. What do you mean by thread safe?
A: -Thread-safe code is code that will work even if many Threads are executing it simultaneously. A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

Q. What is Synchronization?
A: -Synchronization in java is the capability to control the access of multiple threads to any shared resource. Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Q. What is the difference between setSpeed() and sleep() methods?
A: -Both sleep() and setSpeed() are used to delay the speed of execution. The main difference between them is that: setSpeed sets a speed that will apply a delay time before every Selenium operation. sleep() will set up wait only for once when called.


Q. What is the base class for Exception and Error?
A: -Throwable class is the base class for Exception and Error.

Q. What is Exception in Java?
A: -It is any event that interrupts the normal flow of program execution. Example for exceptions are, arithmetic exception, Nullpointer exception, Divide by zero exception, etc. Exceptions in Java are something that is out of developers control.

Q. What is Exception Handling?
A: -Exception Handling is a process of mechanism that is used to handle runtime errors. It is used priority to handle checked exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of exceptions: Checked and unchecked exception.

Q. How many types of exception can occur in a Java program?
A: -There are two types of Exception: Checked and unchecked exception. An error is considered as an Unchecked exception.
* Checked Exception:- Checked exception are the one which are checked at compile time. For ex: - ClassnotFoundException.
* Unchecked Exception:- Unckecked Exceptions are the one which are handled at the runtime because they cannot be checked at the compile – time.
For ex: - Arithmatic Exception, Nullpointer Exception, ArrayindexoutofBond Exception etc.
* Error: - Error cause the program to exit since they are not recoverable.
For ex: - OutofMemoryError, AssertError etc.

Q. How to handle exception?
A: -Java exception handling is managed via five keywords:
try: this keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.
catch:  this block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finally: this block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw: this keyword is used to throw an exception.
throws: this keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
try catch syntax:
try{
//code that may throw an exception
}catch(ExceptionClassName ref){
}
try finally block
try{
//code that may throw an exception
}finally{
}

Q. What is the difference between Throw and Throws?
A: -Throw: The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Throws is also a keyword in java which is used in the method signature to indicate that this method may throw mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using try-catch blocks or using throws keyword.

No comments:

Post a Comment