美文网首页
习题改正

习题改正

作者: 牛倩贱 | 来源:发表于2018-12-17 23:53 被阅读0次

    public class ClassTest01 {

    String str = new String ("hello");

    char[] ch = {'a','b','c'};

    public static void fun (String str, char ch[]) {

    str = "world";

    ch[0] = 'd';

    }

    public static void main(String[] args) {

    ClassTest01 test1 = new ClassTest01();

    test1.fun(test1.str, test1.ch);

    System.out.println(test1.str+"and");

    System.out.println(test1.ch);

    }

    }

    输出结果是(a)

    a.hello  and  dbc

    b.world and abc

    c.hello  and  abc

    d.world and dbc

    解释:因为java中的传递都是值传递,即就是你可以通过方法来改变被引用的对象中的属性值,却无法改变这个对象引用本身,在值传递的时候方法中的str也指向了“hello”,方法外的str也指向了“hello”,但在方法中执行了str=“world”这条语句,实际上不是吧hello改为world,而是又创建了一个str,所以当调用Test1.str的时候,是调用了方法外的str,所以便输出了hello而不是world,但是在执行ch[0] = 'd'时char[ ] ch = {'a','b','c'}是数组,数组存放在堆中,所以当方法通过形参修改值时会去堆中修改,当成员变量ch再去访问时,堆中的值已经修改,所以输出dbc。

    习题改正

    java的栈,堆,常量池和方法区。

    栈:存放引用

    堆:存放new对象和数组

    常量池:存放常量

    方法区---方法中的局部变量:存放在方法运行时临时建立的方法栈中,其随着栈的销毁而结束

    2.public class Test02 {

    public int add(int a,int b){

    try{

    return a+b;

    }

    catch (Exception e){

    System.out.println("catch语句块");

    }

    finally{

    System.out.println("finally语句块");

    }

    return 0;

    }

    public static void main(String[] args) {

    Test02 test = new Test02();

    System.out.println("和是:"+test.add(9, 34));

    }

    }

    a.catch语句块 和是:43

    b.编译异常

    c.finally语句块 和是:43

    d.和是:43 finally语句块

    结果(c)

    解释:

    finally{}代码块比return先执行。

    多个return是按顺序执行的的,多个return执行了一个后,后面的return就不会执行了。

    不管有没有异常抛出, finally都会在return返回前执行。

    疑问:为什么把return放在finally里面,结果就变成了finally语句块 和是0?

    答:因为finally比其他的先执行,所以后面的return就会被先执行,导致前面的return不在执行

    相关文章

      网友评论

          本文标题:习题改正

          本文链接:https://www.haomeiwen.com/subject/vgiihqtx.html