Thursday, December 8, 2022

LeetCode- challange + Java 8







14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

 

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

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

 Binary Tree 






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

Example for Nullable class

package com.example.java8.Optional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class OptionalMain {

public static void main(String[] args) {

Customer customer_1 = new Customer(101, "Ali_1");
Customer customer_2 = new Customer(102, "Ali_2");
Customer customer_3 = new Customer(103, null);
Map<String, Customer> cusMap = new HashMap<>();
cusMap.put("Ali_1", customer_1);
cusMap.put("Ali_2", customer_2);
cusMap.put("Ali_3", customer_3);
String[] str = {"Ali_1", "Ali_2", "Ali_4"};
Arrays.stream(str).forEach(strA-> Optional.ofNullable(cusMap.get(strA)).ifPresent(cus->System.out.print(cus)));
}

}


OUTPUT:-

Customer [id=101, name=Ali_1]Customer [id=102, name=Ali_2]

Monday, August 29, 2022

Read Big file in Java

Distributed Sorting - Google Interview Question - Algorithm & System Design








Thursday, June 30, 2022

Interview questions for 10 years Java experience

 JAVA Interview Questions


Java 8 Interview Questions for Freshers

1. Describe the newly added features in Java 8?

Here are the newly added features of Java 8:


Feature 

Lambda expression : A function that can be shared or referred to as an object.

Functional Interfaces : Single abstract method interface.

Method References : Uses function as a parameter to invoke a method.

Default method: It provides an implementation of methods within interfaces enabling 'Interface evolution' facilities.

Stream API : Abstract layer that provides pipeline processing of the data.

Date Time API : New improved joda-time inspired APIs to overcome the drawbacks in previous versions

Optional : Wrapper class to check the null values and helps in further processing based on the value.

Nashorn, JavaScript Engine An improvised version of JavaScript Engine that enables JavaScript executions in Java, to replace Rhino.

2. In which programming paradigm Java 8 falls?

Object-oriented programming language.

Functional programming language.

Procedural programming language.

Logic programming language

3. What are the significant advantages of Java 8?

Compact, readable, and reusable code.

Less boilerplate code.

Parallel operations and execution.

Can be ported across operating systems.

High stability.

Stable environment.

Adequate support

You can download a PDF version of Java 8 Interview Questions.


Download PDF


4. What is MetaSpace? How does it differ from PermGen?


JVM

PremGen: MetaData information of classes was stored in PremGen (Permanent-Generation) memory type before Java 8. PremGen is fixed in size and cannot be dynamically resized. It was a contiguous Java Heap Memory.


MetaSpace: Java 8 stores the MetaData of classes in native memory called 'MetaSpace'. It is not a contiguous Heap Memory and hence can be grown dynamically which helps to overcome the size constraints. This improves the garbage collection, auto-tuning, and de-allocation of metadata.


5. What are functional or SAM interfaces?

Functional Interfaces are an interface with only one abstract method. Due to which it is also known as the Single Abstract Method (SAM) interface. It is known as a functional interface because it wraps a function as an interface or in other words a function is represented by a single abstract method of the interface.


Functional interfaces can have any number of default, static, and overridden methods. For declaring Functional Interfaces @FunctionalInterface annotation is optional to use. If this annotation is used for interfaces with more than one abstract method, it will generate a compiler error.


@FunctionalInterface // Annotation is optional 

public interface Foo() { 

// Default Method - Optional can be 0 or more 

public default String HelloWorld() { 

return "Hello World"; 

// Static Method - Optional can be 0 or more 

public static String CustomMessage(String msg) { 

return msg; 

// Single Abstract Method 

public void bar(); 


public class FooImplementation implements Foo { 

// Default Method - Optional to Override

@Override

public default String HelloWorld() { 

return "Hello Java 8"; 

// Method Override

@Override

public void bar() {

System.out.println(“Hello World”);


public static void main(String[] args) { 


FooImplementation fi = new FooImplementation();

System.out.println(fi.HelloWorld());

System.out.println(fi.CustomMessage(“Hi”));

fi.bar();

}

6. Can a functional interface extend/inherit another interface?

A functional interface cannot extend another interface with abstract methods as it will void the rule of one abstract method per functional interface. E.g:


interface Parent { 

public int parentMethod(); 

@FunctionalInterface // This cannot be FunctionalInterface 

interface Child extends Parent { 

public int childMethod(); 

// It will also extend the abstract method of the Parent Interface 

// Hence it will have more than one abstract method 

// And will give a compiler error 

}

It can extend other interfaces which do not have any abstract method and only have the default, static, another class is overridden, and normal methods. For eg:


interface Parent { 

public void parentMethod(){ 

System.out.println("Hello"); 

@FunctionalInterface 

interface Child extends Parent { 

public int childMethod(); 

}

7. What is the default method, and why is it required?

A method in the interface that has a predefined body is known as the default method. It uses the keyword default. default methods were introduced in Java 8 to have 'Backward Compatibility in case JDK modifies any interfaces. In case a new abstract method is added to the interface, all classes implementing the interface will break and will have to implement the new method. With default methods, there will not be any impact on the interface implementing classes. default methods can be overridden if needed in the implementation. Also, it does not qualify as synchronized or final.


@FunctionalInterface // Annotation is optional 

public interface Foo() { 

// Default Method - Optional can be 0 or more 

public default String HelloWorld() { 

return "Hello World"; 

// Single Abstract Method 

public void bar(); 

}

8. What are static methods in Interfaces?

Static methods, which contains method implementation is owned by the interface and is invoked using the name of the interface, it is suitable for defining the utility methods and cannot be overridden.


9. What are some standard Java pre-defined functional interfaces?

Some of the famous pre-defined functional interfaces from previous Java versions are Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional interfaces like Supplier, Consumer, Predicate, etc. Please refer to the java.util.function doc for other predefined functional interfaces and its description introduced in Java 8.


Runnable: use to execute the instances of a class over another thread with no arguments and no return value. 


Callable: use to execute the instances of a class over another thread with no arguments and it either returns a value or throws an exception.


Comparator: use to sort different objects in a user-defined order


Comparable: use to sort objects in the natural sort order


10. What are the various categories of pre-defined function interfaces?

Function: To transform arguments in returnable value.


Predicate: To perform a test and return a Boolean value.


Consumer: Accept arguments but do not return any values.


Supplier: Do not accept any arguments but return a value. 


Operator: Perform a reduction type operation that accepts the same input types.


11. What is the lambda expression in Java and How does a lambda expression relate to a functional interface?

Lambda expression is a type of function without a name. It may or may not have results and parameters. It is known as an anonymous function as it does not have type information by itself. It is executed on-demand. It is beneficial in iterating, filtering, and extracting data from a collection.


As lambda expressions are similar to anonymous functions, they can only be applied to the single abstract method of Functional Interface. It will infer the return type, type, and several arguments from the signature of the abstract method of functional interface.


Java 8 Interview Questions for Experienced

12. What is the basic structure/syntax of a lambda expression?

FunctionalInterface fi = (String name) -> { 

System.out.println("Hello "+name); 

return "Hello "+name; 

}

Lambda expression can be divided into three distinct parts as below:


1. List of Arguments/Params:


(String name) 


A list of params is passed in () round brackets. It can have zero or more params. Declaring the type of parameter is optional and can be inferred for the context. 


2. Arrow Token:


-> 

Arrow token is known as the lambda arrow operator. It is used to separate the parameters from the body, or it points the list of arguments to the body. 3. Expression/Body:


System.out.println("Hello "+name); 

return "Hello "+name; 

}

A body can have expressions or statements. {} curly braces are only required when there is more than one line. In one statement, the return type is the same as the return type of the statement. In other cases, the return type is either inferred by the return keyword or void if nothing is returned.


13. What are the features of a lambda expression?

Below are the two significant features of the methods that are defined as the lambda expressions: 


Lambda expressions can be passed as a parameter to another method. 

Lambda expressions can be standalone without belonging to any class.

14. What is a type interface?

Type interface is available even in earlier versions of Java. It is used to infer the type of argument by the compiler at the compile time by looking at method invocation and corresponding declaration.


15. What are the types and common ways to use lambda expressions?

A lambda expression does not have any specific type by itself. A lambda expression receives type once it is assigned to a functional interface. That same lambda expression can be assigned to different functional interface types and can have a different type.


For eg consider expression s -> s.isEmpty() :


Predicate<String> stringPredicate = s -> s.isEmpty(); 

Predicate<List> listPredicate = s -> s.isEmpty();

Function<String, Boolean> func = s -> s.isEmpty();

Consumer<String> stringConsumer = s -> s.isEmpty();


Common ways to use the expression


Assignment to a functional Interface —> Predicate<String> stringPredicate = s -> s.isEmpty();

Can be passed as a parameter that has a functional type —> stream.filter(s -> s.isEmpty())

Returning it from a function —> return s -> s.isEmpty()

Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()


16. In Java 8, what is Method Reference?

Method reference is a compact way of referring to a method of functional interface. It is used to refer to a method without invoking it. :: (double colon) is used for describing the method reference. The syntax is class::methodName


For e.g.: 


Integer::parseInt(str) \\ method reference


str -> Integer.ParseInt(str); \\ equivalent lambda


17. What does the String::ValueOf expression mean?

It is a static method reference to method Valueof() of class String. It will return the string representation of the argument passed.


18. What is an Optional class?

Optional is a container type which may or may not contain value i.e. zero(null) or one(not-null) value. It is part of java.util package. There are pre-defined methods like isPresent(), which returns true if the value is present or else false and the method get(), which will return the value if it is present.


static Optional<String> changeCase(String word) {

if (name != null && word.startsWith("A")) {

   return Optional.of(word.toUpperCase());

  }

else {

return Optional.ofNullable(word); // someString can be null

}

}


Optional Class

19. What are the advantages of using the Optional class?

Below are the main advantage of using the Optional class: 


It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null checks, which results in better, readable, and robust code It acts as a wrapper around the object and returns an object instead of a value, which can be used to avoid run-time NullPointerExceptions.


20. What are Java 8 streams?

A stream is an abstraction to express data processing queries in a declarative way. 


A Stream, which represents a sequence of data objects & series of operations on that data is a data pipeline that is not related to Java I/O Streams does not hold any data permanently.

The key interface is java.util.stream.Stream<T>. It accepts Functional Interfaces so that lambdas can be passed. Streams support a fluent interface or chaining. Below is the basic stream timeline marble diagram:



Java 8 Streams

21. What are the main components of a Stream?

Components of the stream are:


A data source

Set of Intermediate Operations to process the data source

Single Terminal Operation that produces the result


Components of Stream

22. What are the sources of data objects a Stream can process?

A Stream can process the following data:


A collection of an Array.

An I/O channel or an input device.

A reactive source (e.g., comments in social media or tweets/re-tweets) 

A stream generator function or a static factory.

23. What are Intermediate and Terminal operations?

Intermediate Operations:


Process the stream elements.

Typically transforms a stream into another stream.

Are lazy, i.e., not executed till a terminal operation is invoked.

Does internal iteration of all source elements.

Any number of operations can be chained in the processing pipeline.

Operations are applied as per the defined order.

Intermediate operations are mostly lambda functions.

Terminal Operations:


Kick-starts the Stream pipeline.

used to collect the processed Stream data.

int count = Stream.of(1, 2, 3, 4, 5)

.filter(i -> i <4) // Intermediate Operation filter

.count(); // Terminal Operation count

24. What are the most commonly used Intermediate operations?

Filter(Predicate<T>) - Allows selective processing of Stream elements. It returns elements that are satisfying the supplied condition by the predicate.


map(Funtion<T, R>) - Returns a new Stream, transforming each of the elements by applying the supplied mapper function.= sorted() - Sorts the input elements and then passes them to the next stage.


distinct() - Only pass on elements to the next stage, not passed yet.


limit(long maxsize) - Limit the stream size to maxsize.


skip(long start) - Skip the initial elements till the start.


peek(Consumer) - Apply a consumer without modification to the stream.


flatMap(mapper) - Transform each element to a stream of its constituent elements and flatten all the streams into a single stream.


25. What is the stateful intermediate operation? Give some examples of stateful intermediate operations.

To complete some of the intermediate operations, some state is to be maintained, and such intermediate operations are called stateful intermediate operations. Parallel execution of these types of operations is complex.


For Eg: sorted() , distinct() , limit() , skip() etc. 


Sending data elements to further steps in the pipeline stops till all the data is sorted for sorted() and stream data elements are stored in temporary data structures.


26. What is the most common type of Terminal operations?

collect() - Collects single result from all elements of the stream sequence.

reduce() - Produces a single result from all elements of the stream sequence

count() - Returns the number of elements on the stream.

min() - Returns the min element from the stream.

max() - Returns the max element from the stream.

Search/Query operations

anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.

Takes a Predicate as input for the match condition.

Stream processing will be stopped, as and when the result can be determined.

Iterative operations

forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.

forEachOrdered() - It is helpful to maintain order in parallel streams.

27. What is the difference between findFirst() and findAny()?

findFirst() findAny()

Returns the first element in the Stream Return any element from the Stream

Deterministic in nature Non-deterministic in nature

28. How are Collections different from Stream?

Collections are the source for the Stream. Java 8 collection API is enhanced with the default methods returning Stream<T> from the collections.


Collections Streams

Data structure holds all the data elements No data is stored. Have the capacity to process an infinite number of elements on demand

External Iteration Internal Iteration

Can be processed any number of times Traversed only once

Elements are easy to access No direct way of accessing specific elements

Is a data store Is an API to process the data

29. What is the feature of the new Date and Time API in Java 8?

Immutable classes and Thread-safe 

Timezone support

Fluent methods for object creation and arithmetic

Addresses I18N issue for earlier APIs

Influenced by popular joda-time package

All packages are based on the ISO-8601 calendar system

30. What are the important packages for the new Data and Time API?

java.time

dates 

times 

Instants 

durations 

time-zones 

periods

Java.time.format

Java.time.temporal

java.time.zone

31. Explain with example, LocalDate, LocalTime, and LocalDateTime APIs.

LocalDate


Date with no time component

Default format - yyyy-MM-dd (2020-02-20)

LocalDate today = LocalDate.now();  // gives today’s date

LocalDate aDate = LocalDate.of(2011, 12, 30); //(year, month, date)

LocalTime


Time with no date with nanosecond precision

Default format - hh:mm:ss:zzz (12:06:03.015) nanosecond is optional

LocalTime now = LocalTime.now();  // gives time now

LocalTime aTime2 = LocalTime.of(18, 20, 30); // (hours, min, sec)

LocalDateTime


Holds both Date and Time

Default format - yyyy-MM-dd-HH-mm-ss.zzz (2020-02-20T12:06:03.015)

LocalDateTime timestamp = LocalDateTime.now(); // gives timestamp now

//(year, month, date, hours, min, sec)

LocalDateTime dt1 = LocalDateTime.of(2011, 12, 30, 18, 20, 30);

32. Define Nashorn in Java 8

Nashorn is a JavaScript processing engine that is bundled with Java 8. It provides better compliance with ECMA (European Computer Manufacturers Association) normalized JavaScript specifications and better performance at run-time than older versions.


33. What is the use of JJS in Java 8?

As part of Java 8, JJS is a command-line tool that helps to execute the JavaScript code in the console. Below is the example of CLI commands:


JAVA>jjs

jjs> print("Hello, Java 8 - I am the new JJS!")

Hello, Java 8 - I am the new JJS!

jjs> quit()

>>


Conclusion

All in all, Java is a prevalent programming language securing the second rank in popularity in both TIOBE and PYPL programming language ranking. The world's leading tech giants like Twitter, LinkedIn, Amazon, PayPal, etc., use Java to build their web apps and backend web systems. Java is also one of the primary languages used to develop Android apps; an operating system backed and promoted by Google.


As of today, there are 1,751,661 questions around Java on StackOverflow and 123,776 Java public repositories on GitHub and continuously increasing. Considering Java 8 to be one of the most stable versions, there are immense career opportunities and scope in the same. Just understand the concepts, implement them and get ready for the interviews!


Additional Resources


Practice Coding

Java MCQ

Java Tutorials

Spring Boot Interview Questions

Hibernate Interview Questions

How To Become A Java Developer

Online Java Compiler

Features of Java

Java 9 Features

Java IDEs

Java Frameworks

Highest Paying Jobs In India (IT Sector)

Java 8 MCQs

1.

Using Optional<T> type eliminates NullPointerException?



True


False

2.

Methods of Optional<T> class



get()


isPresent()


ofNullable()


map()


All of the above

3.

Which is not the type of Lambda Expression?



is a function type


is a functional interface


has no definite type when seen in isolation


depends on the context in which it appears

4.

Lambdas vs. Anonymous Inner classes - what is false?



Differ in their syntax



Thursday, May 5, 2022

Interview Question on Live Interview

 Ness Technology. 5-May-2022 Thursday @ 10:00 AM


1.  write a code for  

 Program : Find lowest and highest index of a specified number N in Sorted ArrayList.

eg. Input : [10, 12, 12, 12, 12, 50, 51, 89, 90, 1775, 1899] N=12 Output : [1, 4]


2. SQL : List all departments name and employee name having highest salary within department

Tables : Emp, Dept

3. How to improve performance of your application code side as well as Database side.

4. How do you copy A table to B table , with very huge datas.

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

Capgemini


@vallidation

Java 8

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

 Xabia

Memory leak methods in java 8

HTTPS configuration in Spring boot

Data base questions


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


Str_1 ="Hello how are you"
Str_2 ="wow"

can we make letters of one string to another string.

2. HashCode
3. equals methods
4. Java primitive type 
5. Java wrapper classes

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

Brillio

1. Linked list create you custom LinkList
2. System design
3. what is security , LoadBalancer, Central login ,  Availability, Chache, Redis, 
4. Create a system when need to compare product price , date of delivery from flipkart, amazone, myntra.

5.  Kafka
6. Synchronous  and asynchronous messages in microservices.

7. Compare price values and delivery date in JAVA-8.


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





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