Java字符串的一个重要特点就是字符串不可变。这种不可变性是通过内部的private final char[]字段,以及没有任何修改char[]的方法实现的。
例子:
1 2 3 4 5 6 7 8
public class Main { public static void main(String[] args) { String s = "Hello"; System.out.println(s); s = s.toUpperCase(); System.out.println(s); } }
toUpperCase函数,转大写
字符串比较
1 2 3 4 5 6 7 8 9 10 11
public class Main { public static void main(String[] args){ String s = "hello word"; System.out.println(s); String ss = s.toUpperCase(); System.out.println(ss); String s2 = new String(new char[] {'H', 'e', 'l', 'l', 'o', '!'}); System.out.println(s2); System.out.println(s.equals(ss)); } }
1 2 3 4 5 6 7 8 9 10 11 12 13
public class Main { public static void main(String[] args){ String s = "hello word"; System.out.println(s); String ss = s.toUpperCase(); // 转大写 System.out.println(ss); String s2 = new String(new char[] {'H', 'e', 'l', 'l', 'o', '!'}); System.out.println(s2); System.out.println(s.equals(ss)); ss = ss.toLowerCase(); // 转小写 System.out.println(ss); } }
public class Main { public static void main(String[] args) { String s = "Hi %s, your score is %d!"; System.out.println(s.formatted("Alice", 80)); System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5)); } }
char[] cs = "Hello".toCharArray(); // String -> char[] String s = new String(cs); // char[] -> String
1 2 3 4 5 6 7 8 9
public class Main { public static void main(String[] args) { char[] cs = "Hello".toCharArray(); String s = new String(cs); System.out.println(s); cs[0] = 'X'; System.out.println(s); } }
public class Main { public static void main(String[] args){ int[] scores = new int[] { 88, 77, 51, 66 }; Score s = new Score(scores); s.printscores(); scores[2] = 123; s.printscores(); } }
class Score{ private int[] scores; public Score(int[] scores){ this.scores = scores; }
public void printscores(){ System.out.println(Arrays.toString(this.scores)); } }
public class Main { public static void main(String[] args) { var sb = new StringBuilder(1024); sb.append("Mr ") .append("Bob") .append("!") .insert(0, "Hello, "); System.out.println(sb.toString()); } }
public class Main { public static void main(String[] args) { Adder adder = new Adder(); adder.add(3).add(5).inc().add(10); System.out.println(adder.value()); } }
class Adder{ private int sum = 0; public Adder add(int n ){ sum += n; return this; } public Adder inc(){ sum ++; return this; } public int value(){ return sum; }
public class Main { public static void main(String[] args) { String[] names = {"Bob", "Alice", "Grace"}; var sj = new StringJoiner(", ", "Hello ", "!"); for (String name : names) { sj.add(name); } System.out.println(sj.toString()); } }