标识符
类名,变量名和方法名
以大小写字母,¥,_ 开始,组成可用数字
关键字不能被当做名字
不建议拼音或者汉字开头,low
数据类型
java是强类型语言,变量的使用严格符合规定,先定义再使用。
分类:
- 基本类型:
- 整数类型:byte 1B,short 2B,int 4B,long 8B(long变量后面加L:long num=10L;)
根据所占位数确定取值范围,一位符号位,剩下位数真值。 - 浮点类型:float 4B(float变量后面加F:fioat num=10.2F;),double 8B。浮点数不精确有误差,最好避免浮点数比较。
- 字符类型:char 2B(char后面只能定义一个字/字符)
- bool类型:1bit,只有true和false两种(boolean flag = true)
结合组原理解更深入
- 整数类型:byte 1B,short 2B,int 4B,long 8B(long变量后面加L:long num=10L;)
- 引用类型:
- 类
- 接口
- 数组
具体实践:
public class Demo01{
public static void main(String args[]){
//整数拓展:进制 二进制0b 八进制0 十进制 十六进制0x
int i = 10;//十进制
int j = 010;//八进制
int k= 0x10;//十六进制
System.out.println(i);
System.out.println(j);
System.out.println(k);
//================================================
//浮点数,小数
//银行,BigDecial 数学工具类,用这个比较
//float 有限离散接近,不准确有误差,不用浮点数比较
float f=0.1f;//0.1
double d=1/10;//0.1
System.out.println(f==d);//falsse
float d1=456787654678976567f;
double d2=d1+1;
System.out.println(d1==d2);//true
//================================================
//字符
char c1='a';
char c2='中';
System.out.println(c1);
System.out.println(c2);
System.out.println((int)c1);//强制类型转换
System.out.println((int)c2);//强制类型转换
//unicode 97=a, 56=A;
char c3='\u0061';//16进制表示,十进制97
System.out.println(c3);
//================================================
//bool值
boolean flag = true;
if(flag){}
if(flag==true){}//与上一行代码等价
//================================================
//对象,内存空间
String sa="hello world";
String sb="hello world";
System.out.println(sa==sb);//true
//new分配内存 比较地址
String sc=new String("hello world");
String sd=new String("hello world");
System.out.println(sc==sd);//false
//比较内存中常量池
}
}
类型转换
不同类型数据转化为同一类型后运算
由低到高:byte,short,char -->int -->long -->float -->double
- 强制类型转换:由高到低。(类型)变量名
- 自动类型转换:由低到高
注意:
- 不能对bool值进行转换
- 不能把对象类型转换为不相干的类型
- 在把高容量转换到低容量的时候,强制转换
- 可能存在内存溢出和精度问题
public class Demo02 {
public static void main(String[] args) {
int i=128;
byte b=(byte)i; //强制类型转换
System.out.println(b);
double c=i; //自动类型转换
System.out.println(c);
int money=10_0000_0000;//数字之间可以用下划线分割
int years=20;
int total1 =money*years;//-1474836480;计算溢出
long total2 =money*years;// -1474836480 默认 int,转换之前已经存在问题了
long total3 =money*((long)years);//20000000000
System.out.println(total1);
System.out.println(total2);
System.out.println(total3);
}
}