您的位置:首页 > 编程语言 > Java开发

java思想- - ->控制程序流程

2009-06-19 10:23 375 查看
java用运算符(operator)来控制程序。

使用java运算符

+,-,*,/,=

几乎所有的运算符都是作用于primitive数据,==,=,!= 是例外,它们可以作用于任何对象。

优先级

先乘除后加减,有括号的先算括号里面的。

x= x + y - x/z + k

x= x + (y-z)/(z+k)

赋值

a = 4; this is right 4 = a ; this is wrong .

primitive持有的是实实在在的数值,不是指向内存的reference。

a = b,如果改变a 的数值,b的数值是不发生变化的。

对象之间的赋值是在用他们的reference。

c = d,那么c ,d 现在都指向d原来的reference。

example:

public class Test{

int i = 0; int ii = 0;

public void static main(String args[]){

Test test1 = new Test();

Test test2 = new Test();

test1.i = 2;

test2.i = 3;

test1.ii = 4;

test2.ii = 5;

test1 = test2;

system.out.println(test1.i + " " + test2.i );

// both the value of them are 3;

System.out.println(test1.ii + " " + test2.ii);

// both the value of them are 5

}

public void static main(String args[]){

Test test1 = new Test();

Test test2 = new Test();

test1.i = 2;

test2.i = 3;

test1.ii = 4;

test2.ii = 5;

test1.i = test2.i;

system.out.println(test1.i + " " + test2.i );

// both the value of them are 3;

System.out.println(test1.ii + " " + test2.ii);

//test1.ii is 4 and test2.ii is 5

}

}

数学运算符

%:是取余数的。

'/'不是四舍五入的,他会把小数都舍去的。example:26/7 = 3 ,!=4

x +=4; x = x + 4;

随机生成数:Random random = new Random();

单元加号和减号的运算符

a = -b; c = a * -b;

自动递增和递减

a++ : 先给a++ = a赋值,然后在a = a+ 1;

++a : 先 a = a + 1,然后在 a++ = a;

a-- :先给a-- = a,然后在a = a-1;

--a : 先 a = a -1 ,然后在a-- = a;

关系运算符:

> ,< , >= ,<= , == , !=

==:比较的是对象的reference

equeals();比较的是对象的内容,不是reference。

逻辑运算符:

&&,||,!

逻辑运算符中短接的问题

example:

boolean a ,b ,c;

if(a||b||c){

// if one of them is true , the condition is true all the time .

}

位运算符:

&:两个都是1返回1

|:有一个1就返回1

~:1返回0,0返回1

^:有且只有一个1,返回1

&=,|=,^= 运算并且赋值。

boolean isfor ^=true;

isfor = isfor^true;

位运算对boolean类型也是适用的:

example:

true^true : false

true^false: true

false^false : false

true|true :true

true|false :true

false|false:false

true&true : true

true &false: false

false&false: false

三元运算符:

boolean—expression ? value1 : value2

逗号运算符的使用:

for(int i=1,j=i+10;i<5;i++,j=i*2) {}

加号运算符:

public void print(){

int a = 2;

int b = 3;

int c = 4;

String s = "ricky" + a + b + c;

//a b c的值不会相加的,编译器会把它们都转换成字符串。连接起来。

}

类型转换运算符:

cast:自动转换,强制转换。

自动转换使用于:小类型--》大类型

int i = 9;

long lg = i;

强制转换:大类型---》小类型 会存在数据丢失的情况

long lg = 232;

int i = (int)lg;

java允许除了boolean意外的primitive类型数据进行转换;

其他任何对象只能在他们的类系里进行转换,

(String类型是个特例)

常量

十六进制:0x开头

八进制:0开头

二进制:由0,1组成。

数字后面:

l/L :long

d/D :double

f/F : float

java中所有的类型占用的空间,在所有的平台上都是相同的。

运算符的优先级别:

单元运算符( + ,- ,++,--)

算数运算符(*,/,%,+,-,<<,>>)

关系运算符(>,<,<=,>=,!=)

关系运算符(&&,||,&,|,^)

条件运算符:a>b ? false: true;

赋值运算符:=,*=
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: