Java SE入门及基础(25)

目录

方法带参(续第24篇)

6.方法参数传递规则

方法传参来自官方的说明

基本数据类型传值案例

基本数据类型传值时传递的是值的拷贝

引用数据类型传值案例

引用数据类型传值时传递的是对象在堆内存上的空间地址

[Java SE文章参考:Java SE入门及基础知识合集-CSDN博客](#Java SE文章参考:Java SE入门及基础知识合集-CSDN博客)

方法带参(续第24篇)

**6.**方法参数传递规则

方法传参来自官方的说明

Primitive arguments, such as an int or a double, are passed into methods by
value. This means that any changes to the values of the parameters exist only
within the scope of the method. When the method returns, the parameters are
gone and any changes to them are lost.
基本数据类型的参数(例如 int 或 double )按值传递给方法。 这意味着对参数值的任何更改仅存在于方法范围内。 当方法返回时,参数消失,对它们的任何更改都将丢失。
Reference data type parameters, such as objects, are also passed into methods
by value. This means that when the method returns, the passed-in reference
still references the same object as before. However, the values of the
object's fields can be changed in the method, if they have the proper access
level.
引用数据类型参数(例如对象)也按值传递到方法中。 这意味着当方法返回时,传入的引用仍然引用与以前相同的对象。 但是,如果对象的字段的值具有适当的访问级别,则可以在方法中更改它们。

基本数据类型传值案例

public class PassingPrimitive {
public static void main ( String [] args ) {
int a = 10 ;
change ( a ); // 调用方法时,实际上传递的是变量 a 的值的拷贝
System . out . println ( a );
}
public static void change ( int number ) {
number ++ ;
}
}

基本数据类型传值时传递的是值的拷贝

引用数据类型传值案例

public class ComputerTest {
public static void main ( String [] args ) {
Computer c1 = new Computer ();
c1 . brand = " 联想 " ;
c1 . type = "T430" ;
c1 . price = 5000 ;
Computer c2 = new Computer ();
c2 . brand = " 联想 " ;
c2 . type = "W530" ;
c2 . price = 6000 ;
Computer c3 = new Computer ();
c3 . brand = " 联想 " ;
c3 . type = "T450" ;
c3 . price = 7000 ;
//这里传递的参数就是实际参数
Computer c4 = new Computer ( " 联想 " , "T430" , 5000 );
updateComputer ( c4 );
System . out . println ( c4 . price );
Computer c5 = new Computer ( " 联想 " , "W530" , 6000 );
Computer c6 = new Computer ( " 联想 " , "T450" , 7000 );
}
public static void updateComputer ( Computer computer ){
computer . price = 10000 ;
}
}

引用数据类型传值时传递的是对象在堆内存上的空间地址

Java SE文章参考:Java SE入门及基础知识合集-CSDN博客

相关推荐
gadiaola22 分钟前
【JVM】Java虚拟机(二)——垃圾回收
java·jvm
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan3 小时前
c++ 单例模式
开发语言·c++·单例模式
coderSong25683 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy4 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之4 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头5 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#