Thêm tham số

Java trung cấp

Jim White

Java Developer

Tham số

  • Cho phép truyền giá trị đầu vào vào phương thức
  • Tăng linh hoạt
  • Cho phép phương thức phản hồi theo đầu vào
  • Khiến phương thức tái sử dụng và hữu ích hơn
Java trung cấp

sayHello(String name)

static void sayHelloV1(){
  System.out.println("Hello, there!");
}
static void sayHello(String name){ // Add String parameter called name
  System.out.println("Hello, " + name + "!"); // Use name in code
}

Giờ ta có thể gọi sayHello() với các tên khác nhau:

sayHello("Alice"); // Prints "Hello, Alice!"
sayHello("Sam"); // Prints "Hello, Sam!"
Java trung cấp

getSquare(int number)

static int getSquare(int number) {
  return number * number
}
getSquare(10); // Returns 100
getSquare(2); // Returns 4
Java trung cấp

Gọi phương thức với tham số

class HelloWorld {
    public static void main (String[] args) {
        sayHello("Alice");
        int threeSquared = getSquared(3); // threeSquared = 9
    }
        static void sayHello(String name){ 
            System.out.println("Hello, " + name + "!"); 
        }
        static int getSquare(int number) {
            return number * number
        }
}
Hello, Alice!
Java trung cấp

Nhiều tham số - mọi kiểu

// Kiểu khác nhau
static void printUser(String name, int age){ 
  System.out.println("User is " + name);
  System.out.println("They are " + age);
}
printUser("Ann", "32");
User is Ann
They are 32
// Cùng kiểu, nhưng nhiều tham số hơn
static int addNumbers(int a, int b, int c){ 
  return a + b + c
}
int sum = addNumbers(2, 4, 6); 
System.out.println(sum);
12
Java trung cấp

Tóm tắt

  • Tham số giúp linh hoạt
  • Đặt tham số trong ngoặc sau tên phương thức
  • Có thể có nhiều tham số, khác kiểu
// Định nghĩa phương thức có tham số
static void printUser(String name, int age, String address){ 
  System.out.println("User is " + name);
  System.out.println("They are " + age);
  System.out.println("They live in " + address);
}
// Gọi phương thức
printUser("Sue", 43, "Canada");
Java trung cấp

Ayo berlatih!

Java trung cấp

Preparing Video For Download...