public class Person {
String name;
int age;
void Introduce() {
System.out.print("Hello, my name is " + name);
System.out.print("My age is " + age);
}
}
public class StringTest {
public static void main(String [] args) {
Person Tom = new Person();
Person Jane = new Person();
System.out.println("toString() of Tom = " + Tom);
System.out.println("toString() of Jane = " + Jane);
String s = "one";
// s.charAt(0) = 'a'; error
System.out.print(s + ": ");
System.out.println((StringTest.class.getName() + "@" + Integer.toHexString(s.hashCode())));
String ps = s;
System.out.print(ps + ": ");
System.out.println((StringTest.class.getName() + "@" + Integer.toHexString(ps.hashCode())));
String news = s.toUpperCase();
System.out.print(news + ": ");
System.out.println((StringTest.class.getName() + "@" + Integer.toHexString(news.hashCode())));
s = new String("two");
System.out.print(s + ": ");
System.out.println((StringTest.class.getName() + "@" + Integer.toHexString(s.hashCode())));
ps = s;
System.out.print(ps + ": ");
System.out.println((StringTest.class.getName() + "@" + Integer.toHexString(ps.hashCode())));
news = s.toUpperCase();
System.out.print(news + ": ");
System.out.println((StringTest.class.getName() + "@" + Integer.toHexString(news.hashCode())));
//String are immutable in Java. You can't change them.
//You need to create a new string with the character replaced.
String Name = "java jjang";
String newName = Name.substring(0,2)+'x'+Name.substring(3);
System.out.println("[1] " + newName);
//Or you can use a StringBuilder:
StringBuilder Name2 = new StringBuilder("java jjang");
Name2.setCharAt(2, 'x');
System.out.println("[2] " + Name2);
String Name3 = "java jjang";
char[] NameChars = Name3.toCharArray();
NameChars[2] = 'x';
Name3 = String.valueOf(NameChars);
System.out.println("[3] " + Name3);
}
}