String class
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=new String(); // 문자열 클래스는 레퍼런스타입이므로 동적할당으로(힙 영역에) 객체 생성해준다.
str=sc.next();
System.out.println(str);
}
}
public class Hello {
public static void main(String[] args) {
String str=new String("superman"); // 문자열객체 생성과 동시에 초기화 , 처음부터 값 넣기
System.out.println(str);
}
}
public class Hello {
public static void main(String[] args) {
String str = new String("superman");
System.out.println(str);
String str2 = "superman";
System.out.println(str2);
if (str == str2) { // 값을 비교하는 것이 아니라 heap 영역에서의 문자열 객체의 위치(주소) 비교하는 것이기 때문에
System.out.println("Same");
} else {
System.out.println("Diff"); // Diff 출력
}
if (str.equals(str2)) { // equals가 문자열 값 비교함수
System.out.println("Same");
} else {
System.out.println("Diff"); // Same 출력
}
}
}
public class Hello {
public static void main(String[] args) {
String str = "superman";
String str2 = "superman"; // 기존의 "superman"이란 값을 가진 str를 참조하여 주소값이 같아짐
//new를 쓰면 다른 객체로 만들어지기 때문에 값은 같을 수 있어도 주소값이 다르다.
if (str == str2) {
System.out.println("Same");
} else {
System.out.println("Diff"); // 같은 객체 참조하여 주소값이 같기 때문에 Same 출력
}
if (str.equals(str2)) {
System.out.println("Same");
} else {
System.out.println("Diff"); // Same 출력
}
}
}
import java.util.Scanner;
public class Hello {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
String str=new String("superman");
String str1=new String("superman");
if(str==str1){ //동적메모리 new는 각자 메모리 생성하기 때문에 주소값 diff 출력
System.out.println("Same");
}else{
System.out.println("diff");
}
if(str.equals(str1)){ //same
System.out.println("same");
}else{
System.out.println("diff");
}
}
}
public class Hello2 {
public static void main(String[] args) {
String str=new String("Superman"); // 처음엔 Superman을 잡으나,
str="Batman"; // str이 Batman을 새로 만든다.
System.out.println(str); // Batman출력
}
}