Java/중요클래스
문자열과 객체 비교
Bohemian life
2012. 4. 11. 22:15
package com.stringex;//문자열 과 객체 비교 public class StringEx1 { public static void main(String[] args) { //암시적 객체생성 //암시적으로 String 객체를 생성할때 문자열이 같으면 객체를 공유함 String str1 = "abc"; String str2 = "abc"; //객체 비교 if(str1==str2) System.out.println("str1과 str2는 같은 객체");//<- else System.out.println("str1과 str2는 다른 객체"); //문자열 비교 if(str1.equals(str2)) System.out.println("str1과 str2는 같은 객체");//<- else System.out.println("str1과 str2는 다른객체"); System.out.println("=-=-=-=-=-=-=-=-=-=-=-"); //명시적 객체생성 //명시적으로 String객체를 생성하면 문자열이 같아도 객체를 따로 생성 String str3 = new String("abc"); String str4 = new String("abc"); if(str3==str4) System.out.println("str3과 str4는 같은 객체"); else System.out.println("str3과 str4는 다른 객체");//<- if(str3.equals(str4)) System.out.println("str3과 str4는 같은 객체");//<- else System.out.println("str3과 str4는 다른 객체"); } }
str1과 str2는 같은 객체
str1과 str2는 같은 객체
=-=-=-=-=-=-=-=-=-=-=-
str3과 str4는 다른 객체
str3과 str4는 같은 객체