Java中String与StringBuffered常见笔试题
1:需求:请设计一个方法,可以实现获取任意范围内的随机数。
package org.wests.InterviewQuestion;
/** * 1:需求:请设计一个方法,可以实现获取任意范围内的随机数。 * @author 代虎 * */
public class Question01 {
public static void getRandom(double start,double end) {
double random = Math.random()*(end-start)+start;
System.out.println(random);
}
public static void main(String[] args) {
getRandom(10, 20);
getRandom(0, 20);
getRandom(100, 200);
}
}
执行结果:
15.760649486959991
12.00285416285148
145.76020942009
2:下面代码执行的结果是:
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.print(s1 == s2);
System.out.print(",");
System.out.println(s1.equals(s2));
}
}
执行结果:false,true
3:下面代码执行的结果是:
public static void main(String arg[]) {
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
operate(a, b);
System.out.println(a + "," + b);
}
static void operate(StringBuffer x, StringBuffer y) {
x.append(y);
y = x;
}
执行结果:AB,B
4、下列代码的执行结果是:
String str1 = "This is a test!";
StringBuffer str2 =new StringBuffer( "This is a test!");
str1 = str1+"Hi";
str2.append("Hi");
System.out.println("str1 == " + str1);
System.out.println("str2 == " + str2);
执行结果:str1 == This is a test ! Hi
str2 == This is a test ! Hi
以下为反编译的结果:
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
// Source File Name: Question04.java
package org.wests.InterviewQuestion;
import java.io.PrintStream;
public class Question04
{
public Question04()
{
}
public static void main(String args[])
{
String str1 = "This is a test!";
StringBuffer str2 = new StringBuffer("This is a test!");
str1 = (new StringBuilder(String.valueOf(str1))).append("Hi").toString();
str2.append("Hi");
System.out.println((new StringBuilder("str1 == ")).append(str1).toString());
System.out.println((new StringBuilder("str2 == ")).append(str2).toString());
}
}
5:下面代码能最后打印的值是?
public class TestValue {
private static int a;
public static void main(String[] args) {
modify(a);
System.out.println(a);
}
public static void modify(int a) {
a++;
}
执行结果: 0