现在的位置: 首页 > 综合 > 正文

Java面试题一(基础)

2013年11月08日 ⁄ 综合 ⁄ 共 1839字 ⁄ 字号 评论关闭

1. 如何得到Java应用程序的可用内存?
答:如下代码实现取得总的内存大小和可用内存大小,并打印到控制台上

public class MemoryExp {
public static void main(String[] args) {
System.out.println("Total Memory"+Runtime.getRuntime().totalMemory());
System.out.println("Free Memory"+Runtime.getRuntime().freeMemory());
}
}
2. 如何写一个不需要main方法的java应用程序?

答:可以使用静态代码块来实现一个可以执行但并没有main方法的Java应用程序。如下面的代码是所示:

class MainMethodNot
{
static
{
System.out.println("This java program have run without the run method");
System.exit(0);
}
}
3. 请说出上例中的代码为什么可以运行?
答:上面的代码可以运行是因为static代码块会在java类被加载的时候被执行,而且是在main方法被调用之前。在运行时,JVM会在执行静态代码块以后搜索main方法,如果不能找到main方法,就会抛出一个异常,为了避免这个异常,可以使用System.exit(0)来结束应用程序。

 

4.介绍一下Java的Map以及如何使用HashMap

Map是一个保存键值对的对象,根据键值可以找到它对应的值。键必须是唯一的,但是值可以重复。HashMap类提供了map接口的主要实现,它使用hash table来实现map接口。这就使得一些常见的操作如get()和put()所用的时间基本不变。

如下代码是一个使用hashmap的实例,它提供了account信息和account balance的对应:

import java.util.*;

public class HashMapDemo {

public static void main( String[] args) {

HashMap hm = new HashMap();
hm.put(“Rohit”, new Double(3434.34));
hm.put(“Mohit”, new Double(123.22));
hm.put(“Ashish”, new Double(1200.34));
hm.put(“Khariwal”, new Double(99.34));
hm.put(“Pankaj”, new Double(-19.34));
Set set = hm.entrySet();

Iterator i = set.iterator();

while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + “ : ” + me.getValue() );
}

//deposit into Rohit’s Account
double balance = ((Double)hm.get(“Rohit”)).doubleValue();
hm.put(“Rohit”, new Double(balance + 1000));

System.out.println(“Rohit new balance : ” + hm.get(“Rohit”));

}
}

运行后的输出如下:

Rohit : 3434.34
Ashish : 1200.34
Pankaj : -19.34
Mohit : 123.22
Khariwal : 99.34
Rohit new balance : 4434.34

5.ArrayList和vector的区别有哪些 ?

一.同步性:Vector是线程安全的,也就是说是同步的,而ArrayList是线程序不安全的,不是同步的
二.数据增长:当需要增长时,Vector默认增长为原来一培,而ArrayList却是原来的一半
就HashMap与HashTable主要从三方面来说。
一.历史原因:Hashtable是基于陈旧的Dictionary类的,HashMap是Java   1.2引进的Map接口的一个实现
二.同步性:Hashtable是线程安全的,也就是说是同步的,而HashMap是线程序不安全的,不是同步的
三.值:只有HashMap可以让你将空值作为一个表的条目的key或value

 

 

抱歉!评论已关闭.