public static void main(String[] args) {
// 두개의 변수가 같은 데이터 타입 일 때 아래와 같이 코드를 작성한다.
String a, b;
}
public static void main(String[] args) {
String a, b;
/*
a = "coding";
b = "everybody";
System.out.println(a+b);
*/
}
/**로 시작하는 주석은 JavaDoc 주석이라고 해서 자바의 문서를 만들 때 사용한다.
/**
* Prints an integer and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(int)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>int</code> to be printed.
*/
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
세미콜론은 문장(statement)의 끝을 의미한다.
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();
| 작은 단위 | 큰단위 |
|---|---|
| 8 bit (비트) | 1 byte |
| 1024 byte (바이트) | 1 kilobyte |
| 1024 kilobyte (킬로바이트) | 1 megabyte |
| 1024 megabyte (메가바이트) | 1 gigabyte |
| 1024 gigabyte (기가바이트) | 1 terabyte |
| 1024 terabyte (테라바이트) | 1 petabyte |
| 1024 petabyte (페타바이트) | 1 exabyte |
| 1024 exabyte (엑사바이트) | 1 zettabyte |
| 데이터 타입 | 메모리의 크기 | 표현 가능 범위 |
|---|---|---|
| byte | 1 byte | -128 ~ 127 |
| short | 2 byte | -32,768 ~ 32,767 |
| int | 4 byte | -2,147,483,648~2,147,483,647 |
| long | 8 byte | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
| 데이터 타입 | 메모리의 크기 | 표현 가능 범위 |
|---|---|---|
| float | 4byte | ±(1.40129846432481707e-45 ~ 3.40282346638528860e+38) |
| double | 8byte | ±(4.94065645841246544e-324d ~ 1.79769313486231570e+308d) |
자바에서는 문자와 문자열이 다르다. 문자(character)는 글자 하나를 의미하고, 문자열은 글자들의 집합을 의미한다.
| 데이터 타입 | 메모리의 크기 | 표현 가능 범위 |
|---|---|---|
| char | 2byte | 모든 유니코드 문자 |
아래 코드는 오류를 발생한다.
int a = 2.2;
2.2는 실수다. 실수를 정수 타입의 변수 a에 저장하려고 했기 때문에 오류가 발생한 것이다. 이것은 변수와 똑같이 상수도 데이터 타입이 있다는 것이다.
그럼 위의 예에서 사용한 상수 2.2의 데이터 타입은 무엇일까? float일까? double일까?
float a = 2.2;
오류 발생 : "Type mismatch: cannot convert from double to float"
double a = 2.2;
자바에서 실수형 상수는 double의 데이터 타입이다.
그럼 float 형 변수에는 어떻게 값을 대입할 수 있나? 2.2가 float 형이라는 것을 분명하게 명시해주면 된다.
float a = 2.2F;
F는 이 기호 앞의 숫자가 float 데이터 타입이라는 것을 명시적으로 표현하는 방법이다.
데이터 타입이 정수인 상수는 어떤 데이터 타입이 될까? int다.
int a = 2147483648;
int의 최댓값인 2147483647 보다 1 많기 때문에 에러가 발생했다.
long a = 2147483648;
"The literal 2147483648 of type int is out of range"
변수는 long 타입이지만 이 변수에 대입되는 상수가 여전히 int 타입이기 때문에 int로 표현할 수 있는 최대 숫자를 여전히 초과하고 있다.
long a = 2147483648L;
상수도 long 타입이 되었고, 그 상수를 담을 변수도 long 타입이 되었다. 그럼 int 보다 작은 데이터 타입인 short나 byte는 어떻게 해야 표현할 수 있을까?
byte a = 100;
short b = 200;
이번에는 오류가 발생하지 않는다. 자바는 byte와 short 타입에 대해서는 int 형을 허용하기 때문에 오류가 발생하지 않는다.
double a = 3.0F;
float -> double (자동)
double -> float (불가능)
아래는 에러가 난다
float a = 3.0;
자동 형 변환의 원칙은 표현범위가 좁은 데이터 타입에서 넓은 데이터 타입으로의 변환만 허용된다는 것이다.

int a = 3;
float b = 1.0F;
double c = a + b;
a + b : int와 float가 만나서 float로 자동 형 변환이 일어난다.
double c = a + b : float와 double이 만나서 double로 자동 형 변환이 일어난다.
float a = 100.0;
int b = 100.0F;
=> 에러발생. 명시적 형 변환 필요
float a = (float)100.0;
int b = (int)100.0F;
| 연산자 | 의미 |
|---|---|
| + | 더하기 |
| - | 빼기 |
| * | 곱하기 |
| / | 나누기 |
| % | 나머지 |
| 연산자 | 의미 |
|---|---|
| + | 양수를 표현한다. 실제로는 사용할 필요가 없다. |
| - | 음수를 표현한다. |
| ++ | 증가(increment) 연산자로 항의 값을 1씩 증가 시킨다. |
| -- | 감소(Decrement) 연산자 |
true
false
\>
\<
\>=
<=
==
!=
문자열 비교 메서드
package org.opentutorials.javatutorials.compare;
public class EqualStringDemo {
public static void main(String[] args) {
String a = "Hello world";
String b = new String("Hello world");
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
package org.opentutorials.javatutorials.condition;
public class Condition1Demo {
public static void main(String[] args) {
if(true){
System.out.println("result : true");
}
}
}
package org.opentutorials.javatutorials.condition;
public class Condition3Demo {
public static void main(String[] args) {
if (true) {
System.out.println(1);
} else {
System.out.println(2);
}
}
}
package org.opentutorials.javatutorials.condition;
public class ElseDemo {
public static void main(String[] args) {
if (false) {
System.out.println(1);
} else if (true) {
System.out.println(2);
} else if (true) {
System.out.println(3);
} else {
System.out.println(4);
}
}
}
if문으로 대체할 수 있어 자주 사용은 안하지만 시각적으로 보기 편해서 사용한다.
package org.opentutorials.javatutorials.condition;
public class SwitchDemo {
public static void main(String[] args) {
System.out.println("switch(1)");
switch(1){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
// one
// two
// three 출력
System.out.println("switch(2)");
switch(2){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
// two
// three 출력
System.out.println("switch(3)");
switch(3){
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
}
// three 출력
}
}
switch(4){
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
case 3:
System.out.println("three");
break;
default:
System.out.println("default");
break;
}
// default 출력
&& : and|| : or! : notint i = 0;
// i의 값이 10보다 작다면 true, 크다면 false가 된다. 현재 i의 값은 0이기 때문에 이 반복문은 실행된다.
while(i<10){
System.out.println("Coding Everybody"+i);
// i의 값에 1을 더한다. 반복문의 중괄호의 마지막 라인에 도달하면 반복문은 반복문을 재호출한다. 이때 i<10의 값을 검사하게 된다.
i++;
}
package org.opentutorials.javatutorials.loop;
public class ForDemo {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Coding Everybody " + i);
}
}
}
탈출
현재 반복 구문 실행 중단 및 다음 반복 구문 실행
배열은 연관된 데이터를 모아서 관리하기 위해서 사용하는 데이터 타입이다. 변수가 하나의 데이터를 저장하기 위한 것이라면 배열은 여러 개의 데이터를 저장하기 위한 것이라고 할 수 있다.
방법1.
package org.opentutorials.javatutorials.array;
public class DefineDemo {
public static void main(String[] args) {
String[] classGroup = { "최진혁", "최유빈", "한이람", "이고잉" };
}
방법2.
package org.opentutorials.javatutorials.array;
public class LengthDemo {
public static void main(String[] args) {
String[] classGroup = new String[4];
classGroup[0] = "최진혁";
System.out.println(classGroup.length);
classGroup[1] = "최유빈";
System.out.println(classGroup.length);
classGroup[2] = "한이람";
System.out.println(classGroup.length);
classGroup[3] = "이고잉";
System.out.println(classGroup.length);
}
// 4
// 4
// 4
// 4
}
현재 담긴 배열의 길이가 아닌 처음에 선언한 길이 4의 크기이다.
package org.opentutorials.javatutorials.array;
public class ArrayLoopDemo {
public static void main(String[] args) {
String[] members = { "최진혁", "최유빈", "한이람" };
for (int i = 0; i < members.length; i++) {
String member = members[i];
System.out.println(member + "이 상담을 받았습니다");
}
}
// 최진혁이 상담을 받았습니다
// 최유빈이 상담을 받았습니다
// 한이람이 상담을 받았습니다
}
package org.opentutorials.javatutorials.array;
public class ForeachDemo {
public static void main(String[] args) {
String[] members = { "최진혁", "최유빈", "한이람" };
for (String e : members) {
System.out.println(e + "이 상담을 받았습니다");
}
}
}
위의 구문은 배열 members의 값을 변수 e에 담아서 중괄호 구간 안으로 전달해준다. 반복문의 종료조건이나 종료조건을 위해서 기준값을 증가시키는 등의 반복적인 작업을 내부적으로 감춘 것이라고 할 수 있다. 자바 5.0부터 도입된 기능이다.
배열은 초기화할 때 그 크기가 정해진다. 그래서 정해진 크기 이상의 값을 넣을 수 없다.