阅读下面的程序: class StringDemo{ public static void main(String[]args){ String s1=“a"; String s2=“b"; show(s1,s2); System.out.printIns1+s2); public static void show(String s1,String s2){ s1=s1+”q”; s2=s2+s1; 上述程序的运行结果为() A、ab B、aqb C.agbaq D.aqaqb
时间: 2023-11-22 08:55:05 浏览: 219
该程序有语法错误,正确的程序如下:
```
class StringDemo {
public static void main(String[] args) {
String s1 = "a";
String s2 = "b";
show(s1, s2);
System.out.println(s1 + s2);
}
public static void show(String s1, String s2) {
s1 = s1 + "q";
s2 = s2 + s1;
System.out.println(s2);
}
}
```
运行结果为 C、agbaq。
相关问题
public class Test{ public static void main(String[] args){ String s1 = "runoob"; String s2 = "runoob"; System.out.println("s1 == s2 is:" + s1 == s2);}}
The code you provided has a small mistake in the print statement. The expression `"s1 == s2 is:" + s1` is concatenated with `== s2` before being passed to `System.out.println()`. This causes a compilation error because you cannot concatenate a string with a boolean value directly.
To fix this, you need to use parentheses to group the concatenation expression properly. Here's the corrected code:
```java
public class Test {
public static void main(String[] args) {
String s1 = "runoob";
String s2 = "runoob";
System.out.println("s1 == s2 is: " + (s1 == s2));
}
}
```
In this corrected code, the expression `(s1 == s2)` is properly grouped and then concatenated with the string `"s1 == s2 is: "`.
下面程序的运行结果是() public class Example { public static void main(String[] args) { String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.print(s1 == s2); String s3 = "Hello"; String s4 = "Hello"; System.out.print(s3 == s4); s1 = s3; s2 = s4; System.out.print(s1 == s2); } }
程序的运行结果是falsefalsetrue。
原因是:在Java中,用new关键字创建的字符串对象,每次都会在堆内存中新分配一块内存,因此s1和s2指向的是不同的对象,所以s1==s2的结果为false。
而用双引号创建的字符串对象,会首先在常量池中查找是否已有相同值的对象,如果有,则直接返回该对象的引用,如果没有,则创建一个新的字符串对象并存储在常量池中。因此s3和s4指向的是同一个对象,所以s3==s4的结果为true。
最后s1=s3,s2=s4,因此s1和s2也指向同一个对象,所以s1==s2的结果为true。
阅读全文