[Java] Object-oriented syntax --class method / argument

Class method / field

Class method

//Define class method getTriangleArea of Figure class
public class Figure {
  public static double getTriangleArea(double width, double height) {
    return width * height / 2;
  }
}

StaticBasic.java


public class StaticBasic {

  public static void main(String[] args) {
    System.out.println(Figure.getTriangleArea(10, 20));
//    var f = new Figure();
//    System.out.println(f.getTriangleArea(10, 20));
  }
}

Utility class

public final class Math{
  private Math() {}
}

Class field

Figure.java


//Pi field, getCircleArea method definition in the class member of Figure class

public class Figure {
  public static double pi = 3.14;

  //Access class fields from class methods
  public static void getCircleArea(double r) {
    System.out.println("The area of the circle is" +  r * r * pi);
  }
}

StaticBasic.java


public class StaticBasic {
  public static void main(String[] args) {
    //Figure can be accessed from the outside
    System.out.println(Figure.pi); //3.14
    Figure.getCircleArea(5); //The area of the circle is 78.5
  }
}

Singleton pattern

public class MySingleton {

  //Save only instance in class field
  private static MySingleton instance = new MySingleton();

  //Declare the constructor private
  private MySingleton() {}
  //Instance acquisition prepared by class method
  public static MySingleton getInstance() {
    return instance;
  }
}

Class constant

public class MyApp {
  public static final String BOOK_TITLE = "Java master!";
}
public class ConstantBasic {
  public static void main(String[] args) {
    System.out.println(MyApp.BOOK_TITLE); //Java master!
    //Cannot be assigned to final field
    //MyApp.BOOK_TITLE = "I will be a Java master!"; //error
  }
}

static initialization block

public class Initializer {
  public static final String DOG;
  public static final String CAT;
  public static final String MOUSE;

  static {
    DOG = "inu";
    CAT = "neko";
    MOUSE  = "nezumi";
  }
}

Initialization execution order

** (1) Class initialization only once **

** (2) Executed every time an object is created **

//Bad example
//Initialization block takes precedence over field initializer
public class Order {
  //Field initializer
  String value = "First!";
  //constructor
  public Order() {
    System.out.println(value); //Second!!
  }
  //Initialization block runs before construct
  {
    value = "Second!!";
  }
}
public class OrderBasic {

  public static void main(String[] args) {
    var o = new Order();
  }
}

Variadic method

public class ArgsParams {
  //As an argument...Receive variadic arguments with
  public int totalProducts(int... values) {
  // public int totalProducts(int[] values) {
    var result = 1;
    //Argument values received by extended for and applied to result
    for (var value : values) {
      result *= value;
    }
    return result;
  }
}
public class ArgsParamsBasic {

  public static void main(String[] args) {
    var v = new ArgsParams();
    System.out.println(v.totalProducts(12, 15, -1));
    System.out.println(v.totalProducts(5, 7, 8, 2, 4, 3));

    // System.out.println(v.totalProducts(new int[] {12, 15, -1}));
  }
}
//The first argument is the normal initial
//Declare the second and subsequent arguments with variable length
//Compile error with no arguments
public class ArgsParamsGood {
  public int totalProducts(int initial, int... values) {
    var result = initial;
    for (var value : values) {
      result *= value;
    }
    return result;
  }
}
public class ArgsParamsGoodClient {
  public static void main(String[] args) {
    var v = new ArgsParamsGood();
    System.out.println(v.totalProducts()); //no arguments
  }
}

Arguments and data types

public class ParamPrimitive {
  public int update(int num) { //Formal argument num
    //Manipulating formal parameters
    num *= 10;
    return num;
  }
}
public class ParamPrimitiveBasic {
  public static void main(String[] args) {
    //Variable num
    var num = 2;
    var p = new ParamPrimitive();
    System.out.println(p.update(num)); //20
    //Does not affect the original variable num
    System.out.println(num); //2
  }
}
public class ParamRef {
  //Copy the reference address of the variable data to the formal argument data
  public int[] update(int[] data) { //Formal argument data
    //Manipulation of formal argument data
    data[0] = 5;
    return data;
  }
}
public class ParamRefBasic {

  public static void main(String[] args) {
    //Actual argument data
    var data = new int[] { 2, 4, 6 };
    var p = new ParamRef();
    //The same value as the actual argument and formal argument will be referenced in the method call.
    System.out.println(p.update(data)[0]); //5
    //Manipulating the formal argument data affects the original variable
    System.out.println(data[0]); //5
  }
}
public class ParamRefArray {
  //Actual argument and formal argument point to the same at the time of method call
  public int[] update(int[] data) {
    //When a new array is assigned, the reference address itself changes.
    data = new int[] { 10, 20, 30 };
    return data;
  }
}
public class ParamRefArrayBasic {
  public static void main(String[] args) {
    var data = new int[] { 2, 4, 6 };
    var p = new ParamRefArray();
    System.out.println(p.update(data)[0]); //10
    System.out.println(data[0]); //2
  }
}

Null measures

import java.util.Map;

public class BookMap {
  //ISBN code: Manage book information by title
  private Map<String, String> data;
  //Initialize book information with argument map
  public BookMap(Map<String, String> map) {
    this.data = map;
  }
  //Obtain the title using the ISBN code (argument isbn) as a key
  public String getTitleByIsbn(String isbn) {
    //Returns null if the specified key does not exist
    return this.data.get(isbn);
  }
}

Main.java


import java.util.Map;
public class Main {
  public static void main(String[] args) {
    var b = new BookMap(Map.of(
        "978-4-7981-5757-3", "philosopher's Stone",
        "978-4-7981-5202-8", "room of Secrets",
        "978-4-7981-5382-7", "Azkaban prisoner"
        ));

    var title = b.getTitleByIsbn("978-4-7981-5757-3");
    if (title == null) {
      System.out.println("Disapparition!(Not)");
    } else {
      System.out.println(title.trim()); //philosopher's Stone
    }
  }
}

Simplify the above code with the Optional class!

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


public class BookMap {
  private Map<String, String> data = new HashMap<>();

  public BookMap(Map<String, String> map) {
    this.data = map;
  }

  public Optional<String> getTitleByIsbn(String isbn) {
    return Optional.ofNullable(this.data.get(isbn));
  }
}
import java.util.HashMap;

public class OptionalNullCheck {

  public static void main(String[] args) {
    var b = new BookMap(
      new HashMap<String, String>() {
        {
          put("978-4-7981-5757-3", "philosopher's Stone");
          put("978-4-7981-5202-8", "room of Secrets");
          put("978-4-7981-5382-7", "Azkaban prisoner");
        }
      });

    var optTitle = b.getTitleByIsbn("978-4-7981-5382-7");
    var title = optTitle.orElse("×");
    System.out.println(title.trim()); //Azkaban prisoner
  }
}
import java.util.Optional;

public class OptionalExample {

  public static void main(String[] args) {
    //Optional object creation
    var opt1 = Optional.of("Sample 1");
    //Null allowed
    var opt2 = Optional.ofNullable(null);
    var opt3 = Optional.empty();

    //Value existence confirmation
    System.out.println(opt1.isPresent()); //true
    //Run lambda expression if value exists
    opt1.ifPresent(value -> {
      System.out.println(value); //Sample 1
    });

    //If the value of opt2 exists, its value is displayed, and if it is null, the argument is displayed.
    System.out.println(opt2.orElse("null value")); //null value

    //Lambda expression execution if opt3 is null
    System.out.println(opt3.orElseGet(() -> {
      return "null value";
    })); //null value
  }
}

Recommended Posts

[Java] Object-oriented syntax --class method / argument
Java programming (class method)
java (method)
[Java] Object-oriented syntax-class / field / method / scope
Java method
Class method
[Java] method
[Java] Object-oriented
[Java] method
[Beginner] Java method / class / external library [Note 23]
[Java] Instance method, instance field, class method, class field, constructor summary
Java control syntax
Java class methods
Java control syntax
[Java] Class inheritance
java Scanner class
Java HashMap class
Object-oriented FizzBuzz (Java)
[Java] Object-oriented summary_Part 1
java (abstract class)
Java8 method reference
[Java] Nested class
Java anonymous class
[Java] Object-oriented syntax-Constructor
[Java] forEach method
Object-oriented (Java) basics
About Java class
[Java] Object-oriented summary_Part 2
[java] abstract class
java8 method reference
[Java] Object class
Java local class
[Java] Random method
[Java] split method
[Java] Object-oriented syntax-Package
[Android] Call Kotlin's default argument method from Java
Java method call from RPG (method call in own class)
[Java SE 11 Silver] Arrays class method summary [Java beginner]
Increment with the third argument of iterate method of Stream class added from Java9
[Java] How to use compareTo method of Date class
About class division (Java)
[Beginner] Java class field method / encapsulation (getter setter) [Note 25]
JAVA DB connection method
About Java StringBuilder class
Java learning 2 (learning calculation method)
[Java] About Singleton Class
Java learning memo (method)
About Java method binding
[Java ~ Method ~] Study memo (5)
[Java] Control syntax notes
About method splitting (Java)
Studying Java 8 (see method)
Java inner class review
Java class type field
About Java String class
6th class: Variables, method
Java programming (class structure)
[Java] Basic method notes
About java abstract class
How to get the class name / method name running in Java
[Java] Integer wrapper class reference