Friday, February 7, 2025

Core Java I note

 


jshell>"Hello".length()

use """ for string text block 

public abstract sealed class JSONValue permits JSONArray, JSONNumber,JSONString{...}

case Executive exec -> "An executive with a title of " + exec.getTitle()


public interface Predicate<T> { boolean test(T t);...}

list.removeIf(e->e==null);


Supplier<Integer> die = ()->(int)(Math.random()*6)+1;

int outcome = die.get();

LocalDate hireDay = Objects.requireNonNullElseGet(day,()->LocalDate.of(1970,1,1));


Method References:

var timer = new Timer(1000,event->System.out.println(event));

it would be nicer to pass the println method: var timer = new Timer(1000,System.out::println);

Runnable task = System.out::println;

Arrays.sort(strings,String::compareToIgnoreCase)

object::instanceMethod like System.out::println the object is System,.out 

Class::instanceMethod String::compareToIgnoreCase is the same as (x,y)->x.compareToIgnoreCase(y)

Class::staticMethod Math::pow is equivalent (x,y)->Math.pow(x,y)

A lamda expression can only be rewritten as a method reference if the body of the lamda expression calls a single method and doesn't

do anything else.

list.removeIf(Objects::isNull); a bit easier to read than list.removeIf(e->e==null);


Constructor References

are just like method references, except that the name of the method is new.

ArrayList<String> names = ...;

Stream<Person> stream = names.stream().map(Person::new);

List<Person> people = stream.toList();


service loaders 

META-INF/services 

public static ServiceLoader<Cipher> cipherLoader = ServiceLoader.load(Cipher.class);

EquityDecision

boolean isEnter(Path dataPath, String dateStr);

boolean isExit(String ric, String dateStr);


The Java Language Specification calls any exception that derives from the class Error or the class RuntimeException

an unchecked Exception. All other exceptions are called checked exceptions.

The compiler checks that you provide exception handlers for all checked exceptions.

RuntimeException: Null pointer access, , an out-of bound array access, a bad cast

checked exception: trying to open a file that doesn't exist.

The rule "If it is a RuntimeException, it was your fault" works pretty well.


System.getLogger("com.mycompany.myapp").log(INFO,"Opening file " + filename);

No comments:

Post a Comment