Java数据类型与运算符

Java数据类型

变量在类中的位置

1.成员变量

2.局部变量

类型 占用空间 表数范围

byte 1字节=8bit -128~127 char 2个字节

short 2字节 -1215~1215-1 float 4个字节

int 4字节 -1231~1231-1 double 8个字节

long 8字节 -1265~1265-1

声明long型变量,必须以“l”或“L”结尾 通常使用变量定义为int型

声明float型变量,必须以“f”或“F”结尾 通常使用变量定义为double型

char:声明一个字符或者转义字符 boolean型 只能取两个值,ture 和false

数据类型之间的运算(不包括boolean型)

1.自动提升

容量小的跟容量大的做运算,自动提升为容量大的(容量大小指的是表示数的范围的大小)

byte —→short—→int—→long —→float—→ double

2.强制转换

Java中允许数值之间进行转换,有可能会丢失一些信息。

double x=9.997;
int nx=(int)x;

如果要进行舍入运算,需要用到Math.round()方法。以便得到最接近的整数。

int n=(int)Math.round(x);//返回的最接近的整数long类型需要使用int强制转换

运算符

1.算数运算符

%是取模(求余数) /运算的时候当操作数都是整数,结果也是整数。否则为浮点除法。

例如:3/2=1 ;3.0/2.0=1.5

2.数学函数与常量

幂运算

Math.pow(x,a); 表示为x的a次方

三角函数

Math.sin Math.cos Math.tan Math.atan Math.atan2

指数函数及反函数

Math.exp Math.log Math.log10

Π与e常量近似值

Math.PI Math.E

3.关系和boolean运算符

三元操作符

condition?expression1:expression2

如果condition为ture,则为expression1值,否则为expression2

3.位运算符

1.按位与运算&

System.out.println(1&9);//00001&01001=00001
//out:1

2.按位或运算|

System.out.println(1|9);//00001|01001=01001
//out:9

3.按位异或运算^

System.out.println(1^9);//00001^01001=01000

4.按位求反~

System.out.println(~9);//~01001=10110(原码)=11001(补码)=-10

计算机里的数都是以补码出现,因为CPU只能做加法,不能做减法

5.左移运算<<

System.out.println(1<<3);//1<<3=00001左移三位低位补0=01000=8

位数向左移动,低位补0

6.右移运算>>或>>>

用符号位填充高位,>>>用0填充高位

原文地址:https://www.cnblogs.com/cwstd/p/13939042.html