Things That I Didn’t Know Before Reading This Book: Head First Java #5

Farhan Pratama
2 min readAug 31, 2023

Hi everyone, I am writing this article as I read the Head First Java book and want to share what I have learned. The reason why I chose this book is because a lot of people recommend it and it’s beginner-friendly. Also, it can help improve my understanding of fundamental Java. Let’s begin!

How HashSet works

HashSet holds non-duplicated objects. But how does a HashSet check for duplicates?

A HashSet check from the hashCode() and equals() method. The first thing HashSet calls is the hashCode() method to check if there are any objects that are already in the set, If there are any then HashSet will call the equals() method to check if the objects are really equals.

a.equals(b) must also mean that a.hashCode() == b.hashCode()

But a.hashCode() == b.hashCode() does NOT have to mean a.equals(b)

Wildcards

Take a look at this method

public void takeAnimals(List<? extends Animal> animals){
for (Animal a: animals){
a.eat()
}
}

It looks unusual, but there’s a way to create a method argument that can accept a List of any Animal subtype. The simplest way is to use a wildcard

How streams work

Take a look at this code

List<String> result = strings.stream()
.sorted()
.skip(2)
.limit(4)
.collect(Collector.toList());

There are 2 operations on our stream, the intermediate and terminal. The intermediate operation is the sorted(), skip(), and limit() method. The terminal operation is the collect() method. Since intermediate operations are lazy, it’s up to the terminal operation to do everything.

  1. Perform all intermediate operations as efficiently as possible. Ideally, just going through the original data once
  2. Work out the result of the operation, which is defined by the terminal operation itself. For example, this could be a list of values, a single value, or a boolean (true/false)
  3. Return the result

Checked Exceptions

All exceptions the compiler cares about are called “checked exceptions” which really means compiler-checked exceptions. Only RuntimeExceptions are excluded from compiler checking. All other exceptions must be acknowledged in your code.

Handle or Declare the exception

  1. Handle

Wrap the risky call in a try/catch block

try{
laundry.doLaundry();
} catch(ClothingException e){
// recovery code
}

2. Declare (duck it)

Declare that your method will throw an exception, so the one who calls your method has to handle the exception (either handle it or declare it)

void foo() throws ClothingException {
laundry.doLaundry();
}

That’s it for the fifth part of this article series, I will be sharing more interesting facts about Java from this book in the next articles! Thank you and bye!

--

--

Farhan Pratama

Fresh Graduate | Software Engineer | Business Analyst | Writer