Java 基础笔记

一、Java中参数传递

Java中方法的参数传递实际上都是值传递,有别于C/C++;在使用对象传递时只能修改对象的属性。

例子1:

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Hello");
    System.out.println("传参前--->>对象地址: "+System.identityHashCode(sb)+", 值: "+sb);
    changeData(sb);
    System.out.println("传参后--->>对象地址: "+System.identityHashCode(sb)+", 值: "+sb);
}

private static void changeData(StringBuffer sb){
    sb.append(" Ok");
    sb = new StringBuffer("Hi ");
    sb.append("World");
    System.out.println("方法中--->>对象地址: "+System.identityHashCode(sb)+", 值: "+sb);
}

执行结果:

传参前--->>对象地址: 1163157884, 值: Hello
方法中--->>对象地址: 1956725890, 值: Hi World
传参后--->>对象地址: 1163157884, 值: Hello Ok

例子2:

public static void main(String[] args) {
     String str = "123456";
     System.out.println(str);
     changeData(str);
     System.out.println(str);
 }
 
 private static void changeData(String str){
     str = "9876";
     System.out.println(str);
 }

执行结果:

123456
9876
123456

例子3:

public static void main(String[] args) {
    User user = new User(1, "张三");
    System.out.println(user.toString());
    changeData(user);
    System.out.println(user.toString());
}

private static void changeData(User user){
   user.setId(2);
   user.setName("李四");
   user = new User(3, "小明");
   System.out.println(user.toString());
}

static class User{
    private int id;
    private String name;
    public User(int id, String name){
        this.id = id;
        this.name = name;
    }

    //get/set method...

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}  

执行结果:

User{id=1, name='张三'}
User{id=3, name='小明'}
User{id=2, name='李四'}

你可能感兴趣的:(Java 基础笔记)