[학습 목표]
1.연산자의 종류와 역할을 이해하고 , 자바의 제어문 (비교문 , 선택문 , 반복문 ) 의 기본 개념을 익힌다. _ ver.jdk21 2. 연산자의 우선순위(Precedence)와 결합 방향(Associativity)을 이해하여 연산이 수행되는 순서를 예측할 수 있다. 3. 다양한 연산자 조합하여 복잡한 연산식(Expression)을 구성하는 방법을 숙지하고 활용할 수 있다. 4. 비교문 , 선택문 , 반복문 등의 제어문을 활용하여 자바 프로그램의 흐름을 제어할 수 있다. |
연산자에 들어가기 전 변수의 종류에 대해 정리하고 넘어가보자.
변수의 종류에 대해 알아보기
지역 변수 : 메소드 안에 선언하는 변수
멤버 변수 : 클래스 안에 선언하는 변수
클래스 내에서 선언 시 static이라는 키워드가 있으면 공유가 된다.
non-static의 경우 -> 자동으로 바인딩이 될 수 없다 -> 주소가 없어 객체로 주소를 만들어 줘야 한다.
ex)
public class ArithOperator {
static int result = 0;
static int value01 = 50;
static int value02 = 20;
//non -static -> 주소가 없음 -> 객체로 주소를 만들어줘야 함
public void prn() {
result = value01 + value02;
System.out.println(value01 + "+ " + value02 + " =" + result);
result = value01 - value02;
System.out.println(value01 + "- " + value02 + " =" + result);
result = value01 * value02;
System.out.println(value01 + "* " + value02 + " =" + result);
result = value01 / value02;
System.out.println(value01 + "/ " + value02 + " =" + result);
result = value01 % value02;
System.out.println(value01 + "% " + value02 + " =" + result);
}
public static void main(String[] args) {
new ArithOperator().prn();
System.out.println("==========================");
new ArithOperator().prn();
System.out.println("==========================");
System.out.println(ArithOperator.result);
}
}
연산자
연산자에는 대입 연산자 , 비트 연산자 , 전위 연산자 , 후위 연산자 등이 있다.
각각의 연산자에 대해 살펴보자
1) 산술 , 증감 , 관계 , 삼항 연산자
산술 연산자 : 산술 연산자는 연산자 중 가장 많이 사용되는 연산자로 덧셈, 뺄셈 등이 있다.
종류 : +, -, *,/, %,=
증감 연산자 : 이 연산자는 피연산자의 값을 1씩 증가 또는 1씩 감소 시키는 연산자이다.
- 전위 연산자 : ++a , --a : a 값을 1 증가하거나 감소한 후 리턴
- 후위 연산자 : a++ , a-- : a 값을 먼저 리턴한 후 연산자 수행
ex)
public class IncDecOperator {
public static void main(String[] args) {
// 전위 , 후위 연산자
// 전위연산자 ++a , --a : a 값을 1 증가하거나 감소한 후 리턴 a = a + 1
// 후위연산자 a++ , a-- : a 값을 먼저 리턴한 후 연산자 수행
int op = 10;
System.out.println(op++); // 10을 리턴한 후 출력되고 , 11이 된다.
System.out.println(op); // 11
System.out.println(++op); // 11을 1 증가한 후 12를 리턴해서 출력된다.
System.out.println(op); // 12
System.out.println(op--); //12을 리턴하고 11이 된다.
System.out.println(op); //11
System.out.println(--op); //10
System.out.println(op); //10
}
}
위 코드에서 보면
System.out.println(op++) 는 후위 연산자로 10의 값이 먼저 출력된 후 1이 증가하게된다.
그래서 그 다음 줄의 코드에서는 11이 출력되는 것을 볼 수 있다.
System.out.println(++op) 는 전위 연산자로 11의 값에서 1증가한 12가 된 상태로 출력되게 된다.
그 다음 줄의 코드도 앞 코드의 결과값과 같이 12가 출력되게 된다.
관계 연산자 : 비교 연산자라고도 하며 두 개의 값을 비교하여 그 결과를 리턴한는 연산자이다.
종류 : < , > , <= , >= , == , !=
삼항 연산자 : 세 개의 피연산자로 구성된 연산자로 조건에 따라 다른 내용을 수행하는 경우에 사용되는 연산자 이다.
형식 : (조건식) ? 식1 : 식 2 -> 조건식이 참이면 식1을 수행하고 거짓이면 식 2를 수행한다.
ex)
public class Ternary {
public static void main(String[] args) {
int y, k;
y = 10;
k = y < 0 ? -y : y;
System.out.println(y + " 의 절대값 " + k);
y = -10;
k = y < 0 ? -y : y;
System.out.println(y + " 의 절대값 " + k);
}
}
위 코드는 삼항 연산자를 사용한 코드이다.
k = y < 0 ? -y : y; 이 코드는 k라는 변수에 만약 y가 0보다 작을 경우 -y를 출력하고 , y가 0보다 클 경우에는 y를 출력하라는 코드이다.
위 y의 값은 10으로 조건식에 거짓이므로 10이라는 결과값이 출력되게 된다.
y 의 값이 -10일 때도 마찬가지로 조건식에 참이므로 -(-10) = 10이 출력되게 된다.
2) 논리 , 비트 , 시프트 , 대입 연산자
논리 연산자 : AND , OR , NOT을 이용하여 각 논리값들 사이에 사용되는 연산자로 결과값을 true나 false로 받을 수 있는 연산자이다.
종류 : && ( 두 값이 모두 참일 때만 true) , || ( 두 값이 모두 거짓일 때만 결과값이 false) , ! (결과값이 참이면 false , 거짓이면 true 리턴 )
ex)
int a=10, b=4;
System.out.println( (a > b++) || ( a< b++)) ; => true
비트 연산자 : 피연산자의 각 비트들을 이용해서 연산이 이루어지는 연산자
종류 : ~ (비트 반전 ) , &( 값 a와 값 b의 각 비트들을 and 연산을 하여 둘 다 참일 경우 1 나머지는 0 리턴 ) , | ( or 연산을 하여 각 비트가 모두 거짓일 경우에만 0 리턴 나머지는 1리턴 ) , ^ ( 각 비트들을 XOR 연산하며 두 비트가 서로 다르면 1 , 같으면 0 리턴 )
public class BitOperator {
public static void prn() {
int a=51;
int b=240;
System.out.println("AND ="+( a&b));
System.out.println("OR=" +(a|b));
System.out.println("XOR="+(a^b));
}
public static void main(String[] args) {
// 정수를 2진 문자열로 변경해보자.
int a=51;
int b=240;
System.out.println("a의 51을 2진 문자열로 = "+ Integer.toBinaryString(a));
System.out.println("b의 240을 2진 문자열로 = "+Integer.toBinaryString(b));
//Integer.toBinaryString(a)의 문자열로 리턴받은 이진 문자열의 16자리로 만들고 빈공간을 0으로 채우기
// 리턴받아서 String.format로 지정한 다음 출력해야한다.
// 이 자체를 메소드로 만들려면...
String str = BinaryStringPadding(a);
System.out.println(str);
String str02 = BinaryStringPadding(b);
System.out.println(str02);
String str03 = BinaryStringPadding(-20);
System.out.println(str03);
int res_a = 2;
System.out.println(BinaryStringPadding(res_a));
float res_b = 1.4f;
System.out.println(BinaryStringPadding(res_b));
double doubleValue = 3.14159485439;
long bits = Double.doubleToLongBits(doubleValue);
String binaryString = Long.toBinaryString(bits); // 변환하기
System.out.println(doubleValue+"\n"+bits+"\n"+binaryString);
System.out.println("===========NaN=============");
double non_value = Double.NaN; // 0.0 / 0.0 -> NaN -> Math.sqrt(-1)
long res03 = Double.doubleToLongBits(non_value);
long res04 = Double.doubleToLongBits(non_value);
////////////////////////////////////////////////////
///Long.toBinaryString() 로 변환해서 출력해보기
String binaryString01 = Long.toBinaryString(res03);
String binaryString02 = Long.toBinaryString(res04);
System.out.println(binaryString01 + '\n'+ binaryString02);
System.out.println(res03+" "+res04);
}
public static String BinaryStringPadding(float res) {
//
String result = String.format("%16s",Float.toHexString(res).replace(' ', '0'));
return result;
}
}
시프트 연산자 : 피연산자의 비트들을 주어진 비트수와 연산자에 특성에 따라 비트를 이동시키는 연산자
ex)
public class ShiftOp {
public static void main(String[] args) {
int x = 100;
// x를 5비트 오른쪽으로 시프트 , 왼쪽 비트를 0으로 채움
System.out.println(" x >> 5 value = " + (x >> 5));
int x1 = -100;
// x를 5비트 오른쪽으로 시프트 , 왼쪽 비트를 1로 채움
System.out.println(" x1 >> 5 value = " + (x1 >> 5));
// x를 5비트 오른쪽으로 시프트 ,왼쪽 비트를 0으로 채움
System.out.println(" x1 >>> 5 value = " + (x1 >>> 5));
}
}
대입 연산자 : 변수에 값을 저장하기 위한 용도로 오른쪽 수식을 계산한 값을 왼쪽에 있는 변수에 대입하는 연산자
종류 : = , += , -= , *= , /=, %= , &= , |= , ^= , <<= , >>= , >>>=
자바의 제어문
자바의 제어문에는 조건문 , 반복문 , 분기문 , 중첩문이 있다.
오늘은 조건문 if 와 반복문 while을 배웠으므로 이 두 개에 대해 공부해보겠다.
1) 조건문
조건문은 프로그램이 특정 조건을 만족할 경우에만 특정 코드 블록을 실행하는 구조를 제공한다.
[선언형식]
if (boolean expression) {
statement;
} else if (boolean expression) {
statement;
} else {
statement;
}
a. ~만일에 ~ 하면
if (boolean expression) {
statement;
}
b. ~ 만일에 ~ 하면 ~ 하고 , 그렇지 않으면 ~ 하자.
if (boolean expression) {
statement;
} else if (boolean expression) {
statement;
}
ex)
// 만일에 a가 0보다 크면 "양수" 출력 , 그렇지 않으면 "아니잖아!"
if ( a > 0 ) {
System.out.println(a);
} else {
System.out.println("아니잖아!!!');
}
c. ~ 만일에 ~ 하면 ~하고 , 그렇지 않으면 ~하자.
if (boolean expression) {
statement;
} else if (boolean expression) {
statement;
}else {
statement;
ex)
//만일에 num이 0보다 크면 양수를 출력하고 , 그렇지 않고 0보다 작으면 음수를 출력하고 , 그렇지 않으면 0을 출력하자
if( num >0 ) {
System.out.println("양수");
}else if ( num < 0 ) {
System.out.println("음수");
}else {
System.out.println("0");
}
2) 반복문
[선언 형식]
while (condition) { //조건식의 결과가 true이면 명령을 실행한다.
statement;
}
ex)
public class Test {
public static void main(String[] args) {
while(true) { // 참이므로 무한 반복을 하게 된다.
System.out.println("무한 반복");
}
}
}
'🦁멋쟁이 사자처럼 15기 > 3월달 수업 내용 정리' 카테고리의 다른 글
멋쟁이 사자처럼 12회 ( 03 / 13 ) (0) | 2025.03.13 |
---|---|
멋쟁이 사자처럼 11회차 ( 03 / 12 ) (0) | 2025.03.12 |
멋쟁이 사자처럼 10회차 ( 03 / 11 ) (0) | 2025.03.11 |
멋쟁이 사자처럼 9회차 ( 03 / 10 ) (0) | 2025.03.10 |
멋쟁이 사자처럼 8회차 ( 03 / 07 ) (0) | 2025.03.07 |