Skip to content

Latest commit

History

73 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

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?
publicinterfaceSup1 {
staticintmyMethod() {
return1;
}
}
publicinterfaceSup2 {
defaultintmyMethod() {
return2;
}
}
// when we implement both interfaces in the same class then the default method winspublicclassImplimplementsSup1, Sup2 {
publicstaticvoidmain(String[] args) {
Impls = newImpl();
intval = 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

intadd(inta, intb) {
returna + 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.

intadd(inta, intb) {
intresult = a + b;
System.out.println("Returning " + result);
returnresult;
}
  • 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**.

    @FunctionalInterfacepublicinterfaceMyFunctionalInterface {
    publicabstractvoidexecute();
    @OverrideStringtoString();
    defaultvoidbeforeTask() {
    System.out.println("beforeTask... ");
    }
    defaultvoidafterTask() {
    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

voiddisplay(){ classLocal{ voidmsg(){System.out.println(data);} } Locall=newLocal(); l.msg(); } 

for example: text and count are free variables

publicstaticvoidrepeatMessage(Stringtext, intcount) {
Runnabler = () -> {
for (inti = 0; i < count; i++) {
System.out.println(text);
}
};
newThread(r).start();
}

Diamond Problem from stackoverflow

 A
/ \
B C
\ / D

Java Jigsaw

image

Java Optional

Optional.ofNullable(user);//Optional of Nullable valueOptional.of(notNullUserList);// Optional of Not Null valuereturnOptional.empty();// Empty Optional// Consume if it is not NullOptional<Address> optAddress = user.getAddress();
optAddress.ifPresent(System.out::println);
// Check if it is Not NullAddressaddress;
if(optAddress.isPresent){
address = optAddress.get();
}
// Get if Object is Not Null, else return defaultAddressdefaultAddress = newAddress (....);
Optional<Address> optAddress = user.getAddress();
Addressaddress = optAddress.orElse(defaultAddress);
// Get if Object is Not Null, else Throw ExceptionOptional<Address> optAddress = user.getAddress();
Addressaddress = optAddress.orElseThrow(UserNotFoundException::new)
// Get ValueOptional<Address> optAddress = user.getAddress();
Addressaddress = optAddress.get();

Important Notes

Java Notes:

Order of Execution in Java

image

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

Random Topics

publicinterfaceFlyBehaviour{
// no method in here - empty
}
  • [Formatting Currency]
publicclassSolution {
publicstaticvoidmain(String[] args) {
Scannerscanner = newScanner(System.in);
doublepayment = scanner.nextDouble();
scanner.close();
// Write your code here.Stringus = NumberFormat.getCurrencyInstance(Locale.US).format(payment);
Stringindia = NumberFormat.getCurrencyInstance(newLocale("en", "in")).format(payment);
Stringchina = NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment);
Stringfrance = 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

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.

Iterable to Collections

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

Releases

Packages

Contributors