티스토리 뷰

지역변수에 final을 선언하는 것

final Local Variable
- final is the only allowed access modifier for local variables.
- final local variable is not required to be initialized during declaration.
- final local variable allows compiler to generate an optimized code.
- final local variable can be used by anonymous inner class or in anonymous methods.

출처: https://www.tutorialspoint.com/final-local-variable-in-Java

지역변수에 final을 선언하는 것과 아닌 것은 취향의 차이일 수 있다고 하나, 찾아보니 위와 같은 효과가 있다고 한다. 느낄 수 없지만 가장 유용한 정보는 컴파일러에게 코드 최적화를 하게 해준다는 것!

 

equals를 테스트 할때

    private int calculate(String operator, int a, int b) {
        // 1번 방법
        if (operator.equals("+")) { 
            return a + b;
        }
        // 2번 방법 ✨이게 더 좋음
        if ("+".equals(operator)) { 
            return a + b;
        }
        
        //...
    }

1번 방법보다 2번 방법이 더 좋다. 왜냐하면 operator가 null이 들어올 수도 있기 때문이다.

1번 방법이라면 operator에 null이 들어오면 널포인터익셉션의 가능성이 생긴다.

2번 방법은 "+"는 이미 고정된 값이라 널포인터익셉션의 가능성이 없다.

 

문자열

new String("abc")로 생성하는 것은 `new`라는 예약어로 항상 새로운 객체를 생성한다. 하지만, String s = "abc" 는 스트링 풀로 관리된다.

String s1 = new String("abc") // 😒 Bad
String s2 = "abc" // 😃 Better

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함