Java中初学者比较爱出错的运算问题

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

其实我开始也是在运算上老爱出错,今天专门把他总结出来,大家可以先不要看答案,自己想想看,应该得到什么样的结果,然后再看看答案,就知道自己错在那里了,希望对大家的学习有所帮助!

public class test

{

public void go()

{

int i=2, j=10;

byte x=2,y=10;

System.out.println((++i)*(j--));//1

System.out.println("i="+i+"j="+j);//2

System.out.println(9/2);//3

System.out.println(5/10);//4

System.out.println(5/10.0);//5

System.out.println(x+y);//6

System.out.println("hello"+2+3);//7

System.out.println(2+3+"hello");//8

System.out.println("hello"=="hello");//9

System.out.println(new String("hello")==new String("hello"));//10

System.out.println(new String("hello").equals(new String("hello")));// 11

class interTest

{

String s="hello";

}

interTest it1=new interTest();

interTest it2=new interTest();

it1.s="hello";

it1.s=it2.s;

System.out.println(it1.equals(it2));//12

}

public static void main(String args[])

{

test t=new test();

t.go();

}

}

答案:

30 当一元运算符在操作数的前面时,是先进行自加,然后在进行运算,而当运算符在操作数的后面是,是先运算后自加,然后自加的数值参加下次运算。和for循环有点类似

1=3,j=9 同上

4 因为9和2全是int类型,所以结果也是int类型,只保留一个整数位4

0 同理

0.5 一个是int,一个是double,结果也就是double

int 20 虽然2个操作数全是byte,但是结果是int

hello23 前面的操作数为字符串,则系统自动将后续的操作数自动转换为字符串

5hello 如果前面的操作数不是字符串,则运算结果由后续操作数决定

true 这2个操作数其实是一个对象

false 这2个对象的值是一样的,但他们是2个不一样的对象

true 使用equals比较的是2个对象的值;

false 并不是所有类的equals()方法都是比较对象内容一样的,string类的equals方法是经过重载(overload)的。而类intertest的方法是从object类继承的,其功能还是比较2个操作数是否是同一对象

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航