W3Schools 자바 | #0 자바 튜토리얼 (입출력, 주석, 변수, 타입, 연산자 등)
Java Tutorial
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
왜 자바인가?
자바는 모바일 앱, 데스트탑 프로그램, 웹 애플리케이션, 웹 서버, 게임, 데이터베이스 등등에 사용된다.
자바는 서로 다른 OS에서 자유롭게 사용할 수 있다.
자바 설치
환경 : Window10 wsl
$ sudo apt install default-jdk
WSL에 JAVA JDK설치하는 방법 (how to install JAVA JDK on WSL) (devbull.xyz)
설치가 끝나고 나면, 다음과 같이 자바가 설치된 걸 확인할 수 있다.
$ java --version
openjdk 11.0.16 2022-07-19
OpenJDK Runtime Environment (build 11.0.16+8-post-Ubuntu-0ubuntu120.04)OpenJDK 64-Bit Server VM (build 11.0.16+8-post-Ubuntu-0ubuntu120.04, mixed mode, sharing)
자바로 "Hello World"를 시작해주자.
public class Main {
public static void main(String[] args){
System.out.println("Hello world");
}
}
자바도 마찬가지로 컴파일해서 실행해주면 된다.
$ javac Main.java
$ java Main
Hello world
자바 문법
// class 명은 항상 대문자로 시작
// 클래스 이름이 Main
// 파일 이름은 클래스 이름과 일치해야 함
public class Main {
// 메소드
public static void main(String[] args){
// 기본 출력
// System은 자바의 내장 클래스 Print line의 줄임말
System.out.println("Hello world");
}
}
자바 출력
// class 명은 항상 대문자로 시작
// 클래스 이름이 Main
// 파일 이름은 클래스 이름과 일치해야 함
public class Main {
// 메소드
public static void main(String[] args){
// 기본 출력
// System은 자바의 내장 클래스 Print line의 줄임말
System.out.println("Hello world");
System.out.println("Hi");
System.out.println("I'm learning JAVA.");
System.out.println(3+3);
}
}
System.out.println() 안에 들어가는 내용을 수정하여 무언가를 출력할 수 있다.
cf) println()과 print()의 차이
// class 명은 항상 대문자로 시작
// 클래스 이름이 Main
// 파일 이름은 클래스 이름과 일치해야 함
public class Main {
// 메소드
public static void main(String[] args){
// 기본 출력
// System은 자바의 내장 클래스 Print line의 줄임말
System.out.println("println : Hello world");
System.out.println("println : Hi");
System.out.println("println : I'm learning JAVA.");
System.out.println("println : " + 3+3);
System.out.print("print : Hello world");
System.out.print("print : Hi");
System.out.print("print : I'm learning JAVA.");
System.out.print("print : " + 3+3);
}
}
출력
$ java Main
println : Hello world
println : Hi
println : I'm learning JAVA.
println : 33
print : Hello worldprint : Hiprint : I'm learning JAVA.print : 33
println이 한 줄에 한 문장씩 출력한다면,
print는 \n 없이 이어서 출력한다.
자바 타입
기본적인 타입
string, int, float, char, boolean
다음과 같은 문법으로 변수를 선언해준다.
type variable_name = value;
String name = "John";
int myNum = 15;
int myNum2;
myNum2 = 10;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
변수 출력
// print String
String myName = "YoungZoo";
System.out.println("Hi " + myName);
String firstName = "Young";
String lastName = "Park";
String fullName = firstName + lastName;
System.out.println(fullName);
// print int
int x = 5;
int y = 6;
System.out.println(x+y);
변수 이름 지정
// 작명
// 클래스명
Sample, Account, AccountManager, VisitServer
// 매소드명
printString, saveMoney, doExpr, calculate, input
// 변수명
number, name, total
// 상수명
CONSTANT_VALUE
자바 데이터 타입
- byte(1바이트) -128~127
- short(2바이트) -32768~32767
- int(4바이트) -2147483648~2147483647
- long(8바이트) -9223372036854775808~9223372036854775808
- float(4바이트) 7자리 수
- double(8바이트) 15자리 수
- boolean(1비트) true/false
- char(2바이트) 아스키 값이나 한 문자
자바 숫자 타입
- 정수 타입 : byte, short, int, long
- 실수 타입 : float, double
- 바이트(1바이트) : -`128~127
byte myNum = 100;
- Short(2바이트) : -32768~32767
short myNum = 5000;
- int(4바이트) -2147483648~2147483647
int myNum = 100000;
- long(8바이트) -9223372036854775808~9223372036854775808
long myNum = 150000000L;
- float(4바이트) 7자리 수
float myNum = 5.75f;
- double(8바이트) 15자리 수
double myNum = 19.99d;
자바 불리언 타입
boolean isItTrue = true;
boolean yesFalse = false;
자바 문자 타입
- char : single character
char myGrade = 'B';
- string : text
String greeting = "hello world";
타입 캐스팅
- Widening Casting
byte -> short -> char -> int -> long -> float -> double
작은 단위가 넓은 단위로 변환된다.
자동으로 해줌
int myInt = 9;
double myDouble = myInt; // Automatic casting
- Narrowing Casting
double -> float -> long -> int - >char->short->byte
넓은 단위를 작은 단위로 변환한다.
직접 선언해주어야 함
double myDouble = 9.78d;
int myInt = (int) myDouble; // narrowing casting (manual)
자바 연산자
- 산수 연산자
- +, -, *, /, %, ++, --
- 대입 연산자
- =, +=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=
- 비교 연산자
- ==, !=, >, <, >=, <=
- 논리 연산자
- &&, ||, !
자바 문자열
// print String
String myName = "YoungZoo";
System.out.println("Hi " + myName);
String firstName = "Young";
String lastName = "Park";
String fullName = firstName + lastName;
System.out.println(fullName);
// print int
int x = 5;
int y = 6;
System.out.println(x+y);
// Java Strings
String greeting = "Hello";
// String length
int length = greeting.length();
// toUpperCase
System.out.println(greeting.toUpperCase());
// toLowerCase
System.out.println(greeting.toLowerCase());
// find a character
System.out.println(greeting.indexOf("ll"));
// string concatenation
String name1 = "park";
String name2 = "young";
System.out.println(name1 + " " + name2);
System.out.println(name1.concat(name2));
// numbers and string
String x = "10";
int y = 20;
String z = x + y;
System.out.println(z);
// special characters
// \'
System.out.println("\'");
// \''
System.out.println("\''");
// \\
System.out.println("\\");
// \n : newline
// \r : carriage return
// \t : tab
// \b : backspace
// \f : form feed
자바 math
// Math.max(x, y)
Math.max(5, 10);
// Math.min(x, y)
Math.min(10, 9);
// Math.sqrt(x);
Math.sqrt(64);
// Math.abs(x) 절댓값
Math.abs(-4.0);
// Math.random(); 0~1
Math.random();
자바 불리언
boolean isJava = true;
boolean notJava = false;
System.out.println(isJava);
System.out.println(notJava);
자바 if문
int time = 20;
if (time < 18){
System.out.println("hi");
}
else {
System.out.println("rain");
}
==
String result = (time < 18) ? "hi" : "rain";
자바 switch
int day = 4;
switch (day){
case 6:
System.out.println("sat");
break;
case 7:
System.out.println("sun");
break;
default:
System.out.println("looking forward to the weekend");
}
자바 while loop
int i=0;
do {
System.out.println(i);
i++;
} while (i<5);
while (i<10){
System.out.println(i);
i++;
}
자바 for loop
// basic for loop
for (int i=0;i<10;i++){
System.out.println(i);
}
// for each loop
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars){
System.out.println(i);
}
break, continue
int j=0;
while (j<10){
System.out.println(j);
j++;
if (j==4){
break;
}
if (j==3){
continue;
}
}
자바 배열
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
cars[0] = "Opel";
System.out.println(cars.length);
for (int i=0;i<cars.length;i++){
System.out.println(cars[i]);
}
for (String i : cars){
System.out.println(i);
}
int[][] myNumbers = {{1,2,3,4},{5,6,7}};
myNumbers[1][2];