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

Java基础学习易错点记录

2017-03-25 16:20 281 查看
测试错误记录:

public class Test {
int x = 30;

public static void main(String args[]) {
int x = 20;
Test ta = new Test();
ta.Method(x);
System.out.println("The x value is" + x);
}

void Method(int y) {
int x = y * y;
}
}


输出值为30,ta.method()并没有改变ta.x的值,只是改变了method里的局部变量x的值;

class Test {
public int i = 10;
}

public class ObParm {
public static void main(String args[]) {
ObParm o = new ObParm();
o.amethod();
}

public void amethod() {
int i = 99;
Test v = new Test();
v.i = 30;
another(v, i);
System.out.println(v.i);
}

public void another(Test v, int i) {
i = 0;
v.i = 20;
Test vh = new Test();
v = vh;
System.out.println(v.i + "," + i);
}
}


输出值为10,0,20;

原因:o.method中定义局部变量i=99,新建Test类的对象v,并更改v.i=30;调用another,传入对象v的引用地址,和i=99;更改i=0,传入地址下的对象v.i=20;新建Test类对象vh,并将v(局部变量)引向vh的地址,输出v.i=10,i=0;返回amethod方法,此处v仍指向原引用地址,输出v.i即20;

public class Test {
public static void main(String args[]) {
System.out.println(args[2]);
}
}


在命令行中输入java Test hello world结果是()?

产生异常:java.lang.ArrayIndexOutOfBoundsException: 2

public class Person {
String name = "Jim";
int age = 21;

public String toString() {
String str = "name:" + name + ",age:" + age;
return str;
}

public static void main(String[] args) {
Person p = new Person();
System.out.println(p);
System.out.println(p.toString());
}
}


输出   name:Jim,age:21 name:Jim,age:21

回顾println()输出函数的定义。

println

public void println(Object x)

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes
print(String)

and then
println()
.
Parameters:
x
- The
Object
to be printed.
int output=10;
boolean b1=false;
if((b1= =true)&&((output+=10)==20)){
System.out.println(“we are equal”+output);
}
else{
System.out.println(“not equal!”+output);
}
 编译并且输出 “not equal! 10”if判断的是短路与,前者为假不再执行后者判断。

public static int getValue(int i) {
int result = 0;
switch (i) {
case 1: result = result + i;
case 2: result = result + i * 2;
case 3: result = result + i * 3;
}
return result;
}


上述方法,当输入为2的时候返回值是(10)。注意case后没有break;

ArrayList list = new ArrayList(20);中的list扩充几次()?

0次,ArrayList在未指明初始大小的情况下默认初始大小为10,并且每次扩充1.5倍;而上述定义指定了初始大小,故不需扩充。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: