728x90

Data types in JAVA

이걸 다시 복습해보자. 일단 int, double, char을 제일 많이쓸거니까 heighlight 쳐놓을게

type description range
boolean true or flase true, false
byte twos-complement integer -128 to 127
char  Unicode character ASCII value 0 to 255
short twos-complement integer  -32768 to 32767
int twos-complement integer  -2147483648 to 2147483647
long twos-complement integer  -9223372036854755808 to 922337203685475587
float IEEE 754 floating point up to 7 decimal digits
double IEEE 754 floating point up to 16 decimal digits

 

Integer overflow 

 

Number conversion

class Main {
    public static void main(String[] args) {
        int big;
        byte small;

        big = 10;
        small = big;

        System.out.println(big);
        System.out.println(small);
    }
}

이렇게 하면 compile error 남. 왜? big(int) 에 들어가있는 value가 small(byte)에 들어가려고하면 에러나지. C면 돌아가기라도 할텐데 자바는 바로 에러난다는걸 보여주는 예시. 

 

+number conversion 예시:

 

3.75를 integer 로 바꾸면 3이 나온다. 이걸 다시 floatfh 바꾸면 3.0이 나온다. 즉 3.75를 int에 넣으면 3이되는거임. 0.75 순삭됨



Character type: Char

char c;

c='a';

Single quotation mark 으로 c 에 character를 넣으면 됨. 

ASCII table 에서 character 0랑 integer 0 는 다르다. 

보셈 character 0은 48에 있음. 

 

Relational Operators

>,< 이런걸 뜻한다. 

근데 여기 룰이 있는데,

Rule #1. The two inputs must be numbers, not necessarily of the same type.

Rule #2. If the two inputs are numbers with different types, the inferior one will be upgraded automatically.

 

relational operator를 사용한 코드:


class Main {
    public static void main(String[] args) {
        double UV_level = 12;
        boolean UV_danger;

        UV_danger = (UV_level > 10);

        // warn the user
        System.out.println("UV Danger: " + UV_danger);
    }
}

자 이 코드를 분석하자면, UV_danger라는 이름을 가진 boolean 변수는 0또는 1이다. boolean 이니까.

그니까 UV_danger는 UV_level이 10보다 클시에 true 인 1, 크지 않을시에 false 인 0이 되는거다. 

지금같은 케이스는 UV_level에 12이고, 10보다 크니까 true 인 1이 UV_danger에 들어갈것이당

 

이러한 operator가 있다. 

== 랑 =는 다르다. =는 assignment operator고 ==는 equality operator다. 

쉽게말하면 =는 걍 값 넣는거고 ==는 같다는뜻.

 

Boolean (or logical) operator

걍 true 냐 false냐 따지는 operator 말하는거다. 

 

 이처럼 !나 &&따위의 operator 를 말한다. 

 

&&(and라는뜻) 는 걍 

condition a && condition b 가 있다면, 

a랑 b 둘다 true 일 시에 true가 나오는거고

두게중 하나라도 false거나 둘다 false면 걍 가차없이 false 나오는거지. 

마치 하나라도 틀리면 0점주는 문제처럼

 

||(or라는뜻) 은 뭐냐면

condition a || condition b 이렇게 있으면 

둘다 false 가 아닌이상 다 true로 나온다. or이니까 둘중에 하나라도 true가 있으면 true인거지. 

 

Operator Precedence & Associativity

자 이런식으로! 뭐가 더 중요하냐 이거임. 지금 저기에선 10>=4+10&&4+6==10이 있으면, (10>=4+10)랑 (4+6==10)를 비교해서 둘다 true이냐를 따지는건데, 일단 첫번째 condition 인 10>=4+10 부터가 false니까 가차없이 false 나오는거지.

 

그래서 결괴는 false. 

 

728x90

'언어는 과-학인가요? > JAVA' 카테고리의 다른 글

1. Java Language Basics  (0) 2022.01.16
JAVA 깔고 쓰는법  (0) 2022.01.15
728x90

모든 언어를 배우면 처음에 하는 Hello world 부터 프린트해볼거다

 

자바의 특징 4가지 

  1. Case-sensitive
  2. Curly braces come in pairs 
  3. Each JAVA program(source file) should contain a class having the same name as the file name
  4. The main method is the start of every Java program.

 

1. Case-sensitive

 

자바는 일단 case sensitive한 언어라서 대소문자 구분이 중요하다. 

먼저 class 를 define할때 class 이름을 대문자로 시작한다. 또 string define 할때도 string 이름 대문자로 쓴다. 

암튼 대소문자 구분 아주 중요함

 

2. Curly braces come in pairs 

 

모든 언어가 그렇듯 대괄호가 항상 짝이 있다 {} 이렇게 

 

3. Each JAVA program(source file) should contain a class having the same name as the file name

 

이거 중요한데 컴퓨터에 저장되어있는 (내가 설정한)파일 이름이랑 class이름이 같아야한다. 아니면 안돌아감. 

예를들면 너가 파일을 prac.java라고 지정해놨으면 class 이름도 class prac{} 로 해야한다. 이때 보통 파일 이름은 대문자를 사용한다.

 

4. The main method is the start of every Java program.

 

메인은 무조건 public static void main(String[] args) {}로 시작하기로 한다. 저게 뭔뜻인진 밑에서 설명할예정

그리고 메인은 항상 class 안에 있다

 


즉 JAVA 에서 hello world 는 다음과같이 print 하면 된다. System.out.println 같은 statement 뒤에는 꼭 ; 이 들어간다. 

class prac{

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

 


주석처리는 c와 비슷하게 /* */로 하면된다. 한줄 주석도 된다 // 이렇게

모든 언어가 그렇듯 적은 코드가 뭔코든지 주석처리해주면 좋다

 

자바 컴파일/실행 과정

 

Variable (변수)

  1. Data를 저장할때 쓰는것
  2. 변수마다 이름을 정해줘야한다. 뜻있는 이름으로.. 초반에 귀찮아서 아무이름이나 했다가 나중에 뭔변순지 헷갈리는거 한두번이 아니다
  3. 변수를 쓰기 전에 declare 해야한다

How to declare Variables? 

variable type은 c랑 거의 똑같다

type description range
boolean true or flase true, false
byte twos-complement integer -128 to 127
char  Unicode character ASCII value 0 to 255
short twos-complement integer  -32768 to 32767
int twos-complement integer  -2147483648 to 2147483647
long twos-complement integer  -9223372036854755808 to 922337203685475587
float IEEE 754 floating point up to 7 decimal digits
double IEEE 754 floating point up to 16 decimal digits

type variablename; 이 format으로 declare하면 된다

 

예를들면 이렇게

class prac 
{
    public static void main(String[] args)
    {   
        int i;
        int n;
        for (i = 0 ; i < 10 ; i++){
            for (n = 0 ; n < i; n++)
            {
                System.out.print("*");
            }
            System.out.println("\n");
        }
    }
}

for문은 그냥 재미로 돌려본거니 무시하고 int i; i=0처럼 declare하면됨

 

class prac 
{
    public static void main(String[] args)
    {   
        int i;
        i=5;
        System.out.println(i);
    }
}

이렇게 variable값을 print할수도 있다

 

Reading user input

  • scanner object 

- 일단 scanner를 import 하기

import java.util.Scanner;

 

 

- create a scanner object from the Scanner class to read input from keyboard (stdin)

Scanner scanner = new Scanner(System.in);

 

Operator Precedence & Associativity

 

Escape Sequences

Common Escape Sequences Descriptions  
\n Insert a newline character  
\t Insert a tab  
\" Insert a double quotation character  " print 할때 " 적고싶으면 \"라고 적어야됨. System.out.println("sss\""); 이렇게 적으면 sss"가 나올거임.
\' Insert a single quotation character  '  
\\ Insert a backslash character  \ \ 넣으려면 \ 두번 쳐야됨

 

Variable naming

Rules Notes
Names are case-sensitive. - E.g., "area" and "Area" are two different variables.
- We prefer "area" than "Area".
A name can only start with:
an alphabet, an underscore "_", or a dollar sign "$".


Subsequent characters can only be:
alphabets, digits, "_", or "$".
Valid names: “cat", "_cat_", "$cat", “cat3"…
Invalid names: "1st_cat", “cat+dog", "^_^" , 
"many cats"…
We prefer starting with a lower-case alphabet, e.g., “cat" instead of “Cat".
A variable name cannot be a keyword or a reserved word. - E.g., cannot use double, void, and class.
  • - List of keywords:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
In Java, we prefer using the Camel Case. http://en.wikipedia.org/wiki/CamelCase. E.g., instead of using "manycatsanddogs" or "many_cats_and_dogs",
we prefer using "manyCatsAndDogs".

 

i++ and ++i

++i

- increase value of i by 1

- The value of the expression "++i" is the value of i after
the increment operation.

 

I++

- increase value of i by 1

- The value of the expression "i++" is the value of i before the increment operation.

 

차이

 

728x90

'언어는 과-학인가요? > JAVA' 카테고리의 다른 글

2. Data type  (0) 2022.01.19
JAVA 깔고 쓰는법  (0) 2022.01.15
728x90

먼저 자바를 쓰기 위해선 자바를 깔아야된다. 

마인크레프트를 깔면 자바가 딸려온다 

자바 까는법은 걍 구글에 install java 치면 친절하게 java.com이 step by step 으로 가르쳐준다. 자바 공식 웹사이트겠지뭐

여기서 깔면됨. 나는 자바 17이다

https://java.com/en/download/help/download_options.html

 

자 자바가 잘 깔렸는지 알아볼려면 mac에서 terminal 열고 

java --version 치면 자신이 깐 자바 버젼을 바로 볼 수 있다.

물론 다른방법으로 볼 수도 있지만 터미널이 제일 효율적임

 

컴파일러는 그냥 vs code 로 통일하기로 했다 

vs code 들어가서 파일이름.java 를 만들면 java extension깔라고 시키는데 걍 시키는데로 깔면 된다

 

이제 모든 준비가 끝났으니 자바를 시작해보겠다

 

 

728x90

'언어는 과-학인가요? > JAVA' 카테고리의 다른 글

2. Data type  (0) 2022.01.19
1. Java Language Basics  (0) 2022.01.16

+ Recent posts