'프로그래밍'에 해당되는 글 363건

  1. 2012.07.28 싱글턴 패턴
  2. 2012.07.28 static 예
  3. 2012.07.28 staticTest[실습]
  4. 2012.07.28 package, import
  5. 2012.07.28 productManagerArray만들기 [실습]
  6. 2012.07.28 배열
  7. 2012.07.28 반복분(for, while)
  8. 2012.07.28 switch문
  9. 2012.07.28 if문
  10. 2012.07.28 Data type, 연산자, 형변환

* 싱글턴 패턴

package statictest;

public class TestSingleton {

 /**
  * @param args
  */
 public static void main(String[] args) {
  SingletonClass sc1 = SingletonClass.getInstance();
  sc1.setNum(100);
  SingletonClass sc2 = SingletonClass.getInstance();
  System.out.println(sc2.getNum());
  
  SingletonClass2 sc3 = SingletonClass2.getInstance();
  sc3.setNum(200);
  SingletonClass2 sc4 = SingletonClass2.getInstance();
  System.out.println(sc4.getNum());

 }

}

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

package statictest;
/*싱클톤 패턴
1. 생성자의 접근 제한자를 private
2. private static 변수로 자신의 타입의 변수를 선언
3. public static 메소드를 통해 2번의 static 변수에 할당된 자신 타입의 객체를 return
*/
public class SingletonClass {
 private static SingletonClass instance = new SingletonClass();
 private int num;
 private SingletonClass(){}
 public static SingletonClass getInstance(){
  return instance;
 }
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 
 
}

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

package statictest;

public class SingletonClass2 {
 private static SingletonClass2 instance;
 private int num;
 private SingletonClass2(){}
 public int getNum() {
  return num;
 }
 public void setNum(int num) {
  this.num = num;
 }
 
 //처음 요청이 들어왔을때 객체를 생성하여 객체 생성을 늦추는 방식.
 public static SingletonClass2 getInstance() {
  if(instance == null){
   instance = new SingletonClass2();
  }
  return instance;
 }
 
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

this, super키워드  (0) 2012.07.28
상속, 생성자  (0) 2012.07.28
static 예  (0) 2012.07.28
staticTest[실습]  (0) 2012.07.28
package, import  (0) 2012.07.28
Posted by 조은성
,

* 정적 초기화영역

class A{
 static{

}
}

1. class loading
2. static block실행
3. main()

ex :  class A{
 private static CustomerDTO c;
 static{
  c = new CDTO();
 }
}

* static 블럭 실행 시점 예제

* class
package : staictest
Name : StaticBlockTest

 

package statictest;

public class StaticBlockTest {
  static{
   System.out.println("static 블럭 1");
  }
  public static void main(String[] args) {
   System.out.println("메인 메소드 실행");
  }
}

----------------
실행화면
static 블럭 1
메인 메소드 실행
(메인보다 static블럭1이 먼저 실행된 것을 볼 수 있다. )
-------------------------------------------

예제2

package statictest;

public class StaticBlockTest {
  static{
   System.out.println("static 블럭 1");
  }
  static{
   System.out.println("static 블럭 2");
  }
}
-------------------------------------------------

실행 화면

static 블럭 1
static 블럭 2
java.lang.NoSuchMethodError: main
Exception in thread "main"

static블럭 찍게 되면 순서 대로 나오고 메인이 없어서 메인이 없다는 에러를 내준다.
----------------------------------------------------

* instance 변수 - 객체마다 다른 값을 가지면 사용한다.
* static 변수 - 공통적인 값, 공통코드값(PI, 비율, 세율) : 비지니스 로직이 많다.

* 싱글턴 디자인 패턴 -> 일하는 객체를 정의하는 class(우리가 했던 것 중에는 productManagerService, ProductDTO(관리하는 사람은 한 사람만 필요하다.)) ->Business Service
- 클래스를 만들때 객체를 오직 하나만 만들수 있는 class(오직 하나의 객체를 공유한다)

ex :
DTO는 값을 표현하기 위해서 만들어진 객체기 때문에 객체를 하나만 부를수는 없다.

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

상속, 생성자  (0) 2012.07.28
싱글턴 패턴  (0) 2012.07.28
staticTest[실습]  (0) 2012.07.28
package, import  (0) 2012.07.28
productManagerArray만들기 [실습]  (0) 2012.07.28
Posted by 조은성
,

* class
package : statictest
Name :  StaticTest

package : statictest
Name :  CustomerDTO


ex :

package statictest;

public class StaticTest {
 public static void main(String[] args) {
  //CustomerDTO 객체 3개 생성
  CustomerDTO c1 = new CustomerDTO("홍길동", 20);
  CustomerDTO c2 = new CustomerDTO("이순신", 28);
  CustomerDTO c3 = new CustomerDTO("길무스", 20);
  
  System.out.println(c1.getName());
  System.out.println(c2.getName());
  //어떤 객체한테 일을 시켰느냐에 따라 결과가 다르게 나온다. 그래서 getter/setter는 객체껄로 한다. 구현은 class에 했어도 객체꺼다. 객체를 생성해야지만 사용가능하다.
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c1.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c2.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c3.getTotalInstanceCount());

  CustomerDTO c4 = new CustomerDTO();  

  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());//static변수를 사용해서 class의 메소드로 만들고 class명.메소드이름 으로 count에 접근하게 한다.
 }
}


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

package statictest;

public class CustomerDTO {
 private String name;
 private int age;
 private static int totalInstanceCount=0;   //클래스에서 생성된 객체의 개수를 저장.
 
 
 //생성자, setter,getter, toString()
 public CustomerDTO(){
  totalInstanceCount++;
 }

 public CustomerDTO(String name, int age) {
  this.name = name;
  this.age = age;
  totalInstanceCount++;
 }

 public static int getTotalInstanceCount(){
  return totalInstanceCount;
 }
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 @Override
 public String toString() {
  return "CustomerDTO [name=" + name + ", age=" + age + "]";
 }


 
}
----------------------------

* 메소드 안에 선언되면 local변수로 스택에 저장된다. args,c1,c2,c3,c4
* class 변수 static붙은 변수 totalInstanceCount
* instance변수는 private로 class에 선언된 변수는 힙에 저장된다. name,age

* compile 시점
1. class Loading ->이 시점에 static변수나 static 메소드는 메모리에 올라온다.
2. 실행 -> main()

메소드 영역                           static영역                              Coastant Pool
->메소드 코드                         ->static 멤버 -변수                     ->final 변수
                                                    -메소드 
CustomerDTO(){}                       int totalInstanceCount;
CustomerDTO(String name,int age){}    getTotalInstanceCount(){}
getName(){}
setName(){}
getAge(){}
setAge(){}
gettotalInstanceCount(){}

class영역(Area)->class별로 구분

* static 변수는 메인 메소드 실행전에 class 로딩시에 하나만 만들어 지고(class에 만들어짐) Instance변수는 객체 생성시마다 여러개가 생성된다.

* static영역은 코드만 있고 직접 접근이 안되서 실행시 클래스로 접근해야 하고, Instance영역은 객체를 통해서 접근해야 한다.
 
* static변수의 묵시적인 초기화 예제

package statictest;

public class StaticTest {
 public static void main(String[] args) {
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());
  //CustomerDTO 객체 3개 생성
  CustomerDTO c1 = new CustomerDTO("홍길동", 20);
  CustomerDTO c2 = new CustomerDTO("이순신", 28);
  CustomerDTO c3 = new CustomerDTO("길무스", 20);
  
  System.out.println(c1.getName());
  System.out.println(c2.getName());
  //어떤 객체한테 일을 시켰느냐에 따라 결과가 다르게 나온다. 그래서 getter/setter는 객체껄로 한다. 구현은 class에 했어도 객체꺼다. 객체를 생성해야지만 사용가능하다.
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c1.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c2.getTotalInstanceCount());
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+c3.getTotalInstanceCount());
  
  CustomerDTO c4 = new CustomerDTO();
  
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());//static변수를 사용해서 class의 메소드로 만들고 class명.메소드이름 으로 count에 접근하게 한다.
  System.out.println("지금까지 CustomerDTO class에서 생성된 객체의 개수 :  "+CustomerDTO.getTotalInstanceCount());
 }
}

실행화면 :

지금까지 CustomerDTO class에서 생성된 객체의 개수 :  0
홍길동
이순신
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  3
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  3
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  3
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  4
지금까지 CustomerDTO class에서 생성된 객체의 개수 :  4

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

싱글턴 패턴  (0) 2012.07.28
static 예  (0) 2012.07.28
package, import  (0) 2012.07.28
productManagerArray만들기 [실습]  (0) 2012.07.28
배열  (0) 2012.07.28
Posted by 조은성
,

- package -  class파일을 모아 놓은 directory(folder).(class가 들어가 있는 패스주소.)->src 코드 작성시 class가 어느 package안에 들어갈 것인지 선언해야한다.

구문 :
package Root_package이름.sub_package명.;  <- sub경로가 없으면 .sub_package명.은 생략가능.(package는 같은 역할을 하는 여러개의 class가 모여진 folder이다.)
package 선언은 소스코드 file당 한번만 할 수 있다.

package 선언은 소스코드의 첫 실행(명령)문으로 와야만한다.
package 명은 식별자 규칙에 따라 준다.
-관례 :  소문자, domain명 꺼꾸로(ex : 도메인 주소가 kosta.or.kr이라면 kr.or.kosta

ex :
package value;

package ab.cd.ef; ->ab/cd/ef
- import = class에서 class를 부를때 파일이 어딨는지 알려준다.

*package, import 예제

//import kosta.dto.Human;
//import kosta.dto.CarDTO;

import kosta.dto.*;
public class TestImport
{
 public static void main(String[] args)
 {
  Human h = new Human("홍길동",23,170.4);
  h.printInfo();
  CarDTO c = new CarDTO();
  c.go();
  }
}

//package 디렉토리 아래 TestImport.java로 저장

//새이름으로 저장 : package 디렉토리 아래에 Human.java로 저장
package kosta.dto;
public class Human
{
 private String name ;
 public int age;
 public double tall;
 public Human(){}
 public Human(String name, int age, double tall){
  this.name=name;
  this.age=age;
  this.tall=tall;
 }

 public void setName(String name){
  this.name = name;
 }
 public String getName(){
  return name;
 }
 public void printInfo(){
  System.out.println(name);
  System.out.println(age);
  System.out.println(tall);
 }

}


//패키지 선언 :  이 클래스가 위치할 경로(디렉토리)를 선언하는 것
package kosta.dto; // /kosta/dto/CarDTO.class
public class CarDTO
{
 private String name;
 private String engine;
 
 public String toString(){
  return "이름 : " +name+",엔진 종류 : "+engine;
 }
 public void go(){
  System.out.println(name+"가 출발합니다.");
 }
}
// package/CarDTO.java

 


* java.lang 패키지의 class들은 import 없이 사용가능.

String,System, Math class등등..(사용을 하려면 API documentation을 확인하면됨. sun에서 제공해주는 설명서)

www.oracle.com(API 다큐멘테이션)

download-> java for develop -> Additional Resources-> Java SE6 Documentation 다운로드

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

static 예  (0) 2012.07.28
staticTest[실습]  (0) 2012.07.28
productManagerArray만들기 [실습]  (0) 2012.07.28
배열  (0) 2012.07.28
반복분(for, while)  (0) 2012.07.28
Posted by 조은성
,

*제품만들기 실습
*폴더 : /productManagerArray 만들기

1. ProductDTO클래스를 UML을 보고 작성하세요. 저장은 productManagerArray 폴더에 하세요.
   toString() - 객체의 모든 attribute의 값을 하나의 String으로 만들어 return 하도록 작성.


public class ProductManagerService 
{
 private ProductDTO[] productList;
 private int totalProductCount; //배열로 부터 현재 데이터가 몇개 들어가 있는지를 알게 해줄 변수

 public ProductManagerService(int length){
  productList = new ProductDTO[length];
 }
 public ProductManagerService(){
  productList = new ProductDTO[100];
 }
 //productList에 제품을 추가하는 메소드
 /*
  instance 변수 productList에 인수로 받은 제품 정보를 추가 하는 메소드
 */
 public void addProduct(ProductDTO productDTO){
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  //3. 배열에 제품정보 추가
  //4. totalProductCount의 값을 1 증가.
 
  /*
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  if(totalCount == productList.length){
   System.out.println("제품정보를 넣을 저장 장소가 없습니다.");
   return;
  }
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  for(int i = 0;i<totalProductCount;i++){
   if(productList[i].getProductId().equals(productDTO.getProductId())){
   System.out.println("같은 제품이 있습니다.");
   return;
  }
  
  //3. 배열에 제품정보 추가
  this.productList[totalProductCount]=productDTO;
  //4. totalProductCount의 값을 1 증가.
  totalProductCount++;
   
  }
  }

  */

  System.out.println("함수를 썼을경수");
  if(totalProductCount==productList.length){
   System.out.println("넣을 공간이 없습니다.");
  }
  else if(searchProductById(productDTO.getProductId())!=null){
   System.out.println("같은 제품이 있습니다.");
  }
  else{
   this.productList[totalProductCount]=productDTO;
   totalProductCount++;
  }
 }
 /*
  instance 변수 productList에 저장된 모든 상품의 정보(id~info)를 출력해 주는 메소드
 */
 public void printProductList(){
  for(int i =0;i<totalProductCount;i++){
  System.out.println(productList[i].toString());
  }
 }
 public ProductDTO searchProductById(String productId){
  ProductDTO pDTO = null;
  for(int i =0;i<totalProductCount;i++){
  if(productId.equals(productList[i].getProductId())){
   pDTO=productList[i];
  
   }
  }
  return pDTO;
  
 }
 public void modifyProductInfo(ProductDTO productDTO){
  for(int i=0;i<totalProductCount;i++){
  if(productDTO.getProductId().equals(productList[i].getProductId())){
  productList[i]=productDTO;
  }
  }
  
 }
 public void removeProductById(String productId){
  for(int i=0;i<totalProductCount;i++){
  if(productList[i].getProductId().equals(productId)){
   productList[totalProductCount]=null;
  }
  }
 }
}

 

 

public class TestProductManager
{
 public static void main(String[] args)
 {
  ProductDTO pdto1 = new ProductDTO("p-111","이름",5000,"제조사","정보");
  ProductDTO pdto2 = new ProductDTO("p-222","마우스",12000,"삼성","휠");
  ProductDTO pdto3 = new ProductDTO("p-333","컴퓨터",43000,"LG","무선 마우스");
  ProductDTO pdto4 = new ProductDTO("3333333333","TV",43000,"LG","무선 마우스");
//  System.out.println(pdto1.getProductName());
//  System.out.println(pdto1.toString());

  ProductManagerService pms = new ProductManagerService(30);
  pms.addProduct(pdto1);
  pms.addProduct(pdto2);
  pms.addProduct(pdto3);

  pms.addProduct(null);

  //pms.addProduct(pdto3);

  pms.printProductList();

  System.out.println("-----------id로 제품정보 조회------------");
  ProductDTO p1 = pms.searchProductById("p-111");
  System.out.println("p-111 제품정보 : "+p1.toString());
  ProductDTO p2 = pms.searchProductById("p-222");
  System.out.println("p-222 제품정보 : "+p1.toString());
  ProductDTO p3 = pms.searchProductById("p-333");
  System.out.println("p-333 제품정보 : "+p1.toString());

  //없는 Id로 조회
  ProductDTO p4 = pms.searchProductById("p-555");
  System.out.println("p-111 제품 정보 : "+p4);


  System.out.println("--------------정보수정--------------");
  pdto1 = new ProductDTO("p-111","노트북",15000000,"제조사","정보");
  pdto2 = new ProductDTO("p-222","마우스",1200000000,"삼성","휠");
  pms.modifyProductInfo(pdto1);
  pms.modifyProductInfo(pdto2);
  pms.printProductList();
 

  System.out.println("--------------정보삭제--------------");
  pms.removeProductById("p-222");
  pms.printProductList();
 // System.out.println("-------------------------------");
 // pms.printProductList();
 }
}


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

public class ProductManagerService 
{
 private ProductDTO[] productList;
 private int totalProductCount; //배열로 부터 현재 데이터가 몇개 들어가 있는지를 알게 해줄 변수

 public ProductManagerService(int length){
  productList = new ProductDTO[length];
 }
 public ProductManagerService(){
  productList = new ProductDTO[100];
 }
 //productList에 제품을 추가하는 메소드
 /*
  instance 변수 productList에 인수로 받은 제품 정보를 추가 하는 메소드
 */
 public void addProduct(ProductDTO productDTO){

  if(isNull(productDTO)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return ;
  }
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  //3. 배열에 제품정보 추가
  //4. totalProductCount의 값을 1 증가.
 
  
  //1.배열(productList)에 제품을 넣을 index가 있는지 체크
  //1-1 없으면 (totalProductCount==배열의 length) 넣을수 없다는 메세지를 출력하고 종료
  if(totalProductCount == productList.length){
   System.out.println("제품정보를 넣을 저장 장소가 없습니다.");
   return;
  }
  //2.productId는 식별자
  //2. 배열(productList)애 같은 productId값을 가진 제품이 저장되 있는지 체크
  //2-1 저장되 있으면 같은 아이디의 제품이 있어 등록할 수 없다는 메세지 출력하고 종료
  /* for(int i = 0;i<totalProductCount;i++){
   if(productList[i].getProductId().equals(productDTO.getProductId())){
   System.out.println("같은 제품이 있습니다. 아이디를 바꾸세요.");
   return;
   }
  }
  */
  ProductDTO p = searchProductById(productDTO.getProductId());
  if(p!=null){
   System.out.println("같은 제품이 있습니다. 아이디를 바꾸세요.");
   return;
  }
  //3. 배열에 제품정보 추가
  this.productList[totalProductCount]=productDTO;
  //4. totalProductCount의 값을 1 증가.
  totalProductCount++;
   
  
  

  
  /*
  //System.out.println("함수를 썼을경우");
  if(totalProductCount==productList.length){
   System.out.println("넣을 공간이 없습니다.");
  }
  else if(searchProductById(productDTO.getProductId())!=null){
   System.out.println("같은 제품이 있습니다.");
  }
  else{
   this.productList[totalProductCount]=productDTO;
   totalProductCount++;
  }
  */
 }
 /*
  instance 변수 productList에 저장된 모든 상품의 정보(id~info)를 출력해 주는 메소드
 */
 public void printProductList(){
  for(int i =0;i<totalProductCount;i++){
  System.out.println(productList[i].toString());
  }
 }
 /*
  productId를 인수로 받아 productList에서 찾아 그 제품의 정보를 return하는 메소드
  없을 경우 -null을 return
 */
 public ProductDTO searchProductById(String productId){

  ProductDTO pDTO = null;
  if(isNull(productId)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return pDTO;
  }

  for(int i =0;i<totalProductCount;i++){
   if(productId.equals(productList[i].getProductId())){ //조회대상
   pDTO=productList[i];
   break;
   }

  }
//  if(pDTO==null){
//   System.out.println("동일한 ID가 없습니다.");
//  }
  return pDTO;
  /*
   for(int i =0;i<totalProductCount;i++){
   if(productId.equals(productList[i].getProductId())){ //조회대상
   return productList[i];
  
   }

  }
  if(pDTO==null){
   System.out.println("동일한 ID가 없습니다.");
  }
  return null;
  */
 }
 /*
  정보를 수정하는 메소드
  id,이름,가격, 제조사,정보
  수정할 내용을 ProductDTO 객체로 받아서 productList에서 id를 가지고 찾아
  id가 같은 제품의 정보를 인수로 받은 정보로 변경한다.

 */


 public void modifyProductInfo(ProductDTO productDTO){
 

  if(isNull(productDTO)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return ;
  }
  for(int i=0;i<totalProductCount;i++){
  if(productDTO.getProductId().equals(productList[i].getProductId())){
   productList[i]=productDTO;
   break;
   }
  }

  
 }
 /*
 인수로 받은 productId를 가지고 productList에서 제품을 찾아 삭제(제거)
 */

 public void removeProductById(String productId){
  
  if(isNull(productId)){
   System.out.println("인자로 null값이 들어 왔습니다.");
   return ;
  }
  for(int i=0;i<totalProductCount;i++){
  if(productList[i].getProductId().equals(productId)){
  
   for(int j=i;j<totalProductCount-1;j++){
   productList[j]=productList[j+1];
   
   }
//   for(int j=i+1;j<totalProductCount-1;j++){
//   productList[j-1]=productList[j];
//   }

   totalProductCount--;
   productList[totalProductCount]=null;
  
   break;
  }

  }
 }

 private boolean isNull(ProductDTO pdto){
  boolean flag = false;
  if(pdto == null){
   flag = true;
  }
  return flag;
 }
 private boolean isNull(String str){
  boolean flag = false;
  if(str == null){
   flag = true;
  }
  return flag;
 }
}

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

public class  ProductDTO
{
 private String productId;
 private String productName;
 private int productPrice;
 private String productMaker;
 private String productInfo;

 public ProductDTO(){}
 public ProductDTO(String productId, String productName, int productPrice, String productMaker, String productInfo){
  this.productId=productId;
  this.productName=productName;
  this.productPrice=productPrice;
  this.productMaker=productMaker;
  this.productInfo=productInfo;
 }
 public String getProductId(){
  return productId;
 }
 public void setProductId(String productId){
  this.productId = productId;
 }
 public String getProductName(){
  return productName;
 }
 public void setProductName(String productName){
  this.productName = productName;
 }
 public int getProductPrice(){
  return productPrice;
 }
 public void setProductName(int productPrice){
  this.productPrice = productPrice;
 }
 public String getProductMaker(){
  return productMaker;
 }
 public void setProductMaker(String productMaker){
  this.productMaker = productMaker;
 }
 public String getProductInfo(){
  return productInfo;
 }
 public void setProductInfo(String productInfo){
  this.productInfo = productInfo;
 }
 public String toString(){
  return productId+" "+productName+" "+productPrice+" "+productMaker+" "+productInfo;
 }

}

============================================================

ex :

public class CommandLineArgs 
{
 //JVM은 실행 시 (java class명) 입력한 값을 main()의 인자로 넘겨준다.
 //예 : java CommandLineArgs A ABC 안녕 -> length 가 3인 배열을 만들어 A, ABC, 안녕
 //값을 넣어 main메소드의 인자로 넘긴다.
 public static void main(String[] args)
 {
  System.out.println("args.length : "+ args.length);
  System.out.println("------command line argument로 넘어온 값들-------------");
  for(int i = 0;i<args.length;i++){
   System.out.println(args[i]);
  }

 }
}

//CommandLineArgs.java
//java CommandLineArgs 안녕 반갑습니다 abc
//java CommandLineArgs "안녕 반갑습니다 abc"

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

staticTest[실습]  (0) 2012.07.28
package, import  (0) 2012.07.28
배열  (0) 2012.07.28
반복분(for, while)  (0) 2012.07.28
switch문  (0) 2012.07.28
Posted by 조은성
,

* 배열 (Array) - 같은 type의 Data를 모아서 관리하는 객체 (상자안에 여러개의 물건을 넣는 방식)
->같은 의미를 가지는 Data들을 모을 때 사용.

배열 변수선언

Datatype[] 식별자
ex :  int[] arr;

- 배열 객체 생성 및 할당

식별자 = new Datatype[length];

length : 모을 수 있는 Data 수


ex :  arr = new int [10];->int data 10개를 모을 수 있는 배열 객체(한번 크기를 정하면 거기서 끝이다.)

- 배열에 값 대입.

변수명 [index]= 값;

대입된 값 사용 :  변수명[index];

* 2012-03-06

- 배열 생성시 값초기화
1.int i[] = {10,,20,30,40};
2.new int[]{10,20,30};


* 배열 ex :

public class ArrayTest
{

 public void createArray1(){
  int[] intArray = new int[3]; //변수 선언 = 배열객체 생성;
  //배열에 값 할당
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

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

  intArray[0]=10;
  intArray[1]=20;
  intArray[2]=30;
  //배열의 값 조회
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");
  //System.out.println(intArray[3]); //length가 3이므로 마지막 index : 2 - > 오류
 }

 public static void main(String[] args)
 {
  ArrayTest at = new ArrayTest();
  at.createArray1();

 }
}


-배열 선언 ex:
public class ArrayTest
{

 public void createArray1(){
  int[] intArray = new int[3]; //변수 선언 = 배열객체 생성;
  //배열에 값 할당
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

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

  intArray[0]=10;
  intArray[1]=20;
  intArray[2]=30;
  //배열의 값 조회
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");
  //System.out.println(intArray[3]); //length가 3이므로 마지막 index : 2 - > 오류
 }
 
 public void createArray2(){
  //배열 선언, 생성, 값할당(초기화)
  double doubleArray[] = {10.5,203.7,102.3,1.6,2E3};
  System.out.println(doubleArray[0]+"\n"+doubleArray[1]+"\n"+doubleArray[2]+"\n"+doubleArray[3]+"\n"+doubleArray[4]);//2E3 : 2*10.0의 세제곱
  System.out.println("doubleArray의 length : "+doubleArray.length);

//for문을 이용한 출력.
  for(int i = 0;i<doubleArray.length;i++){
   System.out.println("doubleArray["+i+"] = "+doubleArray[i]);
  }

//  char [] c ;
//  c = {'a','b','c','d','e'};//선언 생성, 초기화 같이 해야만 한다.

 }
 public static void main(String[] args)
 {
  ArrayTest at = new ArrayTest();
  at.createArray1();
  at.createArray2();

 }
}

* 배열 예제2

public class ArrayTest
{

 public void createArray1(){
  int[] intArray = new int[3]; //변수 선언 = 배열객체 생성;
  //배열에 값 할당
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

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

  intArray[0]=10;
  intArray[1]=20;
  intArray[2]=30;
  //배열의 값 조회
  System.out.println(intArray[0]);
  System.out.println(intArray[1]);
  System.out.println(intArray[2]);

  System.out.println("------------------------------");
  //System.out.println(intArray[3]); //length가 3이므로 마지막 index : 2 - > 오류
 }
 
 public void createArray3(){
  //배열 선언, 생성, 값할당(초기화)
  String stringArray[] = new String[]{"가","나","다"};

//for문을 이용한 출력.
  for(int i = 0;i<stringArray.length;i++){
   System.out.println("stringArray["+i+"] = "+stringArray[i]);
  }

//  char [] c ;
//  c = {'a','b','c','d','e'};//선언 생성, 초기화 같이 해야만 한다.
  test(new boolean[]{true,false,false,false,true});
 }
 public void test(boolean[] boolArray){
  for(int idx = 0;idx<boolArray.length;idx++){
   System.out.println(boolArray[idx]);
  }
 }
  public void createArray2(){
  //배열 선언, 생성, 값할당(초기화)
  double doubleArray[] = {10.5,203.7,102.3,1.6,2E3};
  System.out.println(doubleArray[0]+"\n"+doubleArray[1]+"\n"+doubleArray[2]+"\n"+doubleArray[3]+"\n"+doubleArray[4]);//2E3 : 2*10.0의 세제곱
  System.out.println("doubleArray의 length : "+doubleArray.length);

//for문을 이용한 출력.
  for(int i = 0;i<doubleArray.length;i++){
   System.out.println("doubleArray["+i+"] = "+doubleArray[i]);
  }

//  char [] c ;
//  c = {'a','b','c','d','e'};//선언 생성, 초기화 같이 해야만 한다.

 }
 public static void main(String[] args)
 {
  ArrayTest at = new ArrayTest();
  at.createArray1();
  at.createArray2();
  at.createArray3();

 }
}

* 향상된 for문(jdk1.5이상부터 가능) = 배열/collection의 값들을 조회할때 사용.

배열 : 0번 idx~마지막 idx의 값 조회.

구문 :  for(변수선언 :  배열객체){
 변수로 작업;
}

ex : int [] arr = {1,2,3,4,5};
for(int i :  arr){
System.out.println(i); //배열의 0~마지막 idx까지 조회할때만 사용한다. 값대입이 안된다.
}


* 배열안에 들어간 숫자 객수 찍어보기

public class ArrayCount
{
 public static void main(String[] args)
 {
  int[] arr = new int[10];
  int[] arrayCount=new int[10];
  //1. arr에 0~9의 숫자를 10개 넣으세요.
  //2. 배열에 들어간 숫자들이 각각 몇개가 들어갔는지 출력하세요.
  for(int i=0;i<arr.length;i++){
   arr[i]=(int)(Math.random()*10);
   System.out.print(arr[i]+" ");
   
   arrayCount[arr[i]]++;
  
  }
  System.out.println();
  for(int i=0;i<arrayCount.length;i++){
   System.out.println("arrayCount["+i+"] = "+arrayCount[i]);
  }
 }
}


*rateTest

public class RateTest
{

 public static void starPrint(int tot){
 for(int i=0;i<tot;i++){
 System.out.print("*");
 }
 }
 public static void main(String[] args)
 {
  int data[] = {10,30,20,80,50};
  double rate[] = new double[5];
  double tot=0;


  for(int i =0;i<data.length;i++){
   tot+=data[i];
  }
  System.out.println(""+tot);
  
  for(int i=0;i<rate.length;i++){
   rate[i]=Math.round(data[i]/tot*100);

   System.out.print(data[i]+" : ");
   starPrint((int)rate[i]);
   System.out.println("<"+rate[i]+"%>");
  }

 }
}


* 클래스 배열

선언 :  Student[] stuArr = new Student[30];
생성 :  stuArr[0] = new Student();
        stuArr[1] = new Student();
값   :  stuArr[0].name ="홍길동";
 stuArr[1].study();


* type
stuArr - Student[]
stuArr[0] - Student


ex :

public class ArrayTestRefType
{
 public void createArray1(){
  Human[] humArray = new Human[3];
  humArray[0] = new Human();
  humArray[1] = new Human("이순신",20,172.3);
  humArray[2] = new Human("홍길동",30,182.5);
  
  humArray[0].printInfo();
  System.out.println("-------------------------");
  humArray[1].printInfo();
  System.out.println("-------------------------");
  humArray[2].printInfo();

  System.out.println("----------for문이용---------------");
  for(int i =0;i<humArray.length;i++){
   humArray[i].printInfo();
   System.out.println("-------------------------");
  }
  System.out.println("----------향상된 for문이용---------------");
  for(Human h : humArray){
   h.printInfo();
   System.out.println("-------------------------");
  }
 }
 public static void main(String[] args)
 {
  ArrayTestRefType atrt = new ArrayTestRefType();
  atrt.createArray1();
 }
}

ex2 :


public class ArrayTestRefType
{
 public void createArray1(){
  Human[] humArray = new Human[3];
  humArray[0] = new Human();
  humArray[1] = new Human("이순신",20,172.3);
  humArray[2] = new Human("홍길동",30,182.5);
  
  humArray[0].printInfo();
  System.out.println("-------------------------");
  humArray[1].printInfo();
  System.out.println("-------------------------");
  humArray[2].printInfo();

  System.out.println("----------for문이용---------------");
  for(int i =0;i<humArray.length;i++){
   humArray[i].printInfo();
   System.out.println("-------------------------");
  }
  System.out.println("----------향상된 for문이용---------------");
  for(Human h : humArray){
   h.printInfo();
   System.out.println("-------------------------");
  }

 }
 public void createArray2(){
  //선언,생성,초기화 한번에 처리
 Human humArray[] = {new Human(), new Human("유재석",41,180.0), new Human("박명수",43,178.5)};
 
 for(int i =0;i<humArray.length;i++){
  humArray[i].printInfo();
  System.out.println("######");

 }
 }
 public static void main(String[] args)
 {
  ArrayTestRefType atrt = new ArrayTestRefType();
  atrt.createArray1();
  atrt.createArray2();
 }
}


* class는 type , 객체는 값 잘기억해라.

* 2012.3.7

1. 2차원배열

-선언 :  Datatype[][] 변수명;

int [][]i;
int[]i[];
inti[][];
다 가능

- 생성 및 변수에 대입

변수명 = new Datatype[length][length];
i = new int[3][2];

* 2차원 배열 ex :
public class TwoDimensionArrayTest
{
 public static void main(String[] args)
 {
  //2010,2011 년도 1월~6월(전반기)강수량을 이차원배열을 통해 넣으세요.


  //double[][] rainfall = {{10,20,30,40,50,60},{10,20,30,40,50,60}};
  double[][] rainfall = new double[2][6];
  for(int i=0;i<rainfall.length;i++){
   for(int j=0;j<rainfall[i].length;j++){

    rainfall[i][j]=Math.random()*100;

   }
  }


  for(int i=0;i<2;i++){
   for(int j=0;j<6;j++){

    System.out.printf("201%d년 %d월 강수량 : %.2f\n",i,(j+1),rainfall[i][j]);

   }
  }
  System.out.println("---------향상된 for문---------------");
  for(double[] firstArr :  rainfall){
   for(double rain : firstArr){
    System.out.print(rain+"\t");
   }
   System.out.println();
  }

 

 }
}

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

package, import  (0) 2012.07.28
productManagerArray만들기 [실습]  (0) 2012.07.28
반복분(for, while)  (0) 2012.07.28
switch문  (0) 2012.07.28
if문  (0) 2012.07.28
Posted by 조은성
,

1. 메소드(메소드 타입과 명이 사용법을 알려준다.)
2. $와 _는 변수명 앞에 올수 있다.
3. 메소드와 변수명을 길게 정확하게 주는 이유는 이 메소드나 변수가 뭐하는 거구나 알기 위해서이다.
4.for(1(초기식) ; 2(조건식) ; 3(증감식) ){
    4(반복구문)
}

for문의 수행 순서는 1->2->4->3 이다

5. while문 예제

public class WhileTest{

 public static void main(String[] args)
 {
  //1~10출력

  int x = 1;
  while(x<=10){

  System.out.println(x);
  x++;
  }
  System.out.println("-----------------------------");
  printLoop(10,20);
  System.out.println("-----------------------------");
  printLoop(20,10);
 }
 public static void printLoop(int start, int end){
  if(start<=end){
  while(start<=end){
   
   System.out.println(start);
   start++;
  }
  }else if(start>=end){
  while(start>=end)
  {
   System.out.println(start);
   start--;
  }
  }
 }
}


* for문 예제

class forTest
{
 public static void main(String[] args)
 {
  //1~10 for문 이용 출력

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

  System.out.println(i);
  }
  System.out.println("--------------------");
  printLoop(10,20);
  System.out.println("--------------------");
  printLoop(21,8);
 }
 public static void printLoop(int start, int end){
  if(start<=end){
  for(;start<=end;start++){
    System.out.println(start);
  }
  }else{
  for(;start>=end;start--){
    System.out.println(start);
  }
 }

 }
}

* 중접반복문 예제

//중첩 반복문
public class NestedLoop
{
 public static void main(String[] args)
 {
  for(int i = 1;i<=5;i++){
   for(int j=1;j<=5;j++){
    System.out.print(j+" ");
   }
   System.out.println();
  }
 }
}

* 구구단 예제

import java.io.*;
class gugudan
{
 public static void main(String[] args) throws IOException
 {

  int num = System.in.read()-'0';
  for(int i=1;i<=9;i++){
   for(int j = num;j<=9;j++){
    System.out.print(j+"*"+i+"="+i*j+"\t");
   }
   System.out.println();
  }
 }
}


* continue , break 예제

class BreakContinueTest
{
 public static void breakTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  System.out.println(i);
  if(i==5) break;
  }
  
 }
 public static void continueTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  
  if(i==5) continue;
   System.out.println(i);
  }
 
  
 }
 public static void main(String[] args){
  breakTest();
  System.out.println("----------------------");
  continueTest();
 }
}

*BreakContinueTest 2

class BreakContinueTest
{
 public static void breakTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  System.out.println(i);
  if(i==5) break;
  }
  
 }
 public static void continueTest()
 {
  //1~10 출력 값이 5이면 break
  for(int i =1; i <=10;i++){
  
  if(i==5) continue;
   System.out.println(i);
  }
 
  
 }
 public static void continueTest2()
 {
  int i=1;
  while(i<=10){
   if(i%2==0){
   i++;// 여기서도 증가를 시켜줘야함
    continue;
   }
   System.out.println(i);
   i++;    //여기서만 i++넣으면 무한 반복 하게 된다.
  }
 
  
 }
 public static void main(String[] args){
  breakTest();
  System.out.println("----------------------");
  continueTest();
  System.out.println("----------------------");
  continueTest2();
 }
}

 

* 반복문 완전 빠져나가기(label1으로 반복문 빠져 나가기)

label1 :  for( ; ; ){
  for( ; ; ){
   break label1;
  }
 }


ex :

a :  while(조건){
 b : while(조건){
  c : while(조건){
   break b;  //반복문 b를 빠져나가라,
   break a;  //반복문 a를 빠져나가라,
   break c;  //반복문 c를 빠져나가라,
  }
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

productManagerArray만들기 [실습]  (0) 2012.07.28
배열  (0) 2012.07.28
switch문  (0) 2012.07.28
if문  (0) 2012.07.28
Data type, 연산자, 형변환  (0) 2012.07.28
Posted by 조은성
,

* switch

- switch(식){<- 변수 메소드 호출 type(식에 들어 갈수 있음) :  byte, short, char, int,Enum(jdk 1.5버전부터됨), String(1.7버전부터됨)
case 값1 :
실행구문 A
case 값2 :
실행구문 B
default:
실행구문 C
}
* default는 생략가능
식의 값이 값1이면 A를 실행 , 식의값이 값2이면 B실행 , 값1도 값2도 아니면 default 실행.


(ex :

int i = 2;
switch(i){
case 1:
s.o.p("일");
break;
case 2:
s.o.p("이");
break;
case 3:
s.o.p("삼");
break;
default : 
s.o.p("그밖에");

}


2.
class SwitchTest1{
 public static void main(String[] args)
 {
  //Math.random() : double -> 0<=x<1 실행시 마다 임의적으로 return
  int num = (int)(Math.random()*4)+1; //1~3까지의 수를 찍고 싶으면
  //int num = (int)(Math.random()*51);//0~50을 찍고 싶으면
  System.out.println("num : "+num);
  switch(num){
   case 1:
    System.out.println("스페이드");
   break;
   case 2:
    System.out.println("다이아몬드");
   break;
   case 3:
    System.out.println("클로버");
   break;
   case 4:
    System.out.println("하트");
   break;
  }
 }
}

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

배열  (0) 2012.07.28
반복분(for, while)  (0) 2012.07.28
if문  (0) 2012.07.28
Data type, 연산자, 형변환  (0) 2012.07.28
제한자, 캡슐화, 변수, this  (0) 2012.07.28
Posted by 조은성
,

class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
  if(100>=jumsu && jumsu>=90){
   return 'A';
  }else if(jumsu<=89 && jumsu>=80){
   return 'B';
  }else if(jumsu<=79 && jumsu>=70){
   return 'C';
  }else if(jumsu<=69 && jumsu>=60){
   return 'D';
  }else {
   return 'F';
  }

 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  System.out.println(c1+","+c2+","+c3);//A,F,B

 }
}


2.
class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
  if(100>=jumsu && jumsu>=90){
   return 'A';
  }else if(jumsu>=80){
   return 'B';
  }else if(jumsu>=70){
   return 'C';
  }else ifjumsu>=60){
   return 'D';
  }else {
   return 'F';
  }

 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  System.out.println(c1+","+c2+","+c3);//A,F,B

 }
}
3.

class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
   char grade = ' ';
  if(100>=jumsu && jumsu>=90){
   grade = 'A';
  }else if(jumsu>=80){
   grade = 'B';
  }else if(jumsu>=70){
   grade = 'C';
  }else ifjumsu>=60){
   grade  = 'D';
  }else {
   grade =  'F';
  }
  return grade;

 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  if(


  System.out.println(c1+","+c2+","+c3);//A,F,B

 }
}

* if 예외처리

class IfGrade
{
 /**
 매개변수로 점수를 받는다.0~100
 점수
 100~90 : 'A'를 return
 89~80 : 'B'를 return
 79~70 : 'C'를 return
 69~60 : 'D'를 return
 60 이하 : 'F'를 return
 */
 public char checkGrade(int jumsu){
 
 char grade = ' ';
  if(100>=jumsu && jumsu>=90){
   grade= 'A';
  }else if(jumsu<=89 && jumsu>=80){
   grade= 'B';
  }else if(jumsu<=79 && jumsu>=70){
   grade= 'C';
  }else if(jumsu<=69 && jumsu>=60){
   grade= 'D';
  }else if(jumsu<60){
   grade= 'F';
  }
     return grade;
 }
 public static void main(String[] args)
 {
  IfGrade grade = new IfGrade();
  char c1 = grade.checkGrade(92);
  char c2 = grade.checkGrade(42);
  char c3 = grade.checkGrade(82);
  char c4 = grade.checkGrade(150);

  
  System.out.println(c1+","+c2+","+c3);//A,F,B
  if(c4==' '){
  System.out.println("잘못된 잢이 들어갔습니다.");
  }

 }
}

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

반복분(for, while)  (0) 2012.07.28
switch문  (0) 2012.07.28
Data type, 연산자, 형변환  (0) 2012.07.28
제한자, 캡슐화, 변수, this  (0) 2012.07.28
객체지향(oop)이라면 알아야할 개념  (0) 2012.07.28
Posted by 조은성
,

1. Data type : Data(값)의 구분(종류)
               -> 기준 :  형태, 크기

   -① Primitive Data type(기본 data type)-(ex :  숫자, 문자..(1개의 값 표현밖에 못함))
   -② Reference Data type(참조 data type)-(ex : class(class가 type, 객체(instance) 가 값이된다.)(여러개의 값이 합쳐져 하나의 값을 표현))
       ->Reference Data type의 기본 값은 NULL이다.
(null은 아무 객체도 참조하고 있지 않다는 뜻이다.)
* null값가진변수.xxx->실행시 오류 발생.(Null pointer exception발생)
 
2.타입

①실수 - double(8byte) - 실수형의 기본 type->소수점이하 16자리까지 표현(더 정밀하게 표현한다)
       float(4byte)  - 값F, 값f(ex :  50.2F, 50.2f)->소수점이하 7자리까지 표현

②정수형 - byte(1byte)
  short(2byte)
  int(4byte) - 기본형(20억을 기준으로 사용을 결정한다.)
  long(8byte)


* 10.5->1.05x10->0.105e2
* 1600000000000000 ->16*10^14->16E14

③ 논리형(Logical) - 참/거짓->type은 boolean

   값 : true,false

④ 문자 - char(2byte) : 1글자를 값으로 가진다.
                 값은 ''으로 감싼다.
                 2byte-unicode 한글자
  '\uAOSB(<-유니코드 한글자) -> unicode 1글자(16진수로 나타남)

*escape문자
'\t' - tab
'\n' - enter
'\\' - \문자(역슬러시)
'\'' - '
"\"" - "

3.String - 문자열(0~n글자)을 위한 Data type
         ->class -> Reference Data type
         - new 생성자() 하지 않고 객체 생성

* 사용:

1.변수 = "문자열";
  String s = "ABCDE";
2.변수=new String("문자열");
  String s = new String ("ABCDE");

* 두개의 문자열이 같은지 비교

boolean b = String객체.equals(비교String객체);
        b = "abs".equals("def");
 b = s1.equals(s2)l - s1,s2가 String type

* type이 다른 경우 작은 type 을 큰 type으로 바꾼후 계산한다.
* byte-short-int-long-float-double
      -char

*논리 연산자
- && ->and  true & true -> true 나머진 다 false   (&하나짜리는 뒤에도 검사, &&뒤에짜리는 하나가 참이면 바로 검사를 멈추고 나온다)
- || ->or   false | false ->false 나머진 다 true  (|하나짜리는 뒤에도 검사, ||뒤에짜리는 하나가 참이면 바로 검사를 멈추고 나온다)
- ^->xor  true ^ false -> true
        false ^ true -> true

        t^t->false
        f^f->false
- !->not

!true->false
!false->true

* 조건(삼항)연산자

조건 ? 피연산자1 :  피연산자2;
->boolean- true면 피연산자 1을 쓰고 false면 피연산자 2를쓴다.

int a = (x<5)? 20 :  50;
x가 5보다 작으면 20을 a에 넣고 아니면 50을 넣어라.

* cast 연산자(형변환) :  값의 type을 변환 시켜주는 연산자

- primitive Data type 간의 형변환 가능
- Reference Data type 간의 형변환 가능

사용법 :  (type)값; (int)10.5;

*자동형변환 : upcasting( 작은 type->큰 type)

*명시적코딩 : down casting(큰type->작은type)
 (변수보다 값이 더 큰경우 명시적 형변환이 필요하다)
* primitive Data type에서 형변환을 하면 Data가 깨질수도 있다.

ex :
class TypeCasting{
 public static void main(String[] args)
 {
  
  int var1=10+20; 
  System.out.println("10+20 = "+var1);//String +int->String+String
  
  double var2 = 20+30+25.7;
  System.out.println("20+30+25.7 = "+var2);//String +int->String+String
  
  long var3 = 365L*365*365*365*365*365*5;
 //  long var3 = (long)365*365*365*365*365*365*5;
  System.out.println("365*365*365*365*365*365*365*365*365*365*5 = "+var3);
                //캐스팅 연산 - 대입연산시에만 주의
         boolean b = 'a'<5;
  System.out.println(b); //false나옴
  long I = 10;//(O)
 // int k = 20L;//컴파일 에러
  int l = (int)30L;
  System.out.println(k);//30나옴
  int h = (int)300000000000000000L; //
  System.out.println(h);//이러면 300000000000000000L이 값이 나오지 않음 따라서. 작은 값안으로 강제형변환 하는 것은 좋지 않음.
 }
}

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

switch문  (0) 2012.07.28
if문  (0) 2012.07.28
제한자, 캡슐화, 변수, this  (0) 2012.07.28
객체지향(oop)이라면 알아야할 개념  (0) 2012.07.28
this  (0) 2012.07.28
Posted by 조은성
,