java基本类型和引用做形参传递

用一个列子来说明java基础类型和引用作为形参,是否会改变值

package com.cn.hnust.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Test {

    public static void main(String[] args) {

        User user = new User();
        user.setUsername("zhangsan");
        user.setPassword("123");
        int a = 0;
        changeUser(user);

        System.out.println(user);
        changeInt(a);
        System.out.println(a);

    }

    public static int changeInt(int i) {
        i = 5;
        return i;
    }

    public static User changeUser(User u) {
        u.setUsername("lisi");
        u.setPassword("456");
        return u;
    }

    static class User {
        private String username;

        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String toString() {
            return username + ":" + password;
        }
    }

}

运行结果:

lisi:456
0

很基础的东西,但还是有些人会混淆。记录一下。

posted @ 2016-12-08 11:21  ゞ清茶℡  阅读(512)  评论(0编辑  收藏  举报