Introduction to Java that can be understood even with Krillin (Part 1)

Collect from arrays to object-oriented. Please for review (Not particularly related to the title Krillin)

--The following simple grammar is omitted-- if syntax if-else if-else syntax swith statement while statement do-while statement for statement

Array

Only the same type of data can be stored in each element of the array. (For int, only int, only String, etc.) Subscripts (index) count from 0. (Element 0th ~)

Array creation procedure

Let's create a String type array.

//Define String type array variable dragonBall
String[] dragonBall;
//Create 7 String type elements and assign them to complete the array dragonBall
dragonBall = new String[7]; 

//It is also possible to create in one line
String[] dragonBall = new String[7];

I want to know the number of elements in an array

Use ** length **. If you do System.out.println (dragonBall.length);, 7 will be output.

I want to assign an element to an array

When substituting a two-star sphere (Arshinchu) for the second (first element) of the array dragonBall dragonBall [1] =" Two-star ball ";

Array elements are automatically initialized

What if I output an element with nothing assigned to the array?

String[] dragonBall = new String[7];
System.out.println(dragonBall[0]);

↑ null is output and no error occurs. Arrays are automatically initialized just like ints and Strings. ・ Int, double type ⇒ 0 ・ Boolean type ⇒ false ・ String type ⇒ null

Create and initialize the array at the same time

There are the following two patterns of description methods. ① int [] score1 = new int [] {20,30,40,50}; ⇒ An array of 4 elements is created ② int [] score2 = {20,30}; ⇒ An array of two elements is created

for statement and array

Variables can be used as subscripts for arrays.

public class Main {
    public static void main(String[] args){
        int[] score = {10,20,30};
        for(int i =0 ; score.length ; i++){ //4th line
            System.out.println(score[i]);
        }
    }
}

The variable i changes to 0,1,2. This is called ** turning an array **. By using "length" on the 4th line, the number of elements does not change even if the initial value is changed. There is an advantage that no code modification is required.

Extended for statement

The extended for statement is convenient when you simply want to rotate all array types. for (type variable name: array) {}

int[] score = {10,20,30};
for(int value : score){
    System.out.println(value);
}

As for the movement, the value of the first week is 10 and the value of the second week is 20. It will rotate by the number of elements.

reference

Take a look at the following code. What is in the output b?

int a = 1;
int b = a;
a = 2;
System.out.println(b);

1 is entered in b. Since it was assigned when a = 1, it does not matter what is assigned to a after that.

However, it changes with an array.

int[] a = {1};
int[] b = a;
a[0] = 2;
System.out.println(b[0]);

2 is entered in b. The array a does not contain any direct values. It only knows where the value is. This is called ** reference **. In int [] b = a;, the location is shared.

If you compare a place to an address, Mr. A puts a banana in room 101. With B = A, Mr. A tells B the room number. Mr. A adds an apple. When Mr. B goes to Room 101, there are bananas and apples.

Two-dimensional array

Two-dimensional array example int[][] scores = new int[2][3]; There are two boxes, each containing three boxes. [0] ⇒ [0][1][2] [1] ⇒ [0][1][2] A total of 6 boxes will be prepared.

Exercises.java


public class Main {
    public static void main(String[] args){
        int[][] scores = {{10,20,30}, {40,50,60}};
        System.out.println(scores[1][1]);
        System.out.println(scores.length);
        System.out.println(scores[0].length);
        }
    }
}

Execution result.


50
2
3

Method

Creating a method is called ** method definition **. To use it is called ** calling a method **. The "{}" part after the method name is called the method block. It can be called with method name ();.

public static void main(String[] args){
    methodA();
}
public static void methodA(){
    System.out.println("Called method A");
}

argument

You can pass a value to the method, which is called a ** argument **. More specifically, the value to be passed is called ** actual argument **, and the value to be received is called ** formal argument **.

The side that passes the argument method name (value); Argument recipient ~ method name (variable to which argument type argument is assigned) {}

public static void main(String[] args){
    methodA("Krillin");
}
public static void methodA(String name){
    //The argument krillin is included in the variable name.
    System.out.println(name + "Mr. is.");
}

Pass multiple arguments

Example: The side that passes the argument method name (" Krillin ", 20); Argument recipient ~ method name (String name, int age) {}

Local variables

Local variable independence

Variables declared in a method are called ** local variables **. Local variables are valid only within the method to which the variable belongs. (The effective range is called the scope) It is different from the local variable with the same name declared by another method.

Return value

Returning a value is called ** returning a value **. The data (value) returned is called ** return value **. return statement ⇒ return Return value; You can return the value with.

public static return type method name(Type variable){
return Return value;
}

If there is no value to return, change the "return type" part. Make it "void" which means that nothing is returned.

Return value utilization example.java


public static void main(String[] args){
    int a = 10;
    int b = 20;
    int total = tasu(a, b); //Since the return value is returned, substitute it for total
    System.out.println("The total is" + total + "is.");
}
//Method to add
public static int tasu(int x, int y){
    return x+y;
}

Since the return statement also terminates the method, an error will occur even if code is written after the return statement.

Overload

Defining a method with the same name is called ** overload **. Even if the method name is the same, there is no problem even if it is defined if the formal argument type and the number of arguments are different. It will automatically determine when you call the method.

public static int add(String x, int y){
    return x+y;
}
public static int add(int x, int y){
    return x+y;
}
public static int add(int x, int y,int z){
    return x+y+z;
}

If you call add (" Krillin ", 20), the top method will be called properly.

Pass by reference

Passing the value itself in the sample code so far is called ** passing by value **. Passing an array is called ** passing by reference **.

Reference passing example.java


public class Main {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        //Pass an array (pass by reference).
        printArray(array);
    }
    public static void printArray(int[] array){
        for(int element : array){
            System.out.println(element);
        }
    }
}

Reference passing example 2.java


public class Main {
    public static void main(String[] args) throws Exception {
        int[] array = {1,2,3};
        intArray(array);
        
        for(int i : array){
            System.out.println(i);
        }
    }
    public static void intArray(int[] array){
        for(int i = 0; i < array.length; i++){
            array[i]++;
        }
    }
}

The execution result will be 2,3,4. The value of the array array changes even though it is not returned as a return value Because the array type is a reference type.

Classes and packages

By using ** class **, one program can be divided into multiple parts, that is, ** parts **, Development can be shared. As the number of classes increases, it can be further divided into parts using ** packages **. -The first letter of the class name must be uppercase. -The first letter of the package name is basic lowercase. -Since the packages are independent, it is possible to create the same class name for each package. -The dot "." Is often included in the package name. -When using a package other than your own, you need to attach the package you belong to.

Example: In a certain class of movie package I want to use the tasu method of the CalcLogic class of the Calc.app package. int total = calc.app.CalcLogic.tasu(a,b);

A class like this with the package name at the beginning ** full qualified class name ** It is abbreviated as ** FQCN **.

Package benefits

--If you develop it separately for each package, ** name collision ** will not occur even if the class name is shared with others. --It is recommended that the package name is the reverse of the domain. (foo.exsample.com ⇒ com.exsample.foo)

The domain is unaffected by anyone in the world.

Import statement

import statement: FQCN description can be omitted. import package name.class name;

The amount of description is reduced as follows. int total = calc.app.CalcLogic.tasu(a,b); ⇒ int total = CalcLogic.tasu(a,b);

It's hard if you have a lot of classes you want to import. Use an asterisk when you want to import all classes. For the calc.app package import calc.app*;

API ** API ** is like a useful formula. Import java.util. * To use automatic sorting with java.util.Arrays.sort ().

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        int[] heights = {20,35,10};
        java.util.Arrays.sort(heights);
        for(int h : heights){
            System.out.println(h);
        }
    }
}

The execution result will be 10,20,35.

API meaning
java.lang Required classes
java.util Convenient classes
java.math Math classes
java.net Internet communication class group
java.io File read / write,Data processing classes

java.lang is imported automatically. You can see the details of various APIs by searching for "Java API Reference".

Object Oriented ~ Instances and Classes ~

How to create an object ① Class definition ② Instantiation ③ Completion of instance (object)

If you compare the mechanism of an object with a Gunpla ... ① If you make a basic mold for Gunpla ② Use it to generate various Gunpla ③ Completion If you make the basics, you can easily mass-produce them.

If you compare what you need for a program with an RPG ... ・ Main method (God class, works first) ・ Other methods (character class)

Class description

public class Gokuu{
    String name;
    int hp;
    void attack(){・ ・ ・}
    void jump(){・ ・ ・}
}

Declaring a variable is called ** attribute definition **. The defined variable is called ** field **. The method declaration is called ** operation definition **.

If you add "final" to the beginning of the field declaration, the value cannot be changed. When "final" is attached, it is called ** constant field **. Constant fields are easy to understand and uppercase letters are recommended. final String NAME; final int HP;

this

public class Gokuu{
    String name;
    int hp;
    void attack(){
        this.name = "Goku";
    }
}

"This.name =" Goku ";" and "name =" Goku ";" have the same behavior, Unexpected behavior may occur if "name" is also used for local variables and formal parameters. In order to prevent it, ** this ** indicates that it is its own field.

The following is an extreme example Thanks to "this", it is easy to distinguish between formal parameters and fields.

Example of using name as a formal argument.java


public class Main {
    public static void main(String[] args) {
        //Instance generation (explained later)
        Monster m = new Monster();
        //Pass the argument "Majin Buu"
        m.attack("Majin Buu")
    }
}
public class Monster{
    String name;

    public void attack(String name){
        //Assign formal arguments to fields
        this.name = name;
        System.out.println(this.name + "To attack!")
    }
}

Class diagram

Class ⇒ Attribute ⇒ Operation The diagram summarized by these three is called a class diagram. Fields and methods are collectively called ** members **.

What is possible with class definitions

  1. You can create an instance based on that class.
  2. A variable type is available that contains the instance born from that class.

** How to create an instance ** Class name variable name = new class name ();

When you want to use the attack method of Goku class in a certain class It can be used by creating an instance. Create a "new" instance. Create an instance of Goku class with new Gokuu ();. The variable name is "gokuu1". Since it is an instance of the Goku class, the type is "Gokuu"

Therefore, Gokuu gokuu1 = new Gokuu ();. I also want to use the attack method of the Goku class. It becomes gokuu1.attack ();. If you want to get the HP field of Goku class again Just write gokuu1.hp;.

Generation may be divided into two lines

Goku instance generation.java


Gokuu gokuu1; //Class types can also be used for fields.
gokuu1 = new Gokuu();

You can understand it by looking at the code used when explaining "this" again.

Example of using name as a formal argument.java


public class Main {
    public static void main(String[] args) {
        //Instance generation
        Monster m = new Monster();
        //Pass the argument "Majin Buu"
        m.attack("Majin Buu")
    }
}
public class Monster{
    String name;

    public void attack(String name){
        //Assign formal arguments to fields
        this.name = name;
        System.out.println(this.name + "To attack!")
    }
}

Instance independence

Some values ​​are output by the following code.

Gokuu g1 = new Gokuu();
g1.hp = 100;

Gokuu g2;
g2 = g1;
g2.hp = 200;
System.out.println(g1.hp);

The execution result is 200. g1 and g2 refer to the same "new Gokuu ();". (Same as for array.) So if you change the value with g2, the value of g1 will also change. But when you say ** instance independence ** and g2 "new Gokuu ();" by itself, It is not referenced. You can make a copy of the same HP as Goku No. 1, and you can also make a copy of Goku No. 2 with a different HP.

Use class type for method argument and return value

For the time being, Son Goku asks Karin for recovery.

Example.java


public class Main {
    public static void main(String[] args) {
        Gokuu g1 = new Gokuu();
        g1.hp = 100;
        Karinsama k1 = new Karinsama();
        k1.heal(g1); //Pass Goku and recover.
    }
}

public class Karinsama {
    public void heal(Gokuu g){
        g.hp += 100;
        System.out.println("I had Karin recover HP100 with senzu.")
    }
}

constructor

** There is nothing in the field of the instance just created by new. ** ** However, strictly speaking, the initial value is set.

Initial value of field

Mold value
int,short,long etc. 0
char ¥u000
boolean false
Array null
String,class null

The method that is automatically executed immediately after being new is called ** constructor **. Until now, Goku's HP was decided after the instance, If the basic 100 is fine, substitute 100 first in the Goku class.

public class Gokuu{
    int hp;
    public Gokuu(){
        this.hp = 100;
    }
}

There are two conditions that can be a constructor. (1) The method name is the same as the class. (2) The return value is not declared in the method (** void is also ✖ **)

Fields such as names that you want to change for each instance can be used as arguments.

public class SuperSaiyaJin {
    int hp;
    String name;
    public SuperSaiyaJin(String name){
        this.hp = 100;
        this.name = name;
    }
}
public class Main {
    public static void main(String[] args) {
        SuperSaiyaJin gokuu = new SuperSaiyaJin ("Goku");
        SuperSaiyaJin beji-ta = new SuperSaiyaJin ("Vegeta");
    }
}

In fact, Java always has to define one constructor when instantiating. However, ** because the constructor is automatically generated if no one is defined ** Until now, it was possible to instantiate without worrying about it.

Constructor overload

The constructor also determines by the argument and processes it.

public class SuperSaiyaJin {
    //This works with no arguments
    public SuperSaiyaJin(){
    }
    //This works with arguments
    public SuperSaiyaJin(String name){
    }
}

Use of constructor of the same class

You can call your own constructor with this ();.

public class SuperSaiyaJin {
    int hp;
    String name;
    public SuperSaiyaJin(){
        this("Goku");
    }

    public SuperSaiyaJin(String name){
        this.hp = 100;
        this.name = name;
    }
}

In this state, even if you call SuperSaiyaJin () with no arguments Since there is this (" Goku ");, hp is set to 100.

Static member

Static field

Due to the independence of the instance, each new has its own field. (If you do new by yourself, it will not be referenced (shared)) However, if you use ** static **, it will be shared by all instances. This is convenient when you want to share some fields even if you create instances separately.

Fields with static are called ** static fields **. Static fields can be used without instantiation. Because of this feature, it is also called ** class variable **. Usage: class name.static field name;

Static method

A method with static is called ** static method **. Also known as ** class method **. Together with static fields, they are called ** static members **.

Like static fields, static methods have the following three capabilities.

-(1) Since the method belongs (shared) to the class, it can be called with class name.method name ();. -② You can call it with instance variable name.method name ();. ――③ You can call it without creating an instance.

Example.java


public class Item {
    public static void main(String[] args) {
        static int money;
        static void setRandomMoney(){
             Item.money = (int)(Math.random()*1000);
         }
    }
}

public class Main {
    public static void main(String[] args) {
        //Since it is static, new is unnecessary
        Item.setRandomMoney();
        
        System.out.println(Item.money); //※1
        Item i = new Item();
        System.out.println(i.money); //※2
    }
}

"Math.random ()" generates random numbers less than 0.0 ~ 1.0 (double type) Until now, * 1 and * 2 have different numbers, but this time the variable money is static. In other words, since they are shared, the same value is output.

Static method constraints

** You cannot call a field or method that does not have "static" in a static method. ** **

Methods with static can be called without instantiation, If there is a field declared without static in the block, an error will occur.

This is because fields without static cannot be called unless they are instantiated. ** Fields handled by static methods must be static fields. ** **

Click here for more ⇒ Part 2

Recommended Posts

Introduction to Java that can be understood even with Krillin (Part 1)
Java (super beginner edition) that can be understood in 180 seconds
Java to learn with ramen [Part 1]
Server processing with Java (Introduction part.1)
Object-oriented that can be understood by fairies
Introduction to algorithms with java --Search (breadth-first search)
Set the access load that can be changed graphically with JMeter (Part 2)
Set the access load that can be changed graphically with JMeter (Part 1)
Introduction to java
Introduction to algorithms with java --Search (bit full search)
Organize methods that can be used with StringUtils
[Ruby] Methods that can be used with strings
[Java] char type can be cast to int type
Basic functional interface that can be understood in 3 minutes
How foreign keys can be saved even with nil
Write a class that can be ordered in Java
Play with Java function nodes that can use Java with Node-RED
Compiled kotlin with cli with docker and created an environment that can be executed with java
Syntax and exception occurrence conditions that can be used when comparing with null in Java
Connect to Access database with Java [UCan Access] * Set until it can be executed with VS Code
Only the top level Stream can be parallelized with Java Stream.
Create a page control that can be used with RecyclerView
Firebase-Realtime Database on Android that can be used with copy
Four-in-a-row with gravity that can be played on the console
Problems that can easily be mistaken for Java and JavaScript
Find a Switch statement that can be converted to a Switch expression
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
Be sure to compare the result of Java compareTo with 0
Whether options can be used due to different Java versions
Java to play with Function
[Java] Introduction to lambda expressions
Connect to DB with Java
Connect to MySQL 8 with Java
[Java] Introduction to Stream API
Introduction to Spring Boot Part 1
[Introduction to rock-paper-scissors games] Java
I can no longer connect to a VM with a Docker container that can be connected via SSH
How to make a key pair of ecdsa in a format that can be read by Java
Reference memo / In-memory LDAP server that can be embedded in Java
Static analysis tool that can be used on GitHub [Java version]
A story that I struggled to challenge a competition professional with Java
Summary of ORM "uroboroSQL" that can be used in enterprise Java
File form status check sheet that can be deleted with thumbnails
Connecting to a database with Java (Part 1) Maybe the basic method
SwiftUI View that can be used in combination with other frameworks
The operator that was born to be born, instanceof (Java) ~ How to use the instanceof operator ~
Summary of JDK that can be installed with Homebrew (as of November 2019)
Introduction to Scala from a Java perspective, decompiled and understood (basic)
I tried to solve the past 10 questions that should be solved after registering with AtCoder in Java
Building an SAP system connection environment using JCo to a PC that even Java beginners can do
Introduction to Linux Container / Docker (Part 1)
100% Pure Java BDD with JGiven (Introduction)
[Introduction to Java] About lambda expressions
[Introduction to Java] About Stream API
Introduction to Functional Programming (Java, Javascript)
Dare to challenge Kaggle with Java (1)
Introduction to algorithms with java-Shakutori method
I tried to interact with Java
Introduction to Linux Container / Docker (Part 2)
Java to be involved from today
Reintroduction to Operators with RxJava Part 1