기본 자료형 예제 작성
Java의 기본 자료형은 숫자, 불, 문자가 있다. 다음 예제는 여러 기본 자료형 변수를 선언하고 값을 할당한다. 변수는 값 또는 값을 가리키는 주소를 담는 공간을 의미한다.
public class DataTypePractice {
public static void main(String[] args) {
// 정수
int age = 10;
long distance = 17832L;
// 실수
float temperature = 12.882F;
double elapsedTime = 242.8832;
// 불
boolean visited = true;
// 문자
char grade = 'A';
}
}형 변환 예제 만들기
형 변환은 자료형을 다른 자료형으로 바꾸는 동작이다. 다음은 형 변환의 몇 가지 예제들이다.
public class TypeCastingPractice {
public static void main(String[] args) {
// 1. 자동 형 변환
// int 자료형 → double 자료형
int opacity = 1;
double opacityDouble = opacity;
System.out.println(opacity); // 1
System.out.println(opacityDouble); // 1.0
// float 자료형 → double 자료형
float pi = 3.14F;
double piDouble = pi;
System.out.println(pi); // 3.14
System.out.println(piDouble); // 3.140000104904175
// int 자료형 → Integer 자료형 (자동 박싱)
int ten = 10;
Integer tenInteger = ten;
System.out.println(ten); // 10
System.out.println(tenInteger); // 10
// 2. 명시적 형 변환
// 문자열 자료형 → int 자료형
String ageString = "27";
int age = Integer.parseInt(ageString);
System.out.println(ageString); // 27
System.out.println(age); // 27
// int 자료형 → 문자열 자료형
int bookID = 14;
String bookIDString = Integer.toString(bookID);
System.out.println(bookID); // 14
System.out.println(bookIDString); // 14
// float 자료형 → 문자열 자료형
float height = 160.23425F;
String heightString = Float.toString(height);
System.out.println(height); // 160.23425
System.out.println(heightString); // 160.23425
// double 자료형 → int 자료형
double speed = 62.332;
int speedInt = (int) speed;
System.out.println(speed); // 62.332
System.out.println(speedInt); // 62
}
}연산자 실험
연산자는 하나 이상의 피연산자를 대상으로 임의의 연산을 수행하기 위한 문법 요소다. 다음 예제는 일련의 산술 연산, 비교 연산, 논리 연산을 수행한다.
public class OperationPractice {
public static void main(String[] args) {
// 1. 산술 연산
int a = 10;
int b = 20;
System.out.printf("%d %d %d %d\n", a + b, a - b, a * b, a / b); // 30 -10 200 0
int count = 0;
System.out.println(count++); // 0
System.out.println(++count); // 2
// 2. 비교 연산
System.out.println(1 == 2); // false
System.out.println(2.32 > 2); // true
System.out.println(23 < 12); // false
// 3. 논리 연산
System.out.println(true && true); // true
System.out.println(false && true); // false
System.out.println(true || true); // true
System.out.println(false || true); // true
System.out.println(!true); // false
}
}콘솔 계산기 구현, 예외 상황 처리, 코드 정리 및 주석 작성
import java.util.Scanner;
// 입력한 정수에 대한 사칙 연산을 수행해 출력하는 클래스입니다.
// main 메서드를 실행하고 최소 2개, 최대 3개의 정수를 공백으로 구분해 입력하세요.
public class Sample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("첫 번째 정수: ");
long a = sc.nextLong();
System.out.print("두 번째 정수: ");
long b = sc.nextLong();
System.out.printf("%d + %d = %d\n", a, b, add(a, b));
System.out.printf("%d - %d = %d\n", a, b, subtract(a, b));
System.out.printf("%d * %d = %d\n", a, b, multiply(a, b));
if (b != 0L) {
System.out.printf("%d / %d = %d\n", a, b, divide(a, b));
System.out.printf("%d %% %d = %d\n", a, b, mod(a, b));
} else {
System.out.println("0으로 나눌 수 없습니다.");
}
System.out.print("세 번째 정수: ");
long c = sc.nextLong();
System.out.printf("%d + %d * %d = %d\n", a, b, c, add(a, multiply(b, c)));
System.out.printf("(%d + %d) * %d = %d\n", a, b, c, multiply(add(a, b), c));
System.out.println("새로운 계산을 진행하시겠습니까? (Y/n)");
String answer = sc.next();
if (!answer.equals("Y") && !answer.equals("y")) {
break;
}
}
sc.close();
}
// 두 정수의 합을 반환한다.
static long add(long a, long b) {
return a + b;
}
// 두 정수의 차를 반환한다.
static long subtract(long a, long b) {
return a - b;
}
// 두 정수의 곱을 반환한다.
static long multiply(long a, long b) {
return a * b;
}
// 첫 번재 인자의 정수를 두 번째 인자의 정수로 나눈 몫을 반환한다.
static long divide(long a, long b) {
return a / b;
}
// 첫 번재 인자의 정수를 두 번째 인자의 정수로 나눈 나머지를 반환한다.
static long mod(long a, long b) {
return a % b;
}
}