指出下列程序的运行结果: public class Example{ String str = new String(“good”); char[] ch = {‘a’,’b’,’c’}; public static void main(String[] args){ Example ex= new Example(); ex.change(ex.str,ex.ch); System.out.print(ex.str += ” and ”); System.out.print(ex.ch); } public void change(String str,char ch[]){ str = “test ok”; ch[0] = ‘g’; } } A. good and abc B. good and gbc C. test ok and abc D. test ok and gbc
时间: 2024-04-25 11:26:42 浏览: 11
选项 B. good and gbc 是该程序的运行结果。
在该程序中,创建了一个 Example 类的对象 ex,并调用了 change 方法。在 change 方法中,虽然修改了 ch 数组中的第一个元素,但是修改 str 的语句只是将 str 参数指向了一个新的字符串对象,并不会改变 ex.str 的值。
因此,在主方法中,ex.str 的值仍然是 "good",但是 ex.ch 数组的第一个元素已经被改变为 'g',因此输出的结果为 "good and gbc"。
相关问题
public class Example{ String str=new String("good"); char[]ch={'a','b','c'}; public static void main(String args[]){ Example ex=new Example(); ex.change(ex.str,ex.ch); System.out.print(ex.str+" and "); Sytem.out.print(ex.ch); } public void change(String str,char ch[]){ str="test ok"; ch[0]='g'; } }
您提供的代码存在以下问题:
1. 第10行的 `Sytem.out.print` 应该为 `System.out.print`,即拼写错误。
2. 第16行的 `str="test ok"` 和第17行的 `ch[0]='g'`,虽然在方法内部执行了,但是并没有对 `Example` 类的成员变量 `str` 和 `ch` 进行修改。这是因为 Java 采用的是按值传递,即传递的是对象的引用值,而不是对象本身。因此,在方法内部修改参数的值,并不会影响到原对象的值。
以下是修改后的代码:
```
public class Example {
String str = new String("good");
char[] ch = {'a', 'b', 'c'};
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
}
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'g';
}
}
```
输出结果为:
```
good and gbc
```
可以看到,虽然在方法内部修改了参数的值,但是并没有影响到原对象的值。
public class Example{ String str=new String("good"); char []ch={‘a’,’b’,’c’}; public static void main(String args[]){ Example ex=new Example(); ex.change(ex.str,ex.ch); System.out.print(ex.str+" and "); Sytem.out.print(ex.ch); public void change(String str,char ch[]){ str="testok": ch[0]=’g’;}}
这是一个 Java 程序,定义了一个名为 Example 的类。该类中包含一个字符串类型的属性 str,以及一个字符数组类型的属性 ch。在 main 方法中,程序创建了一个 Example 类的对象 ex,并调用其 change 方法,将 ex.str 和 ex.ch 作为参数传递给该方法。change 方法会修改 str 和 ch 的值,将 str 修改为 "testok",将 ch 数组的第一个元素修改为 'g'。
在 main 方法中,程序先输出 ex.str 的值,由于 str 在 change 方法中被修改过,因此输出结果为 "good"。接着,程序输出 ex.ch 数组的值,由于 ch 数组是一个引用类型,其指向的内存地址在 change 方法中被修改过,因此输出结果为 "gbc"。
需要注意的是,该程序中存在一些语法错误:1、在字符串 "good" 的定义中,双引号应该为英文双引号;2、在程序的最后一行,System.out.print 方法的拼写错误,应该为 System.out.print。