-String属于引用数据类型,翻译为字符串。
class StringTest{
public static void main(String[] args){
String s1 = "hello world";
//String s1 = "a";
//String s1 = "";
//char c = '';编译不通过,可以放空格但是不能什么都不写
System.out.println(s1);
}
}
- 声明String类型变量时,使用一对" "。
- String可以和8中种基本数据类型变量做运算,且只能是连接运算:+.
class StringTest{
public static void main(String[] args){
int number = 1001;
String numberStr = "学号";
String info = numberStr + number;
//+:连接运算
System.out.println(info);
}
}
- 运算的结果仍然是String类型。
- 练习1:
class StringTest{
public static void main(String[] args) {
char c = 'a';//a 97;A 65
int num = 10;
String str = "hello";
System.out.println(c + num + str);
System.out.println(c + str + num);
System.out.println(c + (num + str));
System.out.println((c + num) + str);
System.out.println(str + num + c);
}
}
运行结果:
- 练习2:输出 * *
class StringTest{
public static void main(String[] args) {
System.out.println("* *");
System.out.println('*' + '\t' +'*');
System.out.println('*' + "\t" +'*');
System.out.println('*' + '\t' +"*");
System.out.println('*' + ('\t' +"*"));
}
}
- char对应的是一个ASCII码,char与char之间的加号就是加运算,结果是int类型;
- string字符串用“”;char字符用‘’;
- String的+是连接运算;