JAVA程序阅读题
四、程序阅读题:(每小题6分,共18分)
1.写出以下程序的运行结果。
public class EqualOrNot
{
public static void main(String[] args)
{B b1=new B(5);
B b2=new B(5);
System.out.println(b1==b2);
System.out.println(b1.equals(b2));
}
}
class B
{
int x;
B( int y){ x=y; }
}
1、写出以下程序的运行结果。
class StaticTest {
static int x=1;
int y;
StaticTest(){
y++;
}
public static void main(String args[ ]){
StaticTest st=new StaticTest();
System.out.println("x=" + x);
System.out.println("st.y=" + st.y);
st=new StaticTest();
System.out.println("st.y=" + st.y);
}
static { x++;}
}
x=2
st y=1
st y=1
2、写出以下程序的功能。
public class TestArray{
public static void main(String args[ ]){
int i , j ;int a[ ] = {1,3,2,5,4};
for ( i = 0 ; i < a.length-1; i ++ ) {
int k = i;
for ( j = i ; j < a.length ; j++ )
if ( a[j]>a[k] ) k = j;
int temp =a[i];
a[i] = a[k];a[k] = temp;
}
for ( i =0 ; i
System.out.print(a[i]+" ");
System.out.println( );
}
}
5 4 3 2 1
3、写出以下程序的运行结果。
class MyException extends Exception{
public String toString( ){return "negative"; }
}
public class ExceptionDemo{
public static void mySqrt(int a) throws MyException{
if( a<0 )throw new MyException();
System.out.println(Math.sqrt(a));
}
public static void main( String args[] ){
try{
mySqrt(25 );mySqrt(-5 );}
catch( MyException e ){
System.out.println("Caught "+e);
}
}
}
5.0
Caught negative
2.写出以下程序的运行结果。
import java.io.*;
public class TestString
{
public static void main(String args[ ])
{
StringC s = new StringC (“Hello ","World!");
System.out.println(s);
}
}
class StringC {
String s1;
String s2;
StringC( String str1 , String str2 ){
s1 = str1;
s2 = str2;
}
public String toString( ){
return s1+s2;
}
}
HelloWorld!
4.写出以下程序的功能。
class Test {
public static void main(String