if(true or false) {
조건이 true 시 실행되는 영역
}
if(true or false) {
조건이 true 시 실행되는 영역
} else {
조건이 false 시 실행되는 영역
}
if(true or false) {
조건이 true 시 실행되는 영역
} else if (true or false) {
前조건들이 모두 false & 現조건이 true 시 실행되는 영역
} else {
모두 false 시 실행되는 영역
}
public static void main(String[] args) {
int n = 1;
switch (n) {
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
default:
System.out.println("default");
}
System.out.println("end");
}
//결과
//1
//2
//3
//default
//end
걸리면 break 까지
public static void main(String[] args) {
int n = 1;
switch (n) {
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
case 3:
System.out.println("3");
default:
System.out.println("default");
}
System.out.println("end");
}
//결과
//1
//end
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("달을 입력하시오. >");
int month = scanner.nextInt();
switch (month) {
case 12: case 1: case 2:
System.out.println("겨울 입니다.");
break;
case 3: case 4: case 5:
System.out.println("봄 입니다.");
break;
case 6: case 7: case 8:
System.out.println("여름 입니다.");
break;
case 9: case 10: case 11:
System.out.println("가을 입니다.");
break;
default:
System.out.println("올바른 입력 형식이 아닙니다.");
}
System.out.println("end");
}
class Circle {
//속성
int radius;
String color;
//기능
double calArea() {
return Math.PI * Math.pow(radius, 2);
}
}
Circle circle = new Circle()
Circle
: 참조변수의 타입circle
: 참조변수, 참조값 저장=
: 대입 연산자 👉 변수 초기화new
: 객체 생성 👉 메모리(Heap) 할당Circle()
: 생성자 호출예제1)
static class Student{
String name;
long rollno;
int age;
void printStudent() {
System.out.println("학생의 이름: " + name);
System.out.println("학생의 학번: " + rollno);
System.out.println("학생의 나이: " + age);
}
}
public static void main(String[] args) {
Student student = new Student();
student.name = "Kim";
student.rollno = 20180001;
student.age = 20;
student.printStudent();
}
예제2)
public static void main(String[] args) {
String str1 = "Happy";
String str2 = "Birthday";
System.out.println(str1 + " " + str2);
printString(str1);
printString(str2);
}
private static void printString(String str) { // 참조형 매개변수 (객체 주소를 주고 받는 것)
System.out.println(str);
}
예제3)
static class Rectangle{
private int width;
private int height;
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width*height;
}
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setWidth(10);
rectangle.setHeight(10);
System.out.println(rectangle.getArea());
}
public static void main(String[] args) {
double area = circleArea(10);
System.out.println("area = " + area);
}
private static double circleArea(int r) { // 메서드 선언부
return Math.PI * Math.pow(r, 2);
}