본문 바로가기
JAVA

[JAVA] JAVA에서의 형변환(casting)

by 무사뎀벨레 2021. 12. 23.

 

 

 

 

 

 

 

 

1. 문자 -> 숫자


  1. String -> Int
    String testA = "12345";
    int testB = Integer.parseInt(testA);


  2. String -> Double, Float 
    //String -> Double
    String testA = "10";
    double testB = Double.valueOf(testA);
    
    //String -> Float
    String testA = "10";
    float testB = Float.valueOf(testA);
    ​




 

 

 

 

2. 숫자 -> 문자


  1. Int-> String 
    int testA = 12356;
    String testB = Integer.toString(testA);





  2. Double, Float  -> String
    //1번방식 => String.valueOf(Float값,Double값)
    //2번방식 => Float.toString(Float값,Double값)
    
    float testF = 10.10;
    double testD = 10.10;
    		
    String testS;
    
    testS = String.valueOf(testF); //Float -> String (1번방식)
    testS = Float.toString(testF); //Float -> String (2번방식)
    		
    testS = String.valueOf(testD); //Double -> String (1번방식)
    testS = Double.toString(testD); //Double -> String (2번방식)


     

 

 

 

 

3. 정수 <->  실수


  1. Double, Float -> Int
    //(int)실수값
    double testD = 10.101010;
    float testF = 10.1010
    
    int testI;
    testI = (int)testD; //Double-> Int
    testI = (int)testF; //Float -> Int​



  2. Int -> Double, Float
    //(int)실수값
    int testI = 10;
    	
    double testD = (double)testI; //Int -> Double
    float testF = (float)testI; //Int -> Float​




 

 

4. 기타


  1. String -> Date(문자 -> 날짜)
    String testA = "2021-12-23 11:11:11";
    
    //testA의 날짜 형식과 동일하게 맞춰줍니다.
    //2021-12-23 11:11:11 -> yyyy-MM-dd HH:mm:ss
    SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    Date testB = fm.parse(testA);​



  2. String -> JSON
    //1. Json 문자열
    String strJson = "{\"playerName\":\"son\", "
    + "\"playerNum\":\"7\","
    + "\"playerInfo\":{"
    + "\"age\":30,"
    + "\"foot\":\"right\""
    + "}"
    + "}";
    
    //2. Parser
    JSONParser jsonParser = new JSONParser();
    
    //3. To Object
    Object obj = jsonParser.parse(strJson);
    
    //4. To JsonObject
    JSONObject jsonObj = (JSONObject) obj;
    
    //print
    System.out.println(jsonObj.get("playerName")); //son
    System.out.println(jsonObj.get("playerNum")); //7
    System.out.println(jsonObj.get("playerInfo")); // {"age":30,"foot":"right"}​
반응형

댓글