[Java] Wrapper, Math Classes, if and switch Statements

· Tech· Java
Java

Wrapper class


Byte, Short, Integer, Long, Double, Float, Character

Unlike basic data types (primitive types), the Wrapper class provides data storage, four-rule operations, and method functions.

//In ASCII code, A is "65" and a is "97". That is, the difference between uppercase and lowercase letters is 32.

Wrapperclass.toUpperCase()

Wrapperclass.toLowerCase()

Used when changing lowercase letters to uppercase letters or uppercase letters to lowercase letters in English letters.

@@T64@ @Wrapperclass@@ T72@@.isUpperCase()@ @T79@@

Wrapper class@@T98@ @.isLowerCase()

Wrapper class .isDigit()

() Used to check whether the value in ( ) is an uppercase letter, lowercase letter, or number.

1
2
3
4
5
6
7
8
9
Character chr = new Character('a');
System.out.println@@T 178@@("cha => "+chr); 
System.out.println(chr+1); 
System.out.println((char)(chr-32));  //'A'
System.out.println((char)('a'-32));  //'A'
System.out.println(Character.toUpperCase('a'));  
System.out.println(Character.toLowerCase('A'));
System.out.println(Character.toUpperCase(97));
System.out.println(Character.toLowerCase(65));
cs

 

char ch1 = sc.nextLine().charAt(0);  

 

입력받은 값에서 첫 번째 index 값을 char로 변경하고자 할 때이다. index 값은 0부터 시작하며, 위와 같이 줄여서 사용할 수 있다는 것을 알아두자.

 

Boxing과 UnBoxing

 

기본형 자료 타입을 객체형인 Wrapper 클래스 형태로 변환하는 것을 Boxing(박싱)이라고 한다. 반대로 Wrapper 클래스에서 기본형 자료 타입으로 변환하는 것은 UnBoxing(언박싱)이다. 그리고 각각의 변환시에 간단하게 코드를 줄여서 작성하게 되면 Auto를 붙여 오토박싱, 오토언박싱이라고 한다.

 

박싱은 기본형자료를 Wrapper 클래스 객체를 새로 선언하여 대입해주는 것이다. 이 때, 매개변수 값이 기본형 자료를 대입한다.

오토박싱은 Wrapper 클래스에 기본형 자료를 선언하여 대입하는 것으로 축약된 형태이다.

 

Unboxing substitutes the value of the Wrapper class object into basic data using methods such as .intValue() or .DoubleValue(). 

Auto unboxing is an abbreviated form of assigning a Wrapper class object created to basic data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int a1 = 10;
Integer a2 = new Integer(a1);  // Boxing
System.out.println@@ T422@@("a2 => "+a2);  //10
int b1 = 10;
Integer b2 = b1;  // Auto Boxing
System.out.println@@ T458@@("b2 => "+b2);  //10
              
Integer a3 = new Integer(20);
int a4 = a3.intValue();           //UnBoxing
System.out.println@@ T496@@("a4 => "+a4);  //20
int a5 = new Integer(20);           //Auto UnBoxing(오토언박싱)
System.out.println("a5 => "+a5);  //20
        
Double db1 = new Double(21.2345);
double db2 = db1.doubleValue();           //UnBoxing(언박싱)
System.out.println("db2 => "+db2);  //21.2345
        
double db3 = new Double(21.2345);         //Auto UnBoxing(오토언박싱)
System.out.println("db3 => "+db3);  //21.2345
cs

 

Math 클래스


Math.round( )    Math.ceil( )    Math.floor( )   Math.abs( )

 

순서대로 반올림, 올림, 내림, 절대값을 구하고자 할 때 사용되는 메서드이다.

 

특정 소수부에서의 반올림

 

If you want to round off a specific decimal point, multiply the value up to the decimal point to be rounded by the corresponding number of 10 digits to make it an integer and divide again.  In other words, if you want to display up to 1 decimal place, Math.round(db1*10@@T6 75@@)/10.0 Like this Write it. Please note that when dividing again, you must enter .0 to allow for real numbers. 

1
2
3
4
5
6
7
8
9
10
11
double db1 = 93.456 78, db2 = 86.87654;
// == You want to round to a specific decimal place. ==
          
System.out.println@@T 754@@("\n === After rounding to the first decimal place ===");
System.out.println("db1 => "@@T769@ @+Math.round(db1*@@T7 75@@10)/10.@@T 782@@0+ ", db2 => "@@ T788@@ +Math.round(db2 *10)@ @T801@@/10.0);
//db1 => 93.5, db2 => 86.9
System.out.println@@ T820@@("\n === After rounding to two decimal places ===");
System.out.println("db1 => "+Math.round(db1*100)/100.0+ ", db2 => " +Math.round(db2*100)/100.0);
//db1 => 93.46, db2 => 86.88
cs

 

if, else if 문


문자열의 비교

 

문자열을 비교(==)시 기본형처럼 선언한 문자열은 값만을 비교한다. 하지만 String 클래스 객체 선언으로 만든 문자열 비교시에는 그 문자열이 속해 있는 데이터 주소 값을 비교한다.  하지만 a.equals(b) 를 이용하면 주소 값이 아닌 데이터 값 자체를 비교할 수 있다.

 

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
47
48
49
50
51
52
53
54
55
56
57
58
59
package my.day05.c.IF;
 
import java.util.Scanner;
 
public class CalcMain {
 
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        
        try {
            
            System.out.print("첫번째 정수 입력 => ");
            int num1 = Integer.parseInt(sc.nextLine());
            
            
            System.out.print("두번째 정수 입력 => ");
            int num2 = Integer.parseInt(sc.nextLine());
            System.out.print("사칙연산자 선택 (+ - * /) => ");
            String operator = sc.nextLine();
            
            String result = "";
            
            if("+".equals(operator)) {
                result = String.valueOf(num1 + num2);
            } else if ("-".equals(operator)) {
                result = String.valueOf(num1 - num2);
            } else if ("*".equals(operator)) {
                result = String.valueOf(num1 * num2);
            } else if ("/".equals(operator)) {
                if(num2 == 0
                    result = ">>> 분모에는 0 이 올 수 없습니다! <<<";
                else
                    result = String.valueOf((double)num1 / num2);
            } else {
                System.out.println(">> 사칙연산(+ - * /)만 선택하세요. <<"); 
                sc.close();
                return;
            }
                    
            //***삼항연산자
            result = ("/".equals(operator) && num2==0)? result : num1+"+"+num2+"="+result;
            
            System.out.println(result);
            
        } catch (NumberFormatException e) {    
            
            System.out.println(">>> 정수로 입력해주세요! <<<");
            e.getStackTrace();
                        
        }
 
        sc.close();
    }
    
        
}
 
 
cs

 

switch 문


1
2
3
4
5
6
7
8
switch (key) {
        case value:
            
            break;
 
        default:
            break;
        }
cs

 

switch 문의 구성은 위와 같다. if와 같은 조건문으로 key 와 value 는 비교하려는 값으로 값은 같아야 한다. value 값은 String, byte, int, short, char 타입만 가능하다.

하지만, if문과 달리 value 에는 범위 형태로 작성할 수 없다. case 의 value 를 '또는'으로 작성하고 싶은 경우, case : 를 연달아 작성해서 표현한다. 그리고 case 값이 여러 개인 경우에는 중간에 break; 문을 지워서 값을 출력할 수도 있다.

 

삼항연산자를 이용한 return값 출력

 

(조건식)? 참 : 거짓

조건식이 true 이면 참의 값을 false 이면 거짓의 값을 반환한다. 

1
result = ("/"@@T1 608@@.equals(operator) &@@T 1614@@& num2@@T16 21@@==0)? result : num1+"+"+num 2+"="+result;
cs

Output return value using assignment operator

When printing

gift by decreasing its value one by one. The value of "A" is "amusement park ticket, chicken, pizza, ice cream," and the lower the grade, the lower the value decreases by one. "A" continues to add value until it encounters a break statement (+=).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
String gift() {
          
        String gift = "";
          
switch (grade()) { //Only types String, byte, int, short, char are allowed in //switch()
|
gift + = "Amusement park ticket, ";        
|
|
gift +@@T1790 @@= "Chicken, ";        //Assignment operator
|
gift +@@T1812 @@= "Pizza, ";            
case "D":
gift +@@T1832 @@= "Ice Cream";        
break;
                default:
                  gift = "Honey Night 3";
break;
          return gift;
cs

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164