JAVA面试笔记(7)

来源:互联网 发布:linux统计文件数量 编辑:程序博客网 时间:2024/05/16 23:49

1。求一个长度为10的整数数组中的最大元素,采用随机赋值的方式并输出各元素的值

 

算法描述:

a假定第一个元素为最大元素,将他存储在一个临时变量中

b将这个变量与后面的元素比较,比这个临时变量大的,则存储在这个变量中。

c当所有元素比较完毕后,这个临时变量中存储的就是最大元素

 


public class MaxArray {
 public static void main(String args[]){
  int arr[] = new int[10];
  setValue(arr);
  showValue(arr);
  getMaxValue(arr);
  
 }
 
 public static void setValue(int [] arr){
  for(int i = 0; i < arr.length; i++){
   arr[i] = (int)(Math.random()*100);
  }
 }
 public static void showValue(int [] arr){
  for(int i= 0; i < arr.length; i++){
   System.out.println(" "+arr[i]);
  }
 }
 
 private static void getMaxValue(int[] arr) {
  int max = arr[0];
  for(int i = 0; i < arr.length; i++){
   if(max < arr[i]){
    max = arr[i];
   }
  }
  System.out.println(max);
  
 }
}

 

2。String是最基本数据类型吗?

答不是,基本数据类型包括 byte int char long float double boolean short。String类是final类型的,因此不可以继承且修改这个类。为了提高效率节省空间,我们应该用StringBuffer。

 

3。下面选项哪些返回TRUE?

String s = "hello";

String t = "hello";

char c[] = {'h', 'e', 'l', 'l', 'o'};

 

A. s.equals(t);

B. t.equals(c);

C. s==t;

D. t.equals(new String("hello"));

E. t==c;

 

分析:

String 的equals()方法比较的是两个String对象的内容是否一样,其参数是String对象时才有可能返回TRUE,其他对象都返回FALSE。需要指出的是,由于s和t并非使用new创建的,他们指向内存池中的同一个字符串变量,因此其地址实际上是相同的。ACD