Skip to content

Releases: TinyTank800/LearningJava

Day 4 – Exceptions & Logging

20 Sep 23:17
Compare
Choose a tag to compare

Day 4 – Exceptions & Logging

Q1:

What’s the difference between checked and unchecked exceptions?

Example:

Write a method that tries to read a file. If it doesn’t exist, handle the exception.

Requirement:

  • You can explain checked vs unchecked exceptions.
  • You can write try/catch/finally.
  • You know when to declare throws in a method signature.

Q2:

How do you create and use a custom exception?

Example:

Create an InvalidHealthException that extends RuntimeException. Throw it if a player’s health is set below zero.

Requirement:

  • You can define a new exception class.
  • You can throw exceptions with throw new ....
  • You can catch and handle custom exceptions.

Q3:

Why is logging better than System.out.println for debugging?

Example:

Add java.util.logging (or SLF4J/Logback if you prefer). Log messages at INFO, WARN, and ERROR levels when certain actions happen.

Requirement:

  • You can configure a logger.
  • You can log at different levels (info, warning, error).
  • You understand why logging is preferred over println.

Mini-Project:

Add robust error handling + logging to your previous “game” project.

  • If a player’s health is set below 0, throw a custom exception.
  • Log key game events (Player joined, Player attacked, Player defeated) at INFO level.
  • Log errors (like invalid input) at ERROR level.

Requirement:

  • You can integrate exceptions with game logic.
  • You can use logging to trace program flow.
  • You can clearly separate error handling from normal control flow.

Notes

  • Unchecked are not enforced by compiler and happen at runtime.
  • Checked MUSt be declared or caught as compiler enforces them.
  • Try catch will catch any exception thrown in the try block.
  • Finally will execute no matter what after the try/catch. Usually used for cleanup code.
  • Throws allows you to declare that a method might throw an exception.
  • You can make your own exception by extending Exception or RuntimeException.
  • Logging to a logger allows control over level as well as formatting of messages.
  • Using a logger also allows for better tracking of where and file logging.
  • Also helps keep imports down to one logging library instead of many System.out.println calls.
  • skipped mini project as code already shows same patterns it wanted me to make.

Day 3 – Generics, Enums, Records

17 Sep 02:32
Compare
Choose a tag to compare

Day 3 – Generics, Enums, Records

Q1:

Why do generics exist in Java?

Example:

Create a generic Box<T> class that can hold any type. Put an Integer in one and a String in another.

Requirement:

  • You can declare and use a generic class.
  • You can use type parameters (<T>) correctly.
  • You understand how generics improve type safety and reduce casting.

Q2:

How would you model Minecraft items with an enum?

Example:

Create an enum ItemType { SWORD, PICKAXE, BOW } with custom fields for durability and attack power. Print their values.

Requirement:

  • You can define an enum with constants.
  • You can add fields and methods to an enum.
  • You can iterate over enum values.

Q3:

What are Java records and why are they useful?

Example:

Create a record Position(int x, int y) and instantiate it. Use its built-in methods like toString(), equals(), and accessors.

Requirement:

  • You can declare a record.
  • You understand that records are immutable data carriers.
  • You can use their auto-generated methods.

Mini-Project:

Build a small Inventory system:

  • Use a List<Box<ItemType>> to store items.
  • Create an enum for item types with durability.
  • Represent a player’s inventory as a record with playerName and their item list.

Requirement:

  • You can combine generics, enums, and records in one small program.
  • You can print a summary of the inventory using streams or loops.

Notes

  • Dont fully understand generics or when they are really used but did learn they are good for functions/classes which can take any type and do the same thing with them. Example reading a key value pair.
  • Enums are a way to define a set of custom types with custom fields when used with a constuctor. They can also have methods.
  • Records are a good way to make immutable data objects with auto generated methods, getters, setters, constuctors and such.
  • I made a quick inventory using a record for the inventory to hold playername and a list of items.
  • these items were held inside a generic box class which was using an enum for its item type and since the enum had data i could track durability and damage from it.
  • The Generics allowed me to make a unique object which was cast to an enum type that contained all data i needed. The record then allowed me to store an inventory of unique items for each player using the built in constructors and methods.
  • Records cannot be changed after creation(immutable) so i cant add or remove items from the player. Better to use a hashmap or similar for that.

Day 2 – Collections, Streams, Lambdas

14 Sep 23:08
Compare
Choose a tag to compare

Day 2 – Collections, Streams, Lambdas

Q1:

What’s the difference between a List and a Set?

Example:

Create a List<String> of 5 player names. Create a Set<String> with the same names, but include a duplicate. Print both collections and compare the results.

Requirement:

  • You can add, remove, and get elements from a List.
  • You understand that a Set removes duplicates and has no guaranteed order.

Q2:

What is a Map used for, and how is it different from a List?

Example:

Create a Map<String, Integer> where the key is a player name and the value is their score. Add 3 entries, update one score, and print the results.

Requirement:

  • You can insert, update, and get values by key.
  • You know that a Map does not allow duplicate keys.

Q3:

What does a lambda expression let you do in Java?

Example:

Given a List<String>, use .forEach() with a lambda to print each name in uppercase.

Requirement:

  • You can write a lambda like n -> System.out.println(n).
  • You can use .forEach() with a lambda to process each element.
  • You understand that a lambda is a shorter way of writing an anonymous function.

Q4:

How do streams help with data processing compared to loops?

Example:

From a List<String> names, use a stream to filter only names that start with "A". Collect the results into a new List<String> and print them.

Requirement:

  • You can filter elements in a stream.
  • You can transform (map) values in a stream.
  • You can collect results into a List or Set.

Mini-Project:

Build a simple “Leaderboard.”

  • Use a Map<String, Integer> to store player → score.
  • Use a stream to sort players by score (highest first).
  • Print the ranking in the format:
  1. Alice - 50
  2. Bob - 40
  3. Charlie - 20

Requirement:

  • You can combine Map, streams, and lambdas.
  • You can sort by value instead of key.
  • You can print a leaderboard showing rank, player, and score.

Notes

  • Tried to create a set with duplicates set already using set.of() but that threw an error for duplicate objects.
  • had to use the same list set with duplicates and use set.CopyOf() method which cuts off the duplicates.
  • Sets also seem to have no order.
  • Since creating a list.of() makes an immutable list, I had to create a new arraylist and pass the list.of() to it to be able to add, remove, or update elements.
  • Map is also immutable so creating a new hashmap with map of lets you add.
  • Streams allow you to process maps/collections in a functional way.
  • Using the stream you can then sort that stream with a custom comparator.
  • I used Map.Entry.comparingByValue() to turn the stream into a map of entries then set the compare by value to be a key value set and compare by the values.
  • Reverse makes it go from highest to lowest instead of lowest to highest.
  • Then used a lambda off the stream to upsert the results into a new map and display that using another lambda foreach.
  • Linked has map had to be used as normal hashmap does not contain order of insertion.

Day 1 - Classes, Objects, Inheritance

14 Sep 17:05
Compare
Choose a tag to compare

Day 1 – Classes, Objects, Inheritance

Q1: What’s the difference between a class and an object?

Example: Write a Player class with fields name and health. Create two Player objects with different names.

Requirement:

  • You can define a class with fields and methods.
  • You can instantiate multiple objects.
  • You can extend a class (e.g., Warrior extends Player).

NOTES:
After starting with a basic player class with fields for name and health, I created two player objects with different names.
After the original players I made a warrior class that extended player and added additional functionality like attacking.
After that was created I added the initial game logic and game start logic to make a "game".
This would create a list of players and make them have random attack amounts and fight till only one of them was left.
I made sure to try and keep values final and static where needed to ensure immutability.
Ended up having to go away from a for loop because it would error when removing items/players from the list.
I found out that was due to the for loop using an iterator and would error since a value its trying to loop was removed.