MGNK Junction
Java Interview Questions and Answers
What are the core concepts of OOPS?
OOPS concepts are the foundation of object-oriented programming. They allow programmers to create more complex and reusable code. OOPS core concepts are;
-
Abstraction
-
Encapsulation
-
Polymorphism
-
Inheritance
-
Composition
-
Association
-
Aggregation
What is Abstraction?
Abstraction is the process of hiding the implementation details of an object from the user. This allows the user to focus on the object's behavior without having to worry about how it works.
E.g., a car is an abstract object.
The user of a car does not need to know how the engine works in order to drive the car.
Car class is an abstract class. It defines the basic behavior of a car, such as starting, stopping, accelerating, and breaking. However, it does not specify how these operations are implemented. The implementation of these operations is left to the subclasses of Car.
E.g., ElectricCar class is a subclass of Car.
It implements the start(), stop(), accelerate(), and brake() operations using an electric motor.
GasCar class is another subclass of Car.
It implements the start(), stop(), accelerate(), and brake() operations using a gasoline engine.
The use of abstraction allows programmers to focus on the behavior of objects without having to worry about the implementation details. This makes code more modular and reusable.
class Car {
public void start() {
// Start the engine.
}
public void stop() {
// Stop the engine.
}
public void accelerate() {
// Increase the speed of the car.
}
public void brake() {
// Decrease the speed of the car.
}
}
//Sub class
class ElectricCar extends Car{
public void start() {
System.out.println(“ This is to start the Electric car engine”);
}
public void stop() {
System.out.println(“ This is to stop the Electric car engine”);
}
public void accelerate() {
System.out.println(“ This is to increase the speed of the Electric car”);
}
public void brake() {
System.out.println(“ This is to decrease the speed of the Electric car”);
}
}
//Subclass
class GasolineCar extends Car{
public void start() {
System.out.println(“ This is to start the Gasoline car engine”);
}
public void stop() {
System.out.println(“ This is to stop the Gasoline car engine”);
}
public void accelerate() {
System.out.println(“ This is to increase the speed of the Gasoline car”);
}
public void brake() {
System.out.println(“ This is to decrease the speed of the Gasoline car”);
}
}
//Main Class
class Main{
public static void main(String args[]){
Car obj1 = new ElectricCar();
Obj1.start();
Obj1.accelerate(); //call the method
// obj 1 is a reference variable of class Car and pointed to the object of ElectricCar
Car obj2 = new GasolineCar();
Obj2.start();
Obj2.accelerate();
// obj 2 is a reference variable of class Car and pointed to the object of GasolineCar.
}
}
Output 1:
This is to start the Electric car engine.
This is to increase the speed of the Electric car.
Output 2:
This is to start the Gasoline car engine.
This is to increase the speed of the Gasoline car.
Abstraction in Selenium Automation Framework
In case we use Page Object Model design pattern in Automation Framework so we will have two different class files such as page Objects class file and test class file. Page Objects class includes locators (such as id, name, xpath etc.,) and the actions methods where test class file consists test cases and validation commands.
Here we will use the action methods of page object class in test class file. but we couldn’t see the implementation of the methods. Literally we hide the implementations of the action methods from the tests. This is known as abstraction.
Abstraction vs Interface
Abstraction: Hiding the internal details and showing the essential things to the user.
In Java, abstraction is achieved using abstract classes and interfaces.
An abstract class is a class that cannot be instantiated. It can only be used as a base class for other classes. An abstract class can have both abstract and non-abstract methods. An abstract method is a method that has no implementation. The implementation of an abstract method must be provided by a subclass.
What is Encapsulation?
Encapsulation is the process of grouping data and behavior together into a single unit. This makes it easier to manage the object and to protect its data from unauthorized access.
Basically, it creates and defines the permissions and restrictions of an object and its member variables and methods. i.e., make the member variables of a class private and providing public getter and setter methods. There are four types of access level modifiers: public, protected, private and default.
class Person {
private String name;
private int age;
private Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
The Person class encapsulates the data (such as the name and age) and the behavior (such as getting the name and age) of a person. The data is hidden from the user, and only the constructor of the class can access it. This protects the data from unauthorized access and misuse.
E.g., a user of the Person class cannot directly change the name or age. They can only use the getName() and getAge() methods to get the data. This prevents the user from accidentally or intentionally changing the data in an invalid way.
In this example, the constructor is used to initialize the data members of the Person class. The constructor is private, so it can only be accessed by the Person class itself. This prevents other classes from directly accessing the data members of the Person class.
The getName() and getAge() methods are public, so they can be accessed by other classes.
E.g., getName() method will only return a name that is not empty.
Encapsulation in Selenium
Eg., Create a Page Object for the login page of a website. The Page Object would contain the locators for the username and password fields, as well as the methods that are used to enter the username and password and to submit the login form.
Here the Page Objects Class encapsulates the data member and behavior that is needed to interact with a web page.Prevents unauthorized access to the data that is stored in the Page Objects.
What is the difference between Abstraction and Encapsulation?
​
​
​
​
​
​
​
​
​
What is Polymorphism?
Polymorphism is the ability of an object to behave differently in different contexts. E.g., a car can be used for transportation, recreation, or work. Java supports various forms of polymorphism like polymorphic reference variables, polymorphic method, polymorphic return types and polymorphic argument types.
Here are some examples of polymorphism in Java:
Overloading is a form of compile-time polymorphism where a method has the same name but different parameters. E.g., the following code defines two methods called print():
public void print (String message)
{
System.out.println(message); // print() method is called with a string as the argument
}
public void print (int number)
{
System.out.println(number); // print() method is called with an integer as the argument
}
The compiler will choose the correct method to call based on the type of the argument.
Overriding is a form of runtime polymorphism where a method in a subclass has the same name and parameters as a method in a superclass. The method in the subclass will override the method in the superclass. For example, the following code defines a superclass called Animal and a subclass called Dog:
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
The makeSound() method in the Dog class overrides the makeSound() method in the Animal class. When an object of the Dog class is created and the makeSound() method is called, the Dog version of the method will be called.
Examples for Method Overloading in Selenium
1. Implicit wait is an example of overloading. In Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS etc.
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.manage().timeouts().implicitlyWait(Duration.ofMinutes(2));
2.Action class in TestNG is also an example of overloading.
E.g.,
WebElement link = driver.findElement(By.linkText("My Account"));
WebElement textBox = driver.findElement(By.id("username"));
WebElement element = driver.findElement(By.id("myElement"));
Actions actions = new Actions(driver);
actions.click(link).build().perform();
actions.sendKeys(textBox, "myusername").build().perform();
actions.moveToElement(element).build().perform();
When can a method not be overridden in Java?
There are a few cases where a method cannot be overridden in Java:
-
If the method is declared final, it cannot be overridden.
-
If the method is declared static, it cannot be overridden.
-
If the method is declared private, it cannot be overridden from outside the class in which it is declared.
-
If the method is declared abstract, it must be overridden in a subclass.
In addition, a method cannot be overridden if the method signature is different in the subclass. For example, if the method in the superclass has a return type of void, the method in the subclass cannot have a return type of int.
What is Inheritance?
Inheritance is the process of creating new objects from existing objects. The new object inherits the properties and behaviors of the existing object. For example, a child class can inherit the properties and behaviors of a parent class.
class Animal {
String name;
int age;
public void eat() {
System.out.println("The animal is eating.");
}
}
// child class
class Dog extends Animal {
String breed;
public void bark() {
System.out.println("The dog is barking.");
}
}
// child class
class Cat extends Animal {
String color;
public void meow() {
System.out.println("The cat is meowing.");
}
}
// main class
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.name = "Max";
myDog.age = 3;
myDog.breed = "Labrador";
myDog.eat(); // inherited from Animal class
myDog.bark(); // specific to Dog class
Cat myCat = new Cat();
myCat.name = "Whiskers";
myCat.age = 2;
myCat.color = "Gray";
myCat.eat(); // inherited from Animal class
myCat.meow(); // specific to Cat class
}
}
Animal class is the parent class and Dog and Cat classes are the child classes that inherit from it. The Dog and Cat classes add specific behaviors (bark() and meow()) to the ones inherited from the Animal class (eat()). The Dog and Cat objects can be instantiated and their methods can be called accordingly.
What is multiple inheritance?
Multiple inheritance is a feature of some object-oriented computer programming languages
in which an object or class can inherit features from more than one parent object or parent class.
It is distinct from single inheritance, where an object or class may only inherit from one particular object or class. The child inherits methods and attributes of the parent, allowing for shared functionality.
What is Object?
Objects are the building blocks of Java programs
Contains both data and methods.
E.g.,
// Car class is a blueprint for creating Car objects.
public class car {
String model="mazda"
int price= 45000;
public void drive()
{
system.out.println("I am driving")
}
Car car = new Car(); //creates an object of the Car class and calls the drive() method
car.drive();
//Data is stored in fields, and the methods are called by using the dot notation.
system.out.println(car.model)
system.out.println(car.price);
}
Output
I am driving
mazda
45000
What is a Class?
-
A class is a blueprint for creating objects.
-
Defines the data and the methods that are common to all objects of that type.
-
Allows to create complex data structures and to encapsulate data and behavior
What is a lambda expression?
-
An anonymous function, available from Java 8 that can be passed around as an object
-
Helps to write more concise and expressive code
-
This is basicaaly to bring functional features in Java since its object oriented programming language
-
Passed as arguments to methods that accept functional interfaces (Method arguments)
-
Assigned to variables of functional interface types (Variable assignments)
-
Used to perform operations on streams (Stream operations)
lambda expression: To sort a list of strings in reverse order
List<String> names = Arrays.asList("Alice", "Bob", "Carol"); // Sort the list in reverse order.
Collections.sort(names, (a, b) -> b.compareTo(a)); //Each character of string converted into a Unicode value
System.out.println(names); // Print the sorted list.
//lambda expression takes 2 arguments, a and b, and returns an integer
/*If a > b, returns a positive integer
If a = b, returns 0
If a < b, returns a negative integer*/
Output:
[Carol, Bob, Alice]
Write a program to swap two numbers
public class SwapTwoNumbers {
public static void main(String args[]) {
int num1 = 879;
int num2 = 325;
System.out.println("Before swaping");
System.out.println("num1 : " + num1);
System.out.println("num2 : " + num2);
num1 = num1 - num2;
num2 = num2 + num1;
num1 = num2 - num1;
System.out.println("After swaping");
System.out.println("num1 : " + num1);
System.out.println("num2 : " + num2);
}
}
Write a program to reverse a number.
public class ReverseANumber {
public static void main(String[] args) {
int num=223;
int reversedNum=0;
System.out.println("Given Number : " +num);
while(num != 0)
{
int reminder=num % 10;
reversedNum=reminder +reversedNum*10;
num=num / 10;
}
System.out.println("Reversed Number : " +reversedNum);
}
}
Output
Given Number : 223
Reversed Number : 322
Write a Program to reverse a String
public class ReverseAString{
public static void main(String[] args) {
String myWord = "Learn Java";
String given = " ";
char[] myArray = myWord.toCharArray();
String reversedString = " ";
// print myArray
for (int i = 0; i < myArray.length; i++) {
given = given + myArray[i];
}
System.out.println("Given String : " + given);
// print myReversed Array
for (int i = myArray.length - 1; i >= 0; i--) {
reversedString = reversedString + myArray[i];
}
System.out.println("ReversedString : " + reversedString);
}
}
Output
Given String : Learn Java
ReversedString : avaJ nraeL
Write a program to reverse word by word in given sentence
public class ReverseWordByWord {
public static void main(String[] args) {
String given = "Learning OOPs concepts in Java";
String[] words = given.split(" ");
String reversed = "";
System.out.println("Given : "+given);
for (int i = 0; i < words.length; i++) {
String wordsArray = "";
wordsArray = wordsArray + words[i] + " ";
char[] chArray = wordsArray.toCharArray();
for (int j = wordsArray.length() - 1; j >= 0; j--) {
reversed = reversed + chArray[j];
}
}
System.out.println("Reversed word by word : "+ reversed);
}
}
Write a program to find distinct numbers in an Array
import java.util.ArrayList;
public class FindDistinctNumber {
public static void main(String[] args) {
int arr[] = { 34, 56, 12, 34, 78, 45, 56, 87, 34, 45 };
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
int j = 0;
if (!list.contains(arr[i])) {
list.add(arr[i]);
j++;
for (int k = i + 1; k < arr.length; k++) {
if (arr[i] == arr[k]) {
j++;
}
}
System.out.println(j + " - " + arr[i]);
}
}
System.out.println(list);
}
}
​
Output
[34, 56, 12, 78, 45, 87]
Java Streams
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamExamples {
public static void main(String[] args) {
Stream.of(7,8,5,4,9,1,6,4,5,6).distinct().forEach((n)->System.out.println(n));
List<Integer>sortedList=Stream.of(7,8,5,4,9,1,6,4,5,6).distinct().sorted().collect(Collectors.toList());
System.out.println(sortedList.get(4));
}
}
HashMap example
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashmapExample {
public static void main(String[] args) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(42, "Katty");
hm.put(45, "George");
hm.put(92, "Bob");
hm.put(73, "John");
hm.remove(73);
System.out.println(Arrays.asList(hm));
System.out.println(Collections.singletonList(hm));
hm.forEach((key, value) -> System.out.println(key + " " + value));
Arrays.toString(hm.entrySet().toArray());
System.out.println(hm);
Set sn = hm.entrySet(); // create a new set and store the map elements into them
Iterator it = sn.iterator();
while (it.hasNext()) {
Map.Entry mp = (Map.Entry) it.next();
System.out.println("ID : " + mp.getKey());
System.out.println("Employee name : " + mp.getValue());
}
}
}
Instance variables vs Static variables
​
​
​
​