오늘 포스팅을 따라하기에 앞서 리눅스 우분투에서 자바 소스코드 개발 환경이 구성되어있지 않다면 이전에 다룬 포스팅을 참고해주세요. OpenJDK 8을 설치하는 방법이 소개되어있습니다. 이후 아래 예제를 직접 실행해보면서 따라와주세요.
2023.08.10 - [Linux] - [Linux/Java] 리눅스 우분투에 자바 개발도구 JDK 설치 예제(OpenJDK8)
또한 직접 작성한 예제를 실행하려면 작성한 자바 소스 코드 파일을 컴파일하여야합니다. 아래의 java 파일 컴파일 명령인 javac 사용방법을 확인하고 아래 예제를 진행해주세요.
2023.08.10 - [Linux] - [Linux/Java] 리눅스 우분투에서 java 컴파일 및 실행 예제(javac)
Boolean은 True(1), False(0) 두개의 값을 가지는 타입입니다. 즉 하거나 안하거나 입니다. 이 변수를 가지고 if문 조건문을 작성하는 방법을 알아보겠습니다. 아래는 예제 코드입니다.
public class Example {
public static void main(String[] args) {
boolean condition = true;
if (condition) {
System.out.println("Boolean value is true");
} else {
System.out.println("Boolean value is false");
}
condition = false;
if (condition) {
System.out.println("Boolean value is true");
} else {
System.out.println("Boolean value is false");
}
}
}
다음은 integer 변수에 저장되어있는 정수값이 특정 값보다 크거나 작거나 같을 때 조건문 예제입니다. 맞거나 다르거나 2개의 조건이 아니라 조건1, 조건2, 조건3.... 과 같이 여러개의 조건을 표현하려면 else if문을 사용합니다.
public class Example {
public static void main(String[] args) {
int number = 15;
int threshold = 10;
if (number > threshold) {
System.out.println("Number is greater than the threshold");
} else if (number < threshold) {
System.out.println("Number is less than the threshold");
} else {
System.out.println("Number is equal to the threshold");
}
number = 5;
if (number > threshold) {
System.out.println("Number is greater than the threshold");
} else if (number < threshold) {
System.out.println("Number is less than the threshold");
} else {
System.out.println("Number is equal to the threshold");
}
number = 10;
if (number > threshold) {
System.out.println("Number is greater than the threshold");
} else if (number < threshold) {
System.out.println("Number is less than the threshold");
} else {
System.out.println("Number is equal to the threshold");
}
}
}
마지막으로 자바에서 문자열이 특정 문자열과 동일한지 if 문을 활용하여 비교하는 예제입니다.
public class Example {
public static void main(String[] args) {
String inputString = "Hello";
String targetString = "Hello";
if (inputString.equals(targetString)) {
System.out.println("Input string is equal to the target string");
} else {
System.out.println("Input string is not equal to the target string");
}
inputString = "oooooooooooo!";
if (inputString.equals(targetString)) {
System.out.println("Input string is equal to the target string");
} else {
System.out.println("Input string is not equal to the target string");
}
}
}