JAVA笔记3__字符串String类/对象一对一关联
import java.lang.String; import java.util.Scanner; public class Main { public static void main(String[] args) { //方式一:会创建两个字符串对象(会在字符串常量池中也存一份) String a = new String("dining1"); //【尽量使用这种方式】方式二:最多创建一个字符串对象。(在字符串常量池中找有没有,有则直接指过去,否则创建,然后指过去。) String a1 = "dining2"; System.out.println(a+" "+a1); //case 1: String b = "b1"; String b1 = "b"+1; System.out.println(b==b1); //b和b1在编译期间就已确定,都指向常量池的同一块地方 //case 2: String c = "c1"; int t1 = 1; String c1 = "c"+t1; System.out.println(c==c1); //c1在运行期才确定 //case 3: String d = "d1"; final int t2 = 1; String d1 = "d"+t2; System.out.println(d==d1); //t2在编译期就已确定 //case 4: String e = "e1"; final int t3 = getE(); String e1 = "e"+t3; System.out.println(e==e1); //t3在运行期才确定 } public static int getE(){ return 1; } }
import java.lang.String; import java.util.Scanner; public class Main { //更多String类的属性和方法查Java手册 public static void main(String[] args) { String s = "abcdefg"; char c = s.charAt(s.length()-1); System.out.println(c); //把字符串转换成字符数组 char [] cs = s.toCharArray(); System.out.println(cs.length); for(int i=0;i<cs.length;++i) System.out.print(cs[i]+" "); System.out.println(); byte[] bytes = s.getBytes(); //字节数组 System.out.println(bytes.length); for(int i=0;i<bytes.length;++i) System.out.print(bytes[i]+" "); System.out.println(); String ss = "我是一棵白菜"; String ke1 = ss.substring(1,3); //[1,3) System.out.println(ke1); //....... } }
/** * 对象的一对一关系 */ public class Main { public static void main(String[] args) { Husband h = new Husband("fish7"); Wife w = new Wife("dining"); h.wife = w; w.husband = h; System.out.println("I'm "+h.name+". My wife is "+h.wife.name); System.out.println("I'm "+w.name+". My husband is "+w.husband.name); } } class Husband{ String name; Wife wife; //关联妻子类 public Husband(){}; public Husband(String name) { this.name = name; } } class Wife{ String name; Husband husband; //关联丈夫类 public Wife(){}; public Wife(String name) { this.name = name; } }