변수

1. 변수

1.1정의

단 하나의 값을 저장할 수 있는 공간.

 

1.2변수의 선언

변수타입  변수이름  ;          ( ;   프로그램에서 문장이 끝났음을 알려줌)

int   number ;

 

 

 

변수를 선언할때는 변수의 타입과 이름을 써준다.

 

정수형 변수 number 를 선언하고 변수값을 5로 초기화

 

int number=5;

 

int number;

number=5;

 

 

1.3 변수명 규칙

 

1. 대소문자가 구분이 되며 길이에 제한이없다

2. 예약어를 사용해서는 안된다

3. 숫자로 시작하면 안된다

4. 특수문자는 _ 와 $ 만을 허용한다

 

권장사항 : 클래스의 이름 첫글자는 항상 대문자로한다

 

 

 

2변수의 타입

변수는 크게 2가지로 나누어진다

값을가지는 기본형과 메모리 주소를 가지는 참조형이 있다

 

 

기본형 : boolean , char , byte , short , int ,long ,float ,double

 

참조형 : 8개의 기본형을 제외한 나머지타입

참조형 변수는 선언할때 변수의 타입으로 클래스 이름을 사용하므로

클래스의 이름이 변수의 타입이 됨

 

 

클래스이름 변수명;

Date today;

today=new Date();

 

위 예문은 Date 라는 클래스의 변수 today 를 선언하고 today에 Date 객체의 참조를 집어넣은 예문임

 

 

2.1기본형

 

 

 1byte

  2byte

 4byte

 8byte

 논리형

 boolean

 

 

 

 문자형

 

 char

 

 

 정수형

 byte

 short

 int

 long

 실수형

 

 

 float

 double

 

 

3형변환

3.1 형변환 정의

변수 또는 리터럴의 타입을 다른 타입으로 변환하는 것.

 

3.2 형변환 방법

(형변환할 타입) 피연산자

short number= (short) 50.5;

 

 

이전장에서 설치한 이클립스를 실행해서

 

아래 코드를 복사해서 클래스명을 같이한다음에 돌려서 나오는 값을 확인해 보세요

 

 

예제

 


public class Hello {
 public static void main(String [] args){
  
  
  //논리형
  boolean isTrueVar =true;
  boolean isTrue2Var =false;
  
  //문자형
  char chVar='a';
  
  //정수형
  byte byteVar=5;
  short shortVar=10;
  int intVar=20;
  long longVar = 50;
  
  //실수형
  float floatVar = 50.1f;
  double doubleVar= 50.3;
  
  
  //형변환
  int typeChangeInt=(int)chVar;
  
  //변수 값 확인
  System.out.print("booleanType:");
  System.out.print(isTrueVar+",");
  System.out.println(isTrue2Var);
  
  
  System.out.print("charType:");
  System.out.println(chVar);
  
  System.out.print("byteType:");
  System.out.println(byteVar);
  
  System.out.print("shortType:");
  System.out.println(shortVar);
  
  System.out.print("intType:");
  System.out.println(intVar);
  
  System.out.print("longType:");
  System.out.println(longVar);
  
  System.out.print("floatType:");
  System.out.println(floatVar);
  
  System.out.print("doubleType:");
  System.out.println(doubleVar);
  
  System.out.print("typeChange:");
  System.out.println(typeChangeInt);
  
  System.out.println("수고하셧습니다");
  
 }
}

 

'IT > JAVA' 카테고리의 다른 글

자바 에서 조건문과 반복문  (0) 2017.04.29
프로그래밍 연산자(자바)  (0) 2017.04.27
자바언어 설치 및 이클립스 설치  (1) 2017.04.23
자바의특징 및 역사  (2) 2017.04.22
프로그래밍 자바를 시작해 보자  (0) 2017.04.21

+ Recent posts