网易云课堂 - JAVA语言 学习笔记(第七周)

第七周:函数

7-1函数定义与调用

视频1

视频2

step return 直接从函数中出来。

7-2参数传递与本地变量

视频1,参数传递

形参与实参。

在参数传递过程中,字符串与数组是引用传递,不是值传递。 下面是详解。

Java中的String为什么是不可变的? -- String源码分析

在讨论区中,有一个:

1。数组作为参数

public static void test(int[] b)
	{
		b[0]=10;
	}
	public static void main(String[] args) {
        int a[]={1,2,3,4,5,6};
        test(a);
        for(int i=0;i<a.length;i++)
        {
        	System.out.println(a[i]);
        }
	}
}

输出
10
2
3
4
5
6

结论:数组作为参数,不是值传递,而是引用



2。字符串作为参数

测试1:

public class Main {
	public static void test(String b)
	{
		b="world";
	}
	public static void main(String[] args) {
        String a="hello";
        test(a);
        System.out.println(a);
	}
}
输出

hello

结论:表面看起来,字符串作为参数,是值传递,但是由于字符串是不可变的,所以这个例子不能说明问题





测试2:

public class Main {
	public static String test(String b)
	{
		return b;
	}
	public static void main(String[] args) {
        String a="hello";
        String b=test(a);
        System.out.println(a==b);
	}
}

输出

true

结论:a和b都管理同一个字符串,所以字符串作为参数,是引用传递

我的理解:字符串作为参数的test1中,实际上开始的时候确实b指向了a的hello,但是b='world'的时候,不是改变指向的内容,因为字符串不可变;而是又创建了一个字符串对象'world',b变量现在不去指向hello了,去指向world了。因此,在函数返回的打印的时候,a变量的对象依旧是hello。

视频2,本地变量

进阶中,会详细讲解递归。

注意:

  1. 在同一个大括号中,变量不可以重复定义。
  2. 在外面定义一个变量,不可以在里面括号里定义一个同名的变量。

在进阶课讲解对象,会提到,类得成员变量在构造对象时,会得到默认初始化值。

下面几个注意点:

1.

public static void f(int i, j)
{
    System.out.println(i+j);
}//不可被编译。

必须是  (int i, int j)  

2.

String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); //结果是true, 在debug时,s1 与 s2 指向对象的 id 相同

String s3 = new String("hello1");
String s4 = new String("hello1");
System.out.println(s3 == s4); //结果是false

3.

String对象的,长度是 .length() 是方法。

数组对象的长度是 .length 是属性。

4.

System.out.println("A"+6+2); //输出 A62
System.out.println('A'+6+2); //输出73   (65+6+2)

猜你喜欢

转载自blog.csdn.net/Raina_qing/article/details/83537841