程序员面试中遇到问题

面试时候经常会问的一些问题(不断补充中)

面试必备基础题目(虽然不一定常用,仅用于面试,面试就是把人搞的都不会然后砍价,当然您可以讲我可以查资料完成,但是面试的时候就是没道理的,起码我是经常看到这些题).

如何把一段逗号分割的字符串转换成一个数组?
request.getAttribute()和request.getParameter()有何区别?
response.sendRedirect()和forward()区别?
<%@includefile="xxx.jsp"%>
和<jsp:include>区别?
List和Map区别?
Struts和Spring自动填充表单参数到Bean的大致原理?
说一下你用的Spring+Hibernate的方框图?您都用到了哪些部分?

请用英文简单介绍一下自己.

请把http://tomcat.apache.org/首页的这一段话用中文翻译一下?

ApacheTomcatistheservletcontainerthatisusedintheofficialReferenceImplementationfortheJavaServletandJavaServerPagestechnologies.TheJavaServletandJavaServerPagesspecificationsaredevelopedbySunundertheJavaCommunityProcess.

ApacheTomcatisdevelopedinanopenandparticipatoryenvironmentandreleasedundertheApacheSoftwareLicense.ApacheTomcatisintendedtobeacollaborationofthebest-of-breeddevelopersfromaroundtheworld.Weinviteyoutoparticipateinthisopendevelopmentproject.Tolearnmoreaboutgettinginvolved,clickhere.

ApacheTomcatpowersnumerouslarge-scale,mission-criticalwebapplicationsacrossadiverserangeofindustriesandorganizations.SomeoftheseusersandtheirstoriesarelistedonthePoweredBywikipage.

try{
Connectionconn=...;
Statementstmt=...;

ResultSetrs=stmt.executeQuery("select*fromtable1");

while(rs.next()){

}
}catch(Exceptionex){
}

这段代码有什么不足之处?

HTML的form提交之前如何验证数值不为空?为空的话提示用户并终止提交?

为什么要用ORM?和JDBC有何不一样?

Weblogic的Server,Machine,Node,Domain都有何区别?

简要讲一下EJB的7个TransactionLevel?

最常见的:用JDBC查询学生成绩单,把主要代码写出来.

Tomcat5用query.jsp?name=中文,怎么把这个变量无乱码的取出来?

finally语句一定会执行么?

前几天有一个朋友去面试,被问到这样一个问题,如下

1publicclasssmallT
2{
3publicstaticvoidmain(Stringargs[])
4{
5smallTt=newsmallT();
6intb=t.get();
7System.out.println(b);
8}
9publicintget()
10{
11try
12{
13return2;
14}
15catch(Exceptione)
16{
17return3;
18}
19finally
20{
21return4;
22}
23}
24}
25

输出:
4
我记得学习的时候说有返回值的方法,执行完return语句后就会停止了;另一方面我还记得在try……catch语句中finally语句也是一定要执行的。于是在这里就产生了麻烦。试了一下,发现果然是执行了finally中的值。正好这两天公司在培训,我便把这个问题提给java很厉害的一个讲师,他用断点测试了一下,说是两个值都返回了……
我又改了一小下,在get方法中逐个添上了输出信息到控制台的语句,发现居然能执行。如下

1publicclasstest
2{
3publicstaticvoidmain(Stringargs[])
4{
5testt=newtest();
6intb=t.get();
7System.out.println("Third:a="+b);
8}
9publicintget()
10{
11try
12{
13System.out.println("First:a="+2);
14return2;
15}
16catch(Exceptione)
17{
18System.out.println(3);
19}
20finally
21{
22System.out.println("Second:a="+4);
23return4;
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.Talkaboutoverriding,overloading.
2.TalkaboutJAVAdesignpatternsyouknown.
3.TalkaboutthedifferencebetweenLinkList,ArrayListandVictor.
4.TalkaboutthedifferencebetweenanAbstractclassandanInterface.
5.Classa=newClass();Classb=newClass();
if(a==b)returnstrueorfalse,why?
6.WhyweuseStringBufferwhenconcatenatingstrings?
7.TrytoexplainSingletontous?Isitthreadsafe?Ifno,howtomakeitthreadsafe?
8.TrytoexplainIoc?
9.Howtosetmany-to-manyrelationshipinHibernate?
10.TalkaboutthedifferencebetweenINNERJOINandLFETJOIN.
11.Whyweuseindexindatabase?Howmanyindexesisthemaximuminonetableasyoursuggestion?
12.When‘Final’isusedinclass,methodandproperty,whatdoseitmean?
13.DoyouhaveanyexperienceonXML?TalkaboutanyXMLtoolyouused,e.g.JAXB,JAXG.
14.DoyouhaveanyexperienceonLinux?
15.InOODwhatisthereasonwhenyoucreateaSequencediagram?

补一个内部培训用的PPT:SQLTuninginSybase.zip17KB,英文,Sybase调优,大部分道理是通用的.

数据库三范式是什么?别看问题简单,我也经常答不上来被面试的人写上数据库不行.

还有就是SunJava认证时候会考的一些英文选择题,填空题,模拟题也成.

赴港JAVA开发工程师的面试题目

也是上个星期五的上午,按照与猎头的约定,接受了香港某软件供应商的面试。工作是分析程序员,需赴港工作,以下是面试过程以及题目(大概记下了90%),记下来与大家分享。
第一部分:例行公事的英文自我介绍;
以下部分必须以粤语回答,本人非广东人,粤语会讲,但是不标准。
第二部分:项目经验介绍,着重介绍项目背景,开发流程以及本人在项目开发过程中的角色;
第三部分:面试官根据简历提问:
(1)说出Abstractclass与interface的不同?
(2)Oracle中如何进行错误处理?如果用户反应速度慢,你如何着手解决问题?
(3)图画板上列了两个table,问查询结果,主要是考innerjoin与leftjoin的。
(4)union和unionall有什么不同?
(5)你用什么软件做设计?
(6)是否用过Websphere?
(7)iBatis与Hibernate有什么不同?
(8)谈谈Struts中的Actionservlet。
(9)是否开发过IBMportal项目。
(10)是否介意加班?
(11)如果你去香港工作,你认为你最大的困难是什么?
第四部分:笔试,三个英文考试题目选一个作答,内容都是写一份email。
出来后问了猎头,他说最迟一个星期内就有结果。
结果,晚上就接到电话说通过了,并收到了合同和赴港申请的电子文件。工作地点是九龙,月薪18K(中等偏低),合同期一年。猎头催我尽快签合同,然后他们马上就去办工作签证。
犹豫ing。

每个JAVA初学者应该知道的问题

对于这个系列里的问题,每个学Java的人都应该搞懂。当然,如果只是学Java玩玩就无所谓了。如果你认为自己已经超越初学者了,却不很懂这些问题,请将你自己重归初学者行列。内容均来自于CSDN的经典老贴。
问题一:我声明了什么!
Strings="Helloworld!";
许多人都做过这样的事情,但是,我们到底声明了什么?回答通常是:一个String,内容是“Helloworld!”。这样模糊的回答通常是概念不清的根源。如果要准确的回答,一半的人大概会回答错误。
这个语句声明的是一个指向对象的引用,名为“s”,可以指向类型为String的任何对象,目前指向"Helloworld!"这个String类型的对象。这就是真正发生的事情。我们并没有声明一个String对象,我们只是声明了一个只能指向String对象的引用变量。所以,如果在刚才那句语句后面,如果再运行一句:
Stringstring=s;
我们是声明了另外一个只能指向String对象的引用,名为string,并没有第二个对象产生,string还是指向原来那个对象,也就是,和s指向同一个对象。
问题二:"=="和equals方法究竟有什么区别?
==操作符专门用来比较变量的值是否相等。比较好理解的一点是:
inta=10;
intb=10;
则a==b将是true。
但不好理解的地方是:
Stringa=newString("foo");
Stringb=newString("foo");
则a==b将返回false。
根据前一帖说过,对象变量其实是一个引用,它们的值是指向对象所在的内存地址,而不是对象本身。a和b都使用了new操作符,意味着将在内存中产生两个内容为"foo"的字符串,既然是“两个”,它们自然位于不同的内存地址。a和b的值其实是两个不同的内存地址的值,所以使用"=="操作符,结果会是false。诚然,a和b所指的对象,它们的内容都是"foo",应该是“相等”,但是==操作符并不涉及到对象内容的比较。
对象内容的比较,正是equals方法做的事。
看一下Object对象的equals方法是如何实现的:
booleanequals(Objecto){
returnthis==o;
}
Object对象默认使用了==操作符。所以如果你自创的类没有覆盖equals方法,那你的类使用equals和使用==会得到同样的结果。同样也可以看出,Object的equals方法没有达到equals方法应该达到的目标:比较两个对象内容是否相等。因为答案应该由类的创建者决定,所以Object把这个任务留给了类的创建者。
看一下一个极端的类:
ClassMonster{
privateStringcontent;
...
booleanequals(Objectanother){returntrue;}
}
我覆盖了equals方法。这个实现会导致无论Monster实例内容如何,它们之间的比较永远返回true。
所以当你是用equals方法判断对象的内容是否相等,请不要想当然。因为可能你认为相等,而这个类的作者不这样认为,而类的equals方法的实现是由他掌握的。如果你需要使用equals方法,或者使用任何基于散列码的集合(HashSet,HashMap,HashTable),请察看一下javadoc以确认这个类的equals逻辑是如何实现的。
问题三:String到底变了没有?
没有。因为String被设计成不可变(immutable)类,所以它的所有对象都是不可变对象。请看下列代码:
Strings="Hello";
s=s+"world!";
s所指向的对象是否改变了呢?从本系列第一篇的结论很容易导出这个结论。我们来看看发生了什么事情。在这段代码中,s原先指向一个String对象,内容是"Hello",然后我们对s进行了+操作,那么s所指向的那个对象是否发生了改变呢?答案是没有。这时,s不指向原来那个对象了,而指向了另一个String对象,内容为"Helloworld!",原来那个对象还存在于内存之中,只是s这个引用变量不再指向它了。
通过上面的说明,我们很容易导出另一个结论,如果经常对字符串进行各种各样的修改,或者说,不可预见的修改,那么使用String来代表字符串的话会引起很大的内存开销。因为String对象建立之后不能再改变,所以对于每一个不同的字符串,都需要一个String对象来表示。这时,应该考虑使用StringBuffer类,它允许修改,而不是每个不同的字符串都要生成一个新的对象。并且,这两种类的对象转换十分容易。
同时,我们还可以知道,如果要使用内容相同的字符串,不必每次都new一个String。例如我们要在构造器中对一个名叫s的String引用变量进行初始化,把它设置为初始值,应当这样做:
publicclassDemo{
privateStrings;
...
publicDemo{
s="InitialValue";
}
...
}
而非
s=newString("InitialValue");
后者每次都会调用构造器,生成新对象,性能低下且内存开销大,并且没有意义,因为String对象不可改变,所以对于内容相同的字符串,只要一个String对象来表示就可以了。也就说,多次调用上面的构造器创建多个对象,他们的String类型属性s都指向同一个对象。
上面的结论还基于这样一个事实:对于字符串常量,如果内容相同,Java认为它们代表同一个String对象。而用关键字new调用构造器,总是会创建一个新的对象,无论内容是否相同。
至于为什么要把String类设计成不可变类,是它的用途决定的。其实不只String,很多Java标准类库中的类都是不可变的。在开发一个系统的时候,我们有时候也需要设计不可变类,来传递一组相关的值,这也是面向对象思想的体现。不可变类有一些优点,比如因为它的对象是只读的,所以多线程并发访问也不会有任何问题。当然也有一些缺点,比如每个不同的状态都要一个对象来代表,可能会造成性能上的问题。所以Java标准类库还提供了一个可变版本,即StringBuffer。
问题四:final关键字到底修饰了什么?
final使得被修饰的变量"不变",但是由于对象型变量的本质是“引用”,使得“不变”也有了两种含义:引用本身的不变,和引用指向的对象不变。
引用本身的不变:
finalStringBuffera=newStringBuffer("immutable");
finalStringBufferb=newStringBuffer("notimmutable");
a=b;//编译期错误
引用指向的对象不变:
finalStringBuffera=newStringBuffer("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类型的数据。举个例子:
Strings="IAManObject!";
booleanisObject=sinstanceofObject;
我们声明了一个String对象引用,指向一个String对象,然后用instancof来测试它所指向的对象是否是Object类的一个实例,显然,这是真的,所以返回true,也就是isObject的值为True。
instanceof有一些用处。比如我们写了一个处理账单的系统,其中有这样三个类:
publicclassBill{//省略细节}
publicclassPhoneBillextendsBill{//省略细节}
publicclassGasBillextendsBill{//省略细节}
在处理程序里有一个方法,接受一个Bill类型的对象,计算金额。假设两种账单计算方法不同,而传入的Bill对象可能是两种中的任何一种,所以要用instanceof来判断:
publicdoublecalculate(Billbill){
if(billinstanceofPhoneBill){
//计算电话账单
}
if(billinstanceofGasBill){
//计算燃气账单
}
...
}
这样就可以用一个方法处理两种子类。
然而,这种做法通常被认为是没有好好利用面向对象中的多态性。其实上面的功能要求用方法重载完全可以实现,这是面向对象变成应有的做法,避免回到结构化编程模式。只要提供两个名字和返回值都相同,接受参数类型不同的方法就可以了:
publicdoublecalculate(PhoneBillbill){
//计算电话账单
}
publicdoublecalculate(GasBillbill){
//计算燃气账单
}
所以,使用instanceof在绝大多数情况下并不是推荐的做法,应当好好利用多态。

BeanSoft参加过的一次面试:

2004年8月18日星期三〖农历甲申猴年七月初三〗

笔试题目
1.写出常用的Linux命令
a)列出当前目录
b)列出所有系统变量
c)重命名文件
d)etc...记不住了.

2.WriteaJavaapplicationusetheSingletonpattern,itshouldhaveoneinstanceperclass.Itshouldhavetwointegervariable,oneiscount,onisinita.Thereshouldbetwomethodsinthisclass,andthemethodshouldbethreadsafelyinmulti-threadenvironment.
a)acount()method,aftereachcallthecountshouldbeaddedonby1;
b)areset()method,aftereachcallthecountshouldbesettothevalueofinita.

3.WriteaJavaBeanandaJSPfile.Thepageshouldoutputadatestringinthispattern"今天是2004年8月15日上午10:00",thevalueistakenfromthebean.

4.以下三个题目,任选其一或多个:
1)忘了...,是关于Java的.
2)写一个应用程序,读出STUDENT表中的数据并打印出所有名称.数据库系统任选.
3)写一个Servlet,读取名为url的参数,并连接到此字符串指定的地址上,读取所有内容后显示给客户.

5.6.7.都是关于SQL的,例如SELECT,UPDATE,DELETE之类的,还有的有子查询.数据库系统没有限制.

8.Writeahtmlfile,itshoudhasfollowfunctions:
1)checkwhethertheuser'snameisempty;
2)theemailaddressshouldhasa'@';
3)telephonenumbermustbe'1'-'9','-',''(space).
Pagepicture:
Pleaseinputyourname:
[____________________][Checkinput]
Pleaseinputyouraddress:
[abc@________________][Checkinput]
Pleaseinputyourtelephonenumber:
[____123a____________][Checkinput]

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是Java1.2引进的Map接口的一个实现
二.同步性:Hashtable是线程安全的,也就是说是同步的,而HashMap是线程序不安全的,不是同步的
三.值:只有HashMap可以让你将空值作为一个表的条目的key或value

3、char型变量中能不能存贮一个中文汉字?为什么?
答:是能够定义成为一个中文的,因为java中以unicode编码,一个char占16个字节,所以放一个中文是没问题的

4、多线程有几种实现方法,都是什么?同步有几种实现方法,都是什么?
答:多线程有两种实现方法,分别是继承Thread类与实现Runnable接口
同步的实现方面有两种,分别是synchronized,wait与notify

5、继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
答:父类:
packagetest;
publicclassFatherClass
{
publicFatherClass()
{
System.out.println("FatherClassCreate");
}
}
子类:
packagetest;
importtest.FatherClass;
publicclassChildClassextendsFatherClass
{
publicChildClass()
{
System.out.println("ChildClassCreate");
}
publicstaticvoidmain(String[]args)
{
FatherClassfc=newFatherClass();
ChildClasscc=newChildClass();
}
}
输出结果:
C:\>javatest.ChildClass
FatherClassCreate
FatherClassCreate
ChildClassCreate

6、内部类的实现方式?
答:示例代码如下:
packagetest;
publicclassOuterClass
{
privateclassInterClass
{
publicInterClass()
{
System.out.println("InterClassCreate");
}
}
publicOuterClass()
{
InterClassic=newInterClass();
System.out.println("OuterClassCreate");
}
publicstaticvoidmain(String[]args)
{
OuterClassoc=newOuterClass();
}
}
输出结果:
C:\>javatest/OuterClass
InterClassCreate
OuterClassCreate
再一个例题:
publicclassOuterClass{
privatedoubled1=1.0;
//insertcodehere
}
Youneedtoinsertaninnerclassdeclarationatline3.Whichtwoinnerclassdeclarationsare

valid?(Choosetwo.)
A.classInnerOne{
publicstaticdoublemethoda(){returnd1;}
}
B.publicclassInnerOne{
staticdoublemethoda(){returnd1;}
}
C.privateclassInnerOne{
doublemethoda(){returnd1;}
}
D.staticclassInnerOne{
protecteddoublemethoda(){returnd1;}
}
E.abstractclassInnerOne{
publicabstractdoublemethoda();
}
说明如下:
一.静态内部类可以有静态成员,而非静态内部类则不能有静态成员。故A、B错
二.静态内部类的非静态成员可以访问外部类的静态变量,而不可访问外部类的非静态变量;returnd1出错。

故D错
三.非静态内部类的非静态成员可以访问外部类的非静态变量。故C正确
四.答案为C、E

7、垃圾回收机制,如何优化程序?
希望大家补上,谢谢

8、float型floatf=3.4是否正确?
答:不正确。精度不准确,应该用强制类型转换,如下所示:floatf=(float)3.4

9、介绍JAVA中的CollectionFrameWork(包括如何写自己的数据结构)?
答:CollectionFrameWork如下:
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的通信编程,编程题(或问答),用JAVASOCKET编程,读服务器几个字符,再写入本地显示?
答:Server端程序:
packagetest;
importjava.net.*;
importjava.io.*;

publicclassServer
{
privateServerSocketss;
privateSocketsocket;
privateBufferedReaderin;
privatePrintWriterout;
publicServer()
{
try
{
ss=newServerSocket(10000);
while(true)
{
socket=ss.accept();
StringRemoteIP=socket.getInetAddress().getHostAddress();
StringRemotePort=":"+socket.getLocalPort();
System.out.println("Aclientcomein!IP:"+RemoteIP+RemotePort);
in=newBufferedReader(new

InputStreamReader(socket.getInputStream()));
Stringline=in.readLine();
System.out.println("Cleintsendis:"+line);
out=newPrintWriter(socket.getOutputStream(),true);
out.println("YourMessageReceived!");
out.close();
in.close();
socket.close();
}
}catch(IOExceptione)
{
out.println("wrong");
}
}
publicstaticvoidmain(String[]args)
{
newServer();
}
};
Client端程序:
packagetest;
importjava.io.*;
importjava.net.*;

publicclassClient
{
Socketsocket;
BufferedReaderin;
PrintWriterout;
publicClient()
{
try
{
System.out.println("TrytoConnectto127.0.0.1:10000");
socket=newSocket("127.0.0.1",10000);
System.out.println("TheServerConnected!");
System.out.println("PleaseentersomeCharacter:");
BufferedReaderline=newBufferedReader(new

InputStreamReader(System.in));
out=newPrintWriter(socket.getOutputStream(),true);
out.println(line.readLine());
in=newBufferedReader(newInputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
out.close();
in.close();
socket.close();
}catch(IOExceptione)
{
out.println("Wrong");
}
}
publicstaticvoidmain(String[]args)
{
newClient();
}
};

14、用JAVA实现一种排序,JAVA类实现序列化的方法(二种)?如在COLLECTION框架中,实现比较要实现什么样的接口?
答:用插入法进行排序代码如下
packagetest;
importjava.util.*;
classInsertSort
{
ArrayListal;
publicInsertSort(intnum,intmod)
{
al=newArrayList(num);
Randomrand=newRandom();
System.out.println("TheArrayListSortBefore:");
for(inti=0;i<num;i++)
{
al.add(newInteger(Math.abs(rand.nextInt())%mod+1));
System.out.println("al["+i+"]="+al.get(i));
}
}
publicvoidSortIt()
{
IntegertempInt;
intMaxSize=1;
for(inti=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(intj=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("TheArrayListSortAfter:");
for(inti=0;i<al.size();i++)
{
System.out.println("al["+i+"]="+al.get(i));
}
}
publicstaticvoidmain(String[]args)
{
InsertSortis=newInsertSort(10,100);
is.SortIt();
}
}
JAVA类实现序例化的方法是实现java.io.Serializable接口
Collection框架中实现比较要实现Comparable接口和Comparator接口

15、编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
答:代码如下:
packagetest;

classSplitString
{
StringSplitStr;
intSplitByte;
publicSplitString(Stringstr,intbytes)
{
SplitStr=str;
SplitByte=bytes;
System.out.println("TheStringis:′"+SplitStr+"′SplitBytes="+SplitByte);
}
publicvoidSplitIt()
{
intloopCount;

loopCount=(SplitStr.length()%SplitByte==0)?(SplitStr.length()/SplitByte):(SplitStr.length()/Split

Byte+1);
System.out.println("WillSplitinto"+loopCount);
for(inti=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)));
}
}
}
publicstaticvoidmain(String[]args)
{
SplitStringss=newSplitString("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与请求有关的会话期
applicationservlet正在执行的内容
out用来传送回应的输出
configservlet的构架部件
pageJSP网页本身
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:includepage="included.jsp"flush="true"/>它总是会检查所含文件中的变化,适合用于包含动态页面,并且可以带参数
静态INCLUDE用include伪码实现,定不会检查所含文件的变化,适用于包含静态页面
<%@includefile="included.htm"%>

4、两种跳转方式分别是什么?有什么区别?
答:有两种,分别为:
<jsp:includepage="included.jsp"flush="true">
<jsp:forwardpage="nextpage.jsp"/>
前者页面不会转向include所指的页面,只是显示该页的结果,主页面还是原来的页面。执行完后还会回来,相当于函数调用。并且可以带参数.后者完全转向新页面,不会再回来。相当于goto语句。

Servlet方面

1、说一说Servlet的生命周期?
答:servlet有良好的生存期的定义,包括加载和实例化、初始化、处理请求以及服务结束。这个生存期由javax.servlet.Servlet接口的init,service和destroy方法表达。

2、Servlet版本间(忘了问的是哪两个版本了)的不同?
希望大家补上,谢谢

3、JAVASERVLETAPI中forward()与redirect()的区别?
答:前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。所以,前者更加高效,在前者可以满足需要时,尽量使用forward()方法,并且,这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用sendRedirect()方法。

4、Servlet的基本架构
publicclassServletNameextendsHttpServlet{
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throws
ServletException,IOException{
}
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throws
ServletException,IOException{
}
}

Jdbc、Jdo方面

1、可能会让你写一段Jdbc连Oracle的程序,并实现数据查询.
答:程序如下:
packagehello.ant;
importjava.sql.*;
publicclassjdbc
{
StringdbUrl="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
StringtheUser="admin"
StringthePw="manager"
Connectionc=null;
Statementconn;
ResultSetrs=null;
publicjdbc()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
c=DriverManager.getConnection(dbUrl,theUser,thePw);
conn=c.createStatement();
}catch(Exceptione){
e.printStackTrace();
}
}
publicbooleanexecuteUpdate(Stringsql)
{
try
{
conn.executeUpdate(sql);
returntrue;
}
catch(SQLExceptione)
{
e.printStackTrace();
returnfalse;
}
}
publicResultSetexecuteQuery(Stringsql)
{
rs=null;
try
{
rs=conn.executeQuery(sql);
}
catch(SQLExceptione)
{
e.printStackTrace();
}
returnrs;
}
publicvoidclose()
{
try
{
conn.close();
c.close();
}
catch(Exceptione)
{
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args)
{
ResultSetrs;
jdbcconn=newjdbc();
rs=conn.executeQuery("select*fromtest");
try{
while(rs.next())
{
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
}
}catch(Exceptione)
{
e.printStackTrace();
}
}
}

2、Class.forName的作用?为什么要用?
答:调用该访问返回一个以字符串指定类名的类的对象。

3、Jdo是什么?
答:JDO是Java对象持久化的新的规范,为javadataobject的简称,也是一个用于存取某种数据仓库中的对象的标准化API。JDO提供了透明的对象存储,因此对开发人员来说,存储数据对象完全不需要额外的代码(如JDBCAPI的使用)。这些繁琐的例行工作已经转移到JDO产品提供商身上,使开发人员解脱出来,从而集中时间和精力在业务逻辑上。另外,JDO很灵活,因为它可以在任何数据底层上运行。JDBC只是面向关系数据库(RDBMS)JDO更通用,提供到任何数据底层的存储功能,比如关系数据库、文件、XML以及对象数据库(ODBMS)等等,使得应用可移植性更强。

4、在ORACLE大数据量下的分页解决方法。一般用截取ID方法,还有是三层嵌套方法。
答:一种分页方法
<%
inti=1;
intnumPages=14;
Stringpages=request.getParameter("page");
intcurrentPage=1;
currentPage=(pages==null)?(1):{Integer.parseInt(pages)}
sql="selectcount(*)fromtables"
ResultSetrs=DBLink.executeQuery(sql);
while(rs.next())i=rs.getInt(1);
intintPageCount=1;
intPageCount=(i%numPages==0)?(i/numPages):(i/numPages+1);
intnextPage;
intupPage;
nextPage=currentPage+1;
if(nextPage>=intPageCount)nextPage=intPageCount;
upPage=currentPage-1;
if(upPage<=1)upPage=1;
rs.close();
sql="select*fromtables"
rs=DBLink.executeQuery(sql);
i=0;
while((i<numPages*(currentPage-1))&&rs.next()){i++;}
%>
//输出内容
//输出翻页连接
合计:<%=currentPage%>/<%=intPageCount%><ahref="List.jsp?page=1"temp_href="List.jsp?page=1">第一页</a><a

href="List.jsp?page=<%=upPage%>"temp_href="List.jsp?page=<%=upPage%>">上一页</a>
<%
for(intj=1;j<=intPageCount;j++){
if(currentPage!=j){
%>
<ahref="list.jsp?page=<%=j%>"temp_href="list.jsp?page=<%=j%>">[<%=j%>]</a>
<%
}else{
out.println(j);
}
}
%>
<ahref="List.jsp?page=<%=nextPage%&gt;"temp_href="List.jsp?page=<%=nextPage%>">下一页</a><ahref="List.jsp?page=<%=intPageCount%&gt;"temp_href="List.jsp?page=<%=intPageCount%>">最后页

</a>

Xml方面

1、xml有哪些解析技术?区别是什么?
答:有DOM,SAX,STAX等
DOM:处理大型文件时其性能下降的非常厉害。这个问题是由DOM的树结构所造成的,这种结构占用的内存较多,而且DOM必须在解析文件之前把整个文档装入内存,适合对XML的随机访问SAX:不现于DOM,SAX是事件驱动型的XML解析方式。它顺序读取XML文件,不需要一次全部装载整个文件。当遇到像文件开头,文档结束,或者标签开头与标签结束时,它会触发一个事件,用户通过在其回调事件中写入处理代码来处理XML文件,适合对XML的顺序访问
STAX:StreamingAPIforXML(StAX)

2、你在项目中用到了xml技术的哪些方面?如何实现的?
答:用到了数据存贮,信息配置两方面。在做数据交换平台时,将不能数据源的数据组装成XML文件,然后将XML文件压缩打包加密后通过网络传送给接收者,接收解密与解压缩后再同XML文件中还原相关信息进行处理。在做软件配置时,利用XML可以很方便的进行,软件的各种配置参数都存贮在XML文件中。

3、用jdom解析xml文件时如何解决中文问题?如何解析?
答:看如下代码,用编码方式加以解决
packagetest;
importjava.io.*;
publicclassDOMTest
{
privateStringinFile="c:\\people.xml"
privateStringoutFile="c:\\people.xml"
publicstaticvoidmain(Stringargs[])
{
newDOMTest();
}
publicDOMTest()
{
try
{
javax.xml.parsers.DocumentBuilderbuilder=

javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.dom.Documentdoc=builder.newDocument();
org.w3c.dom.Elementroot=doc.createElement("老师");
org.w3c.dom.Elementwang=doc.createElement("王");
org.w3c.dom.Elementliu=doc.createElement("刘");
wang.appendChild(doc.createTextNode("我是王老师"));
root.appendChild(wang);
doc.appendChild(root);
javax.xml.transform.Transformertransformer=
javax.xml.transform.TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING,"gb2312");
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,"yes");

transformer.transform(newjavax.xml.transform.dom.DOMSource(doc),
new

javax.xml.transform.stream.StreamResult(outFile));
}
catch(Exceptione)
{
System.out.println(e.getMessage());
}
}
}

4、编程用JAVA解析XML的方式.
答:用SAX方式解析XML,XML文件如下:
<?xmlversion="1.0"encoding="gb2312"?>
<person>
<name>王小明</name>
<college>信息学院</college>
<telephone>6258113</telephone>
<notes>男,1955年生,博士,95年调入海南大学</notes>
</person>
事件回调类SAXHandler.java
importjava.io.*;
importjava.util.Hashtable;
importorg.xml.sax.*;
publicclassSAXHandlerextendsHandlerBase
{
privateHashtabletable=newHashtable();
privateStringcurrentElement=null;
privateStringcurrentValue=null;
publicvoidsetTable(Hashtabletable)
{
this.table=table;
}
publicHashtablegetTable()
{
returntable;
}
publicvoidstartElement(Stringtag,AttributeListattrs)
throwsSAXException
{
currentElement=tag;
}
publicvoidcharacters(char[]ch,intstart,intlength)
throwsSAXException
{
currentValue=newString(ch,start,length);
}
publicvoidendElement(Stringname)throwsSAXException
{
if(currentElement.equals(name))
table.put(currentElement,currentValue);
}
}
JSP内容显示源码,SaxXml.jsp:
<HTML>
<HEAD>
<TITLE>剖析XML文件people.xml</TITLE>
</HEAD>
<BODY>
<%@pageerrorPage="ErrPage.jsp"
contentType="text/html;charset=GB2312"%>
<%@pageimport="java.io.*"%>
<%@pageimport="java.util.Hashtable"%>
<%@pageimport="org.w3c.dom.*"%>
<%@pageimport="org.xml.sax.*"%>
<%@pageimport="javax.xml.parsers.SAXParserFactory"%>
<%@pageimport="javax.xml.parsers.SAXParser"%>
<%@pageimport="SAXHandler"%>
<%
Filefile=newFile("c:\\people.xml");
FileReaderreader=newFileReader(file);
Parserparser;
SAXParserFactoryspf=SAXParserFactory.newInstance();
SAXParsersp=spf.newSAXParser();
SAXHandlerhandler=newSAXHandler();
sp.parse(newInputSource(reader),handler);
HashtablehashTable=handler.getTable();
out.println("<TABLEBORDER=2><CAPTION>教师信息表</CAPTION>");
out.println("<TR><TD>姓名</TD>"+"<TD>"+
(String)hashTable.get(newString("name"))+"</TD></TR>");
out.println("<TR><TD>学院</TD>"+"<TD>"+
(String)hashTable.get(newString("college"))+"</TD></TR>");
out.println("<TR><TD>电话</TD>"+"<TD>"+
(String)hashTable.get(newString("telephone"))+"</TD></TR>");
out.println("<TR><TD>备注</TD>"+"<TD>"+
(String)hashTable.get(newString("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与JAVABEAN的区别?
答:JavaBean是可复用的组件,对JavaBean并没有严格的规范,理论上讲,任何一个Java类都可以是一个Bean。但通常情况下,由于JavaBean是被容器所创建(如Tomcat)的,所以JavaBean应具有一个无参的构造器,另外,通常JavaBean还要实现Serializable接口用于实现Bean的持久性。JavaBean实际上相当于微软COM模型中的本地进程内COM组件,它是不能被跨进程访问的。EnterpriseJavaBean相当于DCOM,即分布式组件。它是基于Java的远程方法调用(RMI)技术的,所以EJB可以被远程访问(跨进程、跨计算机)。但EJB必须被布署在诸如Webspere、WebLogic这样的容器中,EJB客户从不直接访问真正的EJB组件,而是通过其容器访问。EJB容器是EJB组件的代理,EJB组件由容器所创建和管理。客户通过容器来访问真正的EJB组件。

3、EJB的基本架构
答:一个EJB包括三个部分:
RemoteInterface接口的代码
packageBeans;
importjavax.ejb.EJBObject;
importjava.rmi.RemoteException;
publicinterfaceAddextendsEJBObject
{
//somemethoddeclare
}
HomeInterface接口的代码
packageBeans;
importjava.rmi.RemoteException;
importjaax.ejb.CreateException;
importjavax.ejb.EJBHome;
publicinterfaceAddHomeextendsEJBHome
{
//somemethoddeclare
}
EJB类的代码
packageBeans;
importjava.rmi.RemoteException;
importjavax.ejb.SessionBean;
importjavx.ejb.SessionContext;
publicclassAddBeanImplementsSessionBean
{
//somemethoddeclare
}

J2EE,MVC方面

1、MVC的各个部分都有那些技术来实现?如何实现?
答:MVC是Model-View-Controller的简写。"Model"代表的是应用的业务逻辑(通过JavaBean,EJB组件实现),"View"是应用的表示面(由JSP页面产生),"Controller"是提供应用的处理过程控制(一般是一个Servlet),通过这种设计模型把应用逻辑,处理过程和显示逻辑分成不同的组件实现。这些组件可以进行交互和重用。

2、应用服务器与WEBSERVER的区别?
希望大家补上,谢谢

3、J2EE是什么?
答:Je22是Sun公司提出的多层(multi-diered),分布式(distributed),基于组件(component-base)的企业级应用模型(enterprieseapplicationmodel).在这样的一个应用系统中,可按照功能划分为不同的组件,这些组件又可在不同计算机上,并且处于相应的层次(tier)中。所属层次包括客户层(clietntier)组件,web层和组件,Business层和组件,企业信息系统(EIS)层。

4、WEBSERVICE名词解释。JSWDL开发包的介绍。JAXP、JAXM的解释。SOAP、UDDI,WSDL解释。
答:WebService描述语言WSDL
SOAP即简单对象访问协议(SimpleObjectAccessProtocol),它是用于交换XML编码信息的轻量级协议。
UDDI的目的是为电子商务建立标准;UDDI是一套基于Web的、分布式的、为WebService提供的、信息注册中心的实现标准规范,同时也包含一组使企业能将自身提供的WebService注册,以使别的企业能够发现的访问协议的实现标准。

5、BS与CS的联系与区别。
希望大家补上,谢谢

6、STRUTS的应用(如STRUTS架构)
答:Struts是采用JavaServlet/JavaServerPages技术,开发Web应用程序的开放源码的framework。采用Struts能开发出基于MVC(Model-View-Controller)设计模式的应用构架。Struts有如下的主要功能:
一.包含一个controllerservlet,能将用户的请求发送到相应的Action对象。
二.JSP自由tag库,并且在controllerservlet中提供关联支持,帮助开发员创建交互式表单应用。
三.提供了一系列实用对象:XML处理、通过JavareflectionAPIs自动处理JavaBeans属性、国际化的提示和消息。

设计模式方面

1、开发中都用到了那些设计模式?用在什么场合?
答:每个模式都描述了一个在我们的环境中不断出现的问题,然后描述了该问题的解决方案的核心。通过这种方式,你可以无数次地使用那些已有的解决方案,无需在重复相同的工作。主要用到了MVC的设计模式。用来开发JSP/Servlet或者J2EE的相关应用。简单工厂模式等。

2、UML方面
答:标准建模语言UML。用例图,静态图(包括类图、对象图和包图),行为图,交互图(顺序图,合作图),实现图,

JavaScript方面

1、如何校验数字型?
varre=/^\d{1,8}$|\.\d{1,2}$/;
varstr=document.form1.all(i).value;
varr=str.match(re);
if(r==null)
{
sign=-4;
break;
}
else{
document.form1.all(i).value=parseFloat(str);
}

CORBA方面

1、CORBA是什么?用途是什么?
答:CORBA标准是公共对象请求代理结构(CommonObjectRequestBrokerArchitecture),由对象管理组织(ObjectManagementGroup,缩写为OMG)标准化。它的组成是接口定义语言(IDL),语言绑定(binding:也译为联编)和允许应用程序间互操作的协议。其目的为:
用不同的程序设计语言书写
在不同的进程中运行
为不同的操作系统开发

LINUX方面

1、LINUX下线程,GDI类的解释。
答:LINUX实现的就是基于核心轻量级进程的"一对一"线程模型,一个线程实体对应一个核心轻量级进程,而线程之间的管理在核外函数库中实现。
GDI类为图像设备编程接口类库。

Hibernate:简述Hibernate和JDBC的优缺点?如何书写一个onetomany配置文件.

Spring的依赖注入是什么意思?给一个Bean的message属性,字符串类型,注入值为"Hello"的XML配置文件该怎么写?

SCJP模拟题200道附答案

Q1Whichofthefollowingstatementsarevalid,giventhefollowingvariabledeclarations:booleana;booleanb;intc;
1)(a|b)
2)(a||a)
3)(a^b)|c
4)(a&c)
5)(a&&c)

Q2Whichofthefollowingcanbeappliedtoconstructors:
1)final
2)static
3)synchronized
4)native
5)Noneofthese.

Q3Whichofthefollowingretaintheirpreferredsize(widthandheight)whenadded(individually)totheNorthsectionofacontainerwithaBorderLayout(assumethatnoothercomponentsorcontainersarepresentintheNorthsection).
1)TextArea
2)Button
3)TextField
4)Checkbox
5)None.Allofthesementionedcomponentswillonlyretaintheirpreferredheight.

Q4Whichofthefollowingarelegalnamesforvariables.
1)_int
2)%large
3)$fred
4)Integer
5)2much

Q5Whichofthefollowingarecorrectwaystocreateafont.
1)Fontf=newFont("Serif",Font.BOLD,24);
2)Fontf=newFont(Font.SERIF,"Bold",24);
3)Fontf=newFont("Serif","Bold",24);
4)Fontf=newFont(Font.SERIF,Font.BOLD,24);

Q6Selectthecorrectstatementsregardingthefollowingpieceofcode.
Filef=newFile("c:\\large.txt");
1)Onexecution,afilecalled"large.txt"willbecreatedonthelocalharddisk.
2)ThecodefailstocompileonaUNIXmachine,becausethedirectoryseparatorisnotcorrect.
3)AfileisNOTcreatedontheharddiskwhenthiscodeisexecuted.
4)Anexceptionisthrownatruntimeifthefile"large.txt"alreadyexists.
5)Thecodefailstocompile,sincethisisnotavalidconstructorfortheFileclass.

Q7WhichofthefollowingstatementsarecorrectregardingtheRandomAccessFileclass?
1)AnIOExceptionisthrownifthespecifiedfiledoesn'texistwhencreatedusingthe"r"mode.
2)Thisclasshasamethodwhichallowsafiletobedeletedfromtheharddisk.
3)ItispossibletousethisclassinconjunctionwiththeDataInputStreamclass.
4)Whenusedwiththe"rw"mode,thespecifiedfileiscreatedonadiskdrive,ifitdoesn'talreadyexist.
5)Therearemethodstoreadandwriteprimatives(eg,readInt(),writeInt(),etc).

Q8Considerthefollowingpieceofcodeandselectthecorrectstatementfromthefollowing.
1.Strings=newString("abcdefgh");
2.s.replace('d','q');
3.System.out.println(s);

1)Thecodefailstocompile,reportinganerroratline2.Stringsareimmutable,andthereforeareplace()methodismeaningless.
2)Thecodecompilescorrectly,anddisplaysthetext"abcqefgh".
3)Thecodecompilescorrectly,anddisplaysthetext"abcdefgh".
4)Thecodecompiles,butanexceptionisthrownwhenline2isexecuted.
5)Thecodecompiles,butanexceptionisthrownatline3.

Q9Whichofthefollowingkeywordscanbeappliedtothevariablesormethodsofaninterface.
1)static
2)private
3)synchronised
4)protected
5)public

Q10TrueorFalse.
OnlyFramescancontainmenubarsorpull-downmenus.
1)True
2)False.

Q11Considerthefollowingpieceofcodeandselectthecorrectstatement(s):
1.classA{
2.protectedintmethod(){
3.}
4.}
5.
6.classBextendsA{
7.intmethod(){
8.}
9.}
1)Thecodefailstocompile,becauseyoucan'toverrideamethodtobemoreprivatethanitsparent.
2)Thecodefailstocompile,becausemethod()isdeclaredasprotected,andisthereforenotavailabletoanysubclass.
3)Thecodecompilescorrectly,butthrowsaNullPointerExceptionatruntime.
4)Thecodefailstocompile.However,itcanbemadetocompilecorrectlybyprefixingline7withtheaccessqualifier"public".
5)Thecodefailstocompile.However,itcanbemadetocompilecorrectlybyprefixingline7withtheaccessqualifier"protected".

Q12TrueorFalse.

TheThrowableclassisthesuperclassofallexceptionsintheJavalanguage.
1)True
2)False

Q13Considerthefollowingpieceofcode(assumetheGraphicscontextgisdefinedcorrectly):
g.setBackground(Color.red);
g.setForeground(Color.white);
g.drawLine(10,10,50,10);
g.setForeground(Color.blue);
g.drawRect(100,100,50,50);

Whatisdisplayedwhenthiscodeisexecuted.
1)Abluelinefrom(10,10)to(50,10)andabluerectanglewithupperleftcornerat(100,100).
2)Awhitelinefrom(10,10)to(50,10)andabluesquarewithtopleftcornerat(100,100).
3)Awhitelinefrom(10,10)to(10,50)andabluesquarewithlowerleftcornerat(100,100).
4)Aredlinefrom(10,10)to(50,10)andaredsquarewithupperleftcornerat(100,100).
5)Nothingisdisplayed.Youmustfirstissuearepaint()command.

Q14Considerthefollowingpieceofcode.
classTest{
publicstaticvoidmain(String[]args){
System.out.println(args[3]);
}
}
Whenthefollowingistypedatthecommandline,whatisdisplayed:
javaTestMetallicaJusticeForAll
1)All
2)For
3)Justice
4)Nothing.
5)Nothing.AnArrayIndexOutOfBoundsExceptionisthrown

Q15Considerthefollowingpieceofcode.
1.Strings="abcd";
2.Integerx=newInteger(3);
3.Strings2=s+4;
4.s2=null;
5.s=null;

Followingtheexecutionofwhichlineabove,istheobjectreferencedbys2availableforgarbagecollection.
1)Line5
2)Itisnotpossibletosaywhenanobjectisavailableforgarbagecollection.
3)Line4
4)Theobjectsarenotavailableuntiltheexecutingthreadisended.

Q16Whatisdisplayedwhenthefollowingpieceofcodeiscompiledandexecuted:
classTest{
publicstaticvoidmain(String[]args){
Baseb=newSubclass();
System.out.println(b.x);
System.out.println(b.method());
}
}

classBase{
intx=2;
intmethod(){
returnx;
}
}

classSubclassextendsBase{
intx=3;
intmethod(){
returnx;
}
}

1)Nothing.Thecodefailstocompilebecausetheobjectbisnotcreatedinavalidway.
2)2
3
3)2
2
4)3
3
5)3
2

Q17Whatisdisplayedwhenthefollowingisexecuted:
Strings1="aaa";
s1.concat("bbb");
System.out.println(s1);
1)Thestring"aaa".
2)Thestring"aaabbb".
3)Nothing.concat()isnotavalidmethodintheStringclass.
4)Thestring"bbbaaa".
5)Thestring"bbb".

Q18TrueorFalse.
ThefollowingisavalidwaytoconstructaStringBuffer.
StringBuffersb1="abcd";
1)True
2)False

Q19Whatistheoutputofthefollowingpieceofcode:
1.intx=6;
2.doubled=7.7;
3.
4.System.out.println((x>d)?99.9:9);

1)9
2)9.0
3)99.9
4)Nothing.AnArithmeticExceptionisthrownatline4.
5)6

Q20Whichofthefollowingcanbeputinapplettags?(selectallthecorrectanswers)
1)CODE
2)WIDTH
3)HEIGHT
4)PARAM
5)ARCHIVE

Q21Whatisprintedoutfollowingtheexecutionofthecodebelow:
1.classTest{
2.staticStrings;
3.publicstaticvoidmain(String[]args){
4.intx=4;
5.if(x<4)
6.System.out.println("Val="+x);
7.else
8.System.out.println(s);
9.}
10.}
Nothing.ThecodefailstocompilebecausetheStringsisn'tdeclaredcorrectly.
1)Thetext"Val=null"isdisplayed.
2)Thestring"Val="isdisplayed.
3)Thetext"null"isdisplayed.
4)Ablanklineoftextisprinted.

Q22TrueorFalse.
TheStringBufferclassdoesnothaveaconcat()method.
1)True
2)False

Q23Whatisdisplayedwhenthefollowingpieceofcodeisexecuted(assumethegraphicscontext,g,iscorrectlysetup):
g.drawString("abc",10,10);
1)Thetext"abc"withthelowerleftpartof"a"locatedatx=10,y=10.
2)Thetext"abc"withtheupperleftpartof"a"locatedatx=10,y=10.
3)Nothing.Thisisnotavalidmethod.

Q24TrueorFalse.
Anonymousclassescannothaveconstructors.
1)True
2)False

Q25ToreferenceaJARfromawebpage,whichofthefollowingkeywordsareused:
1)jar
2)class
3)zip
4)archive
5)package

Q26

Analysethefollowing2classesandselectthecorrectstatements.
classA{
privateintx=0;
staticinty=1;
protectedintq=2;
}

classBextendsA{
voidmethod(){
System.out.println(x);
System.out.println(y);
System.out.println(q);
}
}

1)ThecodefailstocompilebecausethevariablexisnotavailabletoclassB.
2)Thecodecompilescorrectly,andthefollowingisdisplayed:012
3)Thecodefailstocompilebecauseyoucan'tsubclassaclasswithprivatevariables.
4)Removingtheline"System.out.println(x)"willallowthecodetocompilecorrectly.
5)ThecompilerwillcomplainthatthevariablexinclassBisundefined.

Q27Whichofthefollowinginterfacescanbeusedtomanageacollectionofelements,withnoduplication.
1)List
2)Vector
3)Set

Q28Whichofthefollowingstatementsaretrueregardinginnerclasses.
1)Variablesdefinedinsideinnerclassescannotbestatic.
2)Variablesdefinedinsideinnerclassescannotbestaticunlesstheinnerclassitselfisstatic.
3)Non-staticinnerclasses(whicharenotdefinedinamethod)haveaccesstoallclassandinstancevariables,regardlessoftheaccessqualifierofthosevariables.
4)Aninnerclasscanactuallybeasubclassoftheouterclass
5)Innerclassescanbedeclaredasprivate.Toplevel,outerclassescannot.

Q29Whichofthefollowingarevalidwaystodefineanabstractmethod.
1)abstractvoidTest();
2)abstractvoidTest(){}
3)staticabstractvoidTest();
4)finalabstractvoidTest();
5)Methodscannotbedefinedasabstract,onlyvariablescanbeabstract.

Q30Considerthefollowing:
classAextendsInteger{
intx=0;
}
Selectallvalidstatements.
1)Thecodewillcompilecorrectly.
2)ThecodewillnotcompilebecauseIntegerisfinalandcannotbesubclassed.
3)ThecodewillnotcompilebecauseclassAhasnomethodsorconstructor.
4)Thecodewillcompilecorrectly,butwillthrowanArithmeticExceptionatruntime.

Q31Considerthefollowingandselectthecorrectstatement(s):
interfaceA{
intx=0;
A(){
x=5;
}
A(ints){
x=s;
}
}
1)Thisisavalidpieceofcodeanditcompilescorrectly.
2)Thedefaultconstructorisnotrequiredsincethecompilerwillcreateoneforyou.
3)Thecodefailstocompilebecauseinterfacescannothavemorethan1constructor.
4)Thecodefailstocompilebecauseaninterfacecannothaveanyconstructors.
5)Thecodefailstocompile,becauseaclassmusthavemorethan1characterinit'sname.

Q32TrueorFalse.
Atryblockalwaysneedsacatchorafinallyblock(eitherorboth,butnotnone).
1)True
2)False

Q33Whichofthefollowingarevalidwaystodeclarethemain()methodwhichisusedtostartaJavaprogram.
1)publicstaticvoidmain(String[]args)
2)staticpublicvoidmain(String[]args)
3)publicvoidmain(Stringargs[])
4)publicstaticvoidmain(Stringargs[])
5)publicstaticvoidmain(Stringargs)

Q34Considerthefollowingpieceofcode:
booleanb=true;
System.out.println(b);
Whatisdisplayedwhenthiscodeisexecuted?
1)Thetext"true"isdisplayed.
2)Thetext"1"isdisplayed
3)Thecodefailstocompile,becauseconversionstringconversioninthsSystem.out.println()methodonlyappliestointegers.
4)Thecodecompilesbutnothingisdisplayeduponexecution.
5)Thecodefailstocompile.However,changingthefirstlineto"booleanb=TRUE;"willcorrectlydeclareaboolean,andthecodewillcompileanddisplay"TRUE".

Q35Whichofthefollowingpiecesofcodecompileswithoutanyerrors?
1)StringBuffersb1="abcd";
2)Booleanb=newBoolean("abcd");
3)byteb=255;
4)intx=0x1234;
5)floatfl=1.2;

Q36Whichofthefollowingarevalidstatementsregardingthefollowingpieceofcode?
1.Strings1="abcd";
2.StringBuffersb1=newStringBuffer("abcd");
3.intval=6;
4.System.out.println(s1+val);
5.System.out.println(sb1+val);

1)Thetext"abcd6"isdisplayedfollowedby"abcd6".
2)ThecodefailstocompilebecauseStringconversiondoesnotapplytoStringBuffer.
3)Thecodecompilesbutuponexecution,throwsaNullPointerExceptionatline5.
4)Thecodefailstocompileatline2,becausethisisnotavalidwaytocreateaStringBuffer.
5)Thecodefailstocompileatline1,becausethisisnotavalidwaytocreateaString.

Q37TrueorFalse.
Abstractmethodscanbedeclaredasstatic.
1)True
2)False

Q38FlowLayoutisthedefaultlayoutmanagerforwhichofthefollowingcontainers:
1)Panel
2)Applet
3)Frame
4)Window
5)Dialog

Q39Inwhichclassarethefollowingmethodsdefined:
-wait()
-notify()
-notifyAll()
1)Thread
2)Runnable
3)Object
4)Event
5)Synchronize

Q40WhichoneofthefollowingcreatesaninstanceofVectorwithaninitialcapacityof10,andanincrementalcapacityof5.
1)newVector(10,5);
2)newVector(5,10);
3)None.ThereisnoconstructorofVectorwhichprovidesthisfeature.
4)Vectorisdeclaredasfinal,anditisthereforenotpossibletoinstantiateit.

Q41TrueofFalse.
CheckboxGroupisasubclassofComponent.
1)True
2)False

Q42Whichstatements(s)belowaretrueaboutthefollowingpieceofcode.
classTestimplementsRunnable{
publicstaticvoidmain(String[]args){
Threadt=newThread(newTest());
t.start();
}

publicvoidrun(intlimit){
for(intx=0;x<limit;x++)
System.out.println(x);
}
}

1)Allthenumbersupto(butnotincluding)"limit"areprintedout.
2)Nothingisdisplayed.Thereisnoexplicitcalltotherun()method.
3)ThecodefailstocompilebecausetheRunnableinterfaceisnotimplementedcorrectly.
4)ThecodecanbemadetocompilebydeclaringtheclassTesttobeabstract.
5)Thecodecanbemadetocompilebyremovingthewords"implementsRunnable".

Q43Considerthefollowingcodeandselectthestatement(s)whicharetrue:
1.classTestextendsFrame{
2.
3.publicstaticvoidmain(String[]args){
4.Testt=newTest();
5.}
6.
7.Test(){
8.Buttonb=newButton("Hello");
9.add(b,BorderLayout.SOUTH);
10.}
11.
12.}

1)Thecodecompiles.Whenexecuted,nothingisdisplayed.
2)Thecodecompiles.Whenexecuted,abuttonwiththetext"Hello"islocatedatthebottomonthescreen.Thebuttonisastallasthetext,butisthewidthoftheframe.
3)Addinginthefollowingtwolinesbetweenlines9and10willdisplayaframewithabuttonatthebottomoftheframe:setSize(100,100);setVisible(true);
4)Thecodefailstocompile,becausealayoutmanagerwasnotspecified.
5)ThecodefailstocompilebecauseyoucannotsubclasstheFrameclass.

Q44Beforewhichofthefollowingcanthekeyword"synchronized"beplaced,withoutcausingacompileerror.
1)classmethods
2)instancemethods
3)anyblockofcodewithinamethod
4)variables
5)aclass

Q45Considerthefollowingclassdefinitions:
classBase{}
classSubclass1extendsBase{}
classSubclass2extendsBase();
Nowconsiderthefollowingdeclarations:
Baseb=newBase();
Subclass1s1=newSubclass1();
Subclass2s2=newSubclass2();
Now,considerthefollowingassignment:
s1=(Subclass1)s2;
Whichofthefollowingstatementsarecorrectregardingthisassignment(selectone).
1)Theassignmentislegalandcompileswithoutanerror.Noexceptionisthrownatruntime.
2)Thecodefailstocompile.Thecompilercomplainsthattheassignment"s1=(Subclass1)s2"isillegal.
3)ThecodecompilesbutClassCastExceptionisthrownatruntime.
4)Thecodefailstocompile.Youcannotsubclassaparentclassmorethanonce.

Q46Selectallthevalidwaysofinitialisinganarray.
1)intx[]={1,2,3};
2)int[]x[]={{1,2,3},{1,2,3}};
3)intx[3]={1,2,3};
4)int[]x={0,0,0};
5)charc[]={'a','b'};

Q47Whatisthevaliddeclarationforthefinalize()method.
1)protectedvoidfinalize()throwsThrowable
2)finalfinalize()
3)publicfinalfinalize()
4)privatebooleanfinalize()
5)privatefinalvoidfinalize()throwsException

Q48WhatisthemethodusedtoretrieveaparameterpassedintoanappletusingthePARAMtag.
1)getParam()
2)getParameter()
3)getVariable()
4)getVar()
5)Thereisnomethodavailable.Youmustuse"String[]args"approach.

Q49Youhaveabutton,whichisinapanel.Thepanelisinsideaframe.YouassigntheFramea24-pointfontandabackgroundcolourofyellow.Yousetthepaneltohaveabackgroundcolourofred.Whichofthefollowingstatementsaretrue(selectallvalidstatements).
1)Thefontsizeofthebuttonis24-point.
2)Thebackgroundcolourofthebuttonisthesameasthatoftheframe.
3)Thepanelhasafontsizeof8-point.
4)Thebuttoninheritsthefontfromthepanel.
5)Thisisnotavalidconfiguration.Itisnotvalidtoplaceapanelintoaframe.

Q50Considerthefollowingpieceofcodeandselectthecorrectstatement(s):
publicclassTest{
finalintx=0;
Test(){
x=1;
}
finalintaMethod(){
returnx;
}
}

1)Thecodefailstocompile.Thecompilercomplainsbecausethereisafinalmethod("aMethod")inanon-finalclass.
2)Thecodecompilescorrectly.Onexecution,anexceptionisthrownwhentheTest()constructorisexecuted.
3)Thecodefailstocompilebecauseanattemptismadetoalterthevalueofafinalvariable.
4)Removingthe"final"keywordfromtheline"finalintx=0"willallowthecodetocompilecorrectly.
5)Thecodefailstocompilebecauseonlymethodscanbedeclaredasfinal(andtherefore"finalintx=0"isnotvalid).

Q51Whatisdisplayedwhenthefollowingcodefragmentiscompiledandexecuted(assumethattheenvelopingclassandmethodiscorrectlydeclaredanddefined):
StringBuffersb1=newStringBuffer("abcd");
StringBuffersb2=newStringBuffer("abcd");
Strings1=newString("abcd");
Strings2="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)Thecodefailstocompile,complainingthatthelineSystem.out.println(s1=s2);isillegal.
2)Thecodefailstocompilebecausetheequals()methodisnotdefinedfortheStringBufferclass.
3)false
true
true
false
false
4)false
abcd
false
false
false
5)false
true
false
false
true

Q52Whatisthedefaultlayoutmanagerforappletsandpanels?
1)FlowLayout
2)BorderLayout
3)GridBagLayout
4)GridLayout
5)Noneofthese

Q53Whichofthefollowingstatementswillcompilewithoutanerror?
1)Booleanb=newBoolean("abcd");
2)floatf=123;
3)byteb=127;
4)intx=(int)(1.23);
5)shorts=128;

Q54TrueorFalse.
Menuscanbeaddedtocontainers.
1)True
2)False

Q55Whichofthefollowingstatementsaretrueregardingthegraphicalmethods
paint(),repaint()andupdate().
1)paint()schedulesacalltorepaint().
2)repaint()schedulesacalltoupdate().
3)update()callspaint().
4)update()schedulesacalltorepaint().
5)repaint()callspaint()directly.

Q56Towhichofthefollowingcanamenubarcomponentbeadded?
1)Applet
2)Panel
3)Frame
4)Canvas

Q57WithregardtoapplyappletbyHTMLtags,whichofthefollowingstatementsarecorrect?
1)TheCODE,WIDTHandHEIGHTtagsaremandatoryandtheorderisinsignificant.
2)CODEandCODEBASEarecaseinsensitive,andthe.classextensionisoptional.
3)ThePARAMtagiscaseinsensitive.
4)ItispossibletodownloadmultipleJAR'swiththeARCHIVEtag(eg,ARCHIVE="a.jar,b.jar").
5)TheCODEtagistheonlymandatorytag.

Q58Considerthefollowingpieceofcodeandselectthecorrectstatements.
1.Objecto=newString("abcd");
2.Strings=o;
3.System.out.println(s);
4.System.out.println(o);

1)Thefollowingisdisplayed:
abcd
abcd
2)Thecodefailstocompileatline1.
3)Thecodefailstocompileatline2
4)Thecodefailstocompileatline4.
5)Thecodecanbemadetocompilebychangingline1tothefollowing:
Stringo=newString("abcd");

Q59WhichofthefollowingarelegalmethodsfortheStringclass?
1)length()
2)toUpper()
3)toUpperCase()
4)toString()
5)equals()

Q60Whatistheoutputfromthefollowingpieceofcode:
loop1:
for(inti=0;i<3;i++){
loop2:
for(intj=0;j<3;j++){
if(i==j){
breakloop2;
}
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=1j=0i=2j=0i=2j=1

Q61Whatisdisplayedwhenthefollowingpieceofcodeisexecuted:
loop1:
for(inti=0;i<3;i++){
loop2:
for(intj=0;j<3;j++){
if(i==j){
continueloop2;
}
System.out.println("i="+i+"j="+j);
}
}

1)i=0j=0
i=0j=1
i=1j=0
i=1j=1
i=2j=0
i=2j=1
2)i=0j=0
i=1j=1
i=2j=2
3)i=0j=1
i=0j=2
i=1j=0
i=1j=2
i=2j=0
i=2j=1
4)Noneoftheabove.

Q62Considerthefollowingpieceofcode,andselectthecorrectstatement(s):
longval=2;
...
...
Switch(val){
default:
System.out.println("Default");
break;
case1:
System.out.println("1");
break;
case2:
System.out.println("2");
case3:
System.out.println("3");
break;
}

1)Thefollowingisdisplayed:
2
3
2)Thefollowingisdisplayed:
2
3)Thecodefailstocompilebecausethedefaultcasemustbethelastcaseintheswitchstatement.
4)Thecodefailstocompilebecausetheargumentforaswitchstatementcannotbeavariableoftypelong.
5)Thefollowingisdisplayed:
2
3
Default

Q63Considerthefollowingpieceofcode,andselectthecorrectstatement(s):
publicclassTestextendsApplet{
publicvoidinit(){
setLayout(newGridLayout(1,2));
add(newButton("#1"));
add(newButton("#2"));
add(newButton("#3"));
add(newButton("#4"));
}
}

1)TheGridlayoutiscreatedwith1rowand2columns.
2)Addingthebuttonwiththelabel"#3"willcauseanexceptiontobethrown.
3)Addingthebuttonwithlabel"#3"willcauseittooverwritethebuttonwithlabel"#2".
4)Thelayoutautomaticallyextendstoaccommodatetheadditionalbuttons.
5)Only2buttonsaredisplayed,onewithlabel"#1"andonewithlabel"#4".

Q64Whichofthefollowinglayoutmanagerswillretainthepreferredwidthandheightofthecontainedcomponents.
1)GridLayout
2)GridBagLayout
3)BoxLayout
4)FlowLayout
5)BorderLayout

Q65YouconstructaListbycallingList(5,false).
Whichstatementsbelowarecorrect(assumethelayoutmanagersdonotmodifytheListproperties).
1)Thelistsupportsmultipleselection.
2)Thelisthas5visibleitems.
3)Averticalscrollbarwillbeaddedautomaticallyifneeded.
4)Thecodefailstocompile.Thegivenconstructorisnotavalidone.

Q66Whichofthefollowingwilldefinitelystopathreadfromexecuting:
1)wait()
2)notify()
3)yield()
4)suspend()
5)sleep()

Q67Whichofthefollowingisthecorrectmethodtocalltochangethelayoutmanagerforacontainer:
1)setLayoutManager()
2)setLayManager()
3)changeLayout()
4)Youcan'tchangethelayoutmanagerforacontainer.
5)setLayout()

Q68Whichisthecorrectwaytoaddabutton,referencedbyb,toapanel,referencedbyp.
1)add(p,b);
2)p.add(b)
3)b.add(p)
4)Buttonscan'tbeaddedtopanels.
5)add(p)

Q69Whatisdisplayedwhenthefollowingcodeiscompiledandexecuted:
longval=2;
switch(val){
case1:
System.out.println("1");
case2:
System.out.println("2");
default:
System.out.println("default");
}
1)default
2)2
default
3)Thecodefailstocompilebecausetherearenobreakstatementsinthecaseclauses.
4)Thecodefailstocompilebecausealongdatatypeisnotavalidparameterforaswitchstatement.

Q70Whatisdisplayedfollowingtheexecutionofthecodebelow:
1.classTest{
2.Strings;
3.publicstaticvoidmain(String[]args){
4.intx=4;
5.if(x<4)
6.System.out.println("Val="+x);
7.else
8.System.out.println(s);
9.}
10.}

1)Nothing.Thecodedoesn'tcompilebecausethevariableswasn'tinitialised.
2)Thestring"null"isdisplayed.
3)Thecoderuns,butaNullPointerExceptionisthrownatline8.
4)Thecodecompiles.Noexceptionisthrownbutnothingisdisplayed.
5)Nothing.Thecodedoesn'tcompilebecauseyoucan'tmakeastaticreferencetoanon-staticvariable.

Q71Considerthefollowingpieceofcode:
classTest{
intx;
Strings;
floatfl;
boolean[]b=newboolean[5];

publicstaticvoidmain(String[]args){
System.out.println(x);
System.out.println(s);
System.out.println(fl);
System.out.println(b[2]);
}
}
Whatisdisplayedwhenthiscodeisexecuted.
1)0
null
0.0
false
2)0
""
0.0
true
3)Nothing.Thecodefailstocompilebecausethebooleanarrayisincorrectlydeclared.
4)Nothing.ThecodewillnotcompilebecausethestaticmethodcannotaccessthevariablessincethereisnoinstanceoftheTestclass.

Q72Whatisdisplayedwhenthefollowingcodeiscompiledandexecuted:
Strings="abcd";
Strings1=newString(s);
if(s==s1)
System.out.println("thesame");
if(s.equals(s1))
System.out.println("equals");
1)thesame
equals
2)equals
3)thesame
4)Thecodecompiles,butnothingisdisplayeduponexecution.
5)Thecodefailstocompile.

Q73Whatisthelegalrangeforthebytedatatype:
1)0to+255
2)-127to+128
3)-128to+127
4)0to65535
5)-32767to+32768

Q74Whatisdisplayedwhenthefollowingcodeisexecuted:
Strings="abcdef";
System.out.println(s.charAt(4));
1)d
2)e
3)Nothing.AnArrayIndexOutOfBoundsExceptionisthrown
4)Thecodedoesnotcompile.charAt()isnotavalidmethodoftheStringclass.
5)Thecodedoesnotcompilebecausethestringsisnotcreatedcorrectly.

Q75TrueorFalse.
TheStringclassdoesnothaveanappend()method.
1)True
2)False

Q76Considerthefollowingcodesegment.
doubled=-11.1;
doubled1=method(d);
System.out.println(d1);
Iftheoutputofthiscodesegmentis-12.0,thenwhatmethodscouldbecalledinmethod()above.
1)floor()
2)ceil()
3)round()
4)abs()
5)min()

Q77WhatoutputsarepossiblefrominvokingMath.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

Q78Inathread,thewait()methodmustbecalledinsidewhichofthefollowing:
1)Awhile()loop
2)Therun()method
3)synchronisedcode
4)Theconstructor
5)Itdoesn'tmatterwherethewait()iscalledfrom.

Q79Considerthefollowingpieceofcode:
publicclassTestextendsApplet{
publicvoidinit(){
setLayout(newBorderLayout());
add("South",newButton("B1"));
add("North",newButton("B2"));
add("South",newButton("B3"));
}
}
Selectthecorrectstatementsregardingtheabove.
1)Thereare2buttonsdisplayedintheSOUTHsection,B1andB3.
2)OnlyB3isdisplayedintheSOUTHsection.
3)AnexceptionisthrownwhenanattemptismadetoaddasecondcomponenttoSOUTH.
4)OnlyB1isdisplayedintheSOUTHsection.
5)Youcan'taddbuttonstoapplets.

Q80Whatisdisplayedwhenthefollowingpieceofcodeisexecuted:
1.Stringval=null;
2.intx=Integer.parseInt(val);
3.
4.System.out.println(x);
1)0
2)null
3)ANumberFormatExceptionisthrownatline2.
4)Nothingisdisplayed

Q81Considerthefollowingpieceofcode:
classA{
intx=0;
A(intw){
x=w;
}
}

classBextendsA{
intx=0;
B(intw){
x=w+1;
}
}
1)Thecodecompilescorrectly.
2)Thecodefailstocompile,becausebothclassAandBdonothavevalidconstructors.
3)Thecodefailstocompilebecausethereisnodefaultno-argsconstructorforclassA.

Q82GivenanobjectmyListener(whoseclassimplementstheActionListenerinterface),whichofthefollowingarevalidwaystoenablemyListenertoreceiveallactioneventsfromcomponentsmallButton?
1)smallButton.add(myListener);
2)smallButton.addListener(myListener);
3)smallButton.addActionListener(myListener);
4)smallButton.addItem(myListener);

Q83Whichofthefollowingarevalidlistenerinterfaces?
1)ActionListener
2)MouseMotionListener
3)SystemEventListener
4)MouseClickListener
5)WindowListener

Q84Whichofthefollowingisthecorrectwaytosettheforegroundcolourofacomponent,c.
1)c.setForeground("red");
2)c.setColor("Color.red");
3)c.Foreground(Color.red);
4)c.setForegroundColor("red");
5)c.setForeground(Color.red);

Q85WhichofthefollowingarevalidwaystocreateaMapcollection.
1)Mapm=newMap();
2)Mapm=newMap(initcapacity,incrementcapacity);
3)Mapm=newMap(newCollection());
4)Mapisaninterface,andcannotbeinstantiated.

Q86Selectallthecorrectstatementsrelatingtothefollowingpieceofcode?
1.publicclassA{
2.abstractintmethod();
3.voidanotherMethod(){
4.}
5.
6.classBextendsA{
7.intmethod(){
8.return2;
9.}
10.}
1)Changing"extends"to"implements"online6willallowthecodetocompilecorrectly.
2)Themethod()inclassAcannotbeabstractwithouttheentireclassbeingdeclaredasabstract.
3)DeclaringclassAtobeabstractwillallowthecodetocompilecorrectly.
4)TheclassAmusthaveanexplicitdefaultconstructorinorderforittobesubclassedcorrectly.
5)Thecodefailstocompile,becauseclassBdoesnotimplementanotherMethod().

Q87Whichlayoutmanagerdothecommentsbelowreferto:
Allcomponentscontainedinithavethesamewidthandheight.Containedcomponentsarestretchedtohavethesamedimensions.
1)FlowLayout
2)BorderLayout
3)GridLayout

Q88Selectallvalidstatements.
1)WhentypingtextintoaTextField,scrollbarswillautomaticallyappearwhentheTextFieldbecomesfull.
2)WhentypingtextintoaTextArea,scrollbarswillappearwhentextistypedpasttheboundariesoftheTextArea.
3)TextFieldscanhavemorethan1rowoftext.
4)TheclassTextAreaisasuperclassoftheclassTextField.
5)BothTextAreasandTextFieldshaveamethodcalledsetEditable(),whichcanenableordisableeditingofthecomponent.

Q89Inwhichclassisthepaint()methoddefined?
1)Object
2)Applet
3)Component
4)Thread
5)Graphics

Q90Selectthestatementwhichmostcloselydescribestheuserinterfaceofanappletwiththefollowinginit()method:
publicvoidinit(){
Panelp=newPanel();
p.setLayout(newBorderLayout());
p.add(newButton("Hello"),BorderLayout.EAST);
p.add(newButton("Bye"),BorderLayout.WEST);
add(p);
}
1)Twobuttonsaredisplayed.Abuttonwith"Hello"isontherightsideoftheapplet.Thebuttonwith"Bye"isontheleftsideoftheapplet.Bothbuttonsextendfromthecentreoftheapplettoeachside,andaretheheightoftheapplet.
2)Twobuttonsaredisplayed.Abuttonwith"Hello"isontherightsideoftheapplet.Thebuttonwith"Bye"isontheleftsideoftheapplet.Bothbuttonsareonlyaswideasthetextonthebutton,butaretheheightoftheapplet.
3)Twobuttonsaredisplayed.Abuttonwith"Hello"isontherightsideoftheapplet.Thebuttonwith"Bye"isontheleftsideoftheapplet.Bothbuttonsareonlylargeenoughtosupporttheassociatedbuttontexts.

Q91Whatiswrongaboutthefollowingpieceofcode(assumetherelevantimportstatementsarepresent):
publicclassTest{
publicstaticvoidmain(String[]args)throwsIOException{
if(args[0]=="hello")
thrownewIOException();
}
}
1)Nothing.Thecodecompilescorrectly.
2)Thecodefailstocompile.Youcan'tthrowanexceptionfromthemain()method.
3)Thecodefailstocompile.IOExceptionisasystemexception,andcannotbethrownbyapplicationcode.

Q92Considerthefollowingpieceofcode,andselectthestatementswhicharetrue.
classTest{
intx=5;
staticStrings="abcd";
publicstaticvoidmethod(){
System.out.println(s+x);
}
}
1)Thecodecompilesanddisplays"abcd5".
2)Thecodecompiles,butthrowsanexceptionatruntime,becausevariablexisn'tdeclaredasstatic.
3)Thecodefailstocompilebecauseyoucan'tmakeastaticreferencetoanon-staticvariable.
4)Thecodewillcompileifxisdeclaredtobestatic.
5)Thecodewillcompilebyremovingthestatickeywordfromthedeclarationofmethod().

Q93Selectalllegalcodefragmentsfromthefollowing.
1)charc="c";
2)Booleanb=newBoolean("qwerty");
3)Strings="null";
4)intq;
for(intp=0,q=0;p<5;p++){
System.out.println("Val="+p+q);
}
5)intx=3;
Floatf=newFloat(x);

Q94WhichofthefollowingarelegalwaystoconstructaRandomAccessFile?
1)RandomAccessFile("file","r");
2)RandomAccessFile("r","file");
3)RandomAccessFile('r',"file");
4)RandomAccessFile("file",'r');
5)RandomAccessFile("file","rw");

Q95Considerthefollowingcodeandselectthemostappropriatestatements.
1.classTest{
2.publicintdoubleValue(inta)
3.System.out.println(a);
4.return(int)(a*2);
5}
6.
7publicfloatdoubleValue(inta){
8.System.out.println(a);
9.return(float)(a*2);
10.}
11.}
1)ThecodecompilessincethetwodoubleVal()methodshavedifferentreturntypes.
2)Thecodedoesn'tcompilebecausethecompilerseestwomethodswiththesamesignature.
3)ThecodecanbemadetocompilebyredefiningtheparameterfordoubleVal()online7tobe"floata"insteadof"inta".
4)Thecodecanbemadetocompilebyreplacingthepublicdeclarationonline7withprivate.

Q96Whatisdisplayedwhenthefollowingpieceofcodeisexecuted:
classTestextendsThread{
publicvoidrun(){
System.out.println("1");
yield();
System.out.println(2");
suspend();
System.out.println("3");
resume();
System.out.println("4");
}

publicstaticvoidmain(String[]args){
Testt=newTest();
t.start();
}
}
1)1
2
3
4
2)1
2
3
3)1
2
4)Nothing.Thisisnotavalidwaytocreateandstartathread.
5)1

Q97Considerthefollowingpieceofcode,andselectthemostappropriatestatements.
TextFieldt=newTextField("Hello",20);
1)Theuserwillbeabletoeditthestring.
2)Thefieldwillbe20characterswide.
3)Thetextfieldwillbesamesizeonallplatforms,sinceJavaisplatformindependent.
4)Whenenteringtextintothefield,only20characterscanbeentered.
5)Ifthefontischanged,thesizeofthetextfieldwilladjusttoallow20characterstobedisplayed.

Q98TrueofFalse.
Usingtheinstanceofoperatoronaninterfacewillcausearuntimeexception.
1)True
2)False

Q99WhichofthefollowingarevalidwaystocreateaButtoncomponent?
1)newButton();

2)newButton(30,10);where30isthewidthofthebuttonand10istheheight
3)newButton("hello");
4)newButton(newString("hello"));
5)newButton(String("hello"));

Q100WhichofthefollowingareNOTvalidsubclassesofAWTEvent?
1)MouseClickEvent
2)OutputEvent
3)MouseMotionEvent
4)KeyAdapter
5)WindowMinimizeEvent

Q101WhichofthefollowingarevalidmethodsfortheGraphicsclass?
1)drawOval(intx,inty,intwidth,intheight)
2)toString()
3)drawArc(intx,inty,intwidth,intheight,intstartAngle,intarcAngle)
4)drawPolygon(int[]xPoints,int[]yPoints,intnPoints)
5)fillArc(intx,inty,intwidth,intheight,intstartAngle,intarcAngle)

Q102WhichofthefollowingarevalidmethodsintheMathclass?
1)arcTan(doublea)
2)atan(doublea)
3)sqrt(doublea)
4)min(inta,intb)
5)cosine(doublea)

Q103Whichofthefollowingwilldisplaythestring"ica",given:
Strings="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)Noneofthese.

Q104WhichofthefollowingaredefinedintheObjectclass?
1)toString()
2)equals(Objecto)
3)publicstaticvoidmain(String[]args)
4)System.out.println()
5)wait()

Q105Selectallvalidstatementsrelatingtothepaint()methoddefinedintheComponentclass.
1)Ittakes4inttypesasparameters,representingthexandyco-ordinates,widthandheight,respectively.
2)Itisdeclaredasfinal,andsoitcannotbeoverridden.
3)Itisdeclaredasstatic.
4)IttakesaninstanceoftheGraphicscomponentasaparameter.
5)Whenoverridingthepaint()method,youmusthandletheidentificationandrepairofdamagedcomponents.

Q106Whichofthefollowingkeywordscanbeappliedtoamethod?
1)transient
2)volatile
3)private
4)protected
5)final

Q107Whichofthefollowingkeywordscanbeappliedtoatop-levelclass(i.e.,notaninnerclass)?
1)private
2)protected
3)transient
4)public
5)final

Q108Considerthefollowingpieceofcode,andselectallrelevantstatements:
1.classTest{
2.publicstaticvoidmain(String[]args){
3.aMethod();
4.}
5.
6.staticvoidaMethod(){
7.try{
8.System.out.println("abcd");
9.return;
10.}finally{
11.System.out.println("1234");
12.}
13.}
14.}

1)Anexceptionisthrownatline9.
2)Thecodefailstocompile.Thecompilercomplainsaboutthereturnstatementatline9.
3)abcd
1234
4)abcd
5)Thecodefailstocompile,complainingthata'catch'clauseismissingfromline10.

Q109Whichofthefollowingstatementsaretrue.
1)Thetype"int"isa32-bitsignedintegervalue.
2)Thetype"short"isa16-bitunsignedintegervalue.
3)Thetype"char"isa16-bitUnicodecharacter.
4)Thetype"float"isa64-bitfloatingpointvalue.
5)Thetype"long"isa64-bitsignedintegervalue.

Q110Whichlayoutmanagerisdescribedbythefollowing:
Italignscomponentsverticallyandhorizontally,withoutrequiringthatthecomponentsbeofthesamesize.Itmaintainsadynamicrectangulargridofcells,witheachcomponentoccupyingoneormorecells,calleditsdisplayarea.
1)GridLayout
2)FlowLayout
3)GridBagLayout
4)BoxLayout

Q111TrueofFalse.
TheStringBufferclassoverridesthetoString()methodtoreturnaStringrepresentationoftheStringBuffer.
1)True
2)False

Q112Selectthecorrectstatementsfromthefollowing:
1)TheclassRandomAccessFileisasubclassofthejava.io.Fileclass.
2)Theclassjava.io.FileWritercontainsmethodstowriteprimitives(eg,writeInt(),writeFloat(),etc)
3)Theclassjava.io.BufferedOutputStreamcontainsmethodstowriteprimitives(eg,writeInt(),writeFloat(),etc)
4)TheFileclassdefinesamethodwhichcanbeusedtodeletefilesanddirectoriesfromadisk.
5)TheRandomAccessFileclassdefinesamethodwhichcanbeusedtodeletefilesanddirectoriesfromadisk.

Q113TrueorFalse.
Aclasscanimplementmorethanoneinterface,butcanonlyinheritfromasingleparentclass.
1)True
2)False

Q114Whatistheresultofcompilingandexecutingthefollowingcode.
publicclassThreadTestextendsThread{
publicvoidrun(){
System.out.println("Inrun");
yield();
System.out.println("Leavingrun");
}

publicstaticvoidmain(Stringargs[]){
(newThreadTest()).start();
}
}
1)Thecodefailstocompileinthemain()method.
2)Thecodefailstocompileintherun()method.
3)Onlythetext"Inrun"willbedisplayed.
4)Thetext"Inrun"followedby"Leavingrun"willbedisplayed.
5)Thecodecompilescorrectly,butnothingisdisplayed.

Q115Whichofthefollowingwillcompilewithouterrors.
1)Byteb=newByte(123);
2)Byteb=newByte("123");
3)Byteb=newByte();
b=123;
4)Byteb=newByte((int)123.4);
5)Byteb=newByte(0x123);

Q116Considerthefollowingpieceofcodeandselectthecorrectstatement(s):
1.publicclassTest{
2.staticintx;
3.staticpublicvoidmain(String[]args){
4.x=x+1;
5.System.out.println("Valueis"+x);
6.}
7.}
1)Thecodefailstocompile.Thecompilercomplainsthatthevariablexisusedbeforeitisinitialised.
2)Thecodecompilescorrectlyanddisplays"Valueis1"whenexecuted.
3)Thecodecompilescorrectly,butthrowsaNullPointerExceptionatline5.
4)Thecodefailstocompilebecausethe'main'methodisincorrectlydeclared.

Q117Whichofthefollowingaretermed"shortcircuit"logicaloperators.
1)&
2)&&
3)|
4)||
5)^

Q118Whichofthefollowingarevalidexpressions.
1)Objecto=newString("abcd");
2)Booleanb=true;
3)Panelp=newFrame();
4)Appleta=newPanel()
5)Panelp=newApplet()

Q119Whichofthefollowingisavalidwaytodeclareanabstractmethodwhichisintendedtobepublic.
1)publicabstractmethod();
2)publicabstractvoidmethod();
3)publicabstractvoidmethod(){}
4)publicvirtualvoidmethod();
5)publicvoidmethod()implementsabstract;

Q120WhichofthefollowingarevalidwaystodefineaconstructorforclassTest.
1)publicvoidTest(){}
2)publicTest(){}
3)privateTest(){}
4)publicstaticTest(){}
5)finalTest(){}

Q121Whichofthefollowingstatementsarevalidforamethodwhichisoverridingthefollowing:
protectedvoidmethod(intx){..}
1)Theoverridingmethodmusttakeanintasitsonlyparameter.
2)Theoverridingmethodmustreturnavoid.
3)Theoverridingmethodcanbedeclaredasprivate.
4)Theoverridingmethodcanreturnanyvalueitwishes.

Q122TrueorFalse.
Aninnerclasscanimplementaninterfaceorextendaclass.
1)True
2)False

Q123Whichofthefollowingarevalidreturntypesforlistenermethods.
1)boolean
2)void
3)AnobjectoftypeEvent
4)AnobjectoftypeObject
5)Alongvalue,representingtheObjectID.

Q124Considerthefollowingpieceofcodeandselectthecorrectstatements.
1.publicclassTest{
2.publicstaticvoidmain(String[]args){
3.print();
4.}
5.
6.publicstaticvoidprint(){
7.System.out.println("Test");
8.}
9.
10.publicvoidprint(){
11.System.out.println("AnotherTest");
12}
13.}
1)Thecodecompilessuccessfullyanddisplays"Test".
2)Changingthecodeatline10tothefollowing,willallowthecodetocompilecorrectly:
publicvoidprint(intx){
3)Thecodefailstocompile.Thecompilercomplainsaboutastaticreferencetoanon-staticmethod,print().
4)Thecodefailstocompile.Thecompilercomplainsaboutduplicatemethods.
5)Changingthereturntypeonline10from'void'to'int'willallowthecodetocompilecorrectly.

Q125ConsiderthefollowinglistoftagsandattributesoftagsandselecttheoneswhichcanlegallybeplacedbetweentheAPPLETand/APPLETdelimiters.
1)JAVAC
2)JAR
3)CODE
4)NAME
5)PARAM

Q126Whichvariablescananinnerclassaccessfromtheclasswhichencapsulatesit.
1)Allstaticvariables
2)Allfinalvariables
3)Allinstancevariables
4)Onlyfinalinstancevariables
5)Onlyfinalstaticvariables

Q127UsingaFlowLayoutmanager,whichofthefollowingisthecorrectwaytoaddaconponentreferencedbythevariable"c"toacontainer:
1)add(c);
2)add("Center",c);
3)c.add();
4)c.set();
5)set(c);

Q128AssumingthereisaclassXwhichimplementstheActionListenerinterface.
WhichmethodshouldbeusedtoregisterthiswithaButton?
1)addListener(newX());
2)addActionListener(newX());
3)addButtonListener(newX());
4)addActionAdapter(newX());
5)(newX()).addActionListener();

Q129Whatistheresultofcompilingandexecutingthefollowingfragmentofcode:
booleanflag=false;
if(flag=true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
1)Thecodefailstocompileatthe"if"statement.
2)Anexceptionisthrownatrun-timeatthe"if"statement.
3)Thetext"true"isdisplayed.
4)Thetext"false"isdisplayed.
5)Nothingisdisplayed.

Q130Whichofthefollowingisnotasubclassofjava.awt.Component?
1)Frame
2)Container
3)CheckboxGroup
4)Canvas
5)Applet

Q131Whatistheresultwhenthefollowingpieceofcodeiscompiledandexecuted.
1.publicclassCalc{
2.publicstaticvoidmain(Stringargs[]){
3.inttotal=0;
4.
5.for(inti=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)Thecodefailstocompileatline5,becausethevariable"j"isnotdeclaredcorrectly.
2)Thecodefailstocompileatline2,becauseyoucan'thaveastaticmethodinanon-staticclass.
3)Thecodecompilescorrectly,butthrowsanexceptionatline5.
4)Thecodecompilescorrectlybutthrowsanexceptionatline2.
5)Thecodecompilescorrectlyanddisplaysthefollowingwhenexecuted:
i=0:j=10
i=1:j=9
i=2:j=8
Total30

Q132WhichofthefollowingwillcreateaTextFieldcapableofdisplaying10characters,withtheinitialtext"hello"?
1)TextFieldt=newTextField("hello",10);
2)TextFieldt=newTextField(10,"hello");
3)TextFieldt=newTextField();
t.setCols(10);
t.setText("hello");
4)TextFieldt=newTextField();
t.setFieldSize(10);
t.setText("hello");
5)Noneoftheabove.

Q133WhatistheeffectofaddingthesixthelementtoaVectorcreatedusingthefollowingcode:
newVector(5,10);
1)AnIndexOutOfBoundsexceptionisthrown.
2)Thevectorgrowsinsizetoacapacityof10elements.
3)Thevectorgrowsinsizetoacapacityof15elements.
4)Nothing.TheVectorwillhavegrownwhenthefifthelementwasadded,becauseVectorelementsarezero-based.
5)Nothing.ThisisnotavalidwaytocreateaVector.

Q134Whenisthetext"Hithere"displayed?
publicclassStaticTest{
static{
System.out.println("Hithere");
}

publicvoidprint(){
System.out.println("Hello");
}

publicstaticvoidmain(Stringargs[]){
StaticTestst1=newStaticTest();
st1.print();
StaticTestst2=newStaticTest();
st2.print();
}
}
1)Never.
2)EachtimeanewobjectoftypeStaticTestiscreated.
3)OncewhentheclassisloadedintotheJavavirtualmachine.
4)Onlywhenthemain()methodisexecuted.

Q135Whichofthefollowingarevalidwaystoassignthevalueof5toavariableoftype"int"calledtestValue?
1)inttestValue=0x5;
2)inttestValue=(int)(2.1F+3.4D);
3)inttestValue=(octal)5;
4)inttestValue=(0x0A>>1);
5)inttestValue=(0x0A>>>1);

Q136WhichofthefollowingoperationswillcauseanActionEventtobegenerated.
1)Clickingacheckbox.
2)SelectinganoptionfromaChoicebox.
3)Scrollingascrollbar.
4)Clickingabutton.
5)HittingENTERwhentypinginatextfield.

Q137TrueorFalse.
AllListenerinterfacesmethodsaredeclaredaspublicandvoid.
1)True
2)False
Q138TrueorFalse.
InaGridLayout,thewidthandheightofallcellsarethesame.
1)True
2)False

Q139TrueorFalse.
TheBorderLayoutmanageronlyallowsasinglecomponenttobedisplayedineachsector.
1)True
2)False

Q140YouwanttoextendthefunctionalityoftheStringclass,anddecidethatthebestapproachistosubclassString.Whichofthefollowingstatementsarecorrect.
1)Theapproachfails,becausetheStringclassisdeclaredasfinalandcannotbesubclassed.
2)Theapproachsucceeds,anditisthereforepossibletooverridethestandardfunctionalityprovidedbyString.
3)Theapproachfails,becausetheStringclassisdeclaredasabstract,andthereforeitcannotbesubclassed.

Q141Whichofthefollowingarevalidwaystodeterminethenumberofelementsinanarraydefinedasfollows:
intintArray[]={1,2,3};
1)intArray.size;
2)intArray.size();
3)intArray.length;
4)intArray.length();
5)intArray.getSize();

Q142Youhaveacheckboxwithinapanel,andthepaneliscontainedwithinanapplet.Therearenoothercomponentswithintheapplet.
Using"setBackground(Color.white)",youassignthebackgroundcolouroftheapplettowhite.
Whichofthefollowingstatementsaretrue.
1)Thebackgroundcolourofthepaneliswhite.
2)Theforegroundcolourofthecheckboxisthesameastheforegroundcolouroftheapplet.
3)Itisimpossibletodeterminethebackgroundcolourofthecheckboxfromtheimformationsupplied.
4)Youcan'tputapanelinsideanapplet.

Q143Whichofthefollowingcanbeaddedtoamenu?
1)Apanel
2)Abutton
3)Amenu
4)Acheckbox
5)Amenubar

Q144Youconstructanapplicationbymakingthefollowingcall:
Frameapp=newFrame();
app.setSize(100,100);
Whichofthefollowingstatementsarecorrect.
1)Anemptyframeofsize100x100isdisplayed,locatedinthetopleftcornerofthescreen.
2)Anemptyframeofsize100x100isdisplayed,locatedinthecentreofthescreen.
3)Nothingisdisplayed.ThereisnosetSize()methodintheFrameclass.
4)Nothingisdisplayed.Theframewillonlybedisplayedbysettingtheforgroundandbackgroundcolours.
5)Nothingisdisplayed.Aframeiscreatedbydefaultwithzerosize,andinvisible.

Q145Whichofthefollowingarevalidmethodsinthejava.awt.Graphicsclass?
1)drawString()
2)drawOval()
3)fillRect()
4)drawPolyline()
5)fillPolyline()

Q146WhichofthefollowingarevalidcommandlineoptionsfortheJARutility:

1)c(createaneworemptyarchive)
2)m(indicatesthatfirstargumentisthenameofauser-suppliedmanifest)
3)M(donotcreateamanifest)
4)z(ZIPthecontentsofthearchive)
5)L(listthearchivecontents)

Q147Considerthefollowingcodesegmentandselectthecorrectstatement(s):
1.classFinalTest{
2.finalintq;
3.finalintw=0;
4.
5.FinalTest(){
6.q=1;
7.}
8.
9.FinalTest(intx){
10.q=x;
11.}
12.}
1)Thecodefailstocompilebecauseaclasscannothavemorethan1constructor.
2)ThecodefailstocompilebecausetheclassFinalTesthasnoconstructors.
3)Thecodefailstocompilebecausetheanattemptismadetoinitialiseafinalvariableatlines6and10.
4)Thecodecompilescorrectlywithoutanywarningsorerrors.
5)Thecodefailstocompilebecausethefinalvariableqisnotinitialisedcorrectlyatline2.

Q148TrueorFalse.
Itisvalidtothrow(andre-throw)anexceptioninsideacatch{}clause.
Forexample:
...
catch(Exceptione){
throwe;
}
1)True
2)False

Q149TrueorFalse.
AscrollbarwillappearinaTextFieldifmoretextistypedthancanbedisplayedwithintheTextField.
1)True
2)False

Q150TrueorFalse.
Itisvalidtodeclareaninheritedmethodasabstract.
1)True
2)False

Q151Considerthefollowingcodesegmentsandselectthecorrectstatement:
Segment1:
1.inta=3;
2.intb=0;
3.intc=a/b;
Segment2:
4.floata=1.0F;
5.floatb=0.0F;
6.floatc=a/b;
1)Whenexecuted,bothsegmentswillcauseanexceptiontobethrown.
2)Whenexecuted,neithersegmentwillcauseanexceptiontobethrown.
3)OnlySegment1willthrowanexception.
4)OnlySegment2willthrowanexception.

Q152Whichofthefollowingclassesoverridetheequals()method.
1)String
2)Integer
3)Double
4)Date
5)File

Q153Whichofthefollowingisthedefaultlayoutmanagerforapanel.
1)BorderLayout
2)FlowLayout
3)GridBagLayout
4)GridLayout
5)Noneoftheabove.

Q154TrueorFalse.
TheStringBufferclassinheritsfromtheStringclass.
1)True
2)False

Q155TrueorFalse.
TheclassStringhasaconcat()method,whiletheStringBufferclasshasanappend()method.
1)True
2)False

Q156TrueorFalse.
TheprimativewrapperclassesInteger,DoubleandFloatallinheritdirectlyfromthejava.lang.Wrapperclass.
1)True
2)False

Q157WhichofthefollowingarevalidmethodsfortheAppletclass.
1)start()
2)stop()
3)init()
4)destroy()
5)kill()

Q158TrueorFalse.
Alabelcanonlydisplayasinglelineoftext.
1)True
2)False

Q159WhichofthefollowingarevalidmethodsfortheMathclass.
1)random()
2)Random()
3)toDegrees()
4)square()
5)sqr()

Q160TrueorFalse.
JDK1.2containsanArraysclasswhichprovidesvariousmethodsformanipulatingarrays(suchassearchingandsorting).
1)True
2)False

Q161TrueorFalse.
TheClassclasshasnopublicconstructor.
1)True
2)False

Q162Whichofthefollowingstatementsistruewithregardtopersistence.
1)"Serializable"isakeywordwithintheJavalanguage.
2)"Serializable"isaninterface,whichclassescanimplement.
3)"Serializable"isaclass,whichotherclassescanextend.
4)Noneoftheabove.

Q163Whichofthefollowingstatementsiscorrectwithregardtothreads.
1)"Runnable"isakeywordwithintheJavalanguage,usedtoidentifyclasseswhichcanexistasseparatethreads.
2)"Runnable"isaninterface,whichclassescanimplementwhentheywishtoexecuteasaseparatethread.
3)"Runnable"isaclass,whichclassescanextendwhentheywishtoexecuteasaseparatethread.
4)Noneoftheabove.
5)javadoesnotsupportthreads.

Q164Selectthestatementswhicharevalidfromthelistbelow.
1)Theprimativedatatype"char"is16-bitswide.
2)Unicodeuses16-bitstorepresentacharacter.
3)Unicodeuses32-bitstorepresentacharacter.
4)UTFuses24-bitstorepresentacharacter.
5)UTFusesasmanybitsasareneededtorepresentacharacter.

Q165WhenaFrameisconstructed,ithasnosizeandisnotdisplayed.WhichofthefollowingmethodscanbecalledtodisplaytheFrame.
1)setSize()
2)setBounds()
3)setDisplayable()
4)setVisible()
5)setState()

Q166Whichoneofthefollowingiscorrect(assumeAandBarecorrectlydefined).
1)if(AinstanceOfB)
2)if(AinstanceofB)
3)if(A.instanceOf(B))
4)if(Ainstanceof(B))

Q167Whatisdisplayedwhenthefollowingisexecuted:
doubled1=-0.5;
System.out.println("Ceild1="+Math.ceil(d1));
System.out.println("floord1="+Math.floor(d1));
1)Ceild1=-0.0
floord1=-1.0
2)Ceild1=0.0
floord1=-1.0
3)Ceild1=-0.0
floord1=-0.0
4)Ceild1=0.0
floord1=0.0
5)Ceild1=0
floord1=-1

Q168Selectthelayourmanagerwhichisdescribedbythefollowing:
"Itarrangesitsconstituentcomponentsinhorizontalrows.Itwillattempttofitasmanycomponentsaspossibleintothefirstrow,andremainingcomponentswillspilloverintosubsequentrows.Componentsalwaysappearlefttoright,intheordertheywereaddedtothecontainer."
1)FlowLayout
2)GridLayout
3)CardLayout
4)TransverseFlowLayout
5)GridBagLayout

Q169TrueorFalse
Theargumentfora"case"statementmustbeaconstantoraconstantexpressionwhichcanbeevaluatedatcompiletime.
1)True
2)False

Q170Selectthevalidcodefragmentsfromthefollowinglist:
1)publictransientstaticfinalint_FRAMEX=850;
2)this("a","b");
[assumingaconstructorofthetypexxx(String,String)existsforthisclass]
3)privatetransientstaticfinalint_FRAMEX=850;
4)booleanb=0;

Q171TrueorFalse.
TheFileclasscanrepresenteitherafileoradirectorywithinafilesystem.
1)True
2)False

Q172TrueorFalse.
Theargumentforawhile()statementMUSTbeaboolean.
1)True
2)False

Q173TrueorFalse.
Theright-handoperandoftheinstanceofoperatorcanbeaninterface;eg
ainstanceofb
wherebisaninterface.
1)True
2)False

Q174Considerthefollowingclass:
publicclassTest{
publicintsecret;
}
Whichofthefollowingisthecorrectwaytomakethevariable'secret'read-only.


1)Declare'secret'tobeprivate.
2)DeclaretheclassTesttobeprivate.
3)Declare'secret'tobeprivateandwriteamethodgetSecret()whichreturnsthevalueof'secret'.
4)Declare'secret'tobetransient.
5)Declare'secret'tobestatic.

Q175WhichoneofthefollowingmethodsoftheMathclasscanbeusedtofindthesquarerootofanumber.
1)squareRoot()
2)sqrt()
3)root()
4)sqr()
5)Noneoftheabove.Youusethepow()method.

Q176Towhichlayoutmanagerdoesthefollowingstatementrefer:
"itpreservesthepreferredsize(widthandheight)ofeachcomponent".
1)FlowLayout
2)BorderLayout
3)GridLayout
4)GridBagLayout
5)Noneoftheabove.Alllayoutmanagersalterthedimensionsoftheircontainingcomponents.

Q177Considerthefollowingcodefragment,andselectthecorrectstatements(s):
1.publicclassTestextendsMyBaseimplementsMyInterface{
2.intx=0;
3.
4.publicTest(intinVal)throwsException{
5.if(inVal!=this.x){
6.thrownewException("Invalidinput");
7.}
8.}
9.
10.publicstaticvoidmain(Stringargs[]){
11.Testt=newTest(4);
12.}
13.}
1)Thecodefailstocompileatline1.Itisnotvalidtobothimplementaninterfaceandextendfromaparentclasssimultaneously.
2)Thecodefailstocompileatline4.Itisnotvalidforconstructorstothrowexceptions.
3)Thecodefailstocompileatline6,becausethisisnotvalidwaytothrowanexception.
4)Thecodefailstocompileatline11.Thecompilercomplainsthatthereisanuncaughtexception.
5)Thecodefailstocompileatline5,becausethisisnotavalidwaytoreferencevariablex.


Q178Considerthefollowingreal-liferelationships,andselectthecodefragmentwhichmostcloselyrepresentsit.
Anemployeeisaperson.Anemployeehaszeroormoredependants.
[forthecodefragments,assumethatallrelevantpackagesareimported,andallrelevantclassdefinitionsexist].
1)classEmployeeextendsDependants{
Personp;
}
2)classPersonextendsEmployee{
Vectordependants;
}
3)classEmployeeextendsPerson{
Vectordependants;
}
4)abstractclassPersonextendsDependants{
Employeee;
}
5)classDependantimplementsEmployee{
Vectorperson;
}

Q179Whichofthefollowingarevaliddeclarationsforanativemethod.
1)publicnativevoidaMethod();
2)privatenativeStringaMethod();
3)privatenativebooleanaMethod(intval){};
4)publicnativeintaMethod(Stringtest);
5)privatenativebooleanaMethod(booleanflag,Integerval);

Q180Whichofthefollowingarevalidwaystodefineanoctalliteralofvalue17(octal).
1)privatefinalinttheNumber=0x17;
2)privatefinalinttheNumber=017;
3)publicinttheNumber=017;
4)publicinttheNumber=(octal)17;
5)publicintTHE_NUMBER=017;

Q181Considerthefollowingpieceofcodeandselectallstatementswhichyieldabooleanvalueoftrueasaresult.
Doubled1=newDouble(10.0);
Doubled2=newDouble(10.0);
intx=10;
floatf=10.0f;
1)d1==d2;
2)d1==x;
3)f==x;
4)d1.equals(d2);
5)Noneoftheabove

Q182Giventhefollowingdefinition:
Strings=null;
WhichcodefragmentwillcauseanexceptionoftypeNullPointerExceptiontobethrown.
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)Noneoftheabove.

Q183Whichofthefollowingarevaliddeclarationsfora2x2arrayofintegers.
1)inta[][]=newint[10,10];
2)inta[][]=newint[10][10];
3)inta[10,10]=newint[10][10];
4)int[][]a=newint[10][10];
5)int[]a[]=newint[10][10];

Q184Whichvaluesofvariablexwillshow"Message2".
switch(x)
{
case1:
System.out.println("Message1");
case2:
case3:
System.out.println("Message2");
default:
System.out.println("End");
}
1)1
2)2
3)3
4)4
5)none

Q185Whatistheresultofthefollowingcode:
publicclassSuperEx{
Stringr;
Strings;
publicSuperEx(Stringa,Stringb){
r=a;

s=b;
}
publicvoidaMethod(){
System.out.println("r:"+r);
}
}
publicclassNewSuperextendsSuperEx{
publicNewSuper(Stringa,Stringb){
super(a,b);
}
publicstaticvoidmain(Stringargs[]){
SuperExa=newSuperEx("Hi","Tom");
SuperExb=newNewSuper("Hi","Bart");
a.aMethod();
b.aMethod();
}
publicvoidaMethod(){
System.out.println("r:"+r+"s:"+s);
}
}
1)Thefollowingisdisplayed:
r:Hi
s:Hi
2)Compilererrorattheline"SuperExb=newNewSuper("Hi","Bart");"
3)Thefollowingisdisplayed:
r:Hi
r:His:Bart
4)Thefollowingisdisplayed
r:His:Tom
r:His:Bart

Q186Youhaveaclasswithacertainvariableandyoudon'twantthatvariabletobeaccessibletoANYotherclassbutyourown.Yourclassmustbesub-classable.
Whichkeyworddoyouaddtothevariable.
1)private
2)public
3)transient
4)final
5)abstract

Q187Yougetthisdescriptionofaclass:
Employeeisaperson.Foreveryemployee,wekeepavectorwiththeworkinghours,anintegerforthesalaryandavariablethatcanbetrueorfalsewhetherornottheemployeehasacompanycar.
Indicatewhichofthefollowingwouldbeusedtodefinetheclassmembers.
1)Vector
2)Employee
3)Object
4)boolean
5)int

Q188Whichlineofcodecanbeinsertedinplaceofthecomments,toperformtheinitialisationdescribedbythecomments:
publicclassT{
intr;
ints;
T(intx,inty){
r=x;
s=y;
}
}
classSextendsT{
intt;
publicS(intx,inty,intz){
//insertherethecode
//thatwoulddothecorrectinitialisation
//r=xands=y
t=z;
}
}
1)T(x,y);
2)this(x,y);
3)super(x,y);
4)super(x,y,z);
5)None

Q189SupposeaMyExceptionshouldbethrownifCondition()istrue,whichstatementsdoyouhavetoinsert?
1:publicaMethod{
2:
3:if(Condition){
4:
5:}
6:
7:}
1)thrownewException()atline4
2)thrownewMyException()atline4
3)thrownewMyException()atline6
4)throwsnewException()atline2
5)throwsMyExceptionatline1

Q190SupposeaNullPointerExceptionisthrownbytest().Whichmessageisdisplayed?
voidMethod(){
try{
test();
System.out.println("Message1");
}
catch(ArrayOutOfBoundsExceptione){
System.out.println("Message2");
}
finally{
System.out.println("Message3");
}
System.out.println("Message4");
}
1)Message1
2)Message2
3)Message3
4)Message4
5)Noneoftheabove.

Q191Choosetheclassthatcanholdmultipleequalobjectsinanorderedway.
1)Map
2)Collection
3)List
4)Set
5)Vector

Q192Considerthefollowingvariablesdefinitions.
Floatf1=newFloat("10F");
Floatf2=newFloat("10F");
Doubled1=newDouble("10D");
Whichofthefollowingyieldsabooleanvalueoftrue.
1)f1==f2
2)f1.equals(f2)
3)f2.equals(d1)
4)f2.equals(newFloat("10"))

Q193WhatdoesthegetID()methodofAWTEventtellus.
1)Tellsusthexandycoordsofthemouseattheeventtime.
2)TellsuswhichObjecttheeventoriginatedfrom.

3)Tellsuswhichspecialkeyswerepressedattheeventtime.
4)Tellsustheeventtype.
5)TellsusthehowmanypixelswerebetweenthemousepointerandtextonaCanvas.

Q194WhatisthereturntypeofanEventlistener?
1)int
2)NULL
3)void
4)boolean
5)Object

Q195YoucreateaLongobjectusingthefollowing:
Longval=newLong("11");
Whichofthefollowingwillreturnthevalueoftheobjectasabytevalue?
1)byteb=(byte)val;
2)byteb=val.getByte();
3)byteb=(byte)val.getValue();
4)byteb=val.byteValue();
5)Noneoftheabove.

Q196Considerthefollowing.
Strings1="abc";
Strings2="def";
Strings3=newString(s2);
s2=s1;
Whatisthevalueofs3afterthefinallineofcodeisexecuted?
1)"abc"
2)"def"
3)null
4)Anexceptionisthrownwhen"s2=s1"isexecuted.

Q197WhattagsaremandatorywhencreatingHTMLtodisplayanapplet
1)name,width,height
2)code,name
3)codebase,height,width
4)code,width,height
5)Noneoftheabove

Q198Whatisdisplayedwhenthefollowingcodeisexecuted:
Strings1="helloworld";
Strings2=s1.trim();
System.out.println(s2);
1)"helloworld"
2)"helloworld"
3)"helloworld"
4)"helloworld"
5)"helloworld"

Q199WhichofthefollowingaremethodswithintheStringclass.
1)substring()
2)startsWith()
3)toString()
4)toUpperCase()
5)indexOf()

Q200TrueorFalse.
APPLETtagsmustappearbetweenBODYand/BODYtags.
1)True
2)False

ANSWER:
1.1,2
Answers3,4and5areincorrectbecausetheseoperationsrequiresthatanint(c)beconvertedtoaboolean,orthebooleanbeconvertedtoanint.Bothoftheseconversionsareillegal.
2.5
Aconstructorcannotbeabstract,final,native,staticorsynchronized.RefertotheJavaLanguageSpecification(section8.6.3,version1.0).
3.4
Ingeneral,allcomponentsareresizedandonlyretaintheirpreferredheightintheNORTHregion.However,theCheckBoxisnotdeformable,soitretainsit'spreferredsize.
4.1,3,4
5.1
6.3
WhenaFileclassisconstructed,itsimplycreatesahandletoaFileobject.Nofilesarecreatedonthelocalharddisk.
AstheJDKAPIdocumentationpointsout,theFileclassis"anabstractrepresentationoffileanddirectorypathnames".
TheFileclassalsocontainsdirectoryseparatorattributes,whichareplatformspecific.Therefore,thedirectoryseparatorusedisirrelevant.

Also,sincetheFileclasssimplycreatesareferencetoafileobject,noexceptionisthrownifthefilealreadyexistsonthedisk.
7.1,4,5
Answer1iscorrect,becauseinreadmode,thefilemustexistifanyotheroperationsaretobeperformedonit.
TheRandomAccessFileisnotcompatiblewiththeStreamorreader/writerclasses,soAnswer3isincorrect.
8.3
Stringsareimmutable,andsotheycannotbemodified.However,astheJDKAPIdocumentationwillshow,theStringclasshasareplace()method,soanswer1isincorrect.
Ifline2readas"s=s.replace('d','q')"thenanewobjectwouldbecreatedandassignedtos.ThevalueofthisnewStringobjectwouldbe"abcqefgh".However,asline2ispresented,nonewobjectiscreated,andso's'remainsunchanged.
9.1,5
10.2
Icameacrossthestatementduringmystudyfortheexam,andsimplynoteditasfact.Ineverreallylookedtoodeeplyintoit-sopleasedon'temailmeforanexplanation:-)
11.1,4,5

Therefore,Answer1iscorrect,becauseclassBattemptstooverridemethod()tobelesspublic(ie,protectedto"friendly").

Answer2isincorrect,becauseaprotectedvariableormethodisalwaysavailabletochildclasses(thisisthepurposeoftheprotectedkeyword).

Answer3isincorrect,becausealltheinformationneededtoverifythiscodeisavailableatcompiletime.

Answers4and5arecorrectbecauseaddingeither"public"or"protected"toline7actuallymovesithigheruptheaccesshierarchy(ie,morepublicthanfriendly).

12.1
13.2
14.1
15.3
16.2
Theruleforaccessingmethodsandvariablesinaclasshierarchyisasfollows:

-theobjectreferenceisusedwhenaccessingvariables(sothevalueofb.xistherefore2).

-theunderlyingobjectisusedwhenaccessingmethods(sothemethodcalledisactuallythemethoddefinedinSubclass,andinSubclass,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
Answer1iscorrect,becausexisdeclaredasprivatetoclassAandisthereforenotavailabletoanyotherclass(evensubclasses).
Answer3istotallymeaningless,butsoundsvaguelyplausible!
Answer4iscorrect,becausetheonlyproblemwiththecodeistheattempttoreferencethevariablex.
Answer5iscorrect(seeanswer4).
27.3
28.2,3,4,5
29.1
Answer2isincorrect,sincethe{}definesanemptymethod(butstillamethod)soitisnotabstract.
Abstractmethodscannotbestatic,soanswer3isincorrect.
Abstractandfinalarealmostoppositeinmeaningandthereforedonotformavalidkeywordcombination(finalmeansamethodcan'tbeoverridden,abstractmeansamethodmustbeoverridden),soanswer4isincorrect.
30.2
31.4
Interfacescannothaveconstructors,onlyclasseshaveconstructors.
Answer2isavalidstatementwhendealingwithclasses,butnotinthecontextofthecodeinthequestion.
Answer5istotallyuntrue,butpotentiallyconfusing:-)
32.1
33.1,2,4
34.1
Answer2isincorrect,becausebooleanscan'thaveintegervalues(inthiscase,"1").
Answer3isanmeaninglessstatement.
Answer5isincorrect,attemptingtoconfuseC/C++andJavawaysofdefiningtrueandfalsebooleanvalues.
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
Answer1isincorrect,becauseaclasscanhavefinalmethodsandvariableswithouttheneedfortheentireclasstobefinal.
Answer2isincorrect,becausethetypeoferrorinthiscodeisdetectableatcompiletime.
Answer5isinvalid.Finalcanbeappliedtoprimitives.
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
Thereareseveralthingswrongwiththiscode:
-classAmustbedeclaredasabstract,sincemethod()isdeclaredasabstract
-ifclassAisdeclaredasabstract,thenthecodewillcompilecorrectly
-iftheabstractdeclarationofmethod()inclassAisremoved,thecodewillcompile(however,theentireline2mustnowreadasfollows:
intmethod(){}
Inotherwords,amethodbodymustnowbesuppliedsincethemethodisnolongerabstract.
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
Theinstanceofoperatorcanbeusedasfollows:
-onclassestoseeifaparticularclassisderivedfromanother(ie,isaninstanceof)
-oninterfacestoseeifaclassimplementsaparticularinterface
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
1willnotcompile,because123defaultstotypeint,andthereisnoconstructoroftheByteclasswhichtakestypeintasaparameter.
2compilescorrectly,becauseaparseablestringisavalidparameterfortheByteconstructor.
3failstocompile,becausethereisnono-argsconstructorfortheByteclass.
4failstocompile.Whilethecasttoanintisvalid,thesamereasonsasAnswer1apply.
5failstocompile,becausethevalue0x123isahexvalue,andequatestoadecimalvalueof291.ThisisnotwithinthevalidrangefortheBytevalue.
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
ThankstoPrasadforrightlypointingoutthatAnswer2abovealsoworksforacontainerwhichusestheFlowLayoutmanager(eventhoughitdoesn'thavea"Center"area").
ThiscanbeexplainedbythefactthatacontainersuchasaPanelinheritsfromjava.awt.Container,whichhasamethodwithasignatureasfollows:
add(String,Component)
However,whilethisissymanticallycorrect(ie,itwillcompileandfunctioncorrectly),itcan'tbeconsideredasavalidanswersinceFlowlayoutdoesn'thavetheconceptofa"Center"area-atleast,that'smyopinion:-)
However,thisraisesaninterestingpoint-wherepossible,youshouldusestaticclassvariables,whereachoiceisavailable-eg,useBorderLayout.NORTHinsteadof"NORTH"whenaddingcomponentstoacontainer.Thiswillensurethatanyerrorsaretrappedatcompiletime,ratherthanatrun-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.zip700KBJava1.4版本

是我很早以前买的一本英文SCJP辅导书里面所附带的代码.
下载后解压缩得到几个JAR文件下载后Windows下可以双击运行,点击最大化后,然后点击Mark按钮就可以看到正确答案和解释了.
Linux/Windows下都通过命令行键入
java-jarFinal.jar这样的命令即可运行.

现在的Java笔试题的基础部分(corejava)很多都是从类似这样的英文题里面抽取出来的,基本上熟悉之后笔试题会答的很漂亮.
界面截图:


再转载:阅读完此贴你才可以大胆的高薪工作!http://bbs.tarena.com.cn/topic.cgi?forum=1&topic=10848&show=0
大家找工作就要面试,有面试就有对付面试的办法。以下一些题目来自我朋友痛苦的面试经历,他给我总结了一下,我拿来和大家分享!提这些问题的公司包括IBM,E*Trade,Siebel,Motorola,SUN,以及其它大小公司。  
面试是没什么道理可讲的,它的题目有的不合情理、脱离实际。有在纸上写的,有当面考你的,也有在电话里问的,给你IDE的估计很少(否则你赶快去买彩票,说不定中)。所以如果你看完此文后,请不要抱怨说这些问题都能用IDE来解决。你必须在任何情况下准确回答这些问题,在面试中如果出现一两题回答不准确很有可能你就被拒之门外了。  当然这些都是Java的基本题,那些面试的人大多数不会问你Hibernate有多先进,Eclipse的三个组成部分,或commanddesignpattern,他们都是老一辈了,最喜欢问的就是基础知识。别小看了这些基础,我朋友水平挺可以的,结果就栽在一道基础知识的问题上,和高薪无缘。
希望这些知识点对大家有所帮助,愿大家从达内出来后都能找到高薪的工作!


第一,谈谈final,finally,finalize的区别。  final用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。finally是异常处理语句结构的一部分,表示总是执行。finalize是Object类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法,可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等。  

第二,AnonymousInnerClass(匿名内部类)是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)?可以继承其他类或完成其他接口,在swing编程中常用此方式。  

第三,StaticNestedClass和InnerClass的不同,说得越多越好(面试题有的很笼统)。StaticNestedClass是被声明为静态(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的构建参数。注意编译时要增加-source1.4参数,否则报错。]运行时要增加-ea参数,否则assert行被忽略  

第八,GC是什么?为什么要有GC?  GC是垃圾收集的意思(GabageCollection),内存处理是编程人员容易出现问题的地方,忘记或者错误的内存回收会导致程序或系统的不稳定甚至崩溃,Java提供的GC功能可以自动监测对象是否超过作用域从而达到自动回收内存的目的,Java语言没有提供释放已分配内存的显示操作方法。  

第九,Strings=newString("xyz");创建了几个StringObject?两个  

第十,Math.round(11.5)等於多少?Math.round(-11.5)等於多少?Math.round(11.5)==12Math.round(-11.5)==-11round方法返回与参数最接近的长整数,参数加1/2后求其floor.  

第十一,shorts1=1;s1=s11;有什么错?shorts1=1;s1=1;有什么错?shorts1=1;s1=s11;(s11运算结果是int型,需要强制转换类型)shorts1=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()在类中被覆盖,为的是当两个分离的对象的内容和类型相配的话,返回真值。

第十七,给我一个你最常见到的runtimeexception。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不是

第二十,abstractclass和interface有什么区别?声明方法的存在而不去实现它的类被叫做抽象类(abstractclass),它用于要创建一个体现某些基本行为的类,并为该类声明方法,但不能在该类中实现该类的情况。不能创建abstract类的实例。然而可以创建一个变量,其类型是一个抽象类,并让它指向具体子类的一个实例。不能有抽象构造函数或抽象静态方法。Abstract类的子类为它们父类中的所有抽象方法提供实现,否则它们也是抽象类为。取而代之,在子类中实现该方法。知道其行为的其它类可以在类中实现这些方法。接口(interface)是抽象类的变体。在接口中,所有方法都是抽象的。多继承性可通过实现这样的接口而获得。接口中的所有方法都是抽象的,没有一个有程序体。接口只可以定义staticfinal成员变量。接口的实现与子类相似,除了该实现类不能从接口定义中继承行为。当类实现特殊接口时,它定义(即将程序体给予)所有这种接口的方法。然后,它可以在实现了该接口的类的任何对象上调用接口的方法。由于有抽象类,它允许使用接口名作为引用变量的类型。通常的动态联编将生效。引用可以转换到接口类型或从接口类型转换,instanceof运算符可以用来决定某对象的类是否实现了接口。

第二十一,abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized?都不能

第二十二,接口是否可继承接口?抽象类是否可实现(implements)接口?抽象类是否可继承实体类(concreteclass)?接口可以继承接口。抽象类可以实现(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),但却可有不同的hashcode,这句话对不对?不对,有相同的hashcode。

第三十,当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递?是值传递。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方法获取对它的引用,继而调用其中的方法。publicclassSingleton{  privateSingleton(){}  //在自己内部定义自己一个实例,是不是很奇怪?  //注意这是private只供内部调用  privatestaticSingletoninstance=newSingleton();  //这里提供了一个供外部访问本class的静态方法,可以直接访问    publicstaticSingletongetInstance(){    returninstance;    }}第二种形式:publicclassSingleton{  privatestaticSingletoninstance=null;  publicstaticsynchronizedSingletongetInstance(){  //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次      //使用时生成实例,提高了效率!  if(instance==null)    instance=newSingleton();returninstance;  }}其他形式:定义一个类,它的构造函数为private的,所有方法为static的。
一般认为第一种形式要更加安全些


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值