//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));
}
}
var m = new Math (); // error
public final class Math{
private Math() {}
}
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
}
}
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;
}
}
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
}
}
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";
}
}
** (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();
}
}
...
to the argument **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}));
}
}
public void hoge(int... x, int y)
* public void hoge(int... x, int... y)
v.totalProducts ()
, an array of size 0 is passed as an argument//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
}
}
The range of influence on the value passed in the basic type and the reference type is different.
Basic type
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
}
}
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
}
}
}
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
}
}
/ ʻifPresent
: null check / ʻorElseGet
: Null check to get the value **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