Created date: Thu, 21 Jul 2022 14:26 KST
자바에서 연산자는 어떻게 활용할까요?
안녕하세요. shcDE입니다. 이번 포스팅에서는 자바에서 어떻게 연산자를 활용하는지 알아보겠습니다. 프로그래밍을 할 때 쓰이는 연산자란 ‘연산을 수행하는 기호’를 말합니다. 예를 들어 ‘+’ 기호는 덧셈 연산을 수행하며, ‘덧셈 연산자’라고 불립니다. 자바에서는 사칙연산(+, -, *, /)을 비롯해서 다양한 연산자들을 제공합니다. 처음에는 배워야할 연산자가 많아 보이지만, 자주 쓰이는 것들을 중심으로 하여 하나씩 실습을 진행하겠습니다.
시작 전에, 해당 포스팅은 직접 ‘자바의 정석(3판)’을 구매하여 3장을 공부한 내용을 정리한 자료임을 밝힙니다. 추가로 사용한 IDE는 ‘인텔리제이 IDEA CE’이며, 자바8 버전을 사용하였음을 밝힙니다.
우선 단항 연산자에서 증감 연산자에 대해 알아보겠습니다. 증감 연산자는 증가 연산자 ‘++‘와 감소 연산자 ‘–‘로 구성되어 있습니다. 사용 예시는 다음과 같습니다.
- ● 예제 3-1
public class HelloWorldPrint {
public static void main(String[] args) {
int i=5;
i++; // i=i+1;과 같은 의미이다. ++i;로 바꿔 써도 결과는 같다.
System.out.println(i);
i=5; // 결과를 비교하기 위해 i값을 다시 5로 변경
++i;
System.out.println(i);
}
}
6
6
Process finished with exit code 0
독립적인 하나의 문장으로 증감 연산자가 쓰일 경우, 위와 같이 전위형, 후위형 상관 없이 동일한 결과를 호출하게 됩니다. 하지만 다른 수식에 포함되거나, 메서드의 매개변수로 사용된 경우, 즉 단독으로 사용되지 않은 경우 전위형(++i)와 후위형(i++)의 결과는 다릅니다. 해당 결과에 대한 예시는 다음과 같습니다.
- ● 예제 3-2
public class HelloWorldPrint {
public static void main(String[] args) {
int i=5, j=0;
j = i++;
System.out.println("j=i++; 실행 후, i=" + i +", j="+ j);
i=5; // 결과를 비교하기 위해, i와 j의 값을 다시 5와 0으로 변경
j=0;
j = ++i;
System.out.println("j=++i; 실행 후, i=" + i +", j="+ j);
}
}
j=i++; 실행 후, i=6, j=5
j=++i; 실행 후, i=6, j=6
Process finished with exit code 0
위의 사례를 보면 전위형(++i)에서는 i의 값을 증가시킨 후에 읽어오므로 i의 값이 5에서 6으로 증가된 후에 이 값이 j에 저장되며, 후위형(i++)에서는 i값인 5를 먼저 읽어온 다음에 i를 증가시키므로 j에 5가 저장되는 것을 확인할 수 있습니다. 이렇게 후위형과 전위형을 잘 구분하여 코드를 작성하는 것은 중요하다고 볼 수 있습니다.
이제 다음 예제를 통해 메서드 호출 시 증감 연산자가 사용된 예시를 보겠습니다.
- ● 예제 3-3
public class HelloWorldPrint {
public static void main(String[] args) {
int i=5, j=5;
System.out.println(i++);
System.out.println(++j);
System.out.println("i = " + i + ", j = " +j);
}
}
5
6
i = 6, j = 6
Process finished with exit code 0
해당 사례에서는 첫번째 출력은 i값을 먼저 읽어와서 출력하므로 5가 나옵니다. 그리고 두번째 출력은 j를 증가시킨 후에 출력하므로 6이 나옵니다. 그 이후에 세번째 출력에서는 전위형, 후위형의 연산이 모두 적용된 상태에서 다시 출력하므로 i, j 모두 6이 나오는 것을 확인할 수 있습니다.
자바에서는 부호 연산자도 적용시킬 수 있습니다. 다음은 해당 연산자 적용에 대한 예시입니다.
- ● 예제 3-4
public class HelloWorldPrint {
public static void main(String[] args) {
int i = -10;
i = +i;
System.out.println(i);
i=-10;
i = -i;
System.out.println(i);
}
}
-10
10
Process finished with exit code 0
이런 방식으로 음수의 정수도 문제 없이 출력할 수 있습니다.
이제 다음으로 산술 연산자에 대해 알아보겠습니다. 우선 사칙 연산자 실행 예시를 보겠습니다.
- ● 예제 3-5
public class HelloWorldPrint {
public static void main(String[] args) {
int a = 10;
int b = 4;
System.out.printf("%d + %d = %d\n", a, b, a + b);
System.out.printf("%d - %d = %d\n", a, b, a - b);
System.out.printf("%d * %d = %d\n", a, b, a * b);
System.out.printf("%d / %d = %d\n", a, b, a / b);
System.out.printf("%d / %f = %f\n", a, (float)b, a / (float)b);
}
}
10 + 4 = 14
10 - 4 = 6
10 * 4 = 40
10 / 4 = 2
10 / 4.000000 = 2.500000
Process finished with exit code 0
다음 예시와 같이 +, -, *, / 연산자를 활용해서 기본 연산을 실행할 수 있습니다.
하지만 byte 형 연산을 다음과 같이 실행하면 오류가 발생합니다.
- ● 예제 3-6
public class HelloWorldPrint {
public static void main(String[] args) {
byte a = 10;
byte b = 20;
byte c = a + b;
System.out.println(c);
}
}
java: incompatible types: possible lossy conversion from int to byte
해당 에러가 발생하는 이유는 연산자 +가 a, b를 모두 int 형으로 변환 후에 실행하기 때문입니다. 그래서 byte 형을 유지하여 연산을 다음과 같이 실행해야 합니다.
- ● 예제 3-7
public class HelloWorldPrint {
public static void main(String[] args) {
byte a = 10;
byte b = 30;
byte c = (byte)(a * b);
System.out.println(c);
}
}
44
Process finished with exit code 0
앞에 (byte)를 붙이면 정상적으로 byte 형을 유지하여 실행이 되는 것을 확인할 수 있습니다.
이번에는 원하는 값이 출력되지 않는 두 가지 사례를 보겠습니다.
- ● 예제 3-8
public class HelloWorldPrint {
public static void main(String[] args) {
int a = 1000000; // 1,000,000 1백만
int b = 2000000; // 2,000,000 2백만
long c = a * b; // a * b = 2,000,000,000,000 ?
System.out.println(c);
}
}
-1454759936
Process finished with exit code 0
- ● 예제 3-9
public class HelloWorldPrint {
public static void main(String[] args) {
long a = 1000000 * 1000000;
long b = 1000000 * 1000000L;
System.out.println("a="+a);
System.out.println("b="+b);
}
}
a=-727379968
b=1000000000000
Process finished with exit code 0
위의 사례들과 같은 값이 제대로 출력되지 않는 문제를 해결하려면 long 타입 변환을 하여 계산을 하거나, long 타입을 올바르게 입력해야 합니다. 여기에서 3-9의 b 값에서 올바른 값이 나왔으므로, 3-8을 올바르게 수정한 코드만 보여드리겠습니다.
- ● 예제 3-8 수정
public class HelloWorldPrint {
public static void main(String[] args) {
int a = 1000000; // 1,000,000 1백만
int b = 2000000; // 2,000,000 2백만
long c = (long)a * b; // a * b = 2,000,000,000,000 ?
System.out.println(c);
}
}
2000000000000
Process finished with exit code 0
3-8에서 a * b 앞에 (long)을 붙여서 형변환 후 출력하니까 정상적으로 결과가 출력되었습니다.
사칙연산의 순서에 따라 결과가 다르게 나오는 예시는 다음과 같습니다.
- ● 예제 3-10
public class HelloWorldPrint {
public static void main(String[] args) {
int a = 1000000;
int result1 = a * a / a; // 1000000 * 1000000 / 1000000
int result2 = a / a * a; // 1000000 / 1000000 * 1000000
System.out.printf("%d * %d / %d = %d\n", a, a, a, result1);
System.out.printf("%d / %d * %d = %d\n", a, a, a, result2);
}
}
1000000 * 1000000 / 1000000 = -727
1000000 / 1000000 * 1000000 = 1000000
Process finished with exit code 0
위와 같이, 연산의 우선순위가 동일한 경우, 앞의 연산이 먼저 실행되므로 항상 주의하면서 수식을 적는 것을 권장드립니다.
추가로, 사칙연산의 피연산자로 숫자뿐만 아니라 문자도 가능합니다. 활용 사례는 다음과 같습니다.
- ● 예제 3-11
public class HelloWorldPrint {
public static void main(String[] args) {
char a = 'a';
char d = 'd';
char zero = '0';
char two = '2';
System.out.printf("'%c' - '%c' = %d\n", d, a, d - a); // 'd' - 'a' = 3
System.out.printf("'%c' - '%c' = %d\n", two, zero, two - zero);
System.out.printf("'%c'=%d\n", a, (int)a);
System.out.printf("'%c'=%d\n", d, (int)d);
System.out.printf("'%c'=%d\n", zero, (int)zero);
System.out.printf("'%c'=%d\n", two, (int)two);
}
}
'd' - 'a' = 3
'2' - '0' = 2
'a'=97
'd'=100
'0'=48
'2'=50
Process finished with exit code 0
- ● 예제 3-12
public class HelloWorldPrint {
public static void main(String[] args) {
char c1 = 'a'; // c1에는 문자 'a'의 코드값인 97이 저장된다.
char c2 = c1; // c1에 저장되어 있는 값이 c2에 저장된다.
char c3 =' '; // c3을 공백으로 초기화한다.
int i = c1 + 1; // 'a'+1 -> 97+1 -> 98
c3 = (char)(c1 + 1);
c2++;
c2++;
System.out.println("i=" + i);
System.out.println("c2=" + c2);
System.out.println("c3=" + c3);
}
}
i=98
c2=c
c3=b
Process finished with exit code 0
컴파일 오류가 발생하는 식을 컴파일 에러가 발생하지 않는 식으로 대체하면 컴파일 오류가 발생하지 않습니다. 사용 예시는 다음과 같습니다.
- ● 예제 3-13
public class HelloWorldPrint {
public static void main(String[] args) {
char c1 = 'a';
// char c2 = c1+1; // 라인 5 : 컴파일 에러 발생!!!
char c2 = 'a'+1; // 라인 6 : 컴파일 에러 없음
System.out.println(c2);
}
}
b
Process finished with exit code 0
자바에서는 반복문을 통해 알파벳도 연속으로 출력할 수 있습니다. 사용 예시는 다음과 같습니다.
- ● 예제 3-14
public class HelloWorldPrint {
public static void main(String[] args) {
char c = 'a';
for(int i=0; i<26; i++) { // 블럭{} 안의 문장을 26번을 반복한다.
System.out.print(c++); //'a'부터 26개의 문자를 출력한다.
}
System.out.println(); // 줄바꿈을 한다.
c = 'A';
for(int i=0; i<26; i++) { // 블럭{} 안의 문장을 26번을 반복한다.
System.out.print(c++); //'A'부터 26개의 문자를 출력한다.
}
System.out.println();
c='0';
for(int i=0; i<10; i++) { // 블럭{} 안의 문장을 10번 반복한다.
System.out.print(c++); // '0'부터 10개의 문자를 출력한다.
}
System.out.println();
}
}
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
Process finished with exit code 0
문자는 대문자 및 소문자로 변경도 가능합니다. 다음과 같이 32를 빼고 더해서 변경할 수 있습니다.
- ● 예제 3-15
public class HelloWorldPrint {
public static void main(String[] args) {
char lowerCase = 'a';
char upperCase = (char)(lowerCase - 32);
System.out.println(upperCase);
}
}
A
Process finished with exit code 0
float 값을 int로 변형하여 결과를 출력하면 다음과 같이 소수점 아래 값이 버려진 상태로 출력됩니다.
- ● 예제 3-16
public class HelloWorldPrint {
public static void main(String[] args) {
float pi = 3.141592f;
float shortPi = (int)(pi * 1000) / 1000f;
System.out.println(shortPi);
}
}
3.141
Process finished with exit code 0
소수점 넷째 자리에서 반올림하려면 다음과 같이 pi * 1000을 pi * 1000 + 0.5로 바꾸면 됩니다.
- ● 예제 3-17
public class HelloWorldPrint {
public static void main(String[] args) {
double pi = 3.141592;
double shortPi = (int)(pi * 1000 + 0.5) / 1000.0;
System.out.println(shortPi);
}
}
3.142
Process finished with exit code 0
반올림을 할 때 Math.round()를 사용해도 동일한 결과를 보여줄 수 있습니다.
- ● 예제 3-18
public class HelloWorldPrint {
public static void main(String[] args) {
double pi = 3.141592;
double shortPi = Math.round(pi * 1000) / 1000.0;
System.out.println(shortPi);
}
}
3.142
Process finished with exit code 0
나머지 연산자는 다음과 같이 사용할 수 있습니다. 3-20 예제의 경우, 나누는 수로 음수도 허용하지만, 부호가 무시된다는 점 유의해주시길 바랍니다.
- ● 예제 3-19
public class HelloWorldPrint {
public static void main(String[] args) {
int x = 10;
int y = 8;
System.out.printf("%d을 %d로 나누면, %n", x, y);
System.out.printf("몫은 %d이고, 나머지는 %d입니다. %n", x / y, x % y);
}
}
10을 8로 나누면,
몫은 1이고, 나머지는 2입니다.
Process finished with exit code 0
- ● 예제 3-20
public class HelloWorldPrint {
public static void main(String[] args) {
System.out.println(-10%8);
System.out.println(10%-8);
System.out.println(-10%-8);
}
}
-2
2
-2
Process finished with exit code 0
다음으로 비교 연산자 출력 결과는 다음과 같습니다.
- ● 예제 3-21
public class HelloWorldPrint {
public static void main(String[] args) {
System.out.printf("10 == 10.0f \t %b\n", 10==10.0f);
System.out.printf("'0'== 0 \t %b\n", '0'== 0);
System.out.printf("'\\0'== 0 \t %b\n", '\0'== 0);
System.out.printf("'A'== 65 \t %b\n", 'A'== 65);
System.out.printf("'A' > 'B' \t %b\n", 'A' > 'B');
System.out.printf("'A'+1 != 'B' \t %b\n", 'A'+1 != 'B');
}
}
10 == 10.0f true
'0'== 0 false
'\0'== 0 true
'A'== 65 true
'A' > 'B' false
'A'+1 != 'B' false
Process finished with exit code 0
다음은 ‘0.1==0.1f’는 ‘10.0==10.0f’와 다르게 실수형이므로 근사값으로 저장되므로 오차가 발생하여 false가 발생하는 예시입니다.
- ● 예제 3-22
public class HelloWorldPrint {
public static void main(String[] args) {
float f = 0.1f;
double d = 0.1;
double d2 = (double)f;
System.out.printf("10.0==10.0f %b\n", 10.0==10.0f);
System.out.printf("0.1==0.1f %b\n", 0.1==0.1f);
System.out.printf("f =%19.17f\n", f);
System.out.printf("d =%19.17f\n", d);
System.out.printf("d2=%19.17f\n", d2);
System.out.printf("d==f %b\n", d==f);
System.out.printf("d==d2 %b\n", d==d2);
System.out.printf("d2==f %b\n", d2==f);
System.out.printf("(float)d==f %b\n", (float)d==f);
}
}
10.0==10.0f true
0.1==0.1f false
f =0.10000000149011612
d =0.10000000000000000
d2=0.10000000149011612
d==f false
d==d2 false
d2==f true
(float)d==f true
Process finished with exit code 0
문자열의 비교는 다음과 같이 진행할 수 있습니다. 여기에서는 str1과 str2가 내용이 같아도 서로 다른 객체이므로 ‘==‘로 비교하면 false가 출력되는 결과를 보여주고 있습니다. 하지만, equals()를 사용하면 객체가 달라도 true를 반환하는 사실도 보여주고 있습니다. 그래서 문자열을 비교할 때는 항상 equals()를 사용하시는 것을 권장드립니다.
- ● 예제 3-23
public class HelloWorldPrint {
public static void main(String[] args) {
String str1 = "abc";
String str2 = new String("abc");
System.out.printf("\"abc\"==\"abc\" ? %b%n", "abc"=="abc");
System.out.printf(" str1==\"abc\" ? %b%n", str1=="abc");
System.out.printf(" str2==\"abc\" ? %b%n", str2=="abc");
System.out.printf("str1.equals(\"abc\") ? %b%n", str1.equals("abc"));
System.out.printf("str2.equals(\"abc\") ? %b%n", str2.equals("abc"));
System.out.printf("str2.equals(\"ABC\") ? %b%n", str2.equals("ABC"));
System.out.printf("str2.equalsIgnoreCase(\"ABC\") ? %b%n", str2.equalsIgnoreCase("ABC"));
}
}
"abc"=="abc" ? true
str1=="abc" ? true
str2=="abc" ? false
str1.equals("abc") ? true
str2.equals("abc") ? true
str2.equals("ABC") ? false
str2.equalsIgnoreCase("ABC") ? true
Process finished with exit code 0
자바는 논리 연산자도 활용할 수 있습니다. 사용 예시는 다음과 같습니다.
- ● 예제 3-24
public class HelloWorldPrint {
public static void main(String[] args) {
int x = 0;
char ch = ' ';
x = 15;
System.out.printf("x=%2d, 10 < x && x < 20 =%b\n", x, 10 < x && x < 20);
x = 6;
System.out.printf("x=%2d, x%%2==0 || x%%3==0 && x%%6!=0 =%b\n", x, x%2==0||x%3==0&&x%6!=0);
System.out.printf("x=%2d, (x%%2==0 || x%%3==0) && x%%6!=0 =%b\n", x,(x%2==0||x%3==0)&&x%6!=0);
ch='1';
System.out.printf("ch='%c', '0' <= ch && ch <= '9' =%b\n", ch, '0' <= ch && ch <='9');
ch='a';
System.out.printf("ch='%c', 'a' <= ch && ch <= 'z' =%b\n", ch, 'a' <= ch && ch <='z');
ch='A';
System.out.printf("ch='%c', 'A' <= ch && ch <= 'Z' =%b\n", ch, 'A' <= ch && ch <='Z');
ch='q';
System.out.printf("ch='%c', ch=='q' || ch=='Q' =%b\n", ch, ch=='q' || ch=='Q');
}
}
x=15, 10 < x && x < 20 =true
x= 6, x%2==0 || x%3==0 && x%6!=0 =true
x= 6, (x%2==0 || x%3==0) && x%6!=0 =false
ch='1', '0' <= ch && ch <= '9' =true
ch='a', 'a' <= ch && ch <= 'z' =true
ch='A', 'A' <= ch && ch <= 'Z' =true
ch='q', ch=='q' || ch=='Q' =true
Process finished with exit code 0
다음 예제와 같이 if문과 논리 연산자의 결합을 통해 숫자, 문자를 판별할 수 있습니다.
- ● 예제 3-25
import java.util.*; // Scanner를 사용하기 위해 추가
public class HelloWorldPrint {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char ch = ' ';
System.out.printf("문자를 하나 입력하세요.>");
String input = scanner.nextLine();
ch = input.charAt(0);
if('0'<= ch && ch <= '9') {
System.out.printf("입력하신 문자는 숫자입니다. %n");
}
if(('a'<= ch && ch <= 'z') || ('A'<= ch && ch <= 'Z')) {
System.out.printf("입력하신 문자는 영문자입니다. %n");
}
} // main
}
문자를 하나 입력하세요.>7
입력하신 문자는 숫자입니다.
Process finished with exit code 0
문자를 하나 입력하세요.>a
입력하신 문자는 영문자입니다.
Process finished with exit code 0
논리 연산자가 효율적인지 확인하는 방법은 다음과 같이 ||, &&을 사용할 수 있습니다.
- ● 예제 3-26
public class HelloWorldPrint {
public static void main(String[] args) {
int a = 5;
int b = 0;
System.out.printf("a=%d, b=%d%n", a, b);
System.out.printf("a!=0 || ++b!=0 = %b%n", a!=0 || ++b!=0);
System.out.printf("a=%d, b=%d\n", a, b);
System.out.printf("a==0 && ++b!=0 = %b%n", a==0 && ++b!=0);
System.out.printf("a=%d, b=%d%n", a, b);
} // main의 끝
}
a=5, b=0
a!=0 || ++b!=0 = true
a=5, b=0
a==0 && ++b!=0 = false
a=5, b=0
Process finished with exit code 0
논리 부정 연산은 다음과 같이 사용할 수 있습니다.
- ● 예제 3-27
public class HelloWorldPrint {
public static void main(String[] args) {
boolean b = true;
char ch = 'C';
System.out.printf("b=%b\n", b);
System.out.printf("!b=%b\n", !b);
System.out.printf("!!b=%b\n", !!b);
System.out.printf("!!!b=%b\n", !!!b);
System.out.println();
System.out.printf("ch=%c\n", ch);
System.out.printf("ch < 'a' || ch > 'z'=%b\n", ch < 'a' || ch > 'z');
System.out.printf("!('a'<=ch && ch<='z')=%b\n", !('a'<= ch && ch<='z'));
System.out.printf(" 'a'<=ch && ch<='z' =%b\n", 'a'<=ch && ch<='z');
} // main의 끝
}
b=true
!b=false
!!b=true
!!!b=false
ch=C
ch < 'a' || ch > 'z'=true
!('a'<=ch && ch<='z')=true
'a'<=ch && ch<='z' =false
Process finished with exit code 0
다음으로 비트 연산자 사용 예시는 다음과 같습니다.
- ● 예제 3-28
public class HelloWorldPrint {
public static void main(String[] args) {
int x = 0xAB;
int y = 0xF;
System.out.printf("x = %#X \t\t%s%n", x, toBinaryString(x));
System.out.printf("y = %#X \t\t%s%n", x, toBinaryString(y));
System.out.printf("%#X | %#X = %#X \t%s%n", x, y, x | y, toBinaryString(x | y));
System.out.printf("%#X & %#X = %#X \t%s%n", x, y, x & y, toBinaryString(x & y));
System.out.printf("%#X ^ %#X = %#X \t%s%n", x, y, x ^ y, toBinaryString(x ^ y));
System.out.printf("%#X ^ %#X ^ %#X = %#X %s%n", x, y, y, x ^ y ^ y, toBinaryString(x ^ y ^ y));
} // main의 끝
// 10진 정수를 2진수로 변환하는 메서드
static String toBinaryString(int x) {
String zero = "00000000000000000000000000000000";
String tmp = zero + Integer.toBinaryString(x);
return tmp.substring(tmp.length()-32);
}
}
x = 0XAB 00000000000000000000000010101011
y = 0XAB 00000000000000000000000000001111
0XAB | 0XF = 0XAF 00000000000000000000000010101111
0XAB & 0XF = 0XB 00000000000000000000000000001011
0XAB ^ 0XF = 0XA4 00000000000000000000000010100100
0XAB ^ 0XF ^ 0XF = 0XAB 00000000000000000000000010101011
Process finished with exit code 0
비트 전환 연산자 사용 예시는 다음과 같습니다.
- ● 예제 3-29
public class HelloWorldPrint {
public static void main(String[] args) {
byte p = 10;
byte n = -10;
System.out.printf(" p =%d \t%s%n", p, toBinaryString(p));
System.out.printf("~p =%d \t%s%n", ~p, toBinaryString(~p));
System.out.printf("~p+1=%d \t%s%n", ~p+1, toBinaryString(~p+1));
System.out.printf("~~p =%d \t%s%n", ~~p, toBinaryString(~~p));
System.out.println();
System.out.printf(" n =%d%n", n);
System.out.printf("~(n-1)=%d%n", ~(n-1));
} // main의 끝
// 10진수 정수를 2진수로 변환하는 메서드
static String toBinaryString(int x) {
String zero = "00000000000000000000000000000000";
String tmp = zero + Integer.toBinaryString(x);
return tmp.substring(tmp.length()-32);
}
}
p =10 00000000000000000000000000001010
~p =-11 11111111111111111111111111110101
~p+1=-10 11111111111111111111111111110110
~~p =10 00000000000000000000000000001010
n =-10
~(n-1)=10
Process finished with exit code 0
쉬프트 연산자를 활용하여 작성한 코드의 두 가지 예시는 다음과 같습니다.
- ● 예제 3-30
public class HelloWorldPrint {
public static void main(String[] args) {
int dec = 8;
System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
System.out.println();
dec = -8;
System.out.printf("%d >> %d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec >> 0));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 1, dec >> 1, toBinaryString(dec >> 1));
System.out.printf("%d >> %d = %4d \t%s%n", dec, 2, dec >> 2, toBinaryString(dec >> 2));
System.out.printf("%d << %d = %4d \t%s%n", dec, 0, dec << 0, toBinaryString(dec << 0));
System.out.printf("%d << %d = %4d \t%s%n", dec, 1, dec << 1, toBinaryString(dec << 1));
System.out.printf("%d << %d = %4d \t%s%n", dec, 2, dec << 2, toBinaryString(dec << 2));
System.out.println();
dec = 8;
System.out.printf("%d >> %2d = %4d \t%s%n", dec, 0, dec >> 0, toBinaryString(dec << 2));
System.out.printf("%d >> %2d = %4d \t%s%n", dec, 32, dec >> 32, toBinaryString(dec << 2));
} // main의 끝
// 10진 정수를 2진수로 변환하는 메서드
static String toBinaryString(int x) {
String zero = "00000000000000000000000000000000";
String tmp = zero + Integer.toBinaryString(x);
return tmp.substring(tmp.length()-32);
}
}
8 >> 0 = 8 00000000000000000000000000001000
8 >> 1 = 4 00000000000000000000000000000100
8 >> 2 = 2 00000000000000000000000000000010
8 << 0 = 8 00000000000000000000000000001000
8 << 1 = 16 00000000000000000000000000010000
8 << 2 = 32 00000000000000000000000000100000
-8 >> 0 = -8 11111111111111111111111111111000
-8 >> 1 = -4 11111111111111111111111111111100
-8 >> 2 = -2 11111111111111111111111111111110
-8 << 0 = -8 11111111111111111111111111111000
-8 << 1 = -16 11111111111111111111111111110000
-8 << 2 = -32 11111111111111111111111111100000
8 >> 0 = 8 00000000000000000000000000100000
8 >> 32 = 8 00000000000000000000000000100000
Process finished with exit code 0
- ● 예제 3-31
public class HelloWorldPrint {
public static void main(String[] args) {
int dec = 1234;
int hex = 0xABCD;
int mask = 0xF;
System.out.printf("hex=%X%n", hex);
System.out.printf("%X%n", hex & mask);
hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
hex = hex >> 4;
System.out.printf("%X%n", hex & mask);
} // main의 끝
}
hex=ABCD
D
C
B
A
Process finished with exit code 0
마지막으로, 조건 연산자 ?를 사용하는 예시는 다음과 같습니다.
- ● 예제 3-32
public class HelloWorldPrint {
public static void main(String[] args) {
int x, y, z;
int absX, absY, absZ;
char signX, signY, signZ;
x = 10;
y = -5;
z = 0;
absX = x >= 0 ? x : -x; // x의 값이 음수이면, 양수로 만든다.
absY = y >= 0 ? y : -y;
absZ = z >= 0 ? z : -z;
signX = x > 0 ? '+' : ( x==0 ? ' ' : '-'); // 조건 연산자를 중첩
signY = y > 0 ? '+' : ( y==0 ? ' ' : '-');
signZ = z > 0 ? '+' : ( z==0 ? ' ' : '-');
System.out.printf("x=%c%d\n", signX, absX);
System.out.printf("y=%c%d\n", signY, absY);
System.out.printf("z=%c%d\n", signZ, absZ);
}
}
x=+10
y=-5
z= 0
Process finished with exit code 0
이상으로 자바에서 연산자를 활용하는 예시에 대해 모두 확인하였습니다. 다음 포스팅은 조건문과 반복문을 활용하는 예시를 가져올 예정입니다. 오늘도 긴 글 읽어주셔서 고생하셨습니다.
감사합니다.
[레퍼런스]