Untitled

 avatar
unknown
plain_text
a year ago
36 kB
8
Indexable
javacore.basics

1. controlflow
    1.1. condition
        Condition.java

public class Condition {
    public static void main(String[] args) {
        String month = "A";
        System.out.println(getQuarter(month));
    }

    public static void ifElseMethod() {
        int x = 20;
        int y = 18;
        if (x > y) {
            System.out.println("x is greater than y");
        }

        int time = 20;
        if (time < 18) {
            System.out.println("Good day.");
        } else {
            System.out.println("Good evening.");
        }

        time = 22;
        if (time < 10) {
            System.out.println("Good morning.");
        } else if (time < 18) {
            System.out.println("Good day.");
        } else {
            System.out.println("Good evening.");
        }

        time = 10;
        String result = (time < 18) ? "Good day." : "Good evening.";
        System.out.println(result);
    }

    public static void switchMethod() {
        // SWITCH
        // Khong dung duoc voi kieu long, float, double hoac boolean va wrapper cua chung
        int day = 8;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Looking forward to the Weekend");
        }

        int switchValue  = 3;
        switch (switchValue) {
            case 1 -> System.out.println("Value was 1");
            case 2 -> System.out.println("Value was 2");
            case 3, 4, 5 -> System.out.println("Value was 3, or 4, or 5");
            default -> System.out.println("Value was not 1, 2, 3, 4, or 5");
        }
    }

    public static String getQuarter(String month) {
        return switch (month) {
            case "January", "February", "March" -> "1st";
            case "April", "May", "June" -> "2nd";
            case "July", "August", "September" -> "3rd";
            case "October", "November", "December" -> "4th";
            default -> {
                String badResponse = month + " is bad";
                yield badResponse;
            }
        };

    }
}

    1.2. loop
        Exercise.java

public class Exercise {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int[] arr = new int[4];
        for (int i = 0; i < 4; i++) {
            arr[i] = scanner.nextInt();
        }

        for (int num : arr) {
            System.out.println(num);
        }
    }

    public static void printSquareStar(int num) {
        if (num < 5) {
            System.out.println("Invalid Value");
            return;
        }

        for (int row = 0; row < num; row++) {
            for (int col = 0; col < num; col++) {
                if (row == 0 || row == num - 1 || col == 0 || col == num - 1
                    || row == col || row == num - col - 1) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }

    public static int getLargestPrime(int num) {
        if (num < 0) {
            return -1;
        }

        int largestPrime = -1;

        for (int i = 2; i <= num; i++) {
            if (num % i != 0) {
                continue;
            }

            if (i == 2) {
                largestPrime = 2;
            } else {
                boolean isPrime = true;
                for (int j = 2; j < i; j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
                largestPrime = isPrime? i : largestPrime;
            }
        }

        return largestPrime;
    }

    public static boolean canPack(int bigCount, int smallCount, int goal) {
        if (bigCount < 0 || smallCount < 0 || goal < 0 || bigCount * 5 + smallCount < goal) {
            return false;
        }
        if (bigCount * 5 + smallCount == goal || smallCount >= goal) {
            return true;
        }

        int sum = 0;
        for (int i = 0; i < bigCount; i++) {
            sum += 5;
            if (sum > goal) {
                return false;
            } else if (sum == goal) {
                return true;
            } else {
                for (int j = 0; j < smallCount; j++) {
                    sum += 1;
                    if (sum == goal) {
                        return true;
                    }
                }
                sum -= smallCount;
            }
        }

        return false;
    }

    public static int reverse(int num) {
        int temp = (num > 0) ? num : -num;
        int reverse = 0;
        while (temp > 9) {
            reverse = reverse * 10 + temp % 10;
            temp /= 10;
        }
        reverse = reverse * 10 + temp;

        return (num > 0)? reverse : - reverse;
    }

    public static int getDigitCount(int num) {
        if (num < 0) {
            return -1;
        }

        int digitCount = 0;
        while (num > 9) {
            digitCount++;
            num /= 10;
        }

        return ++digitCount;
    }

    public static void numberToWords(int num) {
        if (num < 0) {
            System.out.println("Invalid Value");
            return;
        }

        int reverseNum = reverse(num);
        int digitCount = getDigitCount(num);
        int reverseDigitCount = getDigitCount(reverseNum);
        while (reverseNum > 9) {
            switch (reverseNum % 10) {
                case 0 :
                    System.out.println("Zero");
                    break;
                case 1 :
                    System.out.println("One");
                    break;
                case 2 :
                    System.out.println("Two");
                    break;
                case 3 :
                    System.out.println("Three");
                    break;
                case 4 :
                    System.out.println("Four");
                    break;
                case 5 :
                    System.out.println("Five");
                    break;
                case 6 :
                    System.out.println("Six");
                    break;
                case 7 :
                    System.out.println("Seven");
                    break;
                case 8 :
                    System.out.println("Eight");
                    break;
                case 9 :
                    System.out.println("Nine");
                    break;
                default:
                    System.out.println("Error");
                    break;
            }
            reverseNum /= 10;
        }
        switch (reverseNum) {
            case 0 :
                System.out.println("Zero");
                break;
            case 1 :
                System.out.println("One");
                break;
            case 2 :
                System.out.println("Two");
                break;
            case 3 :
                System.out.println("Three");
                break;
            case 4 :
                System.out.println("Four");
                break;
            case 5 :
                System.out.println("Five");
                break;
            case 6 :
                System.out.println("Six");
                break;
            case 7 :
                System.out.println("Seven");
                break;
            case 8 :
                System.out.println("Eight");
                break;
            case 9 :
                System.out.println("Nine");
                break;
            default:
                System.out.println("Error");
                break;
        }

        for (int i = 0; i < digitCount - reverseDigitCount; i++) {
            System.out.println("Zero");
        }
    }

    public static boolean isPerfectNumber(int num) {
        if (num < 1) {
            return false;
        }

        int sum = 0;
        for (int i = 1; i < num; i++) {
            if (num % i == 0) {
                sum += i;
            }
        }

        return sum == num;
    }

    public static int getGreatestCommonDivisor(int first, int second) {
        if (first < 10 || second < 10) {
            return -1;
        }

        while (second != 0) {
            int temp = second;
            second = first % second;
            first = temp;
        }

        return first;
    }

    public static void printFactors(int num) {
        if (num < 1) {
            System.out.println("Invalid Value");
        }

        for (int i = 1; i <= num; i++) {
            if (num % i == 0) {
                System.out.println(i);
            }
        }
    }

    public static boolean hasSameLastDigit(int num1, int num2, int num3) {
        if (!isValid(num1) || !isValid(num2) || !isValid(num3)) {
            return false;
        }

        return (num1 % 10 == num2 % 10)
                || (num2 % 10 == num3 % 10)
                || (num3 % 10 == num1 % 10);
    }

    public static boolean isValid(int num) {
        return num >= 10 && num <= 1000;
    }

    public static boolean hasSharedDigit(int num1, int num2) {
        if (num1 < 10 || num1 > 99 || num2 < 10 || num2 > 99) {
            return false;
        }

        return (num1 % 10 == num2 % 10)
                || (num1 % 10 == num2 / 10)
                || (num1 / 10 == num2 % 10)
                || (num1 / 10 == num2 / 10);
    }

    public static int getEvenDigitSum(int num) {
        if (num < 0) {
            return -1;
        }

        int sum = 0;
        int lastDigit;
        while (num > 9) {
            lastDigit = num % 10;
            sum += (lastDigit % 2 == 0)? lastDigit : 0;
            num /= 10;
        }
        sum += (num % 2 == 0)? num : 0;

        return sum;
    }

    public static int sumFirstAndLastDigit(int num) {
        if (num < 0) {
            return -1;
        }

        int firstDigit = 0;
        int lastDigit = num % 10;

        while (num > 9) {
            num /= 10;
        }
        firstDigit = num;

        return firstDigit + lastDigit;
    }

    public static boolean isPalindrome(int num) {
        int temp = (num > 0) ? num : -num;
        int reverse = 0;
        while (temp > 9) {
            reverse = reverse * 10 + temp % 10;
            temp /= 10;
        }
        reverse = reverse * 10 + temp;

        return (num > 0) ? (reverse == num) : (reverse == -num);
    }
}

        Loop.java

import java.util.Arrays;

public class Loop {
    public static void main(String[] args) {
        whileLoop();
        doWhileLoop();
        forLoop();
        forEachLoop();
        breakAndContinue();

    }

    public static void whileLoop() {
        // WHILE
        int i1 = 0;
        while (i1 < 5) {
            System.out.println(i1);
            i1++;
        }
    }

    public static void doWhileLoop() {
        // DO-WHILE
        int i2 = 0;
        do {
            System.out.println(i2);
            i2++;
        } while (i2 < 5);
    }

    public static void forLoop() {
        // FOR
        for (int i = 1; i <= 2; i++) {
            System.out.println("Outer: " + i); // Executes 2 times

            // Inner loop
            for (int j = 1; j <= 3; j++) {
                System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
            }
        }
    }

    public static void forEachLoop() {
        // FOR-EACH LOOP
        String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
        for (String str : cars) {
            System.out.println(str);
        }

        // FOREACH LOOP
        // chu y for-each khac voi forEach
        Arrays.stream(cars).forEach(System.out::println);
    }

    public static void breakAndContinue() {
        // BREAK
        for (int i = 0; i < 10; i++) {
            if (i == 4) {
                break;
            }
            System.out.println(i);
        }

        // CONTINUE
        int i3 = 0;
        while (i3 < 10) {
            if (i3 == 4) {
                i3++;
                continue;
            }
            System.out.println(i3);
            i3++;
        }
    }
}

########################################

2. datatype
    2.1. strings
        Exercise.java

import java.util.Objects;
import java.util.Scanner;

public class Exercise {

    public static void main(String[] args) {
        gettingTheFullName();
    }

    public static void concatenation() {
        Scanner scanner = new Scanner(System.in);

        String str1 = scanner.nextLine();
        String str2 = scanner.nextLine();

        str1 = "null".equalsIgnoreCase(str1) ? null : str1;
        str2 = "null".equalsIgnoreCase(str2) ? null : str2;

        String concatenated;
        if (str1 == null) {
            concatenated = str2 == null ? "" : str2;
        } else {
            concatenated = str2 == null ? str1 : str1.concat(str2);
        }

        System.out.println(concatenated);

    }

    public static void gettingTheFullName() {
        User tim = new User();
        tim.setFirstName("Tim");
        tim.setLastName("Towler");
        System.out.println(tim.getFullName()); // Tim Towler

        User katie = new User();
        katie.setFirstName("Katie");
        katie.setLastName(null);
        System.out.println(katie.getFullName()); // Katie (without additional spaces)
    }

    public static void luckyTicket() {
        Scanner scanner = new Scanner(System.in);
        char[] ticket = scanner.nextLine().toCharArray();

        int[] numberArray = new int[6];
        for (int i = 0; i < 6; i++) {
            numberArray[i] = Character.getNumericValue(ticket[i]);
        }

        if (numberArray[0] + numberArray[1] + numberArray[2] == numberArray[3] + numberArray[4] + numberArray[5]) {
            System.out.println("Lucky");
        } else {
            System.out.println("Regular");
        }
    }
}

class User {
    private String firstName;
    private String lastName;

    public User() {
        this.firstName = "";
        this.lastName = "";
    }

    public void setFirstName(String firstName) {
        // write your code here
        this.firstName = Objects.requireNonNullElse(firstName, "");
    }

    public void setLastName(String lastName) {
        // write your code here
        this.lastName = lastName != null ? lastName : "";
    }

    public String getFullName() {
        if (this.firstName.equals("") && this.lastName.equals("")) {
            return "Unknown";
        } else if (this.firstName.equals("")) {
            return lastName;
        } else if (this.lastName.equals("")) {
            return firstName;
        } else {
            return firstName + " " + lastName;
        }
    }
}

#################################################

        MyString.java

public class MyString {
    public static void main(String[] args) {

    }

    public static void introducing() {
        // Arrays and Strings
        char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F' };
        String stringFromChars = String.valueOf(chars); // "ABCDEF"

        char[] charsFromString = stringFromChars.toCharArray();
        String theSameString = new String(charsFromString); // "ABCDEF"

        // Splitting the string
        String text = "Hello";
        String[] parts = text.split(""); // {"H", "e", "l", "l", "o"}

        String sentence = "a long text";
        String[] words = sentence.split(" "); // {"a", "long", "text"}

        String text2 = "I'm gonna be a programmer";
        String[] parts2 = text.split(" gonna be "); // {"I'm", "a programmer"}

        // Iterating over a string
        String scientistName = "Isaac Newton";

        for (int i = 0; i < scientistName.length(); i++) {
            System.out.print(scientistName.charAt(i) + " ");
        }
    }

    public static void stringMethod() {
        //String Length
        String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        System.out.println("The length of the txt string is: " + txt.length());

        //There are many string methods available, for example toUpperCase() and toLowerCase():
        String txt2 = "Hello World";
        System.out.println(txt2.toUpperCase());
        System.out.println(txt2.toLowerCase());

        //Finding a Character in a String
        String txt3 = "Please locate where 'locate' occurs!";
        System.out.println(txt3.indexOf("locate"));

        //String Concatenation
        String firstName = "John";
        String lastName = "Doe";
        System.out.println(firstName + " " + lastName);

        System.out.println(firstName.concat(lastName));

        //Chu y
        String x = "10";
        int y = 20;
        String z = x + y; //ket qua la string 1020
        System.out.println(z);

        //Special Characters
        String txt4 = "We are the so-called \"Vikings\" from the north.";
        System.out.println(txt4); //We are the so-called "Vikings" from the north.
        txt4 =  "It\'s alright.";
        System.out.println(txt4);
        txt4 = "The character \\ is called backslash.";
        System.out.println(txt4);

        Integer inte = 100;
    }
}

###########################################

        MyStringBuilder.java

/*
 * StringBuilder cho phep tao mutable string object -> co the modify ma khong tao string moi
 */

public class MyStringBuilder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("I love Java");

        // length()
        System.out.println(sb.length());

        // charAt()
        System.out.println(sb.charAt(5));

        // setCharAt()
        sb = new StringBuilder("start");
        sb.setCharAt(1, 'm');
        System.out.println(sb);

        // deleteCharAt
        sb = new StringBuilder("dessert");
        sb.deleteCharAt(2);
        System.out.println(sb);

        // delete
        sb = new StringBuilder("Welcome");
        sb.delete(0, 3);
        System.out.println(sb); // "come"

        // append
        sb.append(" xyz");
        System.out.println(sb);

        sb.append(1)
                .append(2)
                .append(3);
        System.out.println(sb);

        // insert
        sb = new StringBuilder("I'm a programmer.");
        sb.insert(6, "Java ");
        System.out.println(sb); // "I'm a Java programmer."

        // replace
        sb = new StringBuilder("Let's use C#");
        sb.replace(10, 12, "Java");
        System.out.println(sb); // "Let's use Java"

        // reverse
        sb = new StringBuilder("2 * 3 + 8 * 4");
        sb.reverse();
        System.out.println(sb); // "4 * 8 + 3 * 2"

        // toString
        String myString = sb.toString();
        System.out.println(myString);
    }
}

#########################################

    2.2. wrapperclasses
        AutoboxingAndUnboxing.java

import java.util.ArrayList;

class IntClass {
    private int myValue;

    public IntClass(int myValue) {
        this.myValue = myValue;
    }

    public int getMyValue() {
        return myValue;
    }

    public void setMyValue(int myValue) {
        this.myValue = myValue;
    }
}

public class AutoboxingAndUnboxing {
    public static void main(String[] args) {
        ArrayList<IntClass> intClassArrayList = new ArrayList<>();
        intClassArrayList.add(new IntClass(54));

        Integer integer = 54;
        ArrayList<Integer> intArrayList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            // autoboxing : chuyen mot so nguyen thanh mot doi tuong Integer
            intArrayList.add(Integer.valueOf(i * 10));
        }

        Integer myIntValue = 99; // Integer.valueOf(99)
        // unboxing
        int myInt = integer.intValue();
        // int myInt = integer;
    }
}

######################################

        Main.java

import java.util.ArrayList;

/*
 * Wrapper class cung cap cach su dung kieu du lieu nguyen thuy nhu doi tuong
 * byte - Byte; short - Short; int - Integer; long - Long; float - Float; double - Double; boolean - Boolean; char - Character
 */

public class Main {
	public static void main(String[] args) {
		//truong hop duoi day khong su dung duoc kieu nguyen thuy ma phai dung Wrapper class
		//ArrayList<int> myNumbers = new ArrayList<int>(); 
		ArrayList<Integer> myNumbers = new ArrayList<>();
		
		//tao wrapper class
		Double myDouble = 5.99;
		System.out.println(myDouble);
		Character myChar = 'A';
		System.out.println(myChar.charValue());
		
		//convert
		Integer myInt = 100;
	    String myString = myInt.toString();
	    System.out.println(myString.length());
	    
	    //chuyen tu wrapper ve kieu nguyen thuy hoac nguoc lai
	    int a = 20;
        Integer i = Integer.valueOf(a);		// đổi int thành Integer
        Integer j = a;						// autoboxing, tự động đổi int thành Integer trong nội bộ trình biên dịch
        System.out.println(a + " " + i + " " + j);
        
        Integer b = new Integer(3);
        int x = b.intValue();				// đổi Integer thành int
        int y = b;							// unboxing, tự động đổi Integer thành int trong nội bộ trình biên dịch
 
        System.out.println(b + " " + x + " " + x);
	}
}

##########################################

    DataType.java

import java.util.Scanner;

/**
 * @author thieu.bui
 * tao tai lieu, van ban de nguoi khac doc
 */

//ghi chu 1 dong

/*
 * ghi chu nhieu dong
 */

public class DataType {

    public static void variableAndDataType() {
        /* Variable and Data Type */

        String tenSach = "Lap trinh Java";
        int namXuatBan = 2021;        //4 byte: -2147483648 to 2147483647
        double giaTien = 15.5d;
        boolean conSach = true;
        char mKho = 'M';            //2 byte

        int x = 10, y = 20, z = 30; //khoi tao nhieu bien
        long xx;                    //8 byte: -9223372036854775808 to 9223372036854775807
        long myLongValue = 100L;
        float a = 5.99f;            //4 byte
        double b;                   //8 byte

        final int myNum = 16;        //gia tri cua myNum se khong bi thay doi
        short num = 5000;            //co gia tri tu -32768 toi 32767

        boolean isJavaFun = true;
        boolean isFishTasty = false;
        System.out.println(isJavaFun);     // Outputs true
        System.out.println(isFishTasty);   // Outputs false

        char myGrade = 'B';
        System.out.println(myGrade);

        char myVar1 = 65, myVar2 = 66;
        System.out.println(myVar1);
        System.out.println(myVar2);

        String myString = String.valueOf('\u0054') + String.valueOf('\u0068') + String.valueOf('\u0069') + String.valueOf('\u1EC7') + String.valueOf('\u0075');

        System.out.println("My name is " + '\u0054' + '\u0068');
    }

    public static void castingInJava() {
        /*
         * Java type casting
         *
         * Widening Casting (automatically) - converting a smaller type to a larger type size
         * byte -> short -> char -> int -> long -> float -> double
         *
         * Narrowing Casting (manually) - converting a larger type to a smaller size type
         * double -> float -> long -> int -> char -> short -> byte
         */

        int myInt = 9;
        double myDouble = myInt; // Automatic casting: int to double
        System.out.println(myInt);      // Outputs 9
        System.out.println(myDouble);   // Outputs 9.0

        double myDouble2 = 9.78d;
        int myInt2 = (int) myDouble2; // Manual casting: double to int
        System.out.println(myDouble2);   // Outputs 9.78
        System.out.println(myInt2);      // Outputs 9

        short myMinShortValue = Short.MIN_VALUE;
        int myMinIntValue = Integer.MIN_VALUE;
        byte myMaxByteValue = Byte.MAX_VALUE;
        byte myMinByteValue = Byte.MIN_VALUE;
        byte myNewByteValue = (byte) (10000 / 2);
        int myNewIntValue = myMinIntValue / 2;

        System.out.println(myNewIntValue);
        System.out.println(myNewByteValue);
        System.out.println(Long.SIZE);

        float myFloatValue = -5f / 3;   // Mac dinh so thap phan trong java la kieu double
        double myDoubleValue = 5.0 / 3;

        System.out.println(myFloatValue);
        System.out.println(myDoubleValue);
        System.out.println((float) Long.MAX_VALUE);
    }

    public static void exercise1(){
        byte byteValue = 10;
        short shortValue = 20;
        int intValue = 2_000_000_000;
        long sumOfThree = byteValue + shortValue + intValue;
        long longValue = 50000 + 10 * sumOfThree;
        long longTotal = 50000L + 10L * (byteValue + shortValue + intValue);

        System.out.println(longValue);
        System.out.println(longTotal);
    }

    public static void exercise2(){
        double numberOfPounds = 200d;
        double convertedKilograms = numberOfPounds * 0.45359237;

        System.out.println("Converted kilograms = " + convertedKilograms);
    }

    public static void main(String[] args) {
        //variableAndDataType();
        //castingInJava();
        //exercise1();
        //exercise2();

        Scanner scanner = new Scanner(System.in);
        char ch = scanner.next().charAt(0);
        System.out.println((char) (ch - 1));

    }
}

######################################

    FloatingPoint.java

import java.util.Scanner;

public class FloatingPoint {

    public static void main(String[] args) {
        // arithmeticOperations();

        exercise();
    }

    /*
    float chi bieu dien duoc 6-7 chu so sau thap phan, double la 12-14
     */
    public static void declaring() {
        double zero = 0.0;
        double one = 1.0;
        double negNumber = -1.75;
        double pi = 3.1415;

        System.out.println(pi); // 3.1415

        float f = 0.888888888888888888f; // a value with a lot of decimal digits
        System.out.println(f);           // it only prints 0.8888889

        double eps = 5e-3; // means 5 * 10^(-3) = 0.005
        double n = 0.01e2; // means 0.01 * 10^2 = 1.0
    }

    public static void arithmeticOperations() {
        double one = 1.0;
        double number = one + 1.5; // 2.5

        double a = 1.75;
        double b = 5.0;
        double c = b - a; // 3.25

        double pi = 3.1415;
        double squaredPi = pi * pi; // 9.86902225

        double d1 = 5 / 4; // 1.0
        double d2 = 5.0 / 4; // 1.25

        System.out.println(3.3 / 3); // prints 1.0999999999999999
        double d = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
        System.out.println(d); // it prints 0.9999999999999999
    }

    public static void exercise() {
        Scanner scanner = new Scanner(System.in);
        // put your code here
        float x1 = scanner.nextFloat();
        float y1 = scanner.nextFloat();

        float x2 = scanner.nextFloat();
        float y2 = scanner.nextFloat();

        double expression1 = x1 * x2 + y1 * y2;
        double expression2 = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2);

        float angle = (float) Math.toDegrees(Math.acos(expression1 / expression2));

        System.out.println(angle);
        System.out.printf("%.8f%n", angle);
        System.out.println(Math.round(angle));
        System.out.println(45.0);

        double epsilon = 1e-8;
    }
}

########################################

    TypeOfReference.java

import java.io.File;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Scanner;

public class TypeOfReference {

    public static void main(String[] args) {
        // strongReference();
        // softReference();
    }

    /*
    Trong hau het cac truong hop, ta deu su dung strong reference
    Khi con tham chieu toi doi tuong thi no van con trong bo nho, neu khong co tham chieu thi no se bi xoa
     */
    public static void strongReference() {
        Integer num = 1995;
        num = null;

        System.out.println(num); // null -> GC se xoa doi tuong chua so 1995
    }

    /*
    Object voi soft reference chi bi GC xoa khi application gan het bo nho (thrown an OutOfMemoryError)
    Day la tham chieu manh nhat trong non-strong reference
     */
    public static void softReference() {
        // Chung ta co hai doi tuong, dau tien la mot Integer, thu hai la mot SortReference, tham chieu toi doi tuong
        // Integer bang mot soft reference
        // Doi tuong dau tien duoc goi la referant, cai thu hai la reference object
        Integer num = 1995;
        SoftReference<Integer> softReference = new SoftReference<>(num);

        num = null;
        System.out.println(num);

        num = softReference.get();
        System.out.println(num);
    }

    /*
    Weak reference yeu hon soft reference
    Mot doi tuong voi weak reference co the bi xoa trong lan thu rac (garbage collection) dau tien sau khi tao. Co the
    them tham chieu nay giong voi cach them soft reference va no cung giup "hoi sinh" doi tuong sau khi loai bo strong
    reference cua no
     */
    public static void weakReference() {
        Integer num = 1995;
        WeakReference<Integer> weakReference = new WeakReference<>(num);

        num = null;
        num = weakReference.get();

        System.out.println(num); // 1995
    }

    /*
    Phantom reference la loai tham chieu yeu nhat. No khong dat bat ky muc do tiep can nao cho cac doi tuong
    Phuong thuc get() cua no tra ve null de ngan chan su "hoi sinh" cua doi tuong vi muc dich cua phantom referece la phat
    hien khi nao mot doi tuong bi xoa khoi bo nho
     */
    public static void phantomReference() {

    }

    public void deleteOldFiles(File rootDir, long thresholdDate) {
        Scanner scanner = new Scanner(System.in);
        String string = scanner.next();
        StringBuilder doubleString = new StringBuilder();

        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            doubleString.append(c).append(c);
        }

        System.out.println(doubleString);
    }
}

########################################

3. simpleprogram
    3.1. output
        FormattedOutput.java

public class FormattedOutput {

    public static void main(String[] args) {

    }

    public static void printfMethod() {
        System.out.printf("My Name is %s. I was born in %d", "Mike", 1998);

        System.out.printf("Display a Number %.2f", 15.23);

        char abbr = 'H';
        String element = "Hydrogen";
        System.out.printf("%c stands for %s", abbr, element);
    }

    public static void stringFormat() {
        int age = 22;
        String str = String.format("My age is %d", age);
        System.out.println(str);

        char initial = 'M';
        String surname = "Anderson";
        double height = 1.72;
        String details = "My name is %c. %s.%nMy age is %d.%nMy height is %.2f."
                .formatted(initial, surname, age, height);
    }
}

##########################################

    3.2. parsingvalue_readinginput
        Exercise.java

import java.util.Scanner;

public class Exercise {
    public static void main(String[] args) {
        System.out.println(getBucketCount(2.75, 3.25, 2.5, 1));
    }

    public static int getBucketCount(double width, double height, double areaPerBucket, int extraBuckets) {
        if (width <= 0 || height <= 0 || areaPerBucket <= 0 || extraBuckets <0) {
            return -1;
        }

        return (int) Math.ceil(width * height / areaPerBucket) - extraBuckets;
    }

    public static int getBucketCount(double width, double height, double areaPerBucket) {
        if (width <= 0 || height <= 0 || areaPerBucket <= 0) {
            return -1;
        }

        return (int) Math.ceil(width * height / areaPerBucket);
    }

    public static int getBucketCount(double areaOfWall, double areaPerBucket) {
        if (areaOfWall <= 0 || areaPerBucket <= 0) {
            return -1;
        }

        return (int) Math.ceil(areaOfWall / areaPerBucket);
    }

    public static void inputThenPrintSumAndAverage() {
        Scanner scanner = new Scanner(System.in);

        int sum = 0;
        int avg = 0;
        int count = 0;
        while (scanner.hasNextInt()) {
            sum += scanner.nextInt();
            count++;
            avg = (int) Math.round((double) sum / count);
        }

        System.out.println("SUM = " + sum + " AVG = " + avg);
    }
}

###########################################

        Main.java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //parsingValue();

        try {
            getInputFromConsole();
        } catch (NullPointerException e) {
            getInputFromScanner();
        }
    }

    public static void parsingValue() {
        int currentYear = 2023;
        String usersDateOfBirth = "1999";

        int dateOfBirth = Integer.parseInt(usersDateOfBirth);

        System.out.println("Age = " + (currentYear - dateOfBirth));
    }

    public static void getInputFromConsole() {
        // khi su dung Intellij thi khong chay duoc Console -> Phai dung terminal

        int currentYear = 2023;
        String name = System.console().readLine("Hi, What's your name? ");
        System.out.println("Hi " + name + ", Thanks for talking the course! ");

        String dateOfBirth = System.console().readLine("What year were you born? ");
        int age = currentYear - Integer.parseInt(dateOfBirth);
        System.out.println("So you are " + age + " years old.");
    }

    public static void getInputFromScanner() {
        int currentYear = 2023;

        Scanner scanner = new Scanner(System.in);
        System.out.println("Hi, What's your name? ");
        String name = scanner.nextLine();
        System.out.println("Hi " + name + ", Thanks for talking the course! ");
        System.out.println("What year were you born? ");

        boolean validDOB = false;
        int age = 0;

        do {
            System.out.println("Enter a year of birth >= " + (currentYear - 125) + " and <= " + currentYear);
            try {
                age = checkData(currentYear, scanner.nextLine());
                validDOB = age < 0 ? false : true;
            } catch (NumberFormatException badUserData) {
                System.out.println("Characters not  allowed! Try again.");
            }
        } while (!validDOB);


        System.out.println("So you are " + age + " years old.");
    }

    public static int checkData(int currentYear, String dateOfBirth) {
        int dob = Integer.parseInt(dateOfBirth);
        int minimumYear = currentYear - 125;

        if (dob < minimumYear || dob > currentYear) {
            return -1;
        }

        return currentYear - dob;
    }
}

######################################################

    Main.java

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {// go main sau do ctrl + space
		testInput();
	}

	public static void testInput() {
		Scanner sc = new Scanner(System.in);
		System.out.println("Hello world!"); // go sysout sau do ctrl + space
		System.out.println("I will try it.");

		int x = sc.nextInt();
		int y = ++x;
		System.out.println("2 + 2 = " + y);


		String thongBao = "Xin chao";
		sc.nextLine();
		String hoVaTen = sc.nextLine();
		String tenSach;
		tenSach = "Lap trinh Java";
		System.out.println("Thong bao: " + thongBao);
		System.out.println("Ho va Ten: " + hoVaTen);
		System.out.println("Ten sach: " + tenSach);
	}

}
Editor is loading...
Leave a Comment