看结果1?
package com.swift; class ArrayString { public static void main(String[] args) { String str = "swift:30|sunny:28|Ben:32"; String str1[] = str.split("\\|"); for (int i = 0; i <= str1.length - 1; i++) { String str2[] = str1[i].split("\\:"); System.out.println("名字是" + str2[0] + "-->" + "年龄是" + str2[1]); System.out.println(); } } }
看结果2?
package com.swift; class StringEmail { public static void main(String[] args) { String email="[email protected]"; String email1="[email protected]"; String email2="tiankong.sina.com"; String email3="[email protected]"; String email4="[email protected]"; String email5="@."; System.out.println(operate(email)); System.out.println(operate(email1)); System.out.println(operate(email2)); System.out.println(operate(email3)); System.out.println(operate(email4)); System.out.println(operate(email5)); } public static boolean operate(String str) { boolean flag=true; if (str.indexOf("@")==-1) { flag=false; } if (str.indexOf(".")==-1) { flag=false; } if (str.indexOf(".")<=str.indexOf("@")) { flag=false; } return flag; } }
看结果3?
package com.swift; class StringEquals { public static void main(String[] args) { String str="Hello"; String str1=new String("Hello"); if(str.equals(str1)) System.out.println("111111111"); else System.out.println("00000000000"); } }
看结果4?
package com.swift; public class StringResult { String str = new String("good"); char[] ch = { ‘a‘, ‘b‘, ‘c‘ }; public static void main(String args[]) { StringResult sr = new StringResult(); sr.change(sr.str, sr.ch); System.out.print(sr.str + "and"); System.out.print(sr.ch); } public void change(String str, char ch[]) { str = "test ok"; ch[0] = ‘g‘; } }
看结果5?
package com.swift; class StringJudge { public static void main(String[] args) { String str1="Hello"; String str2=new String(" World"); System.out.println(str1+str2); String a="ok"; String b="ok"; String c=new String ("ok"); if(a==b) System.out.println("1"); else System.out.println("0"); if(a==c) System.out.println("1"); else System.out.println("0"); if(b==c) System.out.println("1"); else System.out.println("0"); if(a.equals(b)) System.out.println("1"); else System.out.println("0"); if(a.equals(c)) System.out.println("1"); else System.out.println("0"); if(b.equals(c)) System.out.println("1"); else System.out.println("0"); } }
如何解释?
不同的是,第一条先在内存中创建了"ok"这个String,然后将reference赋给a,下一条语句String b = "ok";那么JVM将不再创建"ok",而是直接将第一个"ok"的reference赋给b,也就是说,a和b是使用同一块内存,而String c = new String("ok");那JVM将在内存中再创建一块区域放上“ok”这个字符串。
时间: 2024-10-10 13:42:12