Java基本数据类型和引用数据类型中形参问题

/*
    方法的形式参数问题:
		1)基本数据类型特点
            形式参数的改变不会影响实际参数!
        2)引用数据类型特点:
		    String类型:特殊的引用类型:它作为形式参数,效果和基本数据类型一致!
		    形式参数的改变不影响实际参数(String本质就是常量)
	        如果形式参数是数组类型(除String类型外),
		    实际参数传递:传递数组对象 :形式参数的改变会直接影响实际参数
*/
class Demo{
	public static void main(String[] args){
		//定义了两个变量
		int a = 10 ;
		int b = 20 ;
		System.out.println("a:"+a+",b:"+b) ; //a:10,b:20
		change(a,b) ;//10,20
		System.out.println("a:"+a+",b:"+b) ;//10,20
		System.out.println("---------------------------");
		String str = "hello" ;
		System.out.println("str:"+str) ; //"hello"
		change(str) ;
		System.out.println("str:"+str) ;//"hello"
		System.out.println("---------------------------");
		//创建一个数组,静态初始化
		int[] arr = {1,2,3,4,5} ; //int[] arr = new  int[]{1,2,2,3,4,5} ;
		System.out.println(arr[1]) ;
		//重载的change方法
		change(arr) ;
		System.out.println(arr[1]) ;
	}
	//执行change方法
	public static void change(int[] arr){
            //形式参数是引用类型:数组 (实际参数传递:传递的空间地址值)
			//遍历arr数组
			for(int x = 0 ; x < arr.length ; x ++){
				if(arr[x] %2 == 0){
					arr[x] *= 2 ;
				}
			}
	}
	//String类型作为形式参数传递(特殊的引用类型)
	public static void change(String str){ //hello
		System.out.println("str:"+str) ; //"hello"
		str+="javaEE" ;//str = "hello"+"javaEE" ;
		System.out.println("str:"+str) ; //"hellojavaEE"
	}
	public static void change(int a,int b){//形式参数是基本数据类型  10,20
		System.out.println("a:"+a+",b:"+b) ;//a:10,b:20
		a = b ; 
		b = a+ b; 
		System.out.println("a:"+a+",b:"+b) ;
	}
}
(引用,方法参数传递)有以下代码
例子1:
class ClassA{
	int value;
}
public class TestClassA{
	public static void main(String args[]){
	int value = 10;
	changeInt(value);
	System.out.println(value);//10
	ClassA ca = new ClassA();
	ca.value = 10;
	changeObject(ca);
	System.out.println(ca.value);//11
	}
		public static void changeInt(int value){
			value++;	
		}
		public static void changeObject(ClassA ca){
			ca.value++;
		} 
}

//输出 10 11
例子2:
class XingCan
{
    String name;

}
public class XingCanTest {
    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student);//com.test.day08.Student@4554617c
    }
}
//总结:对象中的形式参数传递的是地址值,形参改变会直接影响实际参数

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值