数据类型 与 运算符

1.标识符

  • 作用:给变量,类和方法命名
  • 规则:

  1>以字母、下划线(“_”)、美元符号(“$”)开头
  2>其他部分由字母、下划线、美元符号、数字的任意组合
   3>对大小写敏感,无长度限制但不可用关键字作为标识符

✦Java关键字

byte short int long boolean
char float double if else
do while switch break default
goto case for return try
abstract continue enum new assert
package synchronized private this implements
protected throw throws import public
static void instanceof transient catch
extends final finally interface class
strictfp volatile const native super

注:命名时为了增强程序的可读性,基本不单独使用下划线(_)来命名,且有的公司声明不可用美元符号($)来命名。

2、数据类型

在这里插入图片描述

  • 基本数据类型
数据类型 包装类 默认值 占用存储空间 范围
整型 byte Byte 0 1字节 -128~127
整型 short Short 0 2byte - 2^15 ~ 2^15 - 1
整型 int Integer 0 4byte - 2^31 ~ 2^31 - 1
整型 long Long 0L 8byte - 2^63 ~ 2^63 - 1
浮点型 float Float 0.0f 4byte -3.403E38~3.403E38
浮点型 double Double 0.0d 8byte -10798E308~1.198E308
字符型 char Character \u0000 2byte \u0000~\uffff
布尔型 boolean Boolean false ture/false
  • 引用数据类型
数据类型 说明
类 类型

1>Java类库中定义的类(eg:Object、String、Date)和用户定义的类

2>Java类库中定义的枚举(enum)和用户定义的枚举

接口 类型

1>Java类库中定义的接口和用户定义的接口

2>Java类库中定义的注解和用户定义的注解

数组 类型 一维和多维数组
null 类型 null 类型为空引用类型,使用 null 常量来表示
  • 类型转换

  - 小类型转化为大类型自动转换
  - 大类型转化为小类型需要强制转换
特例:在不超过其表数范围的情况下,可以将整型常量直接赋值给byte、short、char 等类型变量,不需要进行强制转换


short b = 5;//合法
short c = 1234567;//非法

1>自动类型转换(隐式转换)
注意:隐式转换可能会降低精度,eg:从 long 到 float 的转换

在这里插入图片描述
注:白色箭头表示可能会降低精度

转 换 源 转 换 目 标
byte short、int、long、float、double
short int、long、float、double
int long、float、double
long float、double
char int、long、float、double
float double

注:不存在到 char 类型的隐式转换

  • 如果整型常量超过变量范围,则会产生编译错误。例如:

byte b11 = 123;//整型常量 123 从 int 到 byte 的自动转换
short s1 = 123;//整型常量 123 从 int 到 short 的自动转换
long long1 = 123;//整型常量 123 从 int 到 long 的自动转换
float f1 = 123;//整型常量 123 从 int 到 float 的自动转换
double d1 = 123;//整型常量 123 从 int 到 double 的自动转换
byte b22 =255;//编译错误,byte 的取值范围为 -128~127

2>强制类型转换(显示转换)
注:显示转换可能会导致精度损失,也可能由于溢出而导致转换结果不正确


byte b1 = (byte)12.3;//结果:12,精度损失
byte b2 = (byte)128;//结果:-128,由于溢出从而导致转换结果不正确

转 换 源 转换目标
short byte、char
int byte、short、char
long byte、short、char、int
float byte、short、char、int、long
double byte、short、char、int、long
char byte、short

3、优先级顺序

优先级 运算符 简介 结合性
1 [ ]、. 、() 方法调用,属性获取 从左向右
2 !、~、++、– 一元运算符 从右向左
3 *、/、% 乘、除、取模(余数) 从左向右
4 +、- 加减法 从左向右
5 <<、>>、>>> 左位移、右位移、无符号右移 从左向右
6 <、<=、>、>= 小于、小于等于、大于、大于等于 从左向右
7 ==、!= 判断两个值是否相等、判断两个是是否不等 从左向右
8 & 按位与 从左向右
9 ^ 按位异或 从左向右
10 按位或 从左向右
11 && 短路与 从左向右
12 丨丨 短路或 从左向右
13 ?: 条件运算符 从右向左
14 =、+=、-=、/=、%=、&=、丨=、^=、<、<=、>、>=、>>= 混合赋值运算符 从右向左

猜你喜欢

转载自blog.csdn.net/WeiBlogProcedure/article/details/83856801
今日推荐