Java from Basics to Mastery — Part 2
Connecting variables, conditional statements, loops, and methods
The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.
Java programs store values in variables and create flows with conditions and repetition. Breaking up long code into methods allows you to reuse the same rules and make inputs and outputs clear.
Base types and reference types
int level = 10;
double speed = 4.5;
boolean alive = true;
String name = "Rose";
Basic type variables such as int and boolean contain values. String and self-created class type variables contain references pointing to objects.
Local variables must be initialized before use. The compiler does not automatically correct the intent for calculations that exceed numeric ranges and integer division.
Conditions and Repetition
if (health <= 0) {
state = "Dead";
} else if (health < 30) {
state = "Danger";
} else {
state = "Normal";
}
int total = 0;
for (int damage : damages) {
if (damage > 0) {
total += damage;
}
}
if divides the flow according to true and false, and for repeats a set range. Because exceptions or omissions may occur if you directly modify the collection being iterated, it is safer to create a separate result list.
method
static int calculateDamage(int attack, int defense) {
if (attack < 0 || defense < 0) {
throw new IllegalArgumentException("stats must be positive");
}
return Math.max(1, attack - defense);
}
A method declaration includes the return type, name, and parameter type. The caller can give input and receive results without having to know the entire implementation.
Early checking for input that cannot be processed prevents the normal flow from deepening its indentation. You should make sure that the method is a responsibility that can be described with a single name rather than a number of lines.