Java sample code 01

1. Java sample program

I communicated the source posted in SAMPLE GALLERY and added an import statement.

--Java basics --Hello World (output characters to console) --for statement (loop) --if statement (conditional branch) --Switch statement (conditional branch) --Simple four arithmetic operations --Method call --Method call (with arguments) --Array --Multidimensional array --Enter on console --Getting the number of characters --List class --Map class --Set class --Java String class (string) --Determine if the two strings are the same: equals --Judge whether two strings are the same regardless of case: equalsIgnoreCase --Compare the size of strings in lexicographic order: compareTo --Compare large and small strings in lexicographic order regardless of case: compareToIgnoreCase --Concatenation of strings: concat --Get one character: charAt --Get part of the string: substring --Category conversion: toLowerCase, toUpperCase --Java Math class (numerical processing) --Math.max (int, int) (returns a large value) --Math.min (int, int) (returns a small value) --Math.floor (double) --Math.round (double) (rounded) --Math.ceil (double) (rounded up) --Math.abs (int) (absolute value) --Math.abs (double, double) (power) --Math.random () --Java Calendar, Date, DateFormat class (date processing) --Create a Calendar object for today (now) --Get year, month, day, hour, minute, second --Create a Calendar object for a specific date --add (int field, int amount) (Edit the value of Calendar object) --Calendar.before/after (date comparison) --Create java.util.Date object --SimpleDateFormat (display date and time in any format) --Java File (file processing) --Create file: createNewFile () --Delete file: delete () --Creating a directory: mkdir () --Creating a directory: mkdirs () --Get file name (or directory name): getName () --Get Absolute Path: getAbsolutePath () --Get parent directory object: getParentFile () --Get the path of the parent directory: getParent () --Determine whether it is a directory: isDirectory () --Judge whether it is a file: isFile () --Determine if it is a hidden file: isHidden () --Determine if a file (or directory) exists: exists () --Get last modified date: lastModified () --Get all files and directories directly under the directory: listFiles () --Get files and directories directly under the directory by specifying conditions: FilenameFilter --Java BigDecimal class (numerical processing) --Create a BigDecimal object --Addition (addition): add (BigDecimal augend) --Subtraction: subtract (BigDecimal subtrahend) --Multiplication: multiply (BigDecimal multiplicand) --Division: divide (BigDecimal divisor) --Truncation: RoundingMode.FLOOR --Round up: RoundingMode.CEILING --Rounding: RoundingMode.HALF_UP --Absolute value: abs () --Exponentiation: pow (int n)

1. Java sample program

1-1. Java basics

1-1-1.Hello World (characters are output to the console)

public class SampleJava {

  public static void main(String[] args) {
    System.out.println("Hello World!");
  }

}

1-1-2.for statement (loop)

public class SampleJava {

  public static void main(String[] args) {
    int sum = 0;

    //「for (int i = 1; i <= 5; i++) {Regarding
    //int i =1 ⇒ Initialize i with 1
    //i <=5 ⇒ If i is 5 or less, loop processing is performed.
    //i++⇒ Add 1 to i (after the process of no loop is finished)
    for (int i = 1; i <= 5; i++) {
      sum += i;//Add i to the variable sum
    }
    System.out.println(sum);//Show variable sum
  }

}

1-1-3.if statement (conditional branch)

public class SampleJava {

  public static void main(String[] args) {
    int a = 11;//You can change here freely.

    if (a > 10) {//Determine if it is greater than 10
      System.out.println("a is greater than 10.");
    } else {
      System.out.println("a is 10 or less.");
    }
  }

}

1-1-4.switch statement (conditional branch)

public class SampleJava {

  public static void main(String[] args) {
    int score = 4;//You can freely change the number here from 1 to 5.
    String result = null;

    switch (score) {
      case 5://When score is 5
        result = "A";
        break;
      case 4://When score is 4
        result = "B";
        break;
      case 3://When score is 3
        result = "C";
        break;
      case 2://When score is 2
        result = "D";
        break;
      case 1://When score is 1
        result = "E";
        break;
      default://When score is other than the above
        break;
    }

    if (result != null) {
      System.out.println(result + "It is an evaluation.");
    }
  }

}

1-1-5. Simple four arithmetic operations

public class SampleJava {

  public static void main(String[] args) {
    int a = 10;
    int b = 5;

    //Addition
    System.out.println(a + b);

    //Subtraction
    System.out.println(a - b);

    //Multiply
    System.out.println(a * b);

    //division
    System.out.println(a / b);
  }

}

1-1-6. Calling a method

public class SampleJava {

  public static void main(String[] args) {
    moring();
    noon();
    evening();
  }

  private static void moring() {
    System.out.println("It's morning.");
  }

  private static void noon() {
    System.out.println("It's noon.");
  }

  private static void evening() {
    System.out.println("It's night.");
  }

}

1-1-7. Method call (with arguments)

public class SampleJava {

  public static void main(String[] args) {
    int output = plus(10, 30);
    System.out.println(output);
  }

  /**
   *A method that allows you to pass arguments.
   *Returns the result of adding a and b.
   * @param a
   * @param b
   * @return
   */
  private static int plus(int a, int b) {
    return a + b;
  }

}

1-1-8. Array

public class SampleJava {

  public static void main(String[] args) {
    //Array declaration
    int[] intArray = { 10, 20, 30, 40, 50 };

    //below[]Specify the number in and retrieve any value in the array. 0-4 in this example.
    System.out.println(intArray[0]);
  }

}

1-1-9. Multidimensional array

public class SampleJava {

  public static void main(String[] args) {
    //Declaration of multidimensional array
    String[][] testScore = {
      { "National language", "80" }
      , { "arithmetic", "90" }
      , { "society", "70" }
      , { "Science", "75" }
    };

    System.out.println("Subject:" + testScore[1][0] + ", Score:" + testScore[1][1]);
  }

}

1-1-10. Input to the console

import java.util.Scanner;

public class SampleJava {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String inputStr = scan.next();//Get what you typed in the console here
        System.out.println("The characters entered on the console are "" + inputStr + ""is.");
    }

}

1-1-11. Acquisition of the number of characters

public class SampleJava {

  public static void main(String[] args) {
    String str = "Good morning";
    System.out.println(str.length());//length()Get the number of characters with
  }

}

1-1-12.List class

import java.util.ArrayList;
import java.util.List;

public class SampleJava {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("10");
        list.add("15");
        list.add("20");
        System.out.println(list.get(1));//list.get(index)Get the value of list with. 0 at the very beginning
    }

}

1-1-13.Map class

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

public class SampleJava {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        //Map below.put(key, value)Set the value with
        map.put("A", "100");
        map.put("B", "80");
        map.put("C", "60");
        map.put("D", "40");
        map.put("E", "20");

        //map.get(key)Get the value of the key specified in
        System.out.println(map.get("C"));
    }

}

1-1-14. Set class

import java.util.HashSet;
import java.util.Set;

public class SampleJava {

    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        //Add a value to set below. The same value is not added. In the example below, only one A is added.
        set.add("A");
        set.add("A");
        set.add("B");
        set.add("C");

        for (String val : set) {
            System.out.println(val);
        }
    }
}

1. Java sample program

1-2.Java String class (character string)

1-2-1. Judgment whether two character strings are the same: equals

public class SampleString {

  public static void main(String[] args) {
    String str1 = "abcde";
    String str2 = "abcde";
    String str3 = "fghij";

    //「A.equals(B)To determine if A and B have the same value.
    //true because str1 and str2 have the same value.
    System.out.println(str1.equals(str2));

    //Since str1 and str3 are different values, false.
    System.out.println(str1.equals(str3));
  }
}

1-2-2. Judging whether two strings are the same regardless of case: equalsIgnoreCase

public class SampleString {

  public static void main(String[] args) {
    String str1 = "Abcde";
    String str2 = "abcde";
    String str3 = "fghij";

    //「A.equalsIgnoreCase(B), To determine if A and B are the same value, regardless of case.
    //Since str1 and str2 have the same value, true ("A" and "a" are considered to be the same).
    System.out.println(str1.equalsIgnoreCase(str2));

    //Since str1 and str3 are different values, false.
    System.out.println(str1.equalsIgnoreCase(str3));
  }
}

1-2-3. Compare the size of character strings in lexicographic order: compareTo

public class SampleString {

  public static void main(String[] args) {
    String str1 = "def";
    String str2 = "abc";
    String str3 = "ghi";
    String str4 = "def";

    //「A.compareTo(B), Compare the size of the character string in lexicographic order.
    //0 or less if A comes before B in the dictionary
    //0 if A and B are the same
    //0 or more if A comes after B in the dictionary
    //become.

    //Since str1 comes after str2, it becomes 0 or more.
    System.out.println(str1.compareTo(str2));

    //Since str1 comes before str3, it becomes 0 or less.
    System.out.println(str1.compareTo(str3));

    //Since str1 is the same as str4, it becomes 0.
    System.out.println(str1.compareTo(str4));
  }
}

1-2-4. Compare the size of strings in lexicographic order regardless of case: compareToIgnoreCase

public class SampleString {

  public static void main(String[] args) {
    String str1 = "def";
    String str2 = "Def";

    //「A.compareToIgnoreCase(B), Compare the size of the character string in lexicographic order.
    //It is not case sensitive (it is considered the same).

    //Since str1 is the same as str2, it becomes 0 ("d" and "D" are considered to be the same).
    System.out.println(str1.compareToIgnoreCase(str2));
  }
}

1-2-5. String concatenation: concat

public class SampleString {

  public static void main(String[] args) {
    String helloStr = "Hello";
    String spaceStr = " ";
    String worldStr = "World";

    // concat(String str)Combine strings with
    System.out.println(helloStr.concat(spaceStr).concat(worldStr));
  }
}

1-2-6. Get one character: charAt

public class SampleString {

  public static void main(String[] args) {
    String str = "Hello World.";

    //charAt(int index)Get one character in the string with.
    //The character to be acquired is specified by the index argument.
    System.out.println(str.charAt(0));
  }
}

1-2-7. Get part of the string: substring

public class SampleString {

  public static void main(String[] args) {
    String str = "Hello World.";

    //substring(int beginIndex, int endIndex)Get a part of the string with.
    //The character string to be acquired is specified by the index argument.
    System.out.println(str.substring(0, 5));
  }
}

1-2-8. Case conversion: toLowerCase, toUpperCase

public class SampleString {

  public static void main(String[] args) {
    String str1 = "HELLO";
    String str2 = "world";

    //toLowerCase()Convert uppercase letters to lowercase letters with.
    System.out.println(str1.toLowerCase());

    //Convert lowercase letters to uppercase with toUpperCase.
    System.out.println(str2.toUpperCase());
  }
}

1. Java sample program

1-3. Java Math class (numerical processing)

1-3-1.Math.max (int, int) (returns a large value)

public class SampleMath {

  public static void main(String[] args) {
    //Change the values of a and b below to arbitrary
    int a = 10;
    int b = 20;

    //Math.max(int, int)Returns the larger argument.
    System.out.println(Math.max(a, b));
  }
}

1-3-2.Math.min (int, int) (returns a small value)

public class SampleMath {

  public static void main(String[] args) {
    int a = 6;
    int b = 7;

    //Math.min(int, int)Returns the smaller value.
    System.out.println(Math.min(a, b));
  }
}

1-3-3.Math.floor (double) (truncation)

public class SampleMath {

  public static void main(String[] args) {
    double a = 100.9;

    //Math.floor(double).. Truncate after the decimal point.
    System.out.println(Math.floor(a));
  }
}

1-3-4.Math.round (double) (rounded)

public class SampleMath {

  public static void main(String[] args) {
    double a = 7.5;

    //Math.round(double).. Rounded to the nearest whole number.
    System.out.println(Math.round(a));
  }
}

1-3-5.Math.ceil (double) (rounded up)

public class SampleMath {

  public static void main(String[] args) {
    double a = 20.1;

    //Math.ceil(double).. Round up after the decimal point.
    System.out.println(Math.ceil(a));
  }
}

1-3-6.Math.abs (int) (absolute value)

public class SampleMath {

  public static void main(String[] args) {
    int a = -7;

    //Math.abs(int).. Returns the absolute value.
    System.out.println(Math.abs(a));
  }
}

1-3-7.Math.abs (double, double) (power)

public class SampleMath {

  public static void main(String[] args) {
    double a = 10;
    double b = 2;

    //Math.abs(double, double).. Returns a power. In this example, 10 squared is 100
    System.out.println(Math.pow(a, b));
  }
}

1-3-8.Math.random () (random number)

public class SampleMath {

  public static void main(String[] args) {
    //Math.random()。0.0 or more 1.Randomly returns numbers less than 0.
    System.out.println(Math.random());
  }
}

1. Java sample program

1-4. Java Calendar, Date, DateFormat class (date processing)

1-4-1. Create a Calendar object for today (now)

import java.util.Calendar;

public class SampleCalendar {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);
    }
}

1-4-2. Get year, month, day, hour, minute, second

import java.util.Calendar;

public class SampleCalendar {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        System.out.println("Year:" + cal.get(Calendar.YEAR));
        System.out.println("Month:" + (cal.get(Calendar.MONTH) + 1));//Month is 0~Because of 11+1
        System.out.println("Day:" + cal.get(Calendar.DATE));
        System.out.println("Time:" + cal.get(Calendar.HOUR_OF_DAY));
        System.out.println("Minutes: Minutes:" + cal.get(Calendar.MINUTE));
        System.out.println("Seconds:" + cal.get(Calendar.SECOND));
    }
}

1-4-3. Create a Calendar object with a specific date

import java.util.Calendar;

public class SampleCalendar {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(2010, 0, 1);//Set January 1, 2010. Month is 0~Since it is 11, set 0.

        //「2010/1/1 "is displayed.
        System.out.println(cal.get(Calendar.YEAR)
                + "/" + (cal.get(Calendar.MONTH) + 1)
                + "/" + cal.get(Calendar.DATE));
    }
}

1-4-4.add (int field, int amount) (Edit the value of Calendar object)

import java.util.Calendar;

public class SampleCalendar {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();

        //Today's date is displayed
        displayConsole(cal);

        //add(int field, int amount)You can increase or decrease each value of the Calendar object such as year, month, and day with.
        //The following is reducing the number of days by one day.
        cal.add(Calendar.DATE, -1);
        displayConsole(cal);

        //The following is increasing the month by one month.
        cal.add(Calendar.MONTH, 1);
        displayConsole(cal);
    }

    private static void displayConsole(Calendar cal) {
        System.out.println(cal.get(Calendar.YEAR)
                + "/" + cal.get(Calendar.MONTH)
                + "/" + cal.get(Calendar.DATE));
    }
}

1-4-5.Calendar.before / after (date comparison)

import java.util.Calendar;

public class SampleCalendar {

    public static void main(String[] args) {
        Calendar calA = Calendar.getInstance();
        Calendar calB = Calendar.getInstance();
        calB.add(Calendar.DATE, 1);//Set calB to the value one day later.

        //Returns true if calA is a date and time before calB. True in this example.
        System.out.println(calA.before(calB));
        //Returns true if calA is a date and time after calB. False in this example.
        System.out.println(calA.after(calB));
    }

}

1-4-6. Creating a java.util.Date object

import java.util.Calendar;
import java.util.Date;

public class SampleDate {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        System.out.println(date);
    }

}

1-4-7.SimpleDateFormat (displays the date and time in any format)

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class SampleDate {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();

        //Created a format to display "year". Example: 2016
        DateFormat format = new SimpleDateFormat("yyyy");
        System.out.println(format.format(date));

        //Create a format to display "month". Example: 05
        format = new SimpleDateFormat("MM");
        System.out.println(format.format(date));

        //Create a format to display "day". Example: 01
        format = new SimpleDateFormat("dd");
        System.out.println(format.format(date));

        //Create a format to display "hours". Example: 00
        format = new SimpleDateFormat("HH");
        System.out.println(format.format(date));

        //Create a format to display "minutes". Example: 00
        format = new SimpleDateFormat("mm");
        System.out.println(format.format(date));

        //Create a format to display "seconds". Example: 00
        format = new SimpleDateFormat("ss");
        System.out.println(format.format(date));

        //「○○/○○/○○ ”is displayed. Example: 2000/01/01
        format = new SimpleDateFormat("yyyy/MM/dd");
        System.out.println(format.format(date));

        //"○○ year ○○ month ○○ day ○○:○○:XX (XX hours XX minutes XX seconds) "is displayed. Example: January 1, 2000
        format = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
        System.out.println(format.format(date));

    }

}

1. Java sample program

1-5. Java File (file processing)

1-5-1. Creating a file: createNewFile ()

import java.io.File;
import java.io.IOException;

public class SampleDate {

    public static void main(String[] args) {
        //Creating a file object. In the argument, specify the path of the file to be created.
        File file = new File("C:\\sample\\test.txt");
        try {
            //The file is created below.
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

1-5-2. Delete file: delete ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");
        //Deletes the file specified below.
        file.delete();
    }

}

1-5-3. Creating a directory: mkdir ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\sampledir");
        //Creates the directory specified below.
        file.mkdir();
    }

}

1-5-4. Creating a directory: mkdirs ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\sampledir\\sampledir2");
        //Create a directory below. mkdir()Unlike, it also creates what you need in the parent directory.
        //In this example, "C:\\If you run it with a directory called "sample"
        //Two "sampledir" and "sampledir2" are created.
        file.mkdirs();
    }

}

1-5-5. Get file name (or directory name): getName ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");
        //Get the name of the specified file (or directory)
        System.out.println(file.getName());
    }

}

1-5-6. Get absolute path: getAbsolutePath ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");
        //Get the absolute path of the file
        System.out.println(file.getAbsolutePath());
    }

}

1-5-7. Get parent directory object: getParentFile ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");

        //Get parent directory object
        File parent = file.getParentFile();

        System.out.println(parent);
    }

}

1-5-8. Get the path of the parent directory: getParent ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");

        //Get the path of the parent directory
        String parentPath = file.getParent();

        System.out.println(parentPath);
    }
}

1-5-9. Judgment whether it is a directory: isDirectory ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample");

        //Determine if it is a directory below. True because it is a directory in this example.
        System.out.println(file.isDirectory());
    }
}

1-5-10. Judgment whether it is a file: isFile ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample");

        //Determine if it is a file below. False in this example because it is a directory.
        System.out.println(file.isFile());
    }
}

1-5-11. Determine if it is a hidden file: isHidden ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");

        //Determine if it is a hidden file below.
        System.out.println(file.isHidden());
    }
}

1-5-12. Determine if a file (or directory) exists: exists ()

import java.io.File;

public class SampleDate {

    public static void main(String[] args) {
        File file = new File("C:\\sample\\test.txt");

        //Determine if a file (or directory) exists below
        System.out.println(file.exists());
    }
}

1. Java sample program

1-6. Java BigDecimal class (numerical processing)

1-6-1. Create BigDecimal object

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {
        //Create a BigDecimal object below
        BigDecimal obj = new BigDecimal("1");

        System.out.println(obj);
    }
}

1-6-2. Addition (addition): add (BigDecimal augend)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("1");
        BigDecimal obj2 = new BigDecimal("2");

        //add(BigDecimal augend)Adds with and returns the result.
        BigDecimal result = obj1.add(obj2);

        System.out.println(result);
    }
}

1-6-3. Subtraction: subtract (BigDecimal subtrahend)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("5");
        BigDecimal obj2 = new BigDecimal("3");

        //subtract(BigDecimal subtrahend)Subtract with and return the result.
        BigDecimal result = obj1.subtract(obj2);

        System.out.println(result);
    }
}

1-6-4. Multiplication: multiply (BigDecimal multiplicand)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("2");
        BigDecimal obj2 = new BigDecimal("4");

        //multiply(BigDecimal multiplicand)Multiplies with and returns the result.
        BigDecimal result = obj1.multiply(obj2);

        System.out.println(result);
    }
}

1-6-5. Division: divide (BigDecimal divisor)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("30");
        BigDecimal obj2 = new BigDecimal("5");

        //divide(BigDecimal divisor)Divide by and return the result.
        BigDecimal result = obj1.divide(obj2);

        System.out.println(result);
    }
}

1-6-6. Truncation: RoundingMode.FLOOR

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("400.545");

        //setScale(int newScale, RoundingMode roundingMode)Specify the number of digits and rounding operation with.
        //RoundingMode.FLOOR
        //The following example returns the result of truncating the first decimal place.
        obj1 = obj1.setScale(0, RoundingMode.FLOOR);

        System.out.println(obj1);
    }
}

1-6-7. Round up: RoundingMode.CEILING

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("400.545");

        //setScale(int newScale, RoundingMode roundingMode)Specify the number of digits and rounding operation with.
        //RoundingMode.CEILING
        //The following example returns the result of rounding up the second decimal place.
        obj1 = obj1.setScale(1, RoundingMode.CEILING);

        System.out.println(obj1);
    }
}

1-6-8. Rounding: RoundingMode.HALF_UP

import java.math.BigDecimal;
import java.math.RoundingMode;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("400.545");

        //setScale(int newScale, RoundingMode roundingMode)Specify the number of digits and rounding operation with.
        //RoundingMode.HALF_UP (rounded)
        //The following example returns an object that is the result of rounding off to the third decimal place.
        obj1 = obj1.setScale(2, RoundingMode.HALF_UP);

        System.out.println(obj1);
    }
}

1-6-9. Absolute value: abs ()

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj = new BigDecimal("-1");

        //abs()Returns the absolute value with
        System.out.println(obj.abs());
    }
}

1-6-10. Power: pow (int n)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj = new BigDecimal("2");

        //pow(int n)Returns the result of raising the value to the power (nth power).
        System.out.println(obj.pow(4));
    }
}

1-6-11.max(BigDecimal val)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("4");
        BigDecimal obj2 = new BigDecimal("3");

        //max(BigDecimal val)Compares objects with and returns the larger one.
        System.out.println(obj1.max(obj2));
    }
}

1-6-12.min(BigDecimal val)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("4");
        BigDecimal obj2 = new BigDecimal("3");

        //min(BigDecimal val)Compares objects with and returns the smaller one.
        System.out.println(obj1.min(obj2));
    }
}

1-6-13. Comparison of size: compareTo (BigDecimal val)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("1");
        BigDecimal obj2 = new BigDecimal("3");

        //compareTo(BigDecimal val)
        //Compare the object with that of the argument
        //If it is large, "1"
        //If they are the same, "0"
        //If it is small, "-1」
        //return it.
        if (obj1.compareTo(obj2) > 0) {
            System.out.println("large");
        } else if (obj1.compareTo(obj2) < 0) {
            System.out.println("small");
        } else {
            System.out.println("the same");
        }
    }
}

1-6-14. Remainder of division: remainder (BigDecimal divisor)

import java.math.BigDecimal;

public class SampleBigDecimal {

    public static void main(String[] args) {

        BigDecimal obj1 = new BigDecimal("11");
        BigDecimal obj2 = new BigDecimal("3");

        //remainder(BigDecimal divisor)Divide by and return the remainder.
        BigDecimal result = obj1.remainder(obj2);

        System.out.println(result);
    }
}

Recommended Posts

Java sample code 02
Java sample code 03
Java sample code 04
Java sample code 01
Digital signature sample code (JAVA)
Java parallelization code sample collection
Script Java code
Java code TIPS
[Java] Generics sample
Selenium sample (Java)
Java GUI sample
Java 9 new features and sample code
Java character code
Sample code using Minio from Java
Sample code collection for Azure Java development
Apache beam sample code
[Java] Holiday judgment sample
[Java] Explanation of Strategy pattern (with sample code)
Sample code to convert List to List <String> in Java Stream
Java test code method collection
[Windows] Java code is garbled
Java
Java in Visual Studio Code
Java standard log output sample
Write Java8-like code in Java8
Sample code for log output by Java + SLF4J + Logback
Java
Selenium Sample Reservation Form (Java)
Sample code to parse date and time with Java SimpleDateFormat
Guess the character code in Java
Java Spring environment in vs Code
Java 15 implementation and VS Code preferences
[Java] Boilerplate code elimination using Lombok
Java build with mac vs code
Arbitrary string creation code by Java
Execute packaged Java code with commands
A simple sample callback in Java
Java source code reading java.lang.Math class
[Java] Boilerplate code elimination using Lombok 2
BloomFilter description and implementation sample (JAVA)
[Java] Date period duplication check sample
EXCEL file update sample with JAVA
Java development environment (Mac, VS Code)
[Android] Convert Android Java code to Kotlin
Sample vending machine made in Java
Basic structure of Java source code
How to manage Java code automatically generated by jOOQ & Flyway sample
Sample code to call the Yahoo! Local Search API in Java
Sample code that uses the Mustache template engine JMustache in Java
Java learning (0)
Studying Java ―― 3
[Java] array
[Java] Annotation
Prepare Java development environment with VS Code
[Java] Module
Java array
Java tips, tips
Sample code for Singleton implementation using enum
Java methods
Java method
java (constructor)