
| 분류 | 연산자 | 설명 | |||
|---|---|---|---|---|---|
| 산술 | + - * / % | 사칙연산/나머지 | |||
| 대입 | = += -= *= /= %= | 오른쪽 값을 왼쪽 변수에 대입 | |||
| 증감 | ++ -- | 1씩 증/감 (단항) | |||
| 비교 | > < >= <= == != | 참/거짓 반환 | |||
| 논리 | `&& | !*(비트:& | ^ ~ << >> >>>`)* | 논리식 결합/부정 | |
| 삼항 | ? : | 조건 ? 참 : 거짓 |
&&) > 논리 OR(||) > 대입(=)()가 최고 우선순위.int a=20,b=7;
a+b; a-b; a*b; a/b; a%b; // 27,13,140,2,6
int n=12;
n = n + 3; // 15
n += 3; // 18
n -= 5; // 13
n *= 2; // 26
n /= 2; // 13
n =- 5; // 주의! (음수 대입) == n = (-5)
int x=20;
int r1 = x++ * 3; // 60, x=21
int r2 = ++x * 3; // x 먼저 22 → 66
10 == 20; // false
'a' > 'A'; // true (문자는 내부적으로 정수)
| A | B | A&\&B | A||B | !A |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | F |
| F | T | F | T | T |
| F | F | F | F | T |
false && … 뒤는 실행 안 함, true || … 뒤는 실행 안 함.int n=5;
String s = (n>0) ? "양수" : (n==0) ? "0" : "음수";
접근제어자 반환타입 메소드명(매개변수들) {
// 로직
return 값; // 반환타입이 void면 생략 가능
}
public void hello() { System.out.println("hi"); }
public int add(int a,int b){ return a+b; }
// 호출
hello();
int sum = add(3,4);
public / protected / (default) / privatevoid 또는 타입(int, String, …)public static int sum(int a,int b){ return a+b; }
Application.sum(1,2); // 클래스명으로 호출
sum(2,3); // 같은 클래스면 생략 가능
Calculator c = new Calculator(); // non-static
int min = c.minNumberOf(3,9);
int max = Calculator.maxNumberOf(3,9); // static
package 선언.kr.ac.example.calc.Calculatorpackage a.b;
import x.y.Calculator; // 클래스 임포트
import static x.y.Util.max; // static 임포트
Calculator c = new Calculator();
int m = max(3,5); // 클래스명 생략 가능
Math (전부 static)Math.abs(-7); // 7
Math.min(10,20); // 10
Math.max(20,30); // 30
Math.PI; // 3.1415926535...
Math.random(); // [0.0, 1.0) 실수 난수
원하는 정수 범위 난수 공식
// [min, max] 정수 난수
int r = (int)(Math.random() * (max - min + 1)) + min;
java.util.RandomRandom rd = new Random();
rd.nextInt(10); // 0~9
rd.nextInt(6)+10; // 10~15
rd.nextInt(256)-128;// -128~127
| 메소드 | 반환 |
|---|---|
next() | 공백 전까지 String |
nextLine() | 줄 끝(개행 전)까지 String |
nextInt()/nextLong() | 정수 |
nextFloat()/nextDouble() | 실수 |
nextBoolean() | true/false |
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = sc.nextInt();
double h = sc.nextDouble();
boolean ok = sc.nextBoolean();
// 문자 1개 받기(문자 전용 없음 → 문자열에서 추출)
sc.nextLine(); // 버퍼 정리용 (필요 시)
char ch = sc.nextLine().charAt(0);
next() 후 숫자 입력 시, 공백 포함 입력이면 다음 토큰이 숫자가 아니어서 InputMismatchException 발생 →
공백 포함 문자열은 nextLine() 사용.
숫자 입력(nextInt() 등) 후 곧바로 nextLine() 하면, 남은 개행을 nextLine()이 읽어버려 빈 문자열이 됨 →
중간에 sc.nextLine()으로 개행 소비 후 다시 nextLine().
// 1) 정수 곱에서 오버플로우 방지
int a=1_000_000, b=700_000;
long good = (long)a * b;
// 2) 문자 범위 검사(대문자)
char c='G';
boolean isUpper = (c>='A' && c<='Z');
// 3) 영문자 여부
boolean isAlpha = (c>='A'&&c<='Z') || (c>='a'&&c<='z');
// 4) 삼항 중첩
int n=0;
String sign = (n>0)?"양수":(n==0)?"0":"음수";