KidusMT / JavaBook

Java Best Features

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JavaBook

Java Certifications

Static Methods and Default methods in Interface (Java +8)

You cannot override the static method of the interface; you can just access them using the name of the interface. If you try to override a static method of an interface by defining a similar method in the implementing interface, it will be considered as another (static) method of the class (a.k.a method-hiding).

  • Default vs static method conflict from parent interfaces, which one wins?
public interface Sup1 {
  static int myMethod() {
    return 1;
  }
}
public interface Sup2 {
    default int myMethod() {
        return 2;
    }
}
// when we implement both interfaces in the same class then the default method wins
public class Impl implements Sup1, Sup2 {

  public static void main(String[] args) {
    Impl s = new Impl();
    int val = s.myMethod();
    System.out.println(val);
  }
}

//prints
>> 2

Functional Programming in Java

  • Referential Transparency: any call to the program may be replaced with the corresponding return value without changing the result of the program (no side effects).

below is referential transparent method

int add(int a, int b) {
  return a + b
}

below is NOT, referential transparent method because replacing the method with the result will change the result of the program since the message will no longer be printed.

int add(int a, int b) {
  int result = a + b;
  System.out.println("Returning " + result);
  return result;
}
  • Higher Order Function: function taking function as an argument and also can returning a function as well.

  • First Class Citizen: That means that you can create an "instance" of a function, as have a variable reference that function instance. Java doesn't support first class citizen but the closest we have is with lambda expressions (assigning them to variables).

  • First Class vs Higher order

  • Covariant, Invariant, Contravariant

  • Functional Interfaces (a.k.a Single Abstract Method Interfaces or SAM Interfaces: It can have any number of **default**, **static** methods but can contain **only one abstract method**. It can also declare methods of **object class**.

        @FunctionalInterface
        public interface MyFunctionalInterface {
    
            public abstract void execute();
    
            @Override
            String toString();
    
            default void beforeTask() {
                System.out.println("beforeTask... ");
            }
    
            default void afterTask() {
                System.out.println("afterTask... ");
            }
        }
    • Consumer: accept(T t), andThen(Consumer<? super T> after)
    • Supplier: get()
    • Predicate: test(T t), and(Predicate<? super T> other), isEqual(Object targetRef), negate(), or(Predicate<? super T> other)
    • Function: apply(T t), identity(), compose(Function<? super V,? extends T> before), andThen(Function<? super R,? extends V> after)

The Stream API

image

[javapapers] -> https://javapapers.com/java/java-stream-api/

  • peek method is not stateful from the picture above

Generics Programming

Java 8 Interfaces

  • Default Methods inside methods
  • Static Methods inside methods

Java 8

 void display(){  
   class Local{  
       void msg(){System.out.println(data);}  
   }  
   Local l=new Local();  
   l.msg();  
 }  

for example: text and count are free variables

public static void repeatMessage(String text, int count) {
    Runnable r = () -> {
        for (int i = 0; i < count; i++) {
            System.out.println(text);
        }
    };
    new Thread(r).start();
}

Diamond Problem from stackoverflow

   A
  / \
 B   C
  \ / 
   D

Java Jigsaw

image

Java Optional

Optional.ofNullable(user);//Optional of Nullable value

Optional.of(notNullUserList);// Optional of Not Null value

return Optional.empty();// Empty Optional

// Consume if it is not Null
Optional<Address> optAddress = user.getAddress();
optAddress.ifPresent(System.out::println);

// Check if it is Not Null
Address address;
if(optAddress.isPresent){
    address = optAddress.get();
}

// Get if Object is Not Null, else return default
Address defaultAddress = new Address (....);
Optional<Address> optAddress = user.getAddress();
Address address = optAddress.orElse(defaultAddress);

// Get if Object is Not Null, else Throw Exception
Optional<Address> optAddress = user.getAddress();
Address address = optAddress.orElseThrow(UserNotFoundException::new)

// Get Value
Optional<Address> optAddress = user.getAddress();
Address address = optAddress.get();

Important Notes

Java Notes:

Order of Execution in Java

image

// static blocks
static int a;

static {
   a = 5;
   System.out.println("this is a static block");
}

// instance initialization block
int a;

{
    a = 5;
    System.out.println("this is instance initialization block");
}

Random Topics

public interface FlyBehaviour{
   // no method in here - empty
}
  • [Formatting Currency]
public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();
        
        // Write your code here.
        
        String us = NumberFormat.getCurrencyInstance(Locale.US).format(payment);
        String india = NumberFormat.getCurrencyInstance(new Locale("en", "in")).format(payment);
        String china = NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment);
        String france = NumberFormat.getCurrencyInstance(Locale.FRANCE).format(payment);
        
        System.out.println("US: " + us);
        System.out.println("India: " + india);
        System.out.println("China: " + china);
        System.out.println("France: " + france);
    }
}

Final Keyword

Value Type vs Reference Type

image

image

Method Overriding vs Method Hidding

image

Java Monands

Comparator vs Comparable

Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.

About Amazon Corretto

Iterable to Collections

ArrayList<E> list = new ArrayList<>();
iterable.forEach(list::add);