if (조건문){
조건이 참이면 실행할 영역
}
public static void hiEveryone(int age){
System.out.println("좋은 아침입니다");
System.out.println("제 나이는 "+age+"세 입니다".);
}
public static void main(String[] args) {
hiEveryone(20);
}
1) void/return
a. void 메소드: 결과값을 반환하지 않는 메소드(return이 없음)
-> 함수명 앞에 데이터 타입을 void로 설정
b. return 메소드: 결과값을 반환하는 메소드(return 값이 있음)
-> 함수명 앞에 return 값의 데이터 타입을 적어줌
public double circleArea(double radius){
return Math.PI*radius*radius;
}
2) 클래스 타입/ 인스턴스 타입
a. 클래스 타입: static이 붙은 경우
b. 인스턴스 타입: static이 붙지 않은 경우
public static void printString(String str){
System.out.print(str);
}
public static void main(String[] args){
// 1번
String str1 = "Happy";
String str2 = "Birthday";
// 2번
printString(str1);
printString(str2);
}
cf)
Q. 왜 main 메소드는 String[] 형태의 매개변수를 갖나요?
A.
A)
class Rectangle {
double width;
double height;
public void setWidth(double widNum) {
width = widNum;
}
public void setHeight(double heiNum) {
height = heiNum;
}
public double getArea() {
return width * height;
}
}
public class Example4 {
public static void main(String[] args) {
// 1번
Rectangle rec = new Rectangle();
rec.setWidth(10);
rec.setHeight(10);
System.out.println(rec.getArea());
// 2번
rec.setWidth(20);
rec.setHeight(20);
System.out.println(rec.getArea());
}
}
B)
class Rectangle {
double width;
double height;
public void setWidth(double widNum) {
width = widNum;
}
public void setHeight(double heiNum) {
height = heiNum;
}
public double getArea() {
return width * height;
}
}
public class Example4 {
public static void main(String[] args) {
Rectangle rec = new Rectangle();
Rectangle rec2;
rec2 = rec;
rec2.setWidth(10);
rec2.setHeight(10);
System.out.println(rec2.getArea());
System.out.println(rec.getArea());
}
}
rec와 rec2는 똑같은 주소 값을 가진다
-> rec를 이용해 값을 변경하는 경우, rec2를 이용해 변경하는 경우 모두 Rectangle에 있는 값을 변경한다
new Rectangle(): heap이라는 메모리에 Rectangle를 올린다
-> 인스턴스(객체) 형성
C)
class Rectangle {
double width;
double height;
public void setWidth(double widNum) {
width = widNum;
}
public void setHeight(double heiNum) {
height = heiNum;
}
public double getArea() {
return width * height;
}
}
public class Example4 {
public static void main(String[] args) {
Rectangle rec = new Rectangle();
Rectangle rec2 = new Rectangle();
rec.setWidth(10);
rec.setHeight(10);
rec2.setWidth(20);
rec2.setHeight(20);
System.out.println(rec.getArea());
System.out.println(rec.getArea());
}
}