10月31日java学习

Java数据类型扩展和面试题

数据类型扩展

整数扩展

进制:

  1. 二进制:0b开头

  2. 八进制:0

  3. 十六进制:0x开头


浮点数扩展

浮点数问题:

float f = 0.1f;//0.1
double d = 1.0/10;//0.1

System.out.println(f==d);//false

float d1 = 23131312312312313f;
float d2 = d1+1;

System.out.println(d1==d2);//true

flaot :浮点数是 有限位,且有舍入误差,所以会出现一系列问题。

避免使用浮点数进行比较

(银行业务用BigDecimal 数学类计算。)

字符扩展

强制转换:

char c1= 'a';
char c2= '中';
   System.out.println(c1);
   System.out.println((int)c1);

 

所有的字符本质还是数字

char的编码:Unicode编码表。(U0000-UFFFF).

 char c3 = '\u0061';
System.out.println(C3);

\u是转义字符。

String sa = new String(original:"hello world");
String sb = new String(original:"hello world");
System.out.println(sa==sb);//false

String sc = "hello word";
String sd = "hello word";
System.out.println(sc==sd);//true
//对象 从内存分析

类型转换

强制类型转换 高->低

int i = 128;
byte b = (byte)i;

 

(类型)变量名

自动类型转换 低->高

int i = 128;
double b = i;

注意点

  1. 不能对bool值进行转换!

  2. 不能把对象类型转换为不相干的类型。

  3. 在把高容量转换为低容量时,强制转换。

  4. 转换的时候或者会遇到内存溢出,或者精度问题!

     System.out.println((int)23.7);//23
    System.out.println((int)45.897f);//45
  5. 操作数较大的时候,注意溢出问题!

    int money = 10_0000_0000;
    int years = 20;
    int total = money*years//-1474836480,溢出
        System.out.println(total);  
    long total2 = money*years;//默认是int,转换之前已经计算溢出了。

    long total3 = money*((long)years);//先转换再计算。

     

    变量

    1. 每个变量都有类型,或是基本类型,或是引用类型

    2. 变量名必须是合法的标识符;

    3. 变量声明必须以分号结束。

    变量作用域

    1. 类变量(加static关键字)

    2. 实例变量(类中,但没有static)

    3. 局部变量(方法中)

image-20211031195716897

常量

 final 常量名 = 值;
final double PI = 3.14

常量名一般用大写字符

final为修饰符,不区分先后顺序

变量命名规范

变量:首字母小写和驼峰原则。

类名:首字母大写和驼峰原则。

运算符

有long结果类型为long,无long结果类型为int。

自增自减,初识math类

double pow = Math.pow(2,3);
System.out.println(pow);//8.0

 

很多运算都要使用工具类来操作

posted @ 2021-10-31 22:02  Violetjf  阅读(41)  评论(0)    收藏  举报