Tuesday, April 26, 2022

Java -8 Interview Questions

 Java- 8 Interview Question

netstat -ano | findstr :8080 taskkill /PID {your process id} /F



  1.  What is Type Inference?

Type inference helps the compiler determine the argument types by looking at each method invocation and corresponding declaration.



2. Why are default methods needed in the interface?

Default methods let you add new functionality to your libraries’ interfaces and ensure binary compatibility with older code written for the interfaces.



3. What is Java 8 StringJoiner class used for?

Java 8 StringJoiner class constructs a sequence of characters separated by a delimiter so that users can create a string by passing delimiters such as hyphens and commas.


package com.example.demo.java_8.StringJoiner;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StringJoinerTest {

public static void main(String[] args) {

List<String> str = Arrays.asList("Hello", "World", "Come", "to", "the", "World");
String afterModifyStr = str.stream().collect(Collectors.joining("-", "{(", ")}"));
System.out.println(afterModifyStr);

}

}
OUTPUT:-

{(Hello-World-Come-to-the-World)}


4. Describe the more commonly found functional interfaces in the standard library.

Although many functional interfaces exist, these are the one's users most likely encounter:

  • Function. Takes one argument and returns a result....... Function<T,R> ~~ apply()
  • Consumer. Takes one argument and returns no result....Consumer<T>~~ accept()
  • Supplier. Takes a not argument and returns a result....Supplier<T>~~ get()
  • Predicate. Takes one argument and returns a boolean.....Predicate<T> ~~ test()
  • BiFunction. Takes two arguments and returns a result
  • BinaryOperator. It’s like a BiFunction, except it takes two arguments and returns a result, and they are all the same type
  • UnaryOperator. It’s like a Function, but it takes a single argument and returns a result of the same type

Function (Program Example)



Date API



ALL


BiFunctions



BiPredicate


BiConsumer






Monday, April 25, 2022

JAVA Interview Questions

String
Immutable in String : 138
Immutable : 2
StringBuffer Equals method 
--------------------------------------
Core java - Inheritance: 2
Polymorphism : 51
Encapsulation : 55
Abstraction : 58
----------------------------------------
Arrays : 87
Generic : 70
Collection :71
Set : 54
HashSet works internally : 79
HasHMap : 80
equal : 91
HashCode : 91
//comparable & Comparator //
------------------------------------------------
Error :  100
Exception : 101
---------------------------------------
Copy Constructor : 60
clone: 61
--------------------------------------
Serialization : 176
Externalizatio n : 180
--------------------------------------
Thread : 143
----------------------------------
Static : 147
Constructor : 166
Final : 193

-----------------------------------------
Modifiers: 44
Local Variable: 35
----------------------------------------
Memory :
JVM : 163
---------------------------

Iterator : 85
Garbeg Collector : 105
-------------------------------------------

impo Q : 153
------------------------------------

Project Details : 168

--------------------------
Project Details : 221
Web Services : 236
Spring : 270
spring objective Questions: 330
Servlet & JSP: 238/9
DB : 331
hibernate : 344
Hibernate Cache :  344
Hibernate Criteria : 341
hibernat-Cascade: 350
Hibernate Transaction Management : 351
Batch-Processing :352
Core Java Programming : 372
----------------------------------------------------------------




--------------------------------------------------------------------------------------------------------------





What are the SOLID principles in Java?


SOLID principles are object-oriented design concepts relevant to software development. SOLID is an acronym for five other class-design principles: Single Responsibility Principle, Open-Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle.

PrincipleDescription
Single Responsibility PrincipleEach class should be responsible for a single part or functionality of the system.
Open-Closed PrincipleSoftware components should be open for extension, but not for modification.
Liskov Substitution PrincipleObjects of a superclass should be replaceable with objects of its subclasses without breaking the system.
Interface Segregation PrincipleNo client should be forced to depend on methods that it does not use.
Dependency Inversion PrincipleHigh-level modules should not depend on low-level modules, both should depend on abstractions.

SOLID is a structured design approach that ensures your software is modular and easy to maintain, understand, debug, and refactor. Following SOLID also helps save time and effort in both development and maintenance. SOLID prevents your code from becoming rigid and fragile, which helps you build long-lasting software.

Examples

1. Single responsibility principle

Every class in Java should have a single job to do. To be precise, there should only be one reason to change a class. Here’s an example of a Java class that does not follow the single responsibility principle (SRP):

public class Vehicle {
    public void printDetails() {}
    public double calculateValue() {}
    public void addVehicleToDB() {}
}

The Vehicle class has three separate responsibilities: reporting, calculation, and database. By applying SRP, we can separate the above class into three classes with separate responsibilities.

2. Open-closed principle

Software entities (e.g., classes, modules, functions) should be open for an extension, but closed for modification.

Consider the below method of the class VehicleCalculations:

public class VehicleCalculations {
    public double calculateValue(Vehicle v) {
        if (instanceof Car) {
            return v.getValue() * 0.8;
        if (instanceof Bike) {
            return v.getValue() * 0.5;

    }
}

Suppose we now want to add another subclass called Truck. We would have to modify the above class by adding another if statement, which goes against the Open-Closed Principle.
A better approach would be for the subclasses Car and Truck to override the calculateValue method:

public class Vehicle {
    public double calculateValue() {...}
}
public class Car extends Vehicle {
    public double calculateValue() {
        return this.getValue() * 0.8;
}
public class Truck extends Vehicle{
    public double calculateValue() {
        return this.getValue() * 0.9;
}

Adding another Vehicle type is as simple as making another subclass and extending from the Vehicle class.

3. Liskov substitution principle

The Liskov Substitution Principle (LSP) applies to inheritance hierarchies such that derived classes must be completely substitutable for their base classes.

Consider a typical example of a Square derived class and Rectangle base class:

public class Rectangle {
    private double height;
    private double width;
    public void setHeight(double h) { height = h; }
    public void setWidht(double w) { width = w; }
    ...
}
public class Square extends Rectangle {
    public void setHeight(double h) {
        super.setHeight(h);
        super.setWidth(h);
    }
    public void setWidth(double w) {
        super.setHeight(w);
        super.setWidth(w);
    }
}

The above classes do not obey LSP because you cannot replace the Rectangle base class with its derived class Square. The Square class has extra constraints, i.e., the height and width must be the same. Therefore, substituting Rectangle with Square class may result in unexpected behavior.

4. Interface segregation principle

The Interface Segregation Principle (ISP) states that clients should not be forced to depend upon interface members they do not use. In other words, do not force any client to implement an interface that is irrelevant to them.

Suppose there’s an interface for vehicle and a Bike class:

public interface Vehicle {
    public void drive();
    public void stop();
    public void refuel();
    public void openDoors();
}
public class Bike implements Vehicle {

    // Can be implemented
    public void drive() {...}
    public void stop() {...}
    public void refuel() {...}
    
    // Can not be implemented
    public void openDoors() {...}
}

As you can see, it does not make sense for a Bike class to implement the openDoors() method as a bike does not have any doors! To fix this, ISP proposes that the interfaces be broken down into multiple, small cohesive interfaces so that no class is forced to implement any interface, and therefore methods, that it does not need.

5. Dependency inversion principle

The Dependency Inversion Principle (DIP) states that we should depend on abstractions (interfaces and abstract classes) instead of concrete implementations (classes). The abstractions should not depend on details; instead, the details should depend on abstractions.

Consider the example below. We have a Car class that depends on the concrete Engine class; therefore, it is not obeying DIP.

public class Car {
    private Engine engine;
    public Car(Engine e) {
        engine = e;
    }
    public void start() {
        engine.start();
    }
}
public class Engine {
   public void start() {...}
}

The code will work, for now, but what if we wanted to add another engine type, let’s say a diesel engine? This will require refactoring the Car class.
However, we can solve this by introducing a layer of abstraction. Instead of Car depending directly on Engine, let’s add an interface:

public interface Engine {
    public void start();
}

Now we can connect any type of Engine that implements the Engine interface to the Car class:

public class Car {
    private Engine engine;
    public Car(Engine e) {
        engine = e;
    }
    public void start() {
        engine.start();
    }
}
public class PetrolEngine implements Engine {
   public void start() {...}
}
public class DieselEngine implements Engine {
   public void start() {...}
}





---------------------------------------------------------------------------------------------------------------





Linked List


package com.example.demo.LinkedList;


import java.util.LinkedList;


public class LinkedListDemo {


public static void main(String[] args) {


LinkedList list = new LinkedList();

list.add("Durga");

list.add("Software");

list.add(1);

list.add(null);

list.add(1000.00);

System.out.println(list);

list.addFirst("Perwaiz");

list.addLast("Ali");

System.out.println(list);

list.remove(4);

System.out.println(list);

list.remove("Perwaiz");

System.out.println(list);

list.add(1,"Software Design");

System.out.println(list);

}


}


OUTPUT:-



[Durga, Software, 1, null, 1000.0]

[Perwaiz, Durga, Software, 1, null, 1000.0, Ali]

[Perwaiz, Durga, Software, 1, 1000.0, Ali]

[Durga, Software, 1, 1000.0, Ali]

[Durga, Software Design, Software, 1, 1000.0, Ali]



==============================================================

package com.example.demo.LinkedList;

public class EmployeeLinkedList {
private int id;
private String name;
private double salary;
public EmployeeLinkedList(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "EmployeeLinkedList [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}




package com.example.demo.LinkedList;
import java.util.Iterator;
import java.util.LinkedList;
public class EmployeeLinkedListMainDemo {
public static void main(String[] args) {
EmployeeLinkedList emp_1 = new EmployeeLinkedList(101, "Ali_1", 33201);
EmployeeLinkedList emp_2 = new EmployeeLinkedList(102, "Ali_2", 33202);
EmployeeLinkedList emp_3 = new EmployeeLinkedList(103, "Ali_3", 33203);
EmployeeLinkedList emp_4 = new EmployeeLinkedList(104, "Ali_4", 33204);
EmployeeLinkedList emp_5 = new EmployeeLinkedList(105, "Ali_5", 33205);
EmployeeLinkedList emp_6 = new EmployeeLinkedList(106, "Ali_6", 33206);
LinkedList<EmployeeLinkedList> list = new LinkedList<>();
list.add(emp_1);
list.add(emp_2);
list.add(emp_3);
list.add(emp_4);
list.add(emp_5);
list.add(emp_6);
System.out.println(list);
list.set(1, new EmployeeLinkedList(102, "Ali-1012", 3320102));
list.set(5, new EmployeeLinkedList(106, "Ali-106", 3320106));

Iterator<EmployeeLinkedList> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}



OUTPUT:-


[EmployeeLinkedList [id=101, name=Ali_1, salary=33201.0], EmployeeLinkedList [id=102, name=Ali_2, salary=33202.0], EmployeeLinkedList [id=103, name=Ali_3, salary=33203.0], EmployeeLinkedList [id=104, name=Ali_4, salary=33204.0], EmployeeLinkedList [id=105, name=Ali_5, salary=33205.0], EmployeeLinkedList [id=106, name=Ali_6, salary=33206.0]]

EmployeeLinkedList [id=101, name=Ali_1, salary=33201.0]

EmployeeLinkedList [id=102, name=Ali-1012, salary=3320102.0]

EmployeeLinkedList [id=103, name=Ali_3, salary=33203.0]

EmployeeLinkedList [id=104, name=Ali_4, salary=33204.0]

EmployeeLinkedList [id=105, name=Ali_5, salary=33205.0]

EmployeeLinkedList [id=106, name=Ali-106, salary=3320106.0]

-----------------------------------------------------------------------------------------------------------------------------

ConcurrentHashMap Details