Han's Poignant JAVA Diary

Han's Poignant JAVA Diary

土偶

Resources

Introduction

JAVA is a programming language, you can use it to command the machine works for you.

Class and Main Method

3000 years ago, someone made a great clay figure. Today, we will make the clay figure great again, with JAVA.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
    }
}

I guess you can write down the code above on the paper with pencil and with your eyes closed.(Just kidding, for Java's sake don't do that.) But you might not know what you are doing, what have you created. Let's break it down.

You have created a Class . Just like the clay figure has head and body, so does the Class . The head defines what the class is, while the body contains its behaviors and properties.

public class ClayFigure // the HEAD
{                                                   // everything
    public static void main(String[] args) {        // between the
        System.out.println("Hello, clay figure!");  // curly braces
    }                                               // belongs to
}                                                   // the BODY

In the Class , the main Method also has head and body.

The main() method is where your program starts running.

public static void main(String[] args) // this is the HEAD
{                                              // everything between
    System.out.println("Hello, clay figure!"); // the curly braces
}                                              // belongs to the BODY

Define and Call Method

You don't know the main method is a Method ? Now you do. Let's define another Method . Remember? Head and Body.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
    }
 
    public static void laugh() {
        System.out.println("ha");
    }
}

Now we have method laugh , which is public static void , and in its body, it prints out "ha". Let's call the laugh method in the main method.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
        laugh();
    }
 
    public static void laugh() {
        System.out.println("ha");
    }
}

It seems our clay figure is happy, let's make it happier.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
        laugh();
        laugh();
        laugh();
        laugh();
    }
 
    public static void laugh() {
        System.out.println("ha");
    }
}
 

Yes, you can use name of the method followed by () to call the method. The () is called parentheses . You can put arguments inside the parentheses. Let's make the clay figure laugh 40 times...

You don't want to write laugh(); 40 times? Of course. You can use a loop to do that.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
        for (int i = 0; i < 40; i++) {
            laugh();
        }
    }
 
    public static void laugh() {
        System.out.println("ha");
    }
}
 
  • Postfix (i++, i--): The variable is used first, then changed.
  • Prefix (++i, --i): The variable is changed first, then used.

Arguments and Parameters

Or we can make the method laugh smarter.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
        laugh(40);
    }
 
    public static void laugh(int timesOrWhatever) {
        for (int i = 0; i < timesOrWhatever; i++) {
            System.out.println("ha");
        }
    }
}

That looks better. When we call the method, we passed an argument to the method. The argument is 40 . The argument is stored in the parameter named timesOrWhatever , which has type int . The parameter is like a variable, but it only exists in the method.

  • When you call the method, the thing between the parentheses is the argument . Arguments are the actual values you provide when you call the method.
  • When you define the method, the thing between the parentheses is the parameter . Parameters are variables that are placeholders for the data you want to pass into a method.

AI explain parameter (opens in a new tab)

Some of you might have realized that the main method has String[] args as its parameter. String[] means an array [] of strings String . args is the name of the parameter. You can name the parameter whatever you like.

Overloading

Can we make the clay figure laugh with different sounds? Yes, we can.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
        laugh(4);
        laugh(2, "he");
        laugh(1, "ho");
    }
 
    public static void laugh(int timesOrWhatever) {
        for (int i = 0; i < timesOrWhatever; i++) {
            System.out.println("ha");
        }
    }
 
    public static void laugh(int timesOrWhatever, String sound) {
        for (int i = 0; i < timesOrWhatever; i++) {
            System.out.println(sound);
        }
    }
}

We have two laugh methods. The first one has one parameter, the second one has two parameters. The two methods have the same name, but different parameters. This is called overloading .

A method is overloaded if there are multiple versions with the same name but different parameters.

Return Type

But what is the void in public static void ?

It is the return type of the method. void means the method does not return anything. If the method returns something, you should replace void with the type of the thing it returns. For example, if the method returns a number, you should use int . If the method returns a string, you should use String .

When you go to a ramen restaurant, you are expecting a bowl of ramen. Same to the return type of the method.

Let's make methods to return the weight and height of the clay figure.

public class ClayFigure {
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
 
        System.out.println("Weight: " + weight());
        System.out.println("Height: " + height());
    }
 
    // https://bunka.nii.ac.jp/heritages/detail/515725
    public static int weight() {
        return 1440;
    }
 
    public static double height() {
        return 34.2;
    }
}

The weight method returns an int , the height method returns a double . You can use the return keyword to return the value, remember to match the return type .

Class, Instance, Object

  • Class: The blueprint of the clay figure.
  • Object: The clay figure.
  • Instance: Same as object. Usually used to say "This object is an instance of that class".
blueprint on the left, clay figure on the right

When you have a blueprint(class), you can create as many clay figure(instance) as you want. To create an instance , you can use the new keyword followed by the class name and () .

ClayFigure clayFigureAomori = new ClayFigure();
// the ClayFigure on the left is the type of the variable
// when you create a class, you are also creating a new type
  • ClayFigure : This is the class name. It acts as the blueprint for creating objects, just like a recipe for a dish or a design for a clay figure.
  • clayFigureAomori : This is the variable name. It refers to the instance (or object) you create from the class ClayFigure . The name clayFigureAomori gives this specific object a unique identity, as if we were naming the clay figure based on where it was found (in 青森).
  • new ClayFigure() : The new keyword creates a new instance of the ClayFigure class. The part ClayFigure() is calling the constructor. A constructor?

Constructor

constructor loves you

Let's create a simple class:

public class ClayFigure {
 
}

This is an empty class called ClayFigure. Now, let's add a constructor:

public class ClayFigure {
 
    public ClayFigure() {
        System.out.println("This is the constructor");
    }
}
  • The constructor has the same name as the class (ClayFigure).
  • Inside the constructor, we added a simple System.out.println("This is the constructor"); to show that the constructor runs when an object is created.

Let's create an object using the new keyword:

public class ClayFigure {
 
    public ClayFigure() {
        System.out.println("This is the constructor");
    }
 
    public static void main(String[] args) {
        // Create a new object of ClayFigure
        ClayFigure myFigure = new ClayFigure();
    }
}

When you run this code, you will see:

This is the constructor

This shows that the constructor is automatically called when you create a new object (new ClayFigure();).

  • A constructor:
    • Has no return type (not even void).
    • Must have the same name as the class.
    • Is automatically called when an object is created (new ClayFigure()).
  • You can overload constructors to provide different ways of initializing objects.
  • If you don't define a constructor, Java will automatically provide a default no-argument constructor.

A constructor is used to create objects, while a method is used to perform actions. Even though a constructor looks a bit like a method, it's different.

public class ClayFigure {
 
    // This is the constructor
    public ClayFigure() {
        System.out.println("This is the constructor");
    }
 
    // This is a method
    public void ClayFigure() {
        System.out.println("This is a method");
    }
 
    public static void main(String[] args) {
        // Create an object (calls the constructor)
        ClayFigure myFigure = new ClayFigure();
 
        // Call the method
        myFigure.ClayFigure();
    }
}

When you run this code, it prints:

This is the constructor
This is a method
  • Constructor:
    • It has no return type (not even void).
    • It has the same name as the class.
    • It is called automatically when you create a new object (new ClayFigure();).
  • Method:
    • It has a return type (like void, int, etc.).
    • It can have any name (it could but doesn't have to match the class name).
    • It is called manually when you want to perform some action (e.g., myFigure.ClayFigure();).

Class Variable, Instance Variable, Local Variable

public class ClayFigure {
 
    // https://bunka.nii.ac.jp/heritages/detail/515725
    public int weight = 1440; // instance variable
    public static double height = 34.2; // class variable
 
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
 
        // create an instance of the class
        ClayFigure clayFigureAomori = new ClayFigure();
 
        int age = 3000; // local variable
 
        // access the instance variable from the instance clayFigureAomori
        System.out.println("Weight: " + clayFigureAomori.weight);
 
        // access the class variable from the class ClayFigure
        System.out.println("Height: " + ClayFigure.height);
 
        // access the local variable by its name
        System.out.println("Age: " + age);  
    }
}

Class Variable: use keyword static

class Example {
    static int classVariable = 10; // class variable
}

Definition: A class variable is declared with the static keyword inside a class but outside any method, constructor, or block. It belongs to the class, not to any particular instance. All instances share this variable.

  • Declared with static keyword.
  • Shared among all instances of the class.
  • Accessed via the class name (e.g., ClayFigure.height ).

In Java, certain classes provide useful constants like Math.PI , Integer.MAX_VALUE , and Double.MIN_VALUE . These constants are class variables , also known as static variables.

A class variable belongs to the class itself, rather than to instances of the class. You can access these variables without creating an object, simply by using the class name followed by . and the variable name .

public class ClayFigure {
 
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
 
        System.out.println("PI: " + Math.PI);
        System.out.println("MAX_VALUE: " + Integer.MAX_VALUE);
        System.out.println("MIN_VALUE: " + Double.MIN_VALUE);
    }
}

The Math class, as well as Integer , Double , and others, belong to the java.lang package. The java.lang package is automatically imported into every Java program, meaning you don't need to write an explicit import statement for classes in this package.

When you print Double.MIN_VALUE , you will see a small number: 4.9E-324 . This is an example of scientific notation, a way of representing very small or very large numbers concisely. 4.9E-324 means 4.9 × 10^(-324) , E is the exponent.

Instance Variable: without keyword static

class Example {
    int instanceVariable = 5; // instance variable
}

Definition: An instance variable is declared inside a class but outside any method, constructor, or block. It belongs to an instance of the class. Each object of the class has its own copy.

  • No static keyword.
  • Each object has its own copy of the variable.
  • Accessed via the object reference (e.g., clayFigureAomori.weight ).

static can also be used for method , so there are class method and instance method .

Local Variable: inside a method

class Example {
    void method() {
        int localVariable = 1; // local variable
    }
}

Definition: A local variable is declared inside a method, constructor, or block. It is only accessible within the block where it is declared.

  • Declared within methods or blocks.
  • Exists only during the execution of the method or block.
  • Not accessible outside its scope.

Since local variables are only accessible within the specific block or method where they are declared, there's no need for access modifiers like private , public , or protected . These modifiers control accessibility between classes or objects, which is not relevant for local variables because they can't be accessed from outside the method or block where they are defined.

Access Modifier: public, protected, default, private

When you meet someone, you allow them to access your name(which is public), but not your bank account password(which is private).

Access modifiers ( private , public , protected , etc.) are used to control how variables or methods of a class can be accessed from other classes or instances.

public int weight = 1440; // public: everyone can access it
int age = 3000; // default: all the class in current package can access it
protected String name = "Clay Figure"; // protected: same to default, and its subclasses can access it
private double height = 34.2; // private: only accessible within the class

Todo: explain package

Let's create a mypackage folder and put file ClayFigure.java and Box.java in it.

mypackage/ClayFigure.java
package mypackage;
 
public class ClayFigure {
 
    private int weight = 1440;
    protected double height = 34.2;
    public String name = "Clay Figure";
    int age = 3000;
 
    public static void main(String[] args) {
        System.out.println("Hello, clay figure!");
    }
 
    public static void laugh(int timesOrWhatever) {
        for (int i = 0; i < timesOrWhatever; i++) {
            System.out.println("ha");
        }
    }
 
    public static void laugh(int timesOrWhatever, String sound) {
        for (int i = 0; i < timesOrWhatever; i++) {
            System.out.println(sound);
        }
    }
}
mypackage/Box.java
package mypackage;
 
public class Box {
  public static void main(String[] args) {
 
    ClayFigure ClayFigureInstance = new ClayFigure();
 
    System.out.print("There is a ");
    System.out.println(ClayFigureInstance.name);
 
    System.out.print("The age is ");
    System.out.println(ClayFigureInstance.age);
    System.out.print("The height is ");
    System.out.println(ClayFigureInstance.height);
 
    // uncomment the following line and see the error
    // comment it back then
    // System.out.println(ClayFigureInstance.weight);
 
  }
}

Todo: create exercise about duck class, duck color: white duck, yellow duck, black duck. duck type: living duck, dead duck, rubber duck class name for class variable this for instance variable

Japanese Tech Words

  • 実行(じっこう): execute
  • メソッド : method
  • クラス : class
  • インスタンス : instance
  • 変数(へんすう) : variable
  • 引数(ひきすう): argument
  • パラメータ : parameter
  • 戻り値 : return value
  • クラス変数 : class variable
  • インスタンス変数 : instance variable
  • オーバーロード : overload
  • ループ : loop
  • メインメソッド : main method

To be continued...

Do not shoot this.