字符串初窥
在之前的所有数据类型,都是表示一些基本的类型,但是如果现在要是想表示一串的字符,则就是只能使用字符串进行表示,String表示一个字符串,但是String的开头首字母大写了,所以这是一个类,但是这个类使用起来较为特殊,可以按照基本数据类型的操作那样直接使用。
public class TestDemo01
{
public static void main(String args[])
{
String str = "世界啊,你好吗?我很好!!!";
System.out.println(str);
}
}
但是,在使用String的时候有一点必须注意的:
默认情况下各个基本数据类型间是可以进行转型操作的:byte-->short-->int-->long-->float-->double.但是所有的类型只要是碰到了String,则都会向String转换。
范例:观察基本类型的转型操作
public class TestDemo02
{
public static void main(String args[])
{
int x = 10;
float y = 300.3f;
System.out.println(y/x);
}
}
范例:下面使用String操作
public class TestDemo03
{
public static void main(String args[])
{
int x = 10;
int y = 20;
String str = "x" + "+" + "y" + "="; //此时的"+"表示字符串连接
System.out.println(str+x+y);
}
}
现在的结果是1020,并不是一个正确的结果,因为所有的数字首先都变成了字符串,实际上此处就属于字符串的连接操作。如果要想解决以上的问题,则就需要加上"( )",要求,先进行计算。
public class TestDemo04
{
public static void main(String args[])
{
int x = 10;
int y = 20;
String str = "x" + "+" + "y" + "="; //此时的"+"表示字符串连接
System.out.println(str+(x+y));
}
}