转自:http://www.blogjava.net/beansoft/archive/2007/03/09/102812.html
面试必备基础题目(虽然不一定常用, 仅用于面试, 面试就是把人搞的都不会然后砍价, 当然您可以讲我可以查资料完成, 但是面试的时候就是没道理的, 起码我是经常看到这些题).
如何把一段逗号分割的字符串转换成一个数组?
request.getAttribute() 和 request.getParameter() 有何区别?
response.sendRedirect() 和 forward() 区别?
<%@include file="xxx.jsp"%>
和 <jsp:include> 区别?
List 和 Map 区别?
Struts 和 Spring 自动填充表单参数到 Bean 的大致原理?
说一下你用的 Spring + Hibernate 的方框图? 您都用到了哪些部分?
请用英文简单介绍一下自己.
请把 http://tomcat.apache.org/ 首页的这一段话用中文翻译一下?
Apache Tomcat is the servlet container that is used in the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process.
Apache Tomcat is developed in an open and participatory environment and released under the Apache Software License. Apache Tomcat is intended to be a collaboration of the best-of-breed developers from around the world. We invite you to participate in this open development project. To learn more about getting involved, click here.
Apache Tomcat powers numerous large-scale, mission-critical web applications across a diverse range of industries and organizations. Some of these users and their stories are listed on the PoweredBy wiki page.
try {
Connection conn = ...;
Statement stmt = ...;
ResultSet rs = stmt.executeQuery("select * from table1");
while(rs.next()) {
}
} catch(Exception ex) {
}
这段代码有什么不足之处?
HTML 的 form 提交之前如何验证数值不为空? 为空的话提示用户并终止提交?
为什么要用 ORM? 和 JDBC 有何不一样?
Weblogic 的 Server, Machine, Node, Domain 都有何区别?
简要讲一下 EJB 的 7 个 Transaction Level?
最常见的: 用 JDBC 查询学生成绩单, 把主要代码写出来.
Tomcat 5 用 query.jsp?name=中文, 怎么把这个变量无乱码的取出来?
finally语句一定会执行么?
前几天有一个朋友去面试,被问到这样一个问题,如下
1 public class smallT
2 {
3 public static void main(String args[])
4 {
5 smallT t = new smallT();
6 int b = t.get();
7 System.out.println(b);
8 }
9 public int get()
10 {
11 try
12 {
13 return 2 ;
14 }
15 catch (Exception e)
16 {
17 return 3 ;
18 }
19 finally
20 {
21 return 4 ;
22 }
23 }
24 }
25
输出:
4
我记得学习的时候说有返回值的方法,执行完return语句后就会停止了;另一方面我还记得在try……catch语句中finally语句也是一定要执行的。于是在这里就产生了麻烦。试了一下,发现果然是执行了finally中的值。正好这两天公司在培训,我便把这个问题提给java很厉害的一个讲师,他用断点测试了一下,说是两个值都返回了……
我又改了一小下,在get方法中逐个添上了输出信息到控制台的语句,发现居然能执行。如下
1public class test
2{
3 public static void main(String args[])
4{
5 test t = new test();
6 int b = t.get();
7 System.out.println("Third: a = "+b);
8 }
9 public int get()
10{
11 try
12{
13 System.out.println("First: a = "+2);
14 return 2;
15 }
16 catch(Exception e)
17{
18 System.out.println(3);
19 }
20 finally
21{
22 System.out.println("Second: a = "+4);
23 return 4;
24 }
25 }
26}
27
输出:
First: a = 2
Second: a = 4
Third: a = 4
可这明明是一个需要返回一个int整数的方法啊。
一道面试题目
一个整数,大于0,不用循环和本地变量,按照n,2n,4n,8n的顺序递增,当值大于5000时,把值按照指定顺序输出来。
例:n=1237
则输出为:
1237,
2474,
4948,
9896,
9896,
4948,
2474,
1237,
美资软件公司JAVA工程师电话面试题目
1. Talk about overriding, overloading.
2. Talk about JAVA design patterns you known.
3. Talk about the difference between LinkList, ArrayList and Victor.
4. Talk about the difference between an Abstract class and an Interface.
5. Class a = new Class(); Class b = new Class();
if(a == b) returns true or false, why?
6. Why we use StringBuffer when concatenating strings?
7. Try to explain Singleton to us? Is it thread safe? If no, how to make it thread safe?
8. Try to explain Ioc?
9. How to set many-to-many relationship in Hibernate?
10. Talk about the difference between INNER JOIN and LFET JOIN.
11. Why we use index in database? How many indexes is the maximum in one table as your suggestion?
12. When ‘Final’ is used in class, method and property, what dose it mean?
13. Do you have any experience on XML? Talk about any XML tool you used ,e.g. JAXB, JAXG.
14. Do you have any experience on Linux?
15. In OOD what is the reason when you create a Sequence diagram?
补一个内部培训用的 PPT: SQL Tuning in Sybase.zip 17KB, 英文, Sybase 调优, 大部分道理是通用的.
数据库三范式是什么? 别看问题简单, 我也经常答不上来被面试的人写上数据库不行.
还有就是 Sun Java 认证时候会考的一些英文选择题, 填空题, 模拟题也成.
赴港JAVA开发工程师的面试题目
也是上个星期五的上午,按照与猎头的约定,接受了香港某软件供应商的面试。工作是分析程序员,需赴港工作,以下是面试过程以及题目(大概记下了90%),记下来与大家分享。
第一部分:例行公事的英文自我介绍;
以下部分必须以粤语回答,本人非广东人,粤语会讲,但是不标准。
第二部分:项目经验介绍,着重介绍项目背景,开发流程以及本人在项目开发过程中的角色;
第三部分:面试官根据简历提问:
(1)说出Abstract class与interface的不同?
(2)Oracle中如何进行错误处理?如果用户反应速度慢,你如何着手解决问题?
(3)图画板上列了两个table,问查询结果,主要是考inner join与left join的。
(4)union和union all有什么不同?
(5)你用什么软件做设计?
(6)是否用过Websphere?
(7)iBatis与Hibernate有什么不同?
(8)谈谈Struts中的Action servlet。
(9)是否开发过IBM portal项目。
(10)是否介意加班?
(11)如果你去香港工作,你认为你最大的困难是什么?
第四部分:笔试,三个英文考试题目选一个作答,内容都是写一份email。
出来后问了猎头,他说最迟一个星期内就有结果。
结果,晚上就接到电话说通过了,并收到了合同和赴港申请的电子文件。工作地点是九龙,月薪18K(中等偏低),合同期一年。猎头催我尽快签合同,然后他们马上就去办工作签证。
犹豫ing。
每个JAVA初学者应该知道的问题
对于这个系列里的问题,每个学Java的人都应该搞懂。当然,如果只是学Java玩玩就无所谓了。如果你认为自己已经超越初学者了,却不很懂这些问题,请将你自己重归初学者行列。内容均来自于CSDN的经典老贴。
问题一:我声明了什么!
String s = "Hello world!";
许多人都做过这样的事情,但是,我们到底声明了什么?回答通常是:一个String,内容是“Hello world!”。这样模糊的回答通常是概念不清的根源。如果要准确的回答,一半的人大概会回答错误。
这个语句声明的是一个指向对象的引用,名为“s”,可以指向类型为String的任何对象,目前指向"Hello world!"这个String类型的对象。这就是真正发生的事情。我们并没有声明一个String对象,我们只是声明了一个只能指向String对象的引用变量。所以,如果在刚才那句语句后面,如果再运行一句:
String string = s;
我们是声明了另外一个只能指向String对象的引用,名为string,并没有第二个对象产生,string还是指向原来那个对象,也就是,和s指向同一个对象。
问题二:"=="和equals方法究竟有什么区别?
==操作符专门用来比较变量的值是否相等。比较好理解的一点是:
int a=10;
int b=10;
则a==b将是true。
但不好理解的地方是:
String a=new String("foo");
String b=new String("foo");
则a==b将返回false。
根据前一帖说过,对象变量其实是一个引用,它们的值是指向对象所在的内存地址,而不是对象本身。a和b都使用了new操作符,意味着将在内存中产生两个内容为"foo"的字符串,既然是“两个”,它们自然位于不同的内存地址。a和b的值其实是两个不同的内存地址的值,所以使用"=="操作符,结果会是 false。诚然,a和b所指的对象,它们的内容都是"foo",应该是“相等”,但是==操作符并不涉及到对象内容的比较。
对象内容的比较,正是equals方法做的事。
看一下Object对象的equals方法是如何实现的:
boolean equals(Object o){
return this==o;
}
Object 对象默认使用了==操作符。所以如果你自创的类没有覆盖equals方法,那你的类使用equals和使用==会得到同样的结果。同样也可以看出, Object的equals方法没有达到equals方法应该达到的目标:比较两个对象内容是否相等。因为答案应该由类的创建者决定,所以Object把这个任务留给了类的创建者。
看一下一个极端的类:
Class Monster{
private String content;
...
boolean equals(Object another){ return true;}
}
我覆盖了equals方法。这个实现会导致无论Monster实例内容如何,它们之间的比较永远返回true。
所以当你是用equals方法判断对象的内容是否相等,请不要想当然。因为可能你认为相等,而这个类的作者不这样认为,而类的equals方法的实现是由他掌握的。如果你需要使用equals方法,或者使用任何基于散列码的集合(HashSet,HashMap,HashTable),请察看一下 java doc以确认这个类的equals逻辑是如何实现的。
问题三:String到底变了没有?
没有。因为String被设计成不可变(immutable)类,所以它的所有对象都是不可变对象。请看下列代码:
String s = "Hello";
s = s + " world!";
s 所指向的对象是否改变了呢?从本系列第一篇的结论很容易导出这个结论。我们来看看发生了什么事情。在这段代码中,s原先指向一个String对象,内容是 "Hello",然后我们对s进行了+操作,那么s所指向的那个对象是否发生了改变呢?答案是没有。这时,s不指向原来那个对象了,而指向了另一个 String对象,内容为"Hello world!",原来那个对象还存在于内存之中,只是s这个引用变量不再指向它了。
通过上面的说明,我们很容易导出另一个结论,如果经常对字符串进行各种各样的修改,或者说,不可预见的修改,那么使用String来代表字符串的话会引起很大的内存开销。因为 String对象建立之后不能再改变,所以对于每一个不同的字符串,都需要一个String对象来表示。这时,应该考虑使用StringBuffer类,它允许修改,而不是每个不同的字符串都要生成一个新的对象。并且,这两种类的对象转换十分容易。
同时,我们还可以知道,如果要使用内容相同的字符串,不必每次都new一个String。例如我们要在构造器中对一个名叫s的String引用变量进行初始化,把它设置为初始值,应当这样做:
public class Demo {
private String s;
...
public Demo {
s = "Initial Value";
}
...
}
而非
s = new String("Initial Value");
后者每次都会调用构造器,生成新对象,性能低下且内存开销大,并且没有意义,因为String对象不可改变,所以对于内容相同的字符串,只要一个String对象来表示就可以了。也就说,多次调用上面的构造器创建多个对象,他们的String类型属性s都指向同一个对象。
上面的结论还基于这样一个事实:对于字符串常量,如果内容相同,Java认为它们代表同一个String对象。而用关键字new调用构造器,总是会创建一个新的对象,无论内容是否相同。
至于为什么要把String类设计成不可变类,是它的用途决定的。其实不只String,很多Java标准类库中的类都是不可变的。在开发一个系统的时候,我们有时候也需要设计不可变类,来传递一组相关的值,这也是面向对象思想的体现。不可变类有一些优点,比如因为它的对象是只读的,所以多线程并发访问也不会有任何问题。当然也有一些缺点,比如每个不同的状态都要一个对象来代表,可能会造成性能上的问题。所以Java标准类库还提供了一个可变版本,即 StringBuffer。
问题四:final关键字到底修饰了什么?
final使得被修饰的变量"不变",但是由于对象型变量的本质是“引用”,使得“不变”也有了两种含义:引用本身的不变,和引用指向的对象不变。
引用本身的不变:
final StringBuffer a=new StringBuffer("immutable");
final StringBuffer b=new StringBuffer("not immutable");
a=b;//编译期错误
引用指向的对象不变:
final StringBuffer a=new StringBuffer("immutable");
a.append(" broken!"); //编译通过
可见,final只对引用的“值”(也即它所指向的那个对象的内存地址)有效,它迫使引用只能指向初始指向的那个对象,改变它的指向会导致编译期错误。至于它所指向的对象的变化,final是不负责的。这很类似==操作符:==操作符只负责引用的“值”相等,至于这个地址所指向的对象内容是否相等,==操作符是不管的。
理解final问题有很重要的含义。许多程序漏洞都基于此----final只能保证引用永远指向固定对象,不能保证那个对象的状态不变。在多线程的操作中,一个对象会被多个线程共享或修改,一个线程对对象无意识的修改可能会导致另一个使用此对象的线程崩溃。一个错误的解决方法就是在此对象新建的时候把它声明为final,意图使得它“永远不变”。其实那是徒劳的。
问题五:到底要怎么样初始化!
本问题讨论变量的初始化,所以先来看一下Java中有哪些种类的变量。
1. 类的属性,或者叫值域
2. 方法里的局部变量
3. 方法的参数
对于第一种变量,Java虚拟机会自动进行初始化。如果给出了初始值,则初始化为该初始值。如果没有给出,则把它初始化为该类型变量的默认初始值。
int类型变量默认初始值为0
float类型变量默认初始值为0.0f
double类型变量默认初始值为0.0
boolean类型变量默认初始值为false
char类型变量默认初始值为0(ASCII码)
long类型变量默认初始值为0
所有对象引用类型变量默认初始值为null,即不指向任何对象。注意数组本身也是对象,所以没有初始化的数组引用在自动初始化后其值也是null。
对于两种不同的类属性,static属性与instance属性,初始化的时机是不同的。instance属性在创建实例的时候初始化,static属性在类加载,也就是第一次用到这个类的时候初始化,对于后来的实例的创建,不再次进行初始化。这个问题会在以后的系列中进行详细讨论。
对于第二种变量,必须明确地进行初始化。如果再没有初始化之前就试图使用它,编译器会抗议。如果初始化的语句在try块中或if块中,也必须要让它在第一次使用前一定能够得到赋值。也就是说,把初始化语句放在只有if块的条件判断语句中编译器也会抗议,因为执行的时候可能不符合if后面的判断条件,如此一来初始化语句就不会被执行了,这就违反了局部变量使用前必须初始化的规定。但如果在else块中也有初始化语句,就可以通过编译,因为无论如何,总有至少一条初始化语句会被执行,不会发生使用前未被初始化的事情。对于try-catch也是一样,如果只有在try块里才有初始化语句,编译部通过。如果在 catch或finally里也有,则可以通过编译。总之,要保证局部变量在使用之前一定被初始化了。所以,一个好的做法是在声明他们的时候就初始化他们,如果不知道要出事化成什么值好,就用上面的默认值吧!
其实第三种变量和第二种本质上是一样的,都是方法中的局部变量。只不过作为参数,肯定是被初始化过的,传入的值就是初始值,所以不需要初始化。
问题六:instanceof是什么东东?
instanceof是Java的一个二元操作符,和==,>,<是同一类东东。由于它是由字母组成的,所以也是Java的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean类型的数据。举个例子:
String s = "I AM an Object!";
boolean isObject = s instanceof Object;
我们声明了一个String对象引用,指向一个String对象,然后用instancof来测试它所指向的对象是否是Object类的一个实例,显然,这是真的,所以返回true,也就是isObject的值为True。
instanceof有一些用处。比如我们写了一个处理账单的系统,其中有这样三个类:
public class Bill {//省略细节}
public class PhoneBill extends Bill {//省略细节}
public class GasBill extends Bill {//省略细节}
在处理程序里有一个方法,接受一个Bill类型的对象,计算金额。假设两种账单计算方法不同,而传入的Bill对象可能是两种中的任何一种,所以要用instanceof来判断:
public double calculate(Bill bill) {
if (bill instanceof PhoneBill) {
//计算电话账单
}
if (bill instanceof GasBill) {
//计算燃气账单
}
...
}
这样就可以用一个方法处理两种子类。
然而,这种做法通常被认为是没有好好利用面向对象中的多态性。其实上面的功能要求用方法重载完全可以实现,这是面向对象变成应有的做法,避免回到结构化编程模式。只要提供两个名字和返回值都相同,接受参数类型不同的方法就可以了:
public double calculate(PhoneBill bill) {
//计算电话账单
}
public double calculate(GasBill bill) {
//计算燃气账单
}
所以,使用instanceof在绝大多数情况下并不是推荐的做法,应当好好利用多态。
BeanSoft 参加过的一次面试:
2004年8月18日 星期三 〖农历 甲申 猴年 七月初三〗
笔试题目
1. 写出常用的 Linux 命令
a) 列出当前目录
b) 列出所有系统变量
c) 重命名文件
d) etc... 记不住了.
2. Write a Java application use the Singleton pattern, it should have one instance per class. It should have two integer variable, one is count, on is inita. There should be two methods in this class, and the method should be thread safely in multi-thread environment.
a) a count() method, after each call the count should be added on by 1;
b) a reset() method, after each call the count should be set to the value of inita.
3. Write a JavaBean and a JSP file. The page should output a date string in this pattern "今天是2004年8月15日上午10:00", the value is taken from the bean.
4. 以下三个题目, 任选其一或多个:
1) 忘了..., 是关于 Java 的.
2) 写一个应用程序, 读出 STUDENT 表中的数据并打印出所有名称. 数据库系统任选.
3) 写一个 Servlet, 读取名为 url 的参数, 并连接到此字符串指定的地址上, 读取所有内容后显示给客户.
5. 6. 7. 都是关于 SQL 的, 例如 SELECT, UPDATE, DELETE 之类的, 还有的有子查询. 数据库系统没有限制.
8. Write a html file, it shoud has follow functions:
1) check whether the user's name is empty;
2) the email address should has a '@';
3) telephone number must be '1'-'9', '-', ' '(space).
Page picture:
Please input your name:
[____________________] [Check input]
Please input your address:
[abc@________________] [Check input]
Please input your telephone number:
[____123a____________] [Check input]
Java 面试题及其答案
前段时间因为要参加一个笔试,在准备期间在网上找到了两条关于笔试题目的文章,其中一篇为<<有感:应聘Java笔试时可能出现问题>>,还有一篇忘了名字,读后深受启发。
在寻找这些答案的过程中,我将相关答案记录下来,就形成了以下这些东西。需要说明的是以下答案肯定有很多不完整甚至错误的地方,需要各位来更正与完善它,千万不要扔我的鸡蛋啊。
希望本文能够给即将奔赴笔试考场的同仁些许帮助,更希望更多的人加入到收集整理笔试题与完善答案的这些工作中来,为大家更好的获得工作机会做一点贡献。
在此感谢前面两文的作者的对笔试题目的收集与整理。
如有任何意见与建议请通过QQ:6045306,Mail:huijunzi@21cn.com与我联系。
Java基础方面:
1、作用域public,private,protected,以及不写时的区别
答:区别如下:
作用域 当前类 同一package 子孙类 其他package
public √ √ √ √
protected √ √ √ ×
friendly √ √ × ×
private √ × × ×
不写时默认为friendly
2、ArrayList和Vector的区别,HashMap和Hashtable的区别
答:就ArrayList与Vector主要从二方面来说.
一.同步性:Vector是线程安全的,也就是说是同步的,而ArrayList是线程序不安全的,不是同步的
二.数据增长:当需要增长时,Vector默认增长为原来一培,而ArrayList却是原来的一半
就HashMap与HashTable主要从三方面来说。
一.历史原因:Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现
二.同步性:Hashtable是线程安全的,也就是说是同步的,而HashMap是线程序不安全的,不是同步的
三.值:只有HashMap可以让你将空值作为一个表的条目的key或value
3、char型变量中能不能存贮一个中文汉字?为什么?
答:是能够定义成为一个中文的,因为java中以unicode编码,一个char占16个字节,所以放一个中文是没问题的
4、多线程有几种实现方法,都是什么?同步有几种实现方法,都是什么?
答:多线程有两种实现方法,分别是继承Thread类与实现Runnable接口
同步的实现方面有两种,分别是synchronized,wait与notify
5、继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
答:父类:
package test;
public class FatherClass
{
public FatherClass()
{
System.out.println("FatherClass Create");
}
}
子类:
package test;
import test.FatherClass;
public class ChildClass extends FatherClass
{
public ChildClass()
{
System.out.println("ChildClass Create");
}
public static void main(String[] args)
{
FatherClass fc = new FatherClass();
ChildClass cc = new ChildClass();
}
}
输出结果:
C:\>java test.ChildClass
FatherClass Create
FatherClass Create
ChildClass Create
6、内部类的实现方式?
答:示例代码如下:
package test;
public class OuterClass
{
private class InterClass
{
public InterClass()
{
System.out.println("InterClass Create");
}
}
public OuterClass()
{
InterClass ic = new InterClass();
System.out.println("OuterClass Create");
}
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
}
输出结果:
C:\>java test/OuterClass
InterClass Create
OuterClass Create
再一个例题:
public class OuterClass {
private double d1 = 1.0;
//insert code here
}
You need to insert an inner class declaration at line 3. Which two inner class declarations are
valid?(Choose two.)
A. class InnerOne{
public static double methoda() {return d1;}
}
B. public class InnerOne{
static double methoda() {return d1;}
}
C. private class InnerOne{
double methoda() {return d1;}
}
D. static class InnerOne{
protected double methoda() {return d1;}
}
E. abstract class InnerOne{
public abstract double methoda();
}
说明如下:
一.静态内部类可以有静态成员,而非静态内部类则不能有静态成员。 故 A、B 错
二.静态内部类的非静态成员可以访问外部类的静态变量,而不可访问外部类的非静态变量;return d1 出错。
故 D 错
三.非静态内部类的非静态成员可以访问外部类的非静态变量。 故 C 正确
四.答案为C、E
7、垃圾回收机制,如何优化程序?
希望大家补上,谢谢
8、float型float f=3.4是否正确?
答:不正确。精度不准确,应该用强制类型转换,如下所示:float f=(float)3.4
9、介绍JAVA中的Collection FrameWork(包括如何写自己的数据结构)?
答:Collection FrameWork如下:
Collection
├List
│├LinkedList
│├ArrayList
│└Vector
│ └Stack
└Set
Map
├Hashtable
├HashMap
└WeakHashMap
Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements)
Map提供key到value的映射
10、Java中异常处理机制,事件机制?
11、JAVA中的多形与继承?
希望大家补上,谢谢
12、抽象类与接口?
答:抽象类与接口都用于抽象,但是抽象类(JAVA中)可以有自己的部分实现,而接口则完全是一个标识(同时有多重继承的功能)。
13、Java 的通信编程,编程题(或问答),用JAVA SOCKET编程,读服务器几个字符,再写入本地显示?
答:Server端程序:
package test;
import java.net.*;
import java.io.*;
public class Server
{
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server()
{
try
{
ss=new ServerSocket(10000);
while(true)
{
socket = ss.accept();
String RemoteIP = socket.getInetAddress().getHostAddress();
String RemotePort = ":"+socket.getLocalPort();
System.out.println("A client come in!IP:"+RemoteIP+RemotePort);
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String line = in.readLine();
System.out.println("Cleint send is :" + line);
out = new PrintWriter(socket.getOutputStream(),true);
out.println("Your Message Received!");
out.close();
in.close();
socket.close();
}
}catch (IOException e)
{
out.println("wrong");
}
}
public static void main(String[] args)
{
new Server();
}
};
Client端程序:
package test;
import java.io.*;
import java.net.*;
public class Client
{
Socket socket;
BufferedReader in;
PrintWriter out;
public Client()
{
try
{
System.out.println("Try to Connect to 127.0.0.1:10000");
socket = new Socket("127.0.0.1",10000);
System.out.println("The Server Connected!");
System.out.println("Please enter some Character:");
BufferedReader line = new BufferedReader(new
InputStreamReader(System.in));
out = new PrintWriter(socket.getOutputStream(),true);
out.println(line.readLine());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
out.close();
in.close();
socket.close();
}catch(IOException e)
{
out.println("Wrong");
}
}
public static void main(String[] args)
{
new Client();
}
};
14、用JAVA实现一种排序,JAVA类实现序列化的方法(二种)? 如在COLLECTION框架中,实现比较要实现什么样的接口?
答:用插入法进行排序代码如下
package test;
import java.util.*;
class InsertSort
{
ArrayList al;
public InsertSort(int num,int mod)
{
al = new ArrayList(num);
Random rand = new Random();
System.out.println("The ArrayList Sort Before:");
for (int i=0;i<num ;i++ )
{
al.add(new Integer(Math.abs(rand.nextInt()) % mod + 1));
System.out.println("al["+i+"]="+al.get(i));
}
}
public void SortIt()
{
Integer tempInt;
int MaxSize=1;
for(int i=1;i<al.size();i++)
{
tempInt = (Integer)al.remove(i);
if(tempInt.intValue()>=((Integer)al.get(MaxSize-1)).intValue())
{
al.add(MaxSize,tempInt);
MaxSize++;
System.out.println(al.toString());
} else {
for (int j=0;j<MaxSize ;j++ )
{
if
(((Integer)al.get(j)).intValue()>=tempInt.intValue())
{
al.add(j,tempInt);
MaxSize++;
System.out.println(al.toString());
break;
}
}
}
}
System.out.println("The ArrayList Sort After:");
for(int i=0;i<al.size();i++)
{
System.out.println("al["+i+"]="+al.get(i));
}
}
public static void main(String[] args)
{
InsertSort is = new InsertSort(10,100);
is.SortIt();
}
}
JAVA类实现序例化的方法是实现java.io.Serializable接口
Collection框架中实现比较要实现Comparable 接口和 Comparator 接口
15、编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
答:代码如下:
package test;
class SplitString
{
String SplitStr;
int SplitByte;
public SplitString(String str,int bytes)
{
SplitStr=str;
SplitByte=bytes;
System.out.println("The String is:′"+SplitStr+"′SplitBytes="+SplitByte);
}
public void SplitIt()
{
int loopCount;
loopCount=(SplitStr.length()%SplitByte==0)?(SplitStr.length()/SplitByte):(SplitStr.length()/Split
Byte+1);
System.out.println("Will Split into "+loopCount);
for (int i=1;i<=loopCount ;i++ )
{
if (i==loopCount){
System.out.println(SplitStr.substring((i-1)*SplitByte,SplitStr.length()));
} else {
System.out.println(SplitStr.substring((i-1)*SplitByte,(i*SplitByte)));
}
}
}
public static void main(String[] args)
{
SplitString ss = new SplitString("test中dd文dsaf中男大3443n中国43中国人
0ewldfls=103",4);
ss.SplitIt();
}
}
16、JAVA多线程编程。 用JAVA写一个多线程程序,如写四个线程,二个加1,二个对一个变量减一,输出。
希望大家补上,谢谢
17、STRING与STRINGBUFFER的区别。
答:STRING的长度是不可变的,STRINGBUFFER的长度是可变的。如果你对字符串中的内容经常进行操作,特别是内容要修改时,那么使用StringBuffer,如果最后需要String,那么使用StringBuffer的toString()方法
Jsp方面
1、jsp有哪些内置对象?作用分别是什么?
答:JSP共有以下9种基本内置组件(可与ASP的6种内部组件相对应):
request 用户端请求,此请求会包含来自GET/POST请求的参数
response 网页传回用户端的回应
pageContext 网页的属性是在这里管理
session 与请求有关的会话期
application servlet 正在执行的内容
out 用来传送回应的输出
config servlet的构架部件
page JSP网页本身
exception 针对错误网页,未捕捉的例外
2、jsp有哪些动作?作用分别是什么?
答:JSP共有以下6种基本动作
jsp:include:在页面被请求的时候引入一个文件。
jsp:useBean:寻找或者实例化一个JavaBean。
jsp:setProperty:设置JavaBean的属性。
jsp:getProperty:输出某个JavaBean的属性。
jsp:forward:把请求转到一个新的页面。
jsp:plugin:根据浏览器类型为Java插件生成OBJECT或EMBED标记
3、JSP中动态INCLUDE与静态INCLUDE的区别?
答:动态INCLUDE用jsp:include动作实现
<jsp:include page="included.jsp" flush="true" />它总是会检查所含文件中的变化,适合用于包含动态页面,并且可以带参数
静态INCLUDE用include伪码实现,定不会检查所含文件的变化,适用于包含静态页面
<%@ include file="included.htm" %>
4、两种跳转方式分别是什么?有什么区别?
答:有两种,分别为:
<jsp:include page="included.jsp" flush="true">
<jsp:forward page= "nextpage.jsp"/>
前者页面不会转向include所指的页面,只是显示该页的结果,主页面还是原来的页面。执行完后还会回来,相当于函数调用。并且可以带参数.后者完全转向新页面,不会再回来。相当于go to 语句。
Servlet方面
1、说一说Servlet的生命周期?
答:servlet有良好的生存期的定义,包括加载和实例化、初始化、处理请求以及服务结束。这个生存期由javax.servlet.Servlet接口的init,service和destroy方法表达。
2、Servlet版本间(忘了问的是哪两个版本了)的不同?
希望大家补上,谢谢
3、JAVA SERVLET API中forward() 与redirect()的区别?
答:前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。所以,前者更加高效,在前者可以满足需要时,尽量使用forward()方法,并且,这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用sendRedirect()方法。
4、Servlet的基本架构
public class ServletName extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
}
Jdbc、Jdo方面
1、可能会让你写一段Jdbc连Oracle的程序,并实现数据查询.
答:程序如下:
package hello.ant;
import java.sql.*;
public class jdbc
{
String dbUrl="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
String theUser="admin"
String thePw="manager"
Connection c=null;
Statement conn;
ResultSet rs=null;
public jdbc()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
c = DriverManager.getConnection(dbUrl,theUser,thePw);
conn=c.createStatement();
}catch(Exception e){
e.printStackTrace();
}
}
public boolean executeUpdate(String sql)
{
try
{
conn.executeUpdate(sql);
return true;
}
catch (SQLException e)
{
e.printStackTrace();
return false;
}
}
public ResultSet executeQuery(String sql)
{
rs=null;
try
{
rs=conn.executeQuery(sql);
}
catch (SQLException e)
{
e.printStackTrace();
}
return rs;
}
public void close()
{
try
{
conn.close();
c.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
ResultSet rs;
jdbc conn = new jdbc();
rs=conn.executeQuery("select * from test");
try{
while (rs.next())
{
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
2、Class.forName的作用?为什么要用?
答:调用该访问返回一个以字符串指定类名的类的对象。
3、Jdo是什么?
答:JDO是Java对象持久化的新的规范,为java data object的简称,也是一个用于存取某种数据仓库中的对象的标准化API。JDO提供了透明的对象存储,因此对开发人员来说,存储数据对象完全不需要额外的代码(如JDBC API的使用)。这些繁琐的例行工作已经转移到JDO产品提供商身上,使开发人员解脱出来,从而集中时间和精力在业务逻辑上。另外,JDO很灵活,因为它可以在任何数据底层上运行。JDBC只是面向关系数据库(RDBMS)JDO更通用,提供到任何数据底层的存储功能,比如关系数据库、文件、XML以及对象数据库(ODBMS)等等,使得应用可移植性更强。
4、在ORACLE大数据量下的分页解决方法。一般用截取ID方法,还有是三层嵌套方法。
答:一种分页方法
<%
int i=1;
int numPages=14;
String pages = request.getParameter("page") ;
int currentPage = 1;
currentPage=(pages==null)?(1):{Integer.parseInt(pages)}
sql = "select count(*) from tables"
ResultSet rs = DBLink.executeQuery(sql) ;
while(rs.next()) i = rs.getInt(1) ;
int intPageCount=1;
intPageCount=(i%numPages==0)?(i/numPages):(i/numPages+1);
int nextPage ;
int upPage;
nextPage = currentPage+1;
if (nextPage>=intPageCount) nextPage=intPageCount;
upPage = currentPage-1;
if (upPage<=1) upPage=1;
rs.close();
sql="select * from tables"
rs=DBLink.executeQuery(sql);
i=0;
while((i<numPages*(currentPage-1))&&rs.next()){i++;}
%>
//输出内容
//输出翻页连接
合计:<%=currentPage%>/<%=intPageCount%><a href="List.jsp?page=1">第一页</a><a
href="List.jsp?page=<%=upPage%>">上一页</a>
<%
for(int j=1;j<=intPageCount;j++){
if(currentPage!=j){
%>
<a href="list.jsp?page=<%=j%>">[<%=j%>]</a>
<%
}else{
out.println(j);
}
}
%>
<a href="List.jsp?page=<%=nextPage%>">下一页</a><a href="List.jsp?page=<%=intPageCount%>">最后页
</a>
Xml方面
1、xml有哪些解析技术?区别是什么?
答:有DOM,SAX,STAX等
DOM:处理大型文件时其性能下降的非常厉害。这个问题是由DOM的树结构所造成的,这种结构占用的内存较多,而且DOM必须在解析文件之前把整个文档装入内存,适合对XML的随机访问SAX:不现于DOM,SAX是事件驱动型的XML解析方式。它顺序读取XML文件,不需要一次全部装载整个文件。当遇到像文件开头,文档结束,或者标签开头与标签结束时,它会触发一个事件,用户通过在其回调事件中写入处理代码来处理XML文件,适合对XML的顺序访问
STAX:Streaming API for XML (StAX)
2、你在项目中用到了xml技术的哪些方面?如何实现的?
答:用到了数据存贮,信息配置两方面。在做数据交换平台时,将不能数据源的数据组装成XML文件,然后将XML文件压缩打包加密后通过网络传送给接收者,接收解密与解压缩后再同XML文件中还原相关信息进行处理。在做软件配置时,利用XML可以很方便的进行,软件的各种配置参数都存贮在XML文件中。
3、用jdom解析xml文件时如何解决中文问题?如何解析?
答:看如下代码,用编码方式加以解决
package test;
import java.io.*;
public class DOMTest
{
private String inFile = "c:\\people.xml"
private String outFile = "c:\\people.xml"
public static void main(String args[])
{
new DOMTest();
}
public DOMTest()
{
try
{
javax.xml.parsers.DocumentBuilder builder =
javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.dom.Document doc = builder.newDocument();
org.w3c.dom.Element root = doc.createElement("老师");
org.w3c.dom.Element wang = doc.createElement("王");
org.w3c.dom.Element liu = doc.createElement("刘");
wang.appendChild(doc.createTextNode("我是王老师"));
root.appendChild(wang);
doc.appendChild(root);
javax.xml.transform.Transformer transformer =
javax.xml.transform.TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "gb2312");
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
transformer.transform(new javax.xml.transform.dom.DOMSource(doc),
new
javax.xml.transform.stream.StreamResult(outFile));
}
catch (Exception e)
{
System.out.println (e.getMessage());
}
}
}
4、编程用JAVA解析XML的方式.
答:用SAX方式解析XML,XML文件如下:
<?xml version="1.0" encoding="gb2312"?>
<person>
<name>王小明</name>
<college>信息学院</college>
<telephone>6258113</telephone>
<notes>男,1955年生,博士,95年调入海南大学</notes>
</person>
事件回调类SAXHandler.java
import java.io.*;
import java.util.Hashtable;
import org.xml.sax.*;
public class SAXHandler extends HandlerBase
{
private Hashtable table = new Hashtable();
private String currentElement = null;
private String currentValue = null;
public void setTable(Hashtable table)
{
this.table = table;
}
public Hashtable getTable()
{
return table;
}
public void startElement(String tag, AttributeList attrs)
throws SAXException
{
currentElement = tag;
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
currentValue = new String(ch, start, length);
}
public void endElement(String name) throws SAXException
{
if (currentElement.equals(name))
table.put(currentElement, currentValue);
}
}
JSP内容显示源码,SaxXml.jsp:
<HTML>
<HEAD>
<TITLE>剖析XML文件people.xml</TITLE>
</HEAD>
<BODY>
<%@ page errorPage="ErrPage.jsp"
contentType="text/html;charset=GB2312" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.Hashtable" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="org.xml.sax.*" %>
<%@ page import="javax.xml.parsers.SAXParserFactory" %>
<%@ page import="javax.xml.parsers.SAXParser" %>
<%@ page import="SAXHandler" %>
<%
File file = new File("c:\\people.xml");
FileReader reader = new FileReader(file);
Parser parser;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
SAXHandler handler = new SAXHandler();
sp.parse(new InputSource(reader), handler);
Hashtable hashTable = handler.getTable();
out.println("<TABLE BORDER=2><CAPTION>教师信息表</CAPTION>");
out.println("<TR><TD>姓名</TD>" + "<TD>" +
(String)hashTable.get(new String("name")) + "</TD></TR>");
out.println("<TR><TD>学院</TD>" + "<TD>" +
(String)hashTable.get(new String("college"))+"</TD></TR>");
out.println("<TR><TD>电话</TD>" + "<TD>" +
(String)hashTable.get(new String("telephone")) + "</TD></TR>");
out.println("<TR><TD>备注</TD>" + "<TD>" +
(String)hashTable.get(new String("notes")) + "</TD></TR>");
out.println("</TABLE>");
%>
</BODY>
</HTML>
EJB方面
1、EJB2.0有哪些内容?分别用在什么场合? EJB2.0和EJB1.1的区别?
答:规范内容包括Bean提供者,应用程序装配者,EJB容器,EJB配置工具,EJB服务提供者,系统管理员。这里面,EJB容器是EJB之所以能够运行的核心。EJB容器管理着EJB的创建,撤消,激活,去活,与数据库的连接等等重要的核心工作。JSP,Servlet,EJB,JNDI,JDBC,JMS.....
2、EJB与JAVA BEAN的区别?
答:Java Bean 是可复用的组件,对Java Bean并没有严格的规范,理论上讲,任何一个Java类都可以是一个Bean。但通常情况下,由于Java Bean是被容器所创建(如Tomcat)的,所以Java Bean应具有一个无参的构造器,另外,通常Java Bean还要实现Serializable接口用于实现Bean的持久性。Java Bean实际上相当于微软COM模型中的本地进程内COM组件,它是不能被跨进程访问的。Enterprise Java Bean 相当于DCOM,即分布式组件。它是基于Java的远程方法调用(RMI)技术的,所以EJB可以被远程访问(跨进程、跨计算机)。但EJB必须被布署在诸如Webspere、WebLogic这样的容器中,EJB客户从不直接访问真正的EJB组件,而是通过其容器访问。EJB容器是EJB组件的代理,EJB组件由容器所创建和管理。客户通过容器来访问真正的EJB组件。
3、EJB的基本架构
答:一个EJB包括三个部分:
Remote Interface 接口的代码
package Beans;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Add extends EJBObject
{
//some method declare
}
Home Interface 接口的代码
package Beans;
import java.rmi.RemoteException;
import jaax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface AddHome extends EJBHome
{
//some method declare
}
EJB类的代码
package Beans;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javx.ejb.SessionContext;
public class AddBean Implements SessionBean
{
//some method declare
}
J2EE,MVC方面
1、MVC的各个部分都有那些技术来实现?如何实现?
答:MVC是Model-View-Controller的简写。"Model" 代表的是应用的业务逻辑(通过JavaBean,EJB组件实现), "View" 是应用的表示面(由JSP页面产生),"Controller" 是提供应用的处理过程控制(一般是一个Servlet),通过这种设计模型把应用逻辑,处理过程和显示逻辑分成不同的组件实现。这些组件可以进行交互和重用。
2、应用服务器与WEB SERVER的区别?
希望大家补上,谢谢
3、J2EE是什么?
答:Je22是Sun公司提出的多层(multi-diered),分布式(distributed),基于组件(component-base)的企业级应用模型(enterpriese application model).在这样的一个应用系统中,可按照功能划分为不同的组件,这些组件又可在不同计算机上,并且处于相应的层次(tier)中。所属层次包括客户层(clietn tier)组件,web层和组件,Business层和组件,企业信息系统(EIS)层。
4、WEB SERVICE名词解释。JSWDL开发包的介绍。JAXP、JAXM的解释。SOAP、UDDI,WSDL解释。
答:Web Service描述语言WSDL
SOAP即简单对象访问协议(Simple Object Access Protocol),它是用于交换XML编码信息的轻量级协议。
UDDI 的目的是为电子商务建立标准;UDDI是一套基于Web的、分布式的、为Web Service提供的、信息注册中心的实现标准规范,同时也包含一组使企业能将自身提供的Web Service注册,以使别的企业能够发现的访问协议的实现标准。
5、BS与CS的联系与区别。
希望大家补上,谢谢
6、STRUTS的应用(如STRUTS架构)
答:Struts是采用Java Servlet/JavaServer Pages技术,开发Web应用程序的开放源码的framework。 采用Struts能开发出基于MVC(Model-View-Controller)设计模式的应用构架。 Struts有如下的主要功能:
一.包含一个controller servlet,能将用户的请求发送到相应的Action对象。
二.JSP自由tag库,并且在controller servlet中提供关联支持,帮助开发员创建交互式表单应用。
三.提供了一系列实用对象:XML处理、通过Java reflection APIs自动处理JavaBeans属性、国际化的提示和消息。
设计模式方面
1、开发中都用到了那些设计模式?用在什么场合?
答:每个模式都描述了一个在我们的环境中不断出现的问题,然后描述了该问题的解决方案的核心。通过这种方式,你可以无数次地使用那些已有的解决方案,无需在重复相同的工作。主要用到了MVC的设计模式。用来开发JSP/Servlet或者J2EE的相关应用。简单工厂模式等。
2、UML方面
答:标准建模语言UML。用例图,静态图(包括类图、对象图和包图),行为图,交互图(顺序图,合作图),实现图,
JavaScript方面
1、如何校验数字型?
var re=/^\d{1,8}$|\.\d{1,2}$/;
var str=document.form1.all(i).value;
var r=str.match(re);
if (r==null)
{
sign=-4;
break;
}
else{
document.form1.all(i).value=parseFloat(str);
}
CORBA方面
1、CORBA是什么?用途是什么?
答:CORBA 标准是公共对象请求代理结构(Common Object Request Broker Architecture),由对象管理组织 (Object Management Group,缩写为 OMG)标准化。它的组成是接口定义语言(IDL), 语言绑定(binding:也译为联编)和允许应用程序间互操作的协议。 其目的为:
用不同的程序设计语言书写
在不同的进程中运行
为不同的操作系统开发
LINUX方面
1、LINUX下线程,GDI类的解释。
答:LINUX实现的就是基于核心轻量级进程的"一对一"线程模型,一个线程实体对应一个核心轻量级进程,而线程之间的管理在核外函数库中实现。
GDI类为图像设备编程接口类库。
Hibernate: 简述 Hibernate 和 JDBC 的优缺点? 如何书写一个 one to many 配置文件.
Spring 的依赖注入是什么意思? 给一个 Bean 的 message 属性, 字符串类型, 注入值为 "Hello" 的 XML 配置文件该怎么写?
SCJP 模拟题200道附答案
Q1 Which of the following statements are valid, given the following variable declarations: boolean a; boolean b; int c;
1) (a | b)
2)(a || a)
3)(a ^ b) | c
4)(a & c)
5)(a && c)
Q2 Which of the following can be applied to constructors:
1) final
2) static
3) synchronized
4) native
5) None of these.
Q3 Which of the following retain their preferred size (width and height) when added (individually) to the North section of a container with a BorderLayout (assume that no other components or containers are present in the North section).
1) TextArea
2) Button
3) TextField
4) Checkbox
5) None. All of these mentioned components will only retain their preferred height.
Q4 Which of the following are legal names for variables.
1) _int
2) %large
3) $fred
4) Integer
5) 2much
Q5 Which of the following are correct ways to create a font.
1) Font f = new Font("Serif", Font.BOLD, 24);
2) Font f = new Font(Font.SERIF, "Bold", 24);
3) Font f = new Font("Serif", "Bold", 24);
4) Font f = new Font(Font.SERIF, Font.BOLD, 24);
Q6 Select the correct statements regarding the following piece of code.
File f = new File("c:\\large.txt");
1) On execution, a file called "large.txt" will be created on the local harddisk.
2) The code fails to compile on a UNIX machine, because the directory separator is not correct.
3) A file is NOT created on the harddisk when this code is executed.
4) An exception is thrown at runtime if the file "large.txt" already exists.
5) The code fails to compile, since this is not a valid constructor for the File class.
Q7 Which of the following statements are correct regarding the RandomAccessFile class?
1) An IOException is thrown if the specified file doesn't exist when created using the "r" mode.
2) This class has a method which allows a file to be deleted from the harddisk.
3) It is possible to use this class in conjunction with the DataInputStream class.
4) When used with the "rw" mode, the specified file is created on a diskdrive, if it doesn't already exist.
5) There are methods to read and write primatives (eg, readInt(), writeInt(), etc).
Q8 Consider the following piece of code and select the correct statement from the following.
1.String s = new String("abcdefgh");
2.s.replace('d', 'q');
3.System.out.println(s);
1) The code fails to compile, reporting an error at line 2. Strings are immutable, and therefore a replace() method is meaningless.
2) The code compiles correctly, and displays the text "abcqefgh".
3) The code compiles correctly, and displays the text "abcdefgh".
4) The code compiles, but an exception is thrown when line 2 is executed.
5) The code compiles, but an exception is thrown at line 3.
Q9 Which of the following keywords can be applied to the variables or methods of an interface.
1) static
2) private
3) synchronised
4) protected
5) public
Q10 True or False.
Only Frames can contain menu bars or pull-down menus.
1) True
2) False.
Q11 Consider the following piece of code and select the correct statement(s):
1. class A{
2. protected int method(){
3. }
4. }
5.
6. class B extends A{
7. int method(){
8. }
9. }
1) The code fails to compile, because you can't override a method to be more private than its parent.
2) The code fails to compile, because method() is declared as protected, and is therefore not available to any subclass.
3) The code compiles correctly, but throws a NullPointerException at runtime.
4) The code fails to compile. However, it can be made to compile correctly by prefixing line 7 with the access qualifier "public".
5) The code fails to compile. However, it can be made to compile correctly by prefixing line 7 with the access qualifier "protected".
Q12 True or False.
The Throwable class is the superclass of all exceptions in the Java language.
1) True
2) False
Q13 Consider the following piece of code (assume the Graphics context g is defined correctly):
g.setBackground(Color.red);
g.setForeground(Color.white);
g.drawLine(10, 10, 50, 10);
g.setForeground(Color.blue);
g.drawRect(100, 100, 50, 50);
What is displayed when this code is executed.
1) A blue line from (10,10) to (50,10) and a blue rectangle with upper left corner at (100,100).
2) A white line from (10,10) to (50,10) and a blue square with top left corner at (100,100).
3) A white line from (10,10) to (10,50) and a blue square with lower left corner at (100,100).
4) A red line from (10, 10) to (50,10) and a red square with upper left corner at (100,100).
5) Nothing is displayed. You must first issue a repaint() command.
Q14 Consider the following piece of code.
class Test{
public static void main(String [] args){
System.out.println(args[3]);
}
}
When the following is typed at the command line, what is displayed:
java Test Metallica Justice For All
1) All
2) For
3) Justice
4) Nothing.
5) Nothing. An ArrayIndexOutOfBoundsException is thrown
Q15 Consider the following piece of code.
1. String s = "abcd";
2. Integer x = new Integer(3);
3. String s2 = s + 4;
4. s2 = null;
5. s = null;
Following the execution of which line above, is the object referenced by s2 available for garbage collection.
1) Line 5
2) It is not possible to say when an object is available for garbage collection.
3) Line 4
4) The objects are not available until the executing thread is ended.
Q16 What is displayed when the following piece of code is compiled and executed:
class Test{
public static void main(String [] args){
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.method());
}
}
class Base{
int x = 2;
int method(){
return x;
}
}
class Subclass extends Base{
int x = 3;
int method(){
return x;
}
}
1) Nothing. The code fails to compile because the object b is not created in a valid way.
2) 2
3
3) 2
2
4) 3
3
5) 3
2
Q17 What is displayed when the following is executed:
String s1 = "aaa";
s1.concat("bbb");
System.out.println(s1);
1) The string "aaa".
2) The string "aaabbb".
3) Nothing. concat() is not a valid method in the String class.
4) The string "bbbaaa".
5) The string "bbb".
Q18 True or False.
The following is a valid way to construct a StringBuffer.
StringBuffer sb1 = "abcd";
1) True
2) False
Q19 What is the output of the following piece of code:
1. int x = 6;
2. double d = 7.7;
3.
4. System.out.println((x > d) ? 99.9 : 9);
1) 9
2) 9.0
3) 99.9
4) Nothing. An ArithmeticException is thrown at line 4.
5) 6
Q20 Which of the following can be put in applet tags? (select all the correct answers)
1) CODE
2) WIDTH
3) HEIGHT
4) PARAM
5) ARCHIVE
Q21 What is printed out following the execution of the code below:
1. class Test{
2. static String s;
3. public static void main(String []args){
4. int x = 4;
5. if (x < 4)
6. System.out.println("Val = " + x);
7. else
8. System.out.println(s);
9. }
10. }
Nothing. The code fails to compile because the String s isn't declared correctly.
1) The text "Val = null" is displayed.
2) The string "Val = " is displayed.
3) The text "null" is displayed.
4) A blank line of text is printed.
Q22 True or False.
The StringBuffer class does not have a concat() method.
1) True
2) False
Q23 What is displayed when the following piece of code is executed (assume the graphics context, g, is correctly set up):
g.drawString("abc", 10, 10);
1) The text "abc" with the lower left part of "a" located at x = 10, y = 10.
2) The text "abc" with the upper left part of "a" located at x = 10, y = 10.
3) Nothing. This is not a valid method.
Q24 True or False.
Anonymous classes cannot have constructors.
1) True
2) False
Q25 To reference a JAR from a web page, which of the following keywords are used:
1) jar
2) class
3) zip
4) archive
5) package
Q26
Analyse the following 2 classes and select the correct statements.
class A{
private int x = 0;
static int y = 1;
protected int q = 2;
}
class B extends A{
void method(){
System.out.println(x);
System.out.println(y);
System.out.println(q);
}
}
1) The code fails to compile because the variable x is not available to class B.
2) The code compiles correctly, and the following is displayed: 0 1 2
3) The code fails to compile because you can't subclass a class with private variables.
4) Removing the line "System.out.println(x)" will allow the code to compile correctly.
5) The compiler will complain that the variable x in class B is undefined.
Q27 Which of the following interfaces can be used to manage a collection of elements, with no duplication.
1) List
2) Vector
3) Set
Q28 Which of the following statements are true regarding inner classes.
1) Variables defined inside inner classes cannot be static.
2) Variables defined inside inner classes cannot be static unless the inner class itself is static.
3) Non-static inner classes (which are not defined in a method) have access to all class and instance variables, regardless of the access qualifier of those variables.
4) An inner class can actually be a subclass of the outer class
5) Inner classes can be declared as private. Top level, outer classes cannot.
Q29 Which of the following are valid ways to define an abstract method.
1) abstract void Test();
2) abstract void Test() {}
3) static abstract void Test();
4) final abstract void Test();
5) Methods cannot be defined as abstract, only variables can be abstract.
Q30 Consider the following:
class A extends Integer{
int x = 0;
}
Select all valid statements.
1) The code will compile correctly.
2) The code will not compile because Integer is final and cannot be subclassed.
3) The code will not compile because class A has no methods or constructor.
4) The code will compile correctly, but will throw an ArithmeticException at runtime.
Q31 Consider the following and select the correct statement(s):
interface A{
int x = 0;
A(){
x= 5;
}
A(int s){
x = s;
}
}
1) This is a valid piece of code and it compiles correctly.
2) The default constructor is not required since the compiler will create one for you.
3) The code fails to compile because interfaces cannot have more than 1 constructor.
4) The code fails to compile because an interface cannot have any constructors.
5) The code fails to compile, because a class must have more than 1 character in it's name.
Q32 True or False.
A try block always needs a catch or a finally block (either or both, but not none).
1) True
2) False
Q33 Which of the following are valid ways to declare the main() method which is used to start a Java program.
1) public static void main(String [] args)
2) static public void main(String [] args)
3) public void main(String args [])
4) public static void main(String args[])
5) public static void main(String args)
Q34 Consider the following piece of code:
boolean b = true;
System.out.println(b);
What is displayed when this code is executed?
1) The text "true" is displayed.
2) The text "1" is displayed
3) The code fails to compile, because conversion string conversion in ths System.out.println() method only applies to integers.
4) The code compiles but nothing is displayed upon execution.
5) The code fails to compile. However, changing the first line to "boolean b = TRUE;" will correctly declare a boolean, and the code will compile and display "TRUE".
Q35 Which of the following pieces of code compiles without any errors?
1) StringBuffer sb1 = "abcd";
2) Boolean b = new Boolean("abcd");
3) byte b = 255;
4) int x = 0x1234;
5) float fl = 1.2;
Q36 Which of the following are valid statements regarding the following piece of code?
1. String s1 = "abcd";
2. StringBuffer sb1 = new StringBuffer("abcd");
3. int val = 6;
4. System.out.println(s1 + val);
5. System.out.println(sb1 + val);
1) The text "abcd6" is displayed followed by "abcd6".
2) The code fails to compile because String conversion does not apply to StringBuffer.
3) The code compiles but upon execution, throws a NullPointerException at line 5.
4) The code fails to compile at line 2, because this is not a valid way to create a StringBuffer.
5) The code fails to compile at line 1, because this is not a valid way to create a String.
Q37 True or False.
Abstract methods can be declared as static.
1) True
2) False
Q38 FlowLayout is the default layout manager for which of the following containers:
1) Panel
2) Applet
3) Frame
4) Window
5) Dialog
Q39 In which class are the following methods defined:
- wait()
- notify()
- notifyAll()
1) Thread
2) Runnable
3) Object
4) Event
5) Synchronize
Q40 Which one of the following creates an instance of Vector with an initial capacity of 10, and an incremental capacity of 5.
1) new Vector(10, 5);
2) new Vector(5,10);
3) None. There is no constructor of Vector which provides this feature.
4) Vector is declared as final, and it is therefore not possible to instantiate it.
Q41 True of False.
CheckboxGroup is a subclass of Component.
1) True
2) False
Q42 Which statements(s) below are true about the following piece of code.
class Test implements Runnable{
public static void main(String [] args){
Thread t = new Thread(new Test());
t.start();
}
public void run(int limit){
for (int x = 0; x < limit; x++)
System.out.println(x);
}
}
1) All the numbers up to (but not including) "limit" are printed out.
2) Nothing is displayed. There is no explicit call to the run() method.
3) The code fails to compile because the Runnable interface is not implemented correctly.
4) The code can be made to compile by declaring the class Test to be abstract.
5) The code can be made to compile by removing the words "implements Runnable".
Q43 Consider the following code and select the statement(s) which are true:
1. class Test extends Frame{
2.
3. public static void main(String [] args){
4. Test t = new Test();
5. }
6.
7. Test(){
8. Button b = new Button("Hello");
9. add(b, BorderLayout.SOUTH);
10. }
11.
12. }
1) The code compiles. When executed, nothing is displayed.
2) The code compiles. When executed, a button with the text "Hello" is located at the bottom on the screen. The button is as tall as the text, but is the width of the frame.
3) Adding in the following two lines between lines 9 and 10 will display a frame with a button at the bottom of the frame: setSize(100, 100); setVisible(true);
4) The code fails to compile, because a layout manager was not specified.
5) The code fails to compile because you cannot subclass the Frame class.
Q44 Before which of the following can the keyword "synchronized" be placed, without causing a compile error.
1) class methods
2) instance methods
3) any block of code within a method
4) variables
5) a class
Q45 Consider the following class definitions:
class Base{}
class Subclass1 extends Base{}
class Subclass2 extends Base();
Now consider the following declarations:
Base b = new Base();
Subclass1 s1 = new Subclass1();
Subclass2 s2 = new Subclass2();
Now, consider the following assignment:
s1 = (Subclass1)s2;
Which of the following statements are correct regarding this assignment (select one).
1) The assignment is legal and compiles without an error. No exception is thrown at runtime.
2) The code fails to compile. The compiler complains that the assignment "s1 = (Subclass1)s2" is illegal.
3) The code compiles but ClassCastException is thrown at runtime.
4) The code fails to compile. You cannot subclass a parent class more than once.
Q46 Select all the valid ways of initialising an array.
1) int x[] = {1,2,3};
2) int []x[] = {{1,2,3},{1,2,3}};
3) int x[3] = {1,2,3};
4) int []x = {0,0,0};
5) char c[] = {'a', 'b'};
Q47 What is the valid declaration for the finalize() method.
1) protected void finalize() throws Throwable
2) final finalize()
3) public final finalize()
4) private boolean finalize()
5) private final void finalize() throws Exception
Q48 What is the method used to retrieve a parameter passed into an applet using the PARAM tag.
1) getParam()
2) getParameter()
3) getVariable()
4) getVar()
5) There is no method available. You must use "String [] args" approach.
Q49 You have a button, which is in a panel. The panel is inside a frame. You assign the Frame a 24-point font and a background colour of yellow. You set the panel to have a background colour of red. Which of the following statements are true (select all valid statements).
1) The font size of the button is 24-point.
2) The background colour of the button is the same as that of the frame.
3) The panel has a font size of 8-point.
4) The button inherits the font from the panel.
5) This is not a valid configuration. It is not valid to place a panel into a frame.
Q50 Consider the following piece of code and select the correct statement(s):
public class Test{
final int x = 0;
Test(){
x = 1;
}
final int aMethod(){
return x;
}
}
1) The code fails to compile. The compiler complains because there is a final method ("aMethod") in a non-final class.
2) The code compiles correctly. On execution, an exception is thrown when the Test() constructor is executed.
3) The code fails to compile because an attempt is made to alter the value of a final variable.
4) Removing the "final" keyword from the line "final int x = 0" will allow the code to compile correctly.
5) The code fails to compile because only methods can be declared as final (and therefore "final int x = 0" is not valid).
Q51 What is displayed when the following code fragment is compiled and executed (assume that the enveloping class and method is correctly declared and defined):
StringBuffer sb1 = new StringBuffer("abcd");
StringBuffer sb2 = new StringBuffer("abcd");
String s1 = new String("abcd");
String s2 = "abcd";
System.out.println(s1==s2);
System.out.println(s1=s2);
System.out.println(sb1==sb2);
System.out.println(s1.equals(sb1));
System.out.println(sb1.equals(sb2));
1) The code fails to compile, complaining that the line System.out.println(s1=s2); is illegal.
2) The code fails to compile because the equals() method is not defined for the StringBuffer class.
3) false
true
true
false
false
4) false
abcd
false
false
false
5) false
true
false
false
true
Q52 What is the default layout manager for applets and panels?
1) FlowLayout
2) BorderLayout
3) GridBagLayout
4) GridLayout
5) None of these
Q53 Which of the following statements will compile without an error?
1) Boolean b = new Boolean("abcd");
2) float f = 123;
3) byte b = 127;
4) int x = (int)(1.23);
5) short s = 128;
Q54 True or False.
Menus can be added to containers.
1) True
2) False
Q55 Which of the following statements are true regarding the graphical methods
paint(), repaint() and update().
1) paint() schedules a call to repaint().
2) repaint() schedules a call to update().
3) update() calls paint().
4) update() schedules a call to repaint().
5) repaint() calls paint() directly.
Q56 To which of the following can a menubar component be added?
1) Applet
2) Panel
3) Frame
4) Canvas
Q57 With regard to apply applet by HTML tags, which of the following statements are correct?
1) The CODE, WIDTH and HEIGHT tags are mandatory and the order is insignificant.
2) CODE and CODEBASE are case insensitive, and the .class extension is optional.
3) The PARAM tag is case insensitive.
4) It is possible to download multiple JAR's with the ARCHIVE tag (eg, ARCHIVE = "a.jar, b.jar").
5) The CODE tag is the only mandatory tag.
Q58 Consider the following piece of code and select the correct statements.
1. Object o = new String("abcd");
2. String s = o;
3. System.out.println(s);
4. System.out.println(o);
1) The following is displayed:
abcd
abcd
2) The code fails to compile at line 1.
3) The code fails to compile at line 2
4) The code fails to compile at line 4.
5) The code can be made to compile by changing line 1 to the following:
String o = new String("abcd");
Q59 Which of the following are legal methods for the String class?
1) length()
2) toUpper()
3) toUpperCase()
4) toString()
5) equals()
Q60 What is the output from the following piece of code:
loop1:
for(int i = 0; i < 3; i++){
loop2:
for(int j = 0; j < 3; j++){
if (i == j){
break loop2;
}
System.out.print("i = " + i + " j = " + j + " ");
}
}
1)
i = 1
j = 0
2)
i = 1
j = 0
i = 2
j = 1
3) i = 0
j = 1
i = 0
j = 2
i = 1
j = 0
i = 2
j = 0
i = 2
j = 1
4) i = 1
j = 0
i = 2
j = 0
i = 2
j = 1
5)
i = 1 j = 0 i = 2 j = 0 i = 2 j = 1
Q61 What is displayed when the following piece of code is executed:
loop1:
for(int i = 0; i < 3; i++){
loop2:
for(int j = 0; j < 3; j++){
if (i == j){
continue loop2;
}
System.out.println("i = " + i + " j = " + j);
}
}
1) i = 0 j = 0
i = 0 j = 1
i = 1 j = 0
i = 1 j = 1
i = 2 j = 0
i = 2 j = 1
2) i = 0 j = 0
i = 1 j = 1
i = 2 j = 2
3) i = 0 j = 1
i = 0 j = 2
i = 1 j = 0
i = 1 j = 2
i = 2 j = 0
i = 2 j = 1
4) None of the above.
Q62 Consider the following piece of code, and select the correct statement(s):
long val = 2;
...
...
Switch (val){
default:
System.out.println("Default");
break;
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
case 3:
System.out.println("3");
break;
}
1) The following is displayed:
2
3
2) The following is displayed:
2
3) The code fails to compile because the default case must be the last case in the switch statement.
4) The code fails to compile because the argument for a switch statement cannot be a variable of type long.
5) The following is displayed:
2
3
Default
Q63 Consider the following piece of code, and select the correct statement(s):
public class Test extends Applet{
public void init(){
setLayout(new GridLayout(1,2));
add(new Button("#1"));
add(new Button("#2"));
add(new Button("#3"));
add(new Button("#4"));
}
}
1) The Gridlayout is created with 1 row and 2 columns.
2) Adding the button with the label "#3" will cause an exception to be thrown.
3) Adding the button with label "#3" will cause it to overwrite the button with label "#2".
4) The layout automatically extends to accommodate the additional buttons.
5) Only 2 buttons are displayed, one with label "#1" and one with label "#4".
Q64 Which of the following layout managers will retain the preferred width and height of the contained components.
1) GridLayout
2) GridBagLayout
3) BoxLayout
4) FlowLayout
5)BorderLayout
Q65 You construct a List by calling List(5, false).
Which statements below are correct (assume the layout managers do not modify the List properties).
1) The list supports multiple selection.
2) The list has 5 visible items.
3) A vertical scroll bar will be added automatically if needed.
4) The code fails to compile. The given constructor is not a valid one.
Q66 Which of the following will definitely stop a thread from executing:
1) wait()
2) notify()
3) yield()
4) suspend()
5) sleep()
Q67 Which of the following is the correct method to call to change the layout manager for a container:
1) setLayoutManager()
2) setLayManager()
3) changeLayout()
4) You can't change the layout manager for a container.
5) setLayout()
Q68 Which is the correct way to add a button, referenced by b, to a panel, referenced by p.
1) add(p, b);
2) p.add(b)
3) b.add(p)
4) Buttons can't be added to panels.
5) add(p)
Q69 What is displayed when the following code is compiled and executed:
long val = 2;
switch(val){
case 1:
System.out.println("1");
case 2:
System.out.println("2");
default:
System.out.println("default");
}
1) default
2) 2
default
3) The code fails to compile because there are no break statements in the case clauses.
4) The code fails to compile because a long data type is not a valid parameter for a switch statement.
Q70 What is displayed following the execution of the code below:
1. class Test{
2. String s;
3. public static void main(String []args){
4. int x = 4;
5. if (x < 4)
6. System.out.println("Val = " + x);
7. else
8. System.out.println(s);
9. }
10. }
1) Nothing. The code doesn't compile because the variable s wasn't initialised.
2) The string "null" is displayed.
3) The code runs, but a NullPointerException is thrown at line 8.
4) The code compiles. No exception is thrown but nothing is displayed.
5) Nothing. The code doesn't compile because you can't make a static reference to a non-static variable.
Q71 Consider the following piece of code:
class Test{
int x;
String s;
float fl;
boolean [] b = new boolean [5];
public static void main(String []args){
System.out.println(x);
System.out.println(s);
System.out.println(fl);
System.out.println(b[2]);
}
}
What is displayed when this code is executed.
1) 0
null
0.0
false
2) 0
" "
0.0
true
3) Nothing. The code fails to compile because the boolean array is incorrectly declared.
4) Nothing. The code will not compile because the static method cannot access the variables since there is no instance of the Test class.
Q72 What is displayed when the following code is compiled and executed:
String s = "abcd";
String s1 = new String(s);
if (s == s1)
System.out.println("the same");
if (s.equals(s1))
System.out.println("equals");
1) the same
equals
2) equals
3) the same
4) The code compiles, but nothing is displayed upon execution.
5) The code fails to compile.
Q73 What is the legal range for the byte data type:
1) 0 to +255
2) -127 to +128
3) -128 to +127
4) 0 to 65535
5) -32767 to +32768
Q74 What is displayed when the following code is executed:
String s = "abcdef";
System.out.println(s.charAt(4));
1) d
2) e
3) Nothing. An ArrayIndexOutOfBoundsException is thrown
4) The code does not compile. charAt() is not a valid method of the String class.
5) The code does not compile because the string s is not created correctly.
Q75 True or False.
The String class does not have an append() method.
1) True
2) False
Q76 Consider the following code segment.
double d = -11.1;
double d1 = method(d);
System.out.println(d1);
If the output of this code segment is -12.0, then what methods could be called in method() above.
1) floor()
2) ceil()
3) round()
4) abs()
5) min()
Q77 What outputs are possible from invoking Math.random().
1) -0.12
0.56E3
2) 0.12
1.1E1
3) -23.45
0.0
4) 0.356
0.03
5) 1.00
0.99
Q78 In a thread, the wait() method must be called inside which of the following:
1) A while() loop
2) The run() method
3) synchronised code
4) The constructor
5) It doesn't matter where the wait() is called from.
Q79 Consider the following piece of code:
public class Test extends Applet{
public void init(){
setLayout(new BorderLayout());
add("South", new Button("B1"));
add("North", new Button("B2"));
add("South", new Button("B3"));
}
}
Select the correct statements regarding the above.
1) There are 2 buttons displayed in the SOUTH section, B1 and B3.
2) Only B3 is displayed in the SOUTH section.
3) An exception is thrown when an attempt is made to add a second component to SOUTH.
4) Only B1 is displayed in the SOUTH section.
5) You can't add buttons to applets.
Q80 What is displayed when the following piece of code is executed:
1. String val = null;
2. int x = Integer.parseInt(val);
3.
4. System.out.println(x);
1) 0
2) null
3) A NumberFormatException is thrown at line 2.
4) Nothing is displayed
Q81 Consider the following piece of code:
class A{
int x = 0;
A(int w){
x = w;
}
}
class B extends A{
int x = 0;
B(int w){
x = w +1;
}
}
1) The code compiles correctly.
2) The code fails to compile, because both class A and B do not have valid constructors.
3) The code fails to compile because there is no default no-args constructor for class A.
Q82 Given an object myListener (whose class implements the ActionListener interface), which of the following are valid ways to enable myListener to receive all action events from component smallButton?
1) smallButton.add(myListener);
2) smallButton.addListener(myListener);
3) smallButton.addActionListener(myListener);
4) smallButton.addItem(myListener);
Q83 Which of the following are valid listener interfaces?
1) ActionListener
2) MouseMotionListener
3) SystemEventListener
4) MouseClickListener
5) WindowListener
Q84 Which of the following is the correct way to set the foreground colour of a component, c.
1) c.setForeground("red");
2) c.setColor("Color.red");
3) c.Foreground(Color.red);
4) c.setForegroundColor("red");
5) c.setForeground(Color.red);
Q85 Which of the following are valid ways to create a Map collection.
1) Map m = new Map();
2) Map m = new Map(init capacity, increment capacity);
3) Map m = new Map(new Collection());
4)Map is an interface, and cannot be instantiated.
Q86 Select all the correct statements relating to the following piece of code?
1. public class A{
2. abstract int method();
3. void anotherMethod(){
4. }
5.
6. class B extends A{
7. int method(){
8. return 2;
9. }
10. }
1) Changing "extends" to "implements" on line 6 will allow the code to compile correctly.
2) The method() in class A cannot be abstract without the entire class being declared as abstract.
3) Declaring class A to be abstract will allow the code to compile correctly.
4) The class A must have an explicit default constructor in order for it to be subclassed correctly.
5) The code fails to compile, because class B does not implement anotherMethod().
Q87 Which layout manager do the comments below refer to:
All components contained in it have the same width and height. Contained components are stretched to have the same dimensions.
1) FlowLayout
2) BorderLayout
3) GridLayout
Q88 Select all valid statements.
1) When typing text into a TextField, scroll bars will automatically appear when the TextField becomes full.
2) When typing text into a TextArea, scroll bars will appear when text is typed past the boundaries of the TextArea.
3) TextFields can have more than 1 row of text.
4) The class TextArea is a super class of the class TextField.
5) Both TextAreas and TextFields have a method called setEditable(), which can enable or disable editing of the component.
Q89 In which class is the paint() method defined?
1) Object
2) Applet
3) Component
4) Thread
5) Graphics
Q90 Select the statement which most closely describes the user interface of an applet with the following init() method:
public void init(){
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(new Button("Hello"), BorderLayout.EAST);
p.add(new Button("Bye"), BorderLayout.WEST);
add(p);
}
1) Two buttons are displayed. A button with "Hello" is on the right side of the applet. The button with "Bye" is on the left side of the applet. Both buttons extend from the centre of the applet to each side, and are the height of the applet.
2) Two buttons are displayed. A button with "Hello" is on the right side of the applet. The button with "Bye" is on the left side of the applet. Both buttons are only as wide as the text on the button, but are the height of the applet.
3) Two buttons are displayed. A button with "Hello" is on the right side of the applet. The button with "Bye" is on the left side of the applet. Both buttons are only large enough to support the associated button texts.
Q91 What is wrong about the following piece of code (assume the relevant import statements are present):
public class Test{
public static void main (String [] args) throws IOException{
if (args[0] == "hello")
throw new IOException();
}
}
1) Nothing. The code compiles correctly.
2) The code fails to compile. You can't throw an exception from the main() method.
3) The code fails to compile. IOException is a system exception, and cannot be thrown by application code.
Q92 Consider the following piece of code, and select the statements which are true.
class Test{
int x = 5;
static String s = "abcd";
public static void method(){
System.out.println(s + x);
}
}
1) The code compiles and displays "abcd5".
2) The code compiles, but throws an exception at runtime, because variable x isn't declared as static.
3) The code fails to compile because you can't make a static reference to a non-static variable.
4) The code will compile if x is declared to be static.
5) The code will compile by removing the static keyword from the declaration of method().
Q93 Select all legal code fragments from the following.
1) char c = "c";
2) Boolean b = new Boolean("qwerty");
3) String s = "null";
4) int q;
for (int p = 0, q = 0; p < 5; p++){
System.out.println("Val = " + p + q);
}
5) int x = 3;
Float f = new Float(x);
Q94 Which of the following are legal ways to construct a RandomAccessFile?
1) RandomAccessFile("file", "r");
2) RandomAccessFile("r", "file");
3) RandomAccessFile('r', "file");
4) RandomAccessFile("file", 'r');
5) RandomAccessFile("file", "rw");
Q95 Consider the following code and select the most appropriate statements.
1. class Test{
2. public int doubleValue(int a)
3. System.out.println(a);
4. return (int)(a * 2);
5 }
6.
7 public float doubleValue(int a){
8. System.out.println(a);
9. return (float)(a * 2);
10. }
11.}
1) The code compiles since the two doubleVal() methods have different return types.
2) The code doesn't compile because the compiler sees two methods with the same signature.
3) The code can be made to compile by redefining the parameter for doubleVal() on line 7 to be "float a" instead of "int a".
4) The code can be made to compile by replacing the public declaration on line 7 with private.
Q96 What is displayed when the following piece of code is executed:
class Test extends Thread{
public void run(){
System.out.println("1");
yield();
System.out.println(2");
suspend();
System.out.println("3");
resume();
System.out.println("4");
}
public static void main(String []args){
Test t = new Test();
t.start();
}
}
1) 1
2
3
4
2) 1
2
3
3) 1
2
4) Nothing. This is not a valid way to create and start a thread.
5) 1
Q97 Consider the following piece of code, and select the most appropriate statements.
TextField t = new TextField("Hello", 20);
1) The user will be able to edit the string.
2) The field will be 20 characters wide.
3) The text field will be same size on all platforms, since Java is platform independent.
4) When entering text into the field, only 20 characters can be entered.
5) If the font is changed, the size of the textfield will adjust to allow 20 characters to be displayed.
Q98 True of False.
Using the instanceof operator on an interface will cause a runtime exception.
1) True
2) False
Q99 Which of the following are valid ways to create a Button component?
1) new Button();
2) new Button(30, 10); where 30 is the width of the button and 10 is the height
3) new Button("hello");
4) new Button(new String("hello"));
5) new Button(String("hello"));
Q100 Which of the following are NOT valid subclasses of AWTEvent?
1) MouseClickEvent
2) OutputEvent
3) MouseMotionEvent
4) KeyAdapter
5) WindowMinimizeEvent
Q101 Which of the following are valid methods for the Graphics class?
1) drawOval(int x, int y, int width, int height)
2) toString()
3) drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
4) drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
5) fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Q102 Which of the following are valid methods in the Math class?
1) arcTan(double a)
2) atan(double a)
3) sqrt(double a)
4) min(int a, int b)
5) cosine(double a)
Q103 Which of the following will display the string "ica", given:
String s = "Metallica";
1) System.out.println(s.subString(7));
2) System.out.println(s.substring(6));
3) System.out.println(s.subString(6, 8));
4) System.out.println(s.substring(7, 9));
5) None of these.
Q104 Which of the following are defined in the Object class?
1) toString()
2) equals(Object o)
3) public static void main(String [] args)
4) System.out.println()
5) wait()
Q105 Select all valid statements relating to the paint() method defined in the Component class.
1) It takes 4 int types as parameters, representing the x and y co-ordinates, width and height, respectively.
2) It is declared as final, and so it cannot be overridden.
3) It is declared as static.
4) It takes an instance of the Graphics component as a parameter.
5) When overriding the paint() method, you must handle the identification and repair of damaged components.
Q106 Which of the following keywords can be applied to a method?
1) transient
2) volatile
3) private
4) protected
5) final
Q107 Which of the following keywords can be applied to a top-level class (i.e., not an inner class)?
1) private
2) protected
3) transient
4) public
5) final
Q108 Consider the following piece of code, and select all relevant statements:
1. class Test{
2. public static void main(String [] args){
3. aMethod();
4. }
5.
6. static void aMethod(){
7. try{
8. System.out.println("abcd");
9. return;
10. } finally {
11. System.out.println("1234");
12. }
13. }
14.}
1) An exception is thrown at line 9.
2) The code fails to compile. The compiler complains about the return statement at line 9.
3) abcd
1234
4) abcd
5) The code fails to compile, complaining that a 'catch' clause is missing from line 10.
Q109 Which of the following statements are true.
1) The type "int" is a 32-bit signed integer value.
2) The type "short" is a 16-bit unsigned integer value.
3) The type "char" is a 16-bit Unicode character.
4) The type "float" is a 64-bit floating point value.
5) The type "long" is a 64-bit signed integer value.
Q110 Which layout manager is described by the following:
It aligns components vertically and horizontally, without requiring that the components be of the same size. It maintains a dynamic rectangular grid of cells, with each component occupying one or more cells, called its display area.
1) GridLayout
2) FlowLayout
3) GridBagLayout
4) BoxLayout
Q111 True of False.
The StringBuffer class overrides the toString() method to return a String representation of the StringBuffer.
1) True
2) False
Q112 Select the correct statements from the following:
1) The class RandomAccessFile is a subclass of the java.io.File class.
2) The class java.io.FileWriter contains methods to write primitives (eg, writeInt(), writeFloat(), etc)
3) The class java.io.BufferedOutputStream contains methods to write primitives (eg, writeInt(), writeFloat(), etc)
4) The File class defines a method which can be used to delete files and directories from a disk.
5) The RandomAccessFile class defines a method which can be used to delete files and directories from a disk.
Q113 True or False.
A class can implement more than one interface, but can only inherit from a single parent class.
1) True
2) False
Q114 What is the result of compiling and executing the following code.
public class ThreadTest extends Thread {
public void run() {
System.out.println("In run");
yield();
System.out.println("Leaving run");
}
public static void main(String args []) {
(new ThreadTest()).start();
}
}
1) The code fails to compile in the main() method.
2) The code fails to compile in the run() method.
3) Only the text "In run" will be displayed.
4) The text "In run" followed by "Leaving run" will be displayed.
5) The code compiles correctly, but nothing is displayed.
Q115 Which of the following will compile without errors.
1) Byte b = new Byte(123);
2) Byte b = new Byte("123");
3) Byte b = new Byte();
b = 123;
4) Byte b = new Byte((int)123.4);
5) Byte b = new Byte(0x123);
Q116 Consider the following piece of code and select the correct statement(s):
1. public class Test{
2. static int x;
3. static public void main(String [] args){
4. x = x + 1;
5. System.out.println("Value is " + x);
6. }
7. }
1) The code fails to compile. The compiler complains that the variable x is used before it is initialised.
2) The code compiles correctly and displays "Value is 1" when executed.
3) The code compiles correctly, but throws a NullPointerException at line 5.
4) The code fails to compile because the 'main' method is incorrectly declared.
Q117 Which of the following are termed "short circuit" logical operators.
1) &
2) &&
3) |
4) ||
5) ^
Q118 Which of the following are valid expressions.
1) Object o = new String("abcd");
2) Boolean b = true;
3) Panel p = new Frame();
4) Applet a = new Panel()
5) Panel p = new Applet()
Q119 Which of the following is a valid way to declare an abstract method which is intended to be public.
1) public abstract method();
2) public abstract void method();
3) public abstract void method(){}
4) public virtual void method();
5) public void method() implements abstract;
Q120 Which of the following are valid ways to define a constructor for class Test.
1) public void Test(){}
2) public Test(){}
3) private Test(){}
4) public static Test(){}
5) final Test(){}
Q121 Which of the following statements are valid for a method which is overriding the following:
protected void method(int x){..}
1) The overriding method must take an int as its only parameter.
2) The overriding method must return a void.
3) The overriding method can be declared as private.
4) The overriding method can return any value it wishes.
Q122 True or False.
An inner class can implement an interface or extend a class.
1) True
2) False
Q123 Which of the following are valid return types for listener methods.
1) boolean
2) void
3) An object of type Event
4) An object of type Object
5) A long value, representing the Object ID.
Q124 Consider the following piece of code and select the correct statements.
1. public class Test{
2. public static void main(String [] args){
3. print();
4. }
5.
6. public static void print(){
7. System.out.println("Test");
8. }
9.
10. public void print(){
11. System.out.println("Another Test");
12 }
13. }
1) The code compiles successfully and displays "Test".
2) Changing the code at line 10 to the following, will allow the code to compile correctly:
public void print(int x){
3) The code fails to compile. The compiler complains about a static reference to a non-static method, print().
4) The code fails to compile. The compiler complains about duplicate methods.
5) Changing the return type on line 10 from 'void' to 'int' will allow the code to compile correctly.
Q125 Consider the following list of tags and attributes of tags and select the ones which can legally be placed between the APPLET and /APPLET delimiters.
1) JAVAC
2) JAR
3) CODE
4) NAME
5) PARAM
Q126 Which variables can an inner class access from the class which encapsulates it.
1) All static variables
2) All final variables
3) All instance variables
4) Only final instance variables
5) Only final static variables
Q127 Using a FlowLayout manager, which of the following is the correct way to add a conponent referenced by the variable "c" to a container:
1) add(c);
2) add("Center", c);
3) c.add();
4) c.set();
5) set(c);
Q128 Assuming there is a class X which implements the ActionListener interface.
Which method should be used to register this with a Button?
1) addListener(new X());
2) addActionListener(new X());
3) addButtonListener(new X());
4) addActionAdapter(new X());
5) (new X()).addActionListener();
Q129 What is the result of compiling and executing the following fragment of code:
boolean flag = false;
if (flag = true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
1) The code fails to compile at the "if" statement.
2) An exception is thrown at run-time at the "if" statement.
3) The text "true" is displayed.
4) The text "false" is displayed.
5) Nothing is displayed.
Q130 Which of the following is not a subclass of java.awt.Component?
1) Frame
2) Container
3) CheckboxGroup
4) Canvas
5) Applet
Q131 What is the result when the following piece of code is compiled and executed.
1. public class Calc {
2. public static void main (String args []) {
3. int total = 0;
4.
5 . for (int i = 0, j = 10; total < 30; ++i, --j) {
6. System.out.println(" i = " + i + " : j = " + j);
7.
8. total += (i + j);
9.
10. }
11.
12. System.out.println("Total " + total);
13. }
14. }
1) The code fails to compile at line 5, because the variable "j" is not declared correctly.
2) The code fails to compile at line 2, because you can't have a static method in a non-static class.
3) The code compiles correctly, but throws an exception at line 5.
4) The code compiles correctly but throws an exception at line 2.
5) The code compiles correctly and displays the following when executed:
i = 0 : j = 10
i = 1 : j = 9
i = 2 : j = 8
Total 30
Q132 Which of the following will create a TextField capable of displaying 10 characters, with the initial text "hello"?
1) TextField t = new TextField("hello", 10);
2) TextField t = new TextField(10, "hello");
3) TextField t = new TextField();
t.setCols(10);
t.setText("hello");
4) TextField t = new TextField();
t.setFieldSize(10);
t.setText("hello");
5) None of the above.
Q133 What is the effect of adding the sixth element to a Vector created using the following code:
new Vector(5, 10);
1) An IndexOutOfBounds exception is thrown.
2) The vector grows in size to a capacity of 10 elements.
3) The vector grows in size to a capacity of 15 elements.
4) Nothing. The Vector will have grown when the fifth element was added, because Vector elements are zero-based.
5) Nothing. This is not a valid way to create a Vector.
Q134 When is the text "Hi there" displayed?
public class StaticTest {
static {
System.out.println("Hi there");
}
public void print() {
System.out.println("Hello");
}
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}
}
1) Never.
2) Each time a new object of type StaticTest is created.
3) Once when the class is loaded into the Java virtual machine.
4) Only when the main() method is executed.
Q135 Which of the following are valid ways to assign the value of 5 to a variable of type "int" called testValue?
1) int testValue = 0x5;
2) int testValue = (int)(2.1F + 3.4D);
3) int testValue = (octal)5;
4) int testValue = (0x0A >> 1);
5) int testValue = (0x0A >>> 1);
Q136 Which of the following operations will cause an ActionEvent to be generated.
1) Clicking a checkbox.
2) Selecting an option from a Choice box.
3) Scrolling a scroll bar.
4) Clicking a button.
5) Hitting ENTER when typing in a text field.
Q137 True or False.
All Listener interfaces methods are declared as public and void.
1) True
2) False
Q138 True or False.
In a GridLayout, the width and height of all cells are the same.
1) True
2) False
Q139 True or False.
The BorderLayout manager only allows a single component to be displayed in each sector.
1) True
2) False
Q140 You want to extend the functionality of the String class, and decide that the best approach is to subclass String. Which of the following statements are correct.
1) The approach fails, because the String class is declared as final and cannot be subclassed.
2) The approach succeeds, and it is therefore possible to override the standard functionality provided by String.
3) The approach fails, because the String class is declared as abstract, and therefore it cannot be subclassed.
Q141 Which of the following are valid ways to determine the number of elements in an array defined as follows:
int intArray[] = {1,2,3};
1) intArray.size;
2) intArray.size();
3) intArray.length;
4) intArray.length();
5) intArray.getSize();
Q142 You have a check box within a panel, and the panel is contained within an applet. There are no other components within the applet.
Using "setBackground(Color.white)", you assign the background colour of the applet to white.
Which of the following statements are true.
1) The background colour of the panel is white.
2) The foreground colour of the checkbox is the same as the foreground colour of the applet.
3) It is impossible to determine the background colour of the checkbox from the imformation supplied.
4) You can't put a panel inside an applet.
Q143 Which of the following can be added to a menu?
1) A panel
2) A button
3) A menu
4) A checkbox
5) A menubar
Q144 You construct an application by making the following call:
Frame app = new Frame();
app.setSize(100,100);
Which of the following statements are correct.
1) An empty frame of size 100x100 is displayed, located in the top left corner of the screen.
2) An empty frame of size 100x100 is displayed, located in the centre of the screen.
3) Nothing is displayed. There is no setSize() method in the Frame class.
4) Nothing is displayed. The frame will only be displayed by setting the forground and background colours.
5) Nothing is displayed. A frame is created by default with zero size, and invisible.
Q145 Which of the following are valid methods in the java.awt.Graphics class?
1) drawString()
2) drawOval()
3) fillRect()
4) drawPolyline()
5) fillPolyline()
Q146 Which of the following are valid command line options for the JAR utility:
1) c (create a new or empty archive)
2) m (indicates that first argument is the name of a user-supplied manifest)
3) M (do not create a manifest)
4) z (ZIP the contents of the archive)
5) L (list the archive contents)
Q147 Consider the following code segment and select the correct statement(s):
1. class FinalTest{
2. final int q;
3. final int w = 0;
4.
5. FinalTest(){
6. q = 1;
7. }
8.
9. FinalTest(int x){
10. q = x;
11. }
12. }
1) The code fails to compile because a class cannot have more than 1 constructor.
2) The code fails to compile because the class FinalTest has no constructors.
3) The code fails to compile because the an attempt is made to initialise a final variable at lines 6 and 10.
4) The code compiles correctly without any warnings or errors.
5) The code fails to compile because the final variable q is not initialised correctly at line 2.
Q148 True or False.
It is valid to throw (and re-throw) an exception inside a catch{} clause.
For example:
...
catch (Exception e){
throw e;
}
1) True
2) False
Q149 True or False.
A scrollbar will appear in a TextField if more text is typed than can be displayed within the TextField.
1) True
2) False
Q150 True or False.
It is valid to declare an inherited method as abstract.
1) True
2) False
Q151 Consider the following code segments and select the correct statement:
Segment 1:
1. int a = 3;
2. int b = 0;
3. int c = a/b;
Segment 2:
4. float a = 1.0F;
5. float b = 0.0F;
6. float c = a/b;
1) When executed, both segments will cause an exception to be thrown.
2) When executed, neither segment will cause an exception to be thrown.
3) Only Segment 1 will throw an exception.
4) Only Segment 2 will throw an exception.
Q152 Which of the following classes override the equals() method.
1) String
2) Integer
3) Double
4) Date
5) File
Q153 Which of the following is the default layout manager for a panel.
1) BorderLayout
2) FlowLayout
3) GridBagLayout
4) GridLayout
5) None of the above.
Q154 True or False.
The StringBuffer class inherits from the String class.
1) True
2) False
Q155 True or False.
The class String has a concat() method, while the StringBuffer class has an append() method.
1) True
2) False
Q156 True or False.
The primative wrapper classes Integer, Double and Float all inherit directly from the java.lang.Wrapper class.
1) True
2) False
Q157 Which of the following are valid methods for the Applet class.
1) start()
2) stop()
3) init()
4) destroy()
5) kill()
Q158 True or False.
A label can only display a single line of text.
1) True
2) False
Q159 Which of the following are valid methods for the Math class.
1) random()
2) Random()
3) toDegrees()
4) square()
5) sqr()
Q160 True or False.
JDK 1.2 contains an Arrays class which provides various methods for manipulating arrays (such as searching and sorting).
1) True
2) False
Q161 True or False.
The Class class has no public constructor.
1) True
2) False
Q162 Which of the following statements is true with regard to persistence.
1) "Serializable" is a keyword within the Java language.
2) "Serializable" is an interface, which classes can implement.
3) "Serializable" is a class, which other classes can extend.
4) None of the above.
Q163 Which of the following statements is correct with regard to threads.
1) "Runnable" is a keyword within the Java language, used to identify classes which can exist as separate threads.
2) "Runnable" is an interface, which classes can implement when they wish to execute as a separate thread.
3) "Runnable" is a class, which classes can extend when they wish to execute as a separate thread.
4) None of the above.
5) java does not support threads.
Q164 Select the statements which are valid from the list below.
1) The primative data type "char" is 16-bits wide.
2) Unicode uses 16-bits to represent a character.
3) Unicode uses 32-bits to represent a character.
4) UTF uses 24-bits to represent a character.
5) UTF uses as many bits as are needed to represent a character.
Q165 When a Frame is constructed, it has no size and is not displayed. Which of the following methods can be called to display the Frame.
1) setSize()
2) setBounds()
3) setDisplayable()
4) setVisible()
5) setState()
Q166 Which one of the following is correct (assume A and B are correctly defined).
1) if (A instanceOf B)
2) if (A instanceof B)
3) if (A.instanceOf(B))
4) if (A instanceof(B))
Q167 What is displayed when the following is executed:
double d1 = -0.5;
System.out.println("Ceil d1 = " + Math.ceil(d1));
System.out.println("floor d1 = " + Math.floor(d1));
1) Ceil d1 = -0.0
floor d1 = -1.0
2) Ceil d1 = 0.0
floor d1 = -1.0
3) Ceil d1 = -0.0
floor d1 = -0.0
4) Ceil d1 = 0.0
floor d1 = 0.0
5) Ceil d1 = 0
floor d1 = -1
Q168 Select the layour manager which is described by the following:
"It arranges its constituent components in horizontal rows. It will attempt to fit as many components as possible into the first row, and remaining components will spill over into subsequent rows. Components always appear left to right, in the order they were added to the container."
1) FlowLayout
2) GridLayout
3) CardLayout
4) TransverseFlowLayout
5) GridBagLayout
Q169 True or False
The argument for a "case" statement must be a constant or a constant expression which can be evaluated at compile time.
1) True
2) False
Q170 Select the valid code fragments from the following list:
1) public transient static final int _FRAMEX = 850;
2) this("a", "b");
[assuming a constructor of the type xxx(String, String) exists for this class]
3) private transient static final int _FRAMEX = 850;
4) boolean b = 0;
Q171 True or False.
The File class can represent either a file or a directory within a file system.
1) True
2) False
Q172 True or False.
The argument for a while() statement MUST be a boolean.
1) True
2) False
Q173 True or False.
The right-hand operand of the instanceof operator can be an interface; eg
a instanceof b
where b is an interface.
1) True
2) False
Q174 Consider the following class:
public class Test{
public int secret;
}
Which of the following is the correct way to make the variable 'secret' read-only.
1) Declare 'secret' to be private.
2) Declare the class Test to be private.
3) Declare 'secret' to be private and write a method getSecret() which returns the value of 'secret'.
4) Declare 'secret' to be transient.
5) Declare 'secret' to be static.
Q175 Which one of the following methods of the Math class can be used to find the square root of a number.
1) squareRoot()
2) sqrt()
3) root()
4) sqr()
5) None of the above. You use the pow() method.
Q176 To which layout manager does the following statement refer:
"it preserves the preferred size (width and height) of each component".
1) Flow Layout
2) Border Layout
3) Grid Layout
4) Grid Bag Layout
5) None of the above. All layout managers alter the dimensions of their containing components.
Q177 Consider the following code fragment, and select the correct statements(s):
1. public class Test extends MyBase implements MyInterface{
2. int x = 0;
3.
4. public Test(int inVal) throws Exception{
5. if (inVal != this.x){
6. throw new Exception("Invalid input");
7. }
8. }
9.
10. public static void main(String args[]){
11. Test t = new Test(4);
12. }
13.}
1) The code fails to compile at line 1. It is not valid to both implement an interface and extend from a parent class simultaneously.
2) The code fails to compile at line 4. It is not valid for constructors to throw exceptions.
3) The code fails to compile at line 6, because this is not valid way to throw an exception.
4) The code fails to compile at line 11. The compiler complains that there is an uncaught exception.
5) The code fails to compile at line 5, because this is not a valid way to reference variable x.
Q178 Consider the following real-life relationships, and select the code fragment which most closely represents it.
An employee is a person. An employee has zero or more dependants.
[for the code fragments, assume that all relevant packages are imported, and all relevant class definitions exist].
1) class Employee extends Dependants{
Person p;
}
2) class Person extends Employee{
Vector dependants;
}
3) class Employee extends Person{
Vector dependants;
}
4) abstract class Person extends Dependants{
Employee e;
}
5) class Dependant implements Employee{
Vector person;
}
Q179 Which of the following are valid declarations for a native method.
1) public native void aMethod();
2) private native String aMethod();
3) private native boolean aMethod(int val){};
4) public native int aMethod(String test);
5)private native boolean aMethod(boolean flag, Integer val);
Q180 Which of the following are valid ways to define an octal literal of value 17 (octal).
1) private final int theNumber = 0x17;
2) private final int theNumber = 017;
3) public int theNumber = 017;
4) public int theNumber = (octal)17;
5 )public int THE_NUMBER = 017;
Q181 Consider the following piece of code and select all statements which yield a boolean value of true as a result.
Double d1=new Double(10.0);
Double d2=new Double(10.0);
int x=10;
float f=10.0f;
1) d1 == d2;
2) d1 == x;
3) f == x;
4) d1.equals(d2);
5) None of the above
Q182 Given the following definition:
String s = null;
Which code fragment will cause an exception of type NullPointerException to be thrown.
1) if ((s != null) & (s.length()>0))
2) if ((s != null) && (s.length()>0))
3) if ((s != null) | (s.length()>0))
4) if ((s != null) || (s.length()>0))
5) None of the above.
Q183 Which of the following are valid declarations for a 2x2 array of integers.
1) int a[][] = new int[10,10];
2) int a[][] = new int [10][10];
3) int a[10,10] = new int [10][10];
4) int [][]a = new int [10][10];
5) int []a[] = new int [10][10];
Q184 Which values of variable x will show "Message 2".
switch(x)
{
case 1 :
System.out.println("Message 1");
case 2 :
case 3 :
System.out.println("Message 2");
default :
System.out.println("End");
}
1) 1
2) 2
3) 3
4) 4
5) none
Q185 What is the result of the following code :
public class SuperEx {
String r;
String s;
public SuperEx(String a,String b) {
r = a;
s = b;
}
public void aMethod() {
System.out.println("r :" + r);
}
}
public class NewSuper extends SuperEx {
public NewSuper(String a,String b) {
super(a,b);
}
public static void main(String args []) {
SuperEx a = new SuperEx("Hi","Tom");
SuperEx b = new NewSuper("Hi","Bart");
a.aMethod();
b.aMethod();
}
public void aMethod() {
System.out.println("r :" + r + " s:" + s);
}
}
1) The following is displayed:
r:Hi
s:Hi
2) Compiler error at the line "SuperEx b = new NewSuper("Hi","Bart");"
3) The following is displayed:
r:Hi
r:Hi s:Bart
4) The following is displayed
r:Hi s:Tom
r:Hi s:Bart
Q186 You have a class with a certain variable and you don't want that variable to be accessible to ANY other class but your own. Your class must be sub-classable.
Which keyword do you add to the variable.
1) private
2) public
3) transient
4) final
5) abstract
Q187 You get this description of a class :
Employee is a person. For every employee, we keep a vector with the working hours, an integer for the salary and a variable that can be true or false whether or not the employee has a company car.
Indicate which of the following would be used to define the class members.
1) Vector
2) Employee
3) Object
4) boolean
5) int
Q188 Which line of code can be inserted in place of the comments, to perform the initialisation described by the comments:
public class T {
int r;
int s;
T(int x, int y) {
r = x;
s = y;
}
}
class S extends T {
int t;
public S(int x, int y, int z){
// insert here the code
// that would do the correct initialisation
// r= x and s= y
t=z;
}
}
1) T(x, y);
2) this(x, y);
3) super(x, y);
4) super(x, y, z);
5) None
Q189 Suppose a MyException should be thrown if Condition() is true, which statements do you have to insert ?
1: public aMethod {
2:
3: if (Condition) {
4:
5: }
6:
7: }
1) throw new Exception() at line 4
2) throw new MyException() at line 4
3) throw new MyException() at line 6
4) throws new Exception() at line 2
5) throws MyException at line 1
Q190 Suppose a NullPointerException is thrown by test(). Which message is displayed?
void Method(){
try {
test();
System.out.println("Message1");
}
catch (ArrayOutOfBoundsException e) {
System.out.println("Message2");
}
finally {
System.out.println("Message3");
}
System.out.println("Message4");
}
1) Message1
2) Message2
3) Message3
4) Message4
5) None of the above.
Q191 Choose the class that can hold multiple equal objects in an ordered way.
1) Map
2) Collection
3) List
4) Set
5) Vector
Q192 Consider the following variables definitions.
Float f1 = new Float("10F");
Float f2 = new Float("10F");
Double d1 = new Double("10D");
Which of the following yields a boolean value of true.
1) f1 == f2
2) f1.equals(f2)
3) f2.equals(d1)
4) f2.equals(new Float("10"))
Q193 What does the getID() method of AWTEvent tell us.
1) Tells us the x and y coords of the mouse at the event time.
2) Tells us which Object the event originated from.
3) Tells us which special keys were pressed at the event time.
4) Tells us the event type.
5) Tells us the how many pixels were between the mouse pointer and text on a Canvas.
Q194 What is the return type of an Eventlistener ?
1) int
2) NULL
3) void
4) boolean
5) Object
Q195 You create a Long object using the following:
Long val = new Long("11");
Which of the following will return the value of the object as a byte value?
1) byte b = (byte)val;
2) byte b = val.getByte();
3) byte b = (byte)val.getValue();
4) byte b = val.byteValue();
5) None of the above.
Q196 Consider the following.
String s1 = "abc";
String s2 = "def";
String s3 = new String(s2);
s2 = s1;
What is the value of s3 after the final line of code is executed?
1) "abc"
2) "def"
3) null
4) An exception is thrown when "s2 = s1" is executed.
Q197 What tags are mandatory when creating HTML to display an applet
1) name, width, height
2) code, name
3) codebase, height, width
4) code, width, height
5) None of the above
Q198 What is displayed when the following code is executed:
String s1 = " hello world ";
String s2 = s1.trim();
System.out.println(s2);
1) " hello world"
2) "hello world "
3) "hello world"
4) " hello world "
5) "helloworld"
Q199 Which of the following are methods within the String class.
1) substring()
2) startsWith()
3) toString()
4) toUpperCase()
5) indexOf()
Q200 True or False.
APPLET tags must appear between BODY and /BODY tags.
1) True
2) False
ANSWER:
1. 1,2
Answers 3, 4 and 5 are incorrect because these operations requires that an int (c) be converted to a boolean, or the boolean be converted to an int. Both of these conversions are illegal.
2. 5
A constructor cannot be abstract, final, native, static or synchronized. Refer to the Java Language Specification (section 8.6.3, version 1.0).
3. 4
In general, all components are resized and only retain their preferred height in the NORTH region. However, the CheckBox is not deformable, so it retains it's preferred size.
4. 1,3,4
5. 1
6. 3
When a File class is constructed, it simply creates a handle to a File object. No files are created on the local harddisk.
As the JDK API documentation points out, the File class is "an abstract representation of file and directory pathnames".
The File class also contains directory separator attributes, which are platform specific. Therefore, the directory separator used is irrelevant.
Also, since the File class simply creates a reference to a file object, no exception is thrown if the file already exists on the disk.
7. 1,4,5
Answer 1 is correct, because in read mode, the file must exist if any other operations are to be performed on it.
The RandomAccessFile is not compatible with the Stream or reader/writer classes, so Answer 3 is incorrect.
8. 3
Strings are immutable, and so they cannot be modified. However, as the JDK API documentation will show, the String class has a replace() method, so answer 1 is incorrect.
If line 2 read as "s = s.replace('d', 'q')" then a new object would be created and assigned to s. The value of this new String object would be "abcqefgh". However, as line 2 is presented, no new object is created, and so 's' remains unchanged.
9. 1,5
10. 2
I came across the statement during my study for the exam, and simply noted it as fact. I never really looked too deeply into it - so please don't email me for an explanation :-)
11. 1,4,5
Therefore, Answer 1 is correct, because class B attempts to override method() to be less public (ie, protected to "friendly").
Answer 2 is incorrect, because a protected variable or method is always available to child classes (this is the purpose of the protected keyword).
Answer 3 is incorrect, because all the information needed to verify this code is available at compile time.
Answers 4 and 5 are correct because adding either "public" or "protected" to line 7 actually moves it higher up the access hierarchy (ie, more public than friendly).
12. 1
13. 2
14. 1
15. 3
16. 2
The rule for accessing methods and variables in a class hierarchy is as follows:
-the object reference is used when accessing variables (so the value of b.x is therefore 2).
-the underlying object is used when accessing methods (so the method called is actually the method defined in Subclass, and in Subclass, x =3).
17. 1
18. 2
19. 2
20. 1,2,3
1. 3
22. 1
23. 1
24. 1
25. 4
26. 1,4,5
Answer 1 is correct, because x is declared as private to class A and is therefore not available to any other class (even subclasses).
Answer 3 is totally meaningless, but sounds vaguely plausible!
Answer 4 is correct, because the only problem with the code is the attempt to reference the variable x.
Answer 5 is correct (see answer 4).
27. 3
28. 2,3,4,5
29. 1
Answer 2 is incorrect, since the {} defines an empty method (but still a method) so it is not abstract.
Abstract methods cannot be static, so answer 3 is incorrect.
Abstract and final are almost opposite in meaning and therefore do not form a valid keyword combination (final means a method can't be overridden, abstract means a method must be overridden), so answer 4 is incorrect.
30. 2
31. 4
Interfaces cannot have constructors, only classes have constructors.
Answer 2 is a valid statement when dealing with classes, but not in the context of the code in the question.
Answer 5 is totally untrue, but potentially confusing :-)
32. 1
33. 1,2,4
34. 1
Answer 2 is incorrect, because booleans can't have integer values (in this case, "1").
Answer 3 is an meaningless statement.
Answer 5 is incorrect, attempting to confuse C/C++ and Java ways of defining true and false boolean values.
35. 2,4
36. 2
37. 2
38. 1,2
39. 3
40. 1
41. 2
42. 3
43. 1,3
44. 1,2,3
45. 2
46. 1,2,4,5
47. 1
48. 2
49. 1.4
50. 3,4
Answer 1 is incorrect, because a class can have final methods and variables without the need for the entire class to be final.
Answer 2 is incorrect, because the type of error in this code is detectable at compile time.
Answer 5 is invalid. Final can be applied to primitives.
51. 4
52. 1
53. 1,2,3,4,5
54. 2
55. 2.3
56. 3
57. 1,3,4
58. 3,5
59. 1,3,4,5
60. 5
61. 3
62. 4
63. 1,4
64. 4
65. 2,3
66. 1,3,4,5
67. 5
68. 2
69. 4
70. 5
71. 4
72. 2
73. 3
74. 2
75. 1
76. 1
77. 4
78. 3
79. 2
80. 3
81. 3
82. 3
83. 1,2,5
84. 5
85. 4
86. 2,3
There are several things wrong with this code:
- class A must be declared as abstract, since method() is declared as abstract
- if class A is declared as abstract, then the code will compile correctly
- if the abstract declaration of method() in class A is removed, the code will compile (however, the entire line 2 must now read as follows:
int method(){}
In other words, a method body must now be supplied since the method is no longer abstract.
87. 3
88. 2,5
89. 3
90. 2
91. 1
92. 3,4,5
93. 2,3,5
94. 1,5
95. 2,3
96. 3.
97. 1,2
98. 2
The instanceof operator can be used as follows:
- on classes to see if a particular class is derived from another (ie, is an instance of)
- on interfaces to see if a class implements a particular interface
99. 1,3,4
100. 1,2,3,4,5
101. 1,2,3,4,5
102. 2,3,4
103. 2
104. 1,2,5
105. 4
106. 3,4,5
107. 4,5
108. 3
109. 1,3,5
110. 3
111. 1
112. 4
113. 1
114. 4
115. 2
1 will not compile, because 123 defaults to type int, and there is no constructor of the Byte class which takes type int as a parameter.
2 compiles correctly, because a parseable string is a valid parameter for the Byte constructor.
3 fails to compile, because there is no no-args constructor for the Byte class.
4 fails to compile. While the cast to an int is valid, the same reasons as Answer 1 apply.
5 fails to compile, because the value 0x123 is a hex value, and equates to a decimal value of 291. This is not within the valid range for the Byte value.
116. 2
117. 2,4
118. 1,5
119. 2
120. 2,3
121. 1,2
122. 1
123. 2
124. 2,4
125. 3,4,5
126. 1,2,3
127. 1
Thanks to Prasad for rightly pointing out that Answer 2 above also works for a container which uses the Flow Layout manager (even though it doesn't have a "Center" area").
This can be explained by the fact that a container such as a Panel inherits from java.awt.Container, which has a method with a signature as follows:
add(String, Component)
However, while this is symantically correct (ie, it will compile and function correctly), it can't be considered as a valid answer since Flow layout doesn't have the concept of a "Center" area - at least, that's my opinion :-)
However, this raises an interesting point - where possible, you should use static class variables, where a choice is available - eg, use BorderLayout.NORTH instead of "NORTH" when adding components to a container. This will ensure that any errors are trapped at compile time, rather than at run-time :-)
128. 2
129. 3
130. 3
131. 5
132. 1
133. 3
134. 3
135. 1,2,4,5
136. 4,5
137. 1
138. 1
139. 1
140. 1
141. 3
142. 1,2
143. 3
144. 5
145. 1,2,3,4
146. 1,2,3
147. 4
148. 1
149. 2
150. 1
151. 3
152. 1,2,3,4,5
153. 2
154. 2
155. 1
156. 2
157. 1,2,3,4
158. 1
159. 1,3
160. 1
161. 1
162. 2
163. 2
164. 1,2,5
165. 1,2,4
166. 2
167. 1
168. 1
169. 1
170. 1,2,3
171. 1
172. 1
173. 1
174. 3
175. 2
176. 1
177. 4
178. 3
179. 1,2,4,5
180. 2,3,5
181. 3,4
182. 1,3,4
183. 2,4,5
184. 1,2,3
185. 3
186. 1
187. 1
188. 3
189. 2,5
190. 3
191. 5
192. 2,4
193. 4
194. 3
195. 4
196. 2
197. 4
198. 3
199. 1,2,3,4,5
200. 1
SCJP 模拟考试题, 笔试常考
http://beansoft.java-cn.org/download/scjp_emulator.zip 700KB Java 1.4 版本
是我很早以前买的一本英文 SCJP 辅导书里面所附带的代码.
下载后解压缩得到几个 JAR 文件 下载后 Windows 下可以双击运行, 点击最大化后, 然后点击 Mark 按钮就可以看到正确答案和解释了.
Linux/Windows 下都通过命令行键入
java -jar Final.jar 这样的命令即可运行.
现在的 Java 笔试题 的基础部分(core java)很多都是从类似这样的英文题里面抽取出来的, 基本上熟悉之后笔试题会答的很漂亮.
界面截图:
再转载: 阅读完此贴你才可以大胆的高薪工作!http://bbs.tarena.com.cn/topic.cgi?forum=1&topic=10848&show=0
大家找工作就要面试,有面试就有对付面试的办法。以下一些题目来自我朋友痛苦的面试经历,他给我总结了一下,我拿来和大家分享!提这些问题的公司包括IBM, E*Trade, Siebel, Motorola, SUN, 以及其它大小公司。
面试是没什么道理可讲的,它的题目有的不合情理、脱离实际。有在纸上写的,有当面考你的,也有在电话里问的,给你IDE的估计很少(否则你赶快去买彩票, 说不定中)。所以如果你看完此文后,请不要抱怨说这些问题都能用IDE来解决。你必须在任何情况下准确回答这些问题,在面试中如果出现一两题回答不准确很有可能你就被拒之门外了。 当然这些都是Java的基本题,那些面试的人大多数不会问你Hibernate有多先进,Eclipse的三个组成部分,或command design pattern,他们都是老一辈了,最喜欢问的就是基础知识。别小看了这些基础,我朋友水平挺可以的,结果就栽在一道基础知识的问题上,和高薪无缘。
希望这些知识点对大家有所帮助,愿大家从达内出来后都能找到高薪的工作!
第一,谈谈final, finally, finalize的区别。 final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。finally是异常处理语句结构的一部分,表示总是执行。finalize是Object类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法,可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等。
第二,Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)? 可以继承其他类或完成其他接口,在swing编程中常用此方式。
第三,Static Nested Class 和 Inner Class的不同,说得越多越好(面试题有的很笼统)。 Static Nested Class是被声明为静态(static)的内部类,它可以不依赖于外部类实例被实例化。而通常的内部类需要在外部类实例化后才能实例化。
第四,&和&&的区别。 &是位运算符,表示按位与运算,&&是逻辑运算符,表示逻辑与(and).
第五,HashMap和Hashtable的区别。 HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口,主要区别在于HashMap允许空(null)键值(key),由于非线程安全,效率上可能高于Hashtable.
第六,Collection 和 Collections的区别。 Collection是集合类的上级接口,继承与他的接口主要有Set 和List.Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。
第七,什么时候用assert。 1.4新增关键字(语法),用于测试boolean表达式状态,可用于调试程序。使用方法 assert <boolean表达式>,表示如果表达式为真(true),则下面的语句执行,否则抛出AssertionError。另外的使用方式assert < boolean表达式>:<other表达式>,表示如果表达式为真,后面的表达式忽略,否则后面表达式的值用于AssertionError的构建参数。注意编译时要增加-source 1.4 参数,否则报错。]运行时要增加 -ea参数,否则assert行被忽略
第八,GC是什么? 为什么要有GC? GC是垃圾收集的意思(Gabage Collection),内存处理是编程人员容易出现问题的地方,忘记或者错误的内存回收会导致程序或系统的不稳定甚至崩溃,Java提供的GC功能可以自动监测对象是否超过作用域从而达到自动回收内存的目的,Java语言没有提供释放已分配内存的显示操作方法。
第九,String s = new String("xyz");创建了几个String Object? 两个
第十,Math.round(11.5)等於多少? Math.round(-11.5)等於多少? Math.round(11.5)==12Math.round(-11.5)==-11round方法返回与参数最接近的长整数,参数加1/2后求其floor.
第十一,short s1 = 1; s1 = s1 1;有什么错? short s1 = 1; s1 = 1;有什么错? short s1 = 1; s1 = s1 1; (s1 1运算结果是int型,需要强制转换类型)short s1 = 1; s1 = 1;(可以正确编译)
第十二,sleep() 和 wait() 有什么区别? sleep是线程类(Thread)的方法,导致此线程暂停执行指定时间,给执行机会给其他线程,但是监控状态依然保持,到时后会自动恢复。调用sleep不会释放对象锁。wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。
第十三,Java有没有goto? 没有 很十三的问题,如果哪个面试的问到这个问题,我劝你还是别进这家公司。(完)(job.sohu.com)
第十四,数组有没有length()这个方法? String有没有length()这个方法?数组没有length()这个方法,有length的属性。String有有length()这个方法。
第十五,Overload和Override的区别。Overloaded的方法是否可以改变返回值的类型?方法的重写Overriding和重载Overloading是Java多态性的不同表现。重写Overriding是父类与子类之间多态性的一种表现,重载Overloading是一个类中多态性的一种表现。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。子类的对象使用这个方法时,将调用子类中的定义,对它而言,父类中的定义如同被"屏蔽"了。如果在一个类中定义了多个同名的方法,它们或有不同的参数个数或有不同的参数类型,则称为方法的重载(Overloading)。Overloaded的方法是可以改变返回值的类型。
第十六,Set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?Set里的元素是不能重复的,那么用iterator()方法来区分重复与否。equals()是判读两个Set是否相等。equals()和==方法决定引用值是否指向同一对象equals()在类中被覆盖,为的是当两个分离的对象的内容和类型相配的话,返回真值。
第十七,给我一个你最常见到的runtime exception。ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IndexOutOfBoundsException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NullPointerException, ProfileDataException, ProviderException, RasterformatException, SecurityException, SystemException, UndeclaredThrowableException, UnmodifiableSetException, UnsupportedOperationException
第十八,error和exception有什么区别?error 表示恢复不是不可能但很困难的情况下的一种严重问题。比如说内存溢出。不可能指望程序能处理这样的情况。exception 表示一种设计或实现问题。也就是说,它表示如果程序运行正常,从不会发生的情况。
第十九,List, Set, Map是否继承自Collection接口?List,Set是Map不是
第二十,abstract class和interface有什么区别?声明方法的存在而不去实现它的类被叫做抽象类(abstract class),它用于要创建一个体现某些基本行为的类,并为该类声明方法,但不能在该类中实现该类的情况。不能创建abstract 类的实例。然而可以创建一个变量,其类型是一个抽象类,并让它指向具体子类的一个实例。不能有抽象构造函数或抽象静态方法。Abstract 类的子类为它们父类中的所有抽象方法提供实现,否则它们也是抽象类为。取而代之,在子类中实现该方法。知道其行为的其它类可以在类中实现这些方法。接口(interface)是抽象类的变体。在接口中,所有方法都是抽象的。多继承性可通过实现这样的接口而获得。接口中的所有方法都是抽象的,没有一个有程序体。接口只可以定义static final成员变量。接口的实现与子类相似,除了该实现类不能从接口定义中继承行为。当类实现特殊接口时,它定义(即将程序体给予)所有这种接口的方法。然后,它可以在实现了该接口的类的任何对象上调用接口的方法。由于有抽象类,它允许使用接口名作为引用变量的类型。通常的动态联编将生效。引用可以转换到接口类型或从接口类型转换,instanceof 运算符可以用来决定某对象的类是否实现了接口。
第二十一,abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized?都不能
第二十二,接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承实体类(concrete class)?接口可以继承接口。抽象类可以实现(implements)接口,抽象类是否可继承实体类,但前提是实体类必须有明确的构造函数。
第二十三,启动一个线程是用run()还是start()?启动一个线程是调用start()方法,使线程所代表的虚拟处理机处于可运行状态,这意味着它可以由JVM调度并执行。这并不意味着线程就会立即运行。run()方法可以产生必须退出的标志来停止一个线程。
第二十四,构造器Constructor是否可被override?构造器Constructor不能被继承,因此不能重写Overriding,但可以被重载Overloading。
第二十五,是否可以继承String类?String类是final类故不可以继承。
第二十六,当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法?不能,一个对象的一个synchronized方法只能由一个线程访问。
第二十七,try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?会执行,在return前执行。
第二十八,编程题: 用最有效率的方法算出2乘以8等於几?有C背景的程序员特别喜欢问这种问题。2 << 3
第二十九,两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对?不对,有相同的hash code。
第三十,当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递? 是值传递。Java 编程语言只由值传递参数。当一个对象实例作为一个参数被传递到方法中时,参数的值就是对该对象的引用。对象的内容可以在被调用的方法中改变,但对象的引用是永远不会改变的。
第三十一,swtich是否能作用在byte上,是否能作用在long上,是否能作用在String上?switch(expr1)中,expr1是一个整数表达式。因此传递给 switch 和 case 语句的参数应该是 int、 short、 char 或者 byte。long,string 都不能作用于swtich。
第三十二,编程题: 写一个Singleton出来。Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。一般Singleton模式通常有几种种形式:第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。public class Singleton { private Singleton(){} //在自己内部定义自己一个实例,是不是很奇怪? //注意这是private 只供内部调用 private static Singleton instance = new Singleton(); //这里提供了一个供外部访问本class的静态方法,可以直接访问 public static Singleton getInstance() { return instance; } } 第二种形式: public class Singleton { private static Singleton instance = null; public static synchronized Singleton getInstance() { //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次 //使用时生成实例,提高了效率! if (instance==null) instance=new Singleton();return instance; } } 其他形式:定义一个类,它的构造函数为private的,所有方法为static的。
一般认为第一种形式要更加安全些