Java基本语法(变量分类、自动类型的提升运算、string类型的使用)

Java基本语法:变量的分类

一、数据类型
1、基本数据类型(primitive type):
数值型(整数类型(byte,short,int,long)、浮点类型(float,double))
字符型(char)
布尔型(boolean)
2、引用数据类型(reference type)
类(class) <----------------- 字符串在这里
接口(interface)
数组([array])

:byte(1字节=8bit位) short (2字节) int (4字节) long(8字节)
byte范围:-128~127
float(4字节) double(8字节)

二、变量在类中声明的位置:
成员变量 vs 局部变量

class VariableTest1{
	public static void main(String[] args){
	byte b1 =12;
	short s1 = 128;
	int i1 = 1234;
	//声明long型变量,必须以“l”或“L”结尾
	//通常,定义整型变量时,使用int型
	long l1 = 3434231L;
	double d1 = 32.3;
	// 定义float类型变量时,变量要以“f”或“F”结尾
	float f1 = 12.3F;
	System.out.println(f1)
	//定义char型变量,通常使用一对''
	char c1 = 'a';
	//布尔型:boolean,只能取两个值之一:true \ false
	//与c语言不一样,c语言一般用0或1表示,常在条件判断,循环条件中使用
	boolean bbl = ture;
}

自动类型提升运算:

前提:讨论7种基本数据类型变量间得到运算,不包含boolean类型。

1、自动类型提升
当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型
byte–> short–>int–>long–>float–>double
特别的:当byte、char、short三种类型的变量做运算时,结果为int型

2、强制类型转换 (自动类型提升运算的逆运算)
1、需要使用强转符:()
2、注意点:强制类型转换可能导致精度损失

说明:此时的容量大小指的是,表示数的范围的大和小。比如:float容量要大于long的容量

class VariableTest2{
	public static void main(String[] args){
		byte b1 = 2;
		int i1 = 129;
		//编译不通过
		//byte b2 = b1 + i1;
		int i2 = b1 + i1;
		long l1 = b1 + i1;
		System.out.println(i2);
	float f = b1 + i1;
	System.out.println(f);

	short s1 = 123;
	double d1 = s1;
	System.out.println(d1);

	char c1 = 'a';//97
	int i3 = 10;
	int i4 = c1 + i3;
	System.out.println(i4);//107

class VariableTest3{
	public static void main(String[] args){
		double d1 = 12.3;
		int i1 = (int)d1; //截断操作
		System.out.println(i1); //12

		//没有精度损失
		long l1 =123;
		short s2 = (short)l1;

		//精度损失
		int i2 = 128;
		byte b = (byte)i2;
		System.out.println(b)//-128
		}
	}
 }

String类型的使用

1、string属于引用数据类型,翻译为:字符串
2、声明String类型变量时,使用一对“ ”
3、string可以和八种基本数据类型变量做运算,且运算只能是连接运算:+
4、运算的结果任然是String类型

class StringTest{
	public static void main(string[] args){
	String s1 = "Hello World";
	String s2 = "a";
	String s3 = " ";
	Systemm.out.println(s1);
	//char c = ''; //编译不通过

    int number = 1001;
    String numberStr = "学号"String info = numberStr + number; // + (连接运算)
    System.out.println(info);  //学号: 1001
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值