본문 바로가기

-Java

자료형 연산자, 변수의 활용, 제어문

반응형

3번째 자바강의 -2015.03.06

■ 학습목표

자료형 연산자

변수의 활용, 제어문

 

set이란> 만약a에 10이라는 변수를 저장했고 또 30을 저장하면 10은 없어지고 30만 저장된다.

<php> $a=10; //정수 $b="10"; //문자열이됨 $c=$a+$b; //가능함!! php는 자동으로 됨!!

 

static> 클래스를 사용하지 않고 자원 사용가능

heap에 올라가는 자료 = new만 생각해라!!

new 객체 안에 스태틱 자원은 어디에 있는 스태틱 딱 하나만!<<추후 증명!!

 

Tools에 Templates클릭후 Java에 Java클래스 누르고 open in edit를 누르면 생성 후에 나오는 말을

설정 가능하다!

 

단역객체>한번만 실행하고 사라짐! ex) new A().aa();

 

단축키 팁들 (넷빈즈)

//코드 자동정렬 알트 쉬프트f

//드래그 한후 영역 // 컨트롤 쉬프트c

 

1)변수 활용

Ex1_Oper1 실행파일

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46 

   

package ex1;

   

   

public class Ex1_Oper1 {

    public static void main(String[] args) {

        int nA=50;

        int nB=100;

        int r1=nA+nB;

        System.out.println("nA+nB="+r1);

        System.out.println("A==B : "+(nA = nB));

        System.out.println("A==B : "+(nA == nB));

        System.out.println("A==B : "+(nA != nB));

        System.out.println("A==B : "+(nA >= nB));

        System.out.println("A==B : "+(nA <= nB));

        System.out.println("A==B : "+(nA < nB));

        // ==같다 !=같지않다 여기서 =라고 하면 결과값이 100이라나온다 엉뚱한 결과가 나옴

        // System.out.println("A==B : "+(nA = nB)); 이라고 할경우 그 밑부터는 nA가 100으로 변함!! 

        //그래서 그밑에는 100과 100을 비교하게된다!! 이렇기 때문에 같다는 ==라고해야됨! 

          

          

        boolean resA=nA==nB;//이런식으로 하면 나중에 여러번 계산할 필요없이 resA값을 기억해서 효율을 좋게할수있다. 

        System.out.println("비교 :"+resA);//역시 true로 된다. 

          

        String st1= new String("안녕");//new 라는건 새롭게 heap에서 번지수를 만드는것 

        String st2= new String("안녕");//이것도 같다 고로 주소값이 다르다

        System.out.println("st1==st2 :"+(st1==st2));//고로 이답은 false 발생 

        System.out.println("equel을 이용하면?"+(st1.equals(resA)));

          

        String stA1="Java";

        String stA2="Java";//이과정은 바로 힙으로 가지않고 상수풀에서 Java라는 단어가없으면 단어를 만들고 

        //힙으로 저장됨 그러므로 두번째 stA2는 상수풀에 들어가서 Java라는 단어가 있기때문에 같은 주소값을 가진다

        System.out.println("stA1==stA2"+(stA1==stA2));//같은주소값이라 true!

          

        Integer inT1=new Integer(20);

        Integer inT2=new Integer(20);

        System.out.println("inT1==inT2:"+(inT1==inT2));// new라서 위의 스트링처럼 false가됨

          

        Integer inTA1=20;

        Integer inTA2=20;

        System.out.println("inTA1==inTA2:"+(inTA1==inTA2));// 이것도 위의 스트링처럼 True가된다!

          

    }

}

   

  

코드 실행 및 결과

run:

nA+nB=150

A==B : 100

A==B : true

A==B : false

A==B : true

A==B : true

A==B : false

비교 :true

st1==st2 :false

equel을 이용하면?false

stA1==stA2true

inT1==inT2:false

inTA1==inTA2:true

BUILD SUCCESSFUL (total time: 0 seconds)

 

 

Ex2_Oper 실행파일

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28 

package ex1;

   

public class Ex2_Oper {

   

    public static void main(String[] args) {

        int b = 5;

        b += 2; //b=b+2

        System.out.println("b+2 = " + b);

        b -= 5; //b=b-5;

        System.out.println("b-5 = " + b);

        b *= 2;//b=b*2;

        System.out.println("b*2 = " + b);

        b /= 3;//b=b/3;

        System.out.println("b/3 = " + b);

        //제어문할때 나오니 익혀두자

   

        //전치 후치!!

        int n1 = 30;

        System.out.println("n1 : " + (--n1)); //29

        System.out.println("n1 : " + n1);//29

   

        int n2 = 30;

        System.out.println("n2 : " + (n2--)); // 30 이미 앞에서 출력이 됐기때문 

        System.out.println("n2 : " + n2);//29

        //이처럼 전치 후치 수식에 따라 값이 변한다.

   

    }

} 

코드 실행 및 결과

run:

nA+nB=150

A==B : 100

A==B : true

A==B : false

A==B : true

A==B : true

A==B : false

비교 :true

st1==st2 :false

equel을 이용하면?false

stA1==stA2true

inT1==inT2:false

inTA1==inTA2:true

BUILD SUCCESSFUL (total time: 0 seconds)

 

Ex3_Oper 실행파일 (여러분이 복습한 프로젝트에 소스를 기준

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25 

package ex1;

   

public class Ex3_Oper {

    public static void main(String[] args) {

        boolean a1=true;

        boolean a2=false;

        System.out.println("결과값1 : "+(a1&&a2)); //and연산 에이와 비가 둘다 맞을때 트루이다.

        System.out.println("결과값1 : "+(a1||a2));//or연산 에이와 비중에 하나만 맞아도 트루!

          

        int a=100;

        int b=200;

        boolean c=((a+=102)>b)&&(a==(b+=100));        

        System.out.println("c :"+c);//true

        System.out.println("a:"+a);//202

        System.out.println("b:"+b);//300

          

        int aa1=100;

        int b1=200;

        boolean c1=((aa1+=102)>b1)||(aa1==(b1+=100));        

        System.out.println("c1 :"+c1);//true

        System.out.println("aa1:"+aa1);//202

        System.out.println("b1:"+b1);//200

        //앞에 트루라 그뒤는 보지않아서 b의값이 차이가남!       

    }

} 

코드 실행 및 결과

run:

결과값1 : false

결과값1 : true

c :false

a:202

b:300

c1 :true

aa1:202

b1:200

BUILD SUCCESSFUL (total time: 0 seconds)

 

Ex4_Oper 실행파일 (여러분이 복습한 프로젝트에 소스를 기준

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35 

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package ex1;

   

/**

 *

 * @author Administrator

 */

public class Ex4_Oper {

     public static void main(String[] args) {

        int a =11; 

        int b = 5; 

        //-----------------

        int c =a&b; 

        System.out.println("변수 c의 값:"+c);

          

        c=a|b;

        System.out.println("변수 c의 값:"+c);

          

        c=a^b;

        System.out.println("변수 c의 값:"+c);

          

        //쉬프트 연산>비트만큼 자리 이동하는 연산

        a=20; 

        b=4;

        c=a>>b; 

        System.out.println("변수 c의 값:"+c);//1

                //2진법과 쉬프트연산은 제가 모르는거라 결과값만 도출해보았습니다! 

        //비트연산을 &|^이 세가지로만 연산되는것만 개념을 잡자!

          

       }

} 

코드 실행 및 결과

run:

변수 c의 값:1

변수 c의 값:15

변수 c의 값:14

변수 c의 값:1

BUILD SUCCESSFUL (total time: 0 seconds)

 

2)제어문

Ex1_For 실행파일 (여러분이 복습한 프로젝트에 소스를 기준

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32 

package ex2;

   

public class Ex1_For {

      

    public static void main(String[] args)  {

        System.out.println("2 부터 10 까지 출력: ");

          

        for (int i = 1; i < 10; i++) {

            System.out.println((i + 1));

        }

        System.out.println("---------------------");

        for (int i = 1; i < 10; i++) {

            System.out.print((i + 1) + "\t");//\t 탭   1  2   3   4   5 이런식으로나옴         

        }

        System.out.println("");

        System.out.println("---------------------");

        

        // 0부터 50까지 5씩 증가                

        for (int i = 0; i < 50; i += 5) {

            System.out.print((i));

        }

        System.out.println("");

        System.out.println("---------------------");

        //50부터 0까지 5씩! 감소 하면서 출력

        for (int i = 50; i >=0; i-=5) {

            System.out.print((i));

        }

        System.out.println("");

        System.out.println("---------------------");

   

    }

} 

코드 실행 및 결과

run:

2 부터 10 까지 출력:

2

3

4

5

6

7

8

9

10

---------------------

2    3    4    5    6    7    8    9    10    

---------------------

051015202530354045

---------------------

50454035302520151050

---------------------

BUILD SUCCESSFUL (total time: 0 seconds)

 

Ex2_if 실행파일

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package ex2;

   

public class Ex2_if {

   

    public static void main(String[] args) {

   

        String st = "호박";

          

        if (st.equals("사과")) {

            System.out.println("빨간색");

        }if (st.equals("호박")) {

            System.out.println("노란색");

        }if (st.equals("오이")) {

            System.out.println("초록색");

        }

        //다 연산하기때문에 효율이 좋지않음! 오이까지 연산

   

        if (st.equals("사과")) {

            System.out.println("빨간색");

        } else if (st.equals("호박")) {

            System.out.println("노란색");

        } else if (st.equals("오이")) {

            System.out.println("초록색");

        }

        //else if를 써야 다 연산안하고 바로 밑으로 빠져나온다!

    }

}

코드 실행 및 결과

run:

노란색

노란색

BUILD SUCCESSFUL (total time: 0 seconds)

 

Ex1_Scanner 실행파일

Colored By Color Scripter

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18 

package ex3;

   

import java.util.Scanner;

   

   

public class Ex1_Scanner {

     public static void main(String[] args) {

       

        // Scanner는 JDK5부터 제공***** 가장 중요하다!

          

        Scanner sc =new Scanner(System.in);

        System.out.print("글을 쓰시오 : ");

        String msg=sc.nextLine(); //이게바로 블록메서드다! 특정 활동을 하기전엔 멈추게하는 기능!

        System.out.println("메세지 :"+msg);

          

         

     }

} 

코드 실행 및 결과

run:

글을 쓰시오 : 오오

메세지 :오오

BUILD SUCCESSFUL (total time: 4 seconds)

반응형