Java XML Pack

<

小小豆叮

用JSP动态生成柱状图形

<

小小豆叮

Java数据库编程中查询结果的表格式输出

<

小小豆叮

Java服务器端编程安全必读(一)

一、概述 编写安全的Internet应用并不是一件轻而易举的事情:只要看看各个专业公告板就可以找到连续不断的安全漏洞报告。你如何保证自己的Internet应用不象其他人的应用那样满是漏洞?你如何保证自己的名字不会出现在令人难堪的重大安全事故报道中? 如果你使用Java Servlet、JavaServer Pages(JSP)或者EJB,许多难以解决的问题都已经事先解决。当然,漏洞仍有可能出现。下面我们就来看看这些漏洞是什么,以及为什么Java程序员不必担心部分C和Perl程序员必须面对的问题。 C程序员对安全漏洞应该已经很熟悉,但象OpenBSD之类的工程提供了处理此类问题的安全系统。Java语言处理这类问题的经验要比C少20年,但另一方面,Java作为一种客户端编程语言诞生,客户端对安全的要求比服务器端苛刻得多。它意味着Java的发展有着一个稳固的安全性基础。 Java原先的定位目标是浏览器。然而,浏览器本身所带的Java虚拟机虽然很不错,但却并不完美。Sun的《Chronology of security-related bugs and issues》总结了运行时环境的漏洞发现历史。我们知道,当Java用作服务器端编程语言时,这些漏洞不可能被用作攻击手段。但即使Java作为客户端编程语言,重大安全问题的数量也从1996年的6个(其中3个是相当严重的问题)降低到2000年的1个。不过,这种安全性的相对提高并不意味着Java作为服务器端编程语言已经绝对安全,它只意味着攻击者能够使用的攻击手段越来越受到限制。那么,究竟有哪些地方容易受到攻击,其他编程语言又是如何面对类似问题的呢? 二、缓存溢出 在C程序中,缓存溢出是最常见的安全隐患。缓存溢出在用户输入超过已分配内存空间(专供用户输入使用)时出现。缓存溢出可能成为导致应用被覆盖的关键因素。C程序很容易出现缓存溢出,但Java程序几乎不可能出现缓存溢出。 从输入流读取输入数据的C代码通常如下所示: char buffer[1000]; int len = read(buffer); 由于缓存的大小在读入数据之前确定,系统要检查为输入保留的缓存是否足够是很困难的。缓存溢出使得用户能够覆盖程序数据结构的关键部分,从而带来了安全上的隐患。有经验的攻击者能够利用这一点直接把代码和数据插入到正在运行的程序。 在Java中,我们一般用字符串而不是字符数组保存用户输入。与前面C代码等价的Java代码如下所示: String buffer = in.readLine(); 在这里,“缓存”的大小总是和输入内容的大小完全一致。由于Java字符串在创建之后不能改变,缓存溢出也就不可能出现。退一步说,即使用字符数组替代字符串作为缓存,Java也不象C那样容易产生可被攻击者利用的安全漏洞。例如,下面的Java代码将产生溢出: char[] bad = new char[6]; bad[7] = 50;这段代码总是抛出一个java.lang.ArrayOutOfBoundsException异常,而该异常可以由程序自行捕获: try { char[] bad = new char[6]; bad[7] = 50; } catch (ArrayOutOfBoundsException ex) { ... } 这种处理过程永远不会导致不可预料的行为。无论用什么方法溢出一个数组,我们总是得到ArrayOutOfBoundsException异常,而Java运行时底层环境却能够保护自身免受任何侵害。一般而言,用Java字符串类型处理字符串时,我们无需担心字符串的ArrayOutOfBoundsExceptions异常,因此它是一种较为理想的选择。 Java编程模式从根本上改变了用户输入的处理方法,避免了输入缓存溢出,从而使得Java程序员摆脱了最危险的编程漏洞。 三、竞争状态 竞争状态即Race Condition,它是第二类最常见的应用安全漏洞。在创建(更改)资源到修改资源以禁止对资源访问的临界时刻,如果某个进程被允许访问资源,此时就会出现竞争状态。这里的关键问题在于:如果一个任务由两个必不可少的步骤构成,不管你多么想要让这两个步骤一个紧接着另一个执行,操作系统并不保证这一点。例如,在数据库中,事务机制使得两个独立的事件“原子化”。换言之,一个进程创建文件,然后把这个文件的权限改成禁止常规访问;与此同时,另外一个没有特权的进程可以处理该文件,欺骗有特权的进程错误地修改文件,或者在权限设置完毕之后仍继续对原文件进行访问。 一般地,在标准Unix和NT环境下,一些高优先级的进程能够把自己插入到任务的多个步骤之间,但这样的进程在Java服务器上是不存在的;同时,用纯Java编写的程序也不可能修改文件的许可权限。因此,大多数由文件访问导致的竞争状态在Java中不会出现,但这并不意味着Java完全地摆脱了这个问题,只不过是问题转到了虚拟机上。 我们来看看其他各种开发平台如何处理这个问题。在Unix中,我们必须确保默认文件创建模式是安全的,比如在服务器启动之前执行“umask 200”这个命令。有关umask的更多信息,请在Unix系统的命令行上执行“man umask”查看umask的man文档。 在NT环境中,我们必须操作ACL(访问控制表,Access Control List)的安全标记,保护要在它下面创建文件的目录。NT的新文件一般从它的父目录继承访问许可。请参见NT文档了解更多信息。 Java中的竞争状态大多数时候出现在临界代码区。例如,在用户登录过程中,系统要生成一个唯一的数字作为用户会话的标识符。为此,系统先产生一个随机数字,然后在散列表之类的数据结构中检查这个数字是否已经被其他用户使用。如果这个数字没有被其他用户使用,则把它放入散列表以防止其他用户使用。代码如Listing 1所示: (Listing 1) // 保存已登录用户的ID Hashtable hash; // 随机数字生成器 Random rand; // 生成一个随机数字 Integer id = new Integer(rand.nextInt()); while (hash.containsKey(id)) { id = new Integer(rand.nextInt()); } // 为当前用户保留该ID hash.put(id, data); Listing 1的代码可能带来一个严重的问题:如果有两个线程执行Listing 1的代码,其中一个线程在hash.put(...)这行代码之前被重新调度,此时同一个随机ID就有可能被使用两次。在Java中,我们有两种方法解决这个问题。首先,Listing 1的代码可以改写成Listing 2的形式,确保只有一个线程能够执行关键代码段,防止线程重新调度,避免竞争状态的出现。第二,如果前面的代码是EJB服务器的一部分,我们最好有一个利用EJB服务器线程控制机制的唯一ID服务。 (Listing 2) synchronized(hash) { // 生成一个唯一的随机数字 Integer id = new Integer(rand.nextInt()); while (hash.containsKey(id)) { id = new Integer(rand.nextInt()); } // 为当前用户保留该ID hash.put(id, data); } 四、字符串解释执行 在有些编程语言中,输入字符串中可以插入特殊的函数,欺骗服务器使其执行额外的、多余的动作。下面的Perl代码就是一个例子: $data = "mail body"; system("/usr/sbin/sendmail -t $1 < $data"); 显然,这些代码可以作为CGI程序的一部分,或者也可以从命令行调用。通常,它可以按照如下方式调用: perl script.pl honest@true.com 它将把一个邮件(即“mail body”)发送给用户honest@true.com。这个例子虽然简单,但我们却可以按照如下方式进行攻击: perl script.pl honest@true.com;mail cheat@liarandthief.com < /etc/passwd 这个命令把一个空白邮件发送给honest@true.com,同时又把系统密码文件发送给了cheat@liarandthief.com。如果这些代码是CGI程序的一部分,它会给服务器的安全带来重大的威胁。 Perl程序员常常用外部程序(比如sendmail)扩充Perl的功能,以避免用脚本来实现外部程序的功能。然而,Java有着相当完善的API。比如对于邮件发送,JavaMail API就是一个很好的API。但是,如果你比较懒惰,想用外部的邮件发送程序发送邮件: Runtime.getRuntime().exec("/usr/sbin/sendmail -t $retaddr < $data"); 事实上这是行不通的。Java一般不允许把OS级“<”和“;”之类的构造符号作为Runtime.exec()的一部分。你可能会尝试用下面的方法解决这个问题: Runtime.getRuntime().exec("sh /usr/sbin/sendmail -t $retaddr < $data"); <

小小豆叮

在EJB环境中实现“观察者”模式

Observer模式(“观察者”模式)或许是降低对象结合程度的最佳方法之一。例如,在编写一个典型的应用程序时,你可能决定提供一个工厂或管理器触发适当的事件,以这些事件的一组监听器的形式提供分离的业务逻辑;此后,系统的启动类就在工厂或者管理器创建完毕之后,把这些监听器关联到工厂或者管理器。 在大多数J2EE系统中,这种工厂/管理器都是无状态的会话Bean。EJB容器处理对无状态会话Bean的请求,根据请求创建无状态会话Bean的实例,或重用现有的实例。问题在于,每次初始化一个新的Bean实例时都必须伴有一组监听器,这组监听器和为其他实例而运行的监听器完全相同。合理的方案应该是,当一个无状态会话Bean实例被创建的时候,它访问某个知识库,通过一定的方法获知相关的监听器,然后建立和这些监听器的关系。在这篇文章中,我要介绍的就是如何实现这一方案。 一种典型的情形 请考虑下面这种典型的情形。一个在线拍卖系统有一个无状态会话Bean,名为AuctionFactory,这个Bean创建拍卖(auction)对象。对于每一个新创建的拍卖对象,业务逻辑要求系统执行一些附加的操作,比如发送email、更新用户摘要文件,等等。在许多系统上,创建拍卖对象和执行这些附加操作的代码如下所示: public Auction createAuction(int numOfContainers) throws RemoteException{ SomeAuctionClass auction = new SomeAuctionClass (numOfContainers); // 创建拍卖对象之后,接下来要编写下面这种执行附加操作的代码 //(而不是简单地发送一个“拍卖对象已经创建”的事件) sendEmailsAboutNewAuction(auction); updateUserProfiles(auction); doOtherNotificationStuffAboutNewAuction(auction); //等等.... return auction;} 之所以要编写这种质量很差的代码,原因就在于初始化各个Bean实例时附带一组必需的监听器很困难。如果这个Bean是一个事件发布者,而且每一个Bean实例初始化的时候都带有一组它需要的监听器,上述代码可以变得更简洁、更强壮,例如: public Auction createAuction(int numOfContainers) throws RemoteException{ SomeAuctionClass auction = new SomeAuctionClass (numOfContainers); fireAuctionCreated(auction); return auction;} 基本原理说明 实现本文技巧的基本原理其实很简单。一个ListenerRegistry类实现事件发布者类和必须关联到该类的监听器之间的映射。系统的启动模块初始化ListenerRegistry,为每一种发布者类型初始化一组必需的监听器。当发布者被创建或激活,它就访问ListenerRegistry,把它的类传递给ListenerRegistry,获得一组监听器。然后,发布者把所有这些监听器关联到自身。就这么简单。 你也许会很自然地问,“什么是ListenerSupplier?”和“为什么不直接注册和使用EventListener?”确实可以;事实上,该框架的第一个版本就是直接使用事件监听器。但是,如果在ListenerRegistry中使用监听器,这些监听器必须在注册的时候就存在。另一方面,如果注册的是一个“中介者”ListenerSupplier(监听器提供者),你就可以自由地把创建/提取监听器延迟到它绝对必需的时候。ListenerSupplier类似于工厂,但两者的不同之处在于,ListenerSupplier并非必定要创建新的监听器,它的目标是返回监听器。每次getListener()方法被调用时,ListenerSupplier是创建一个新的监听器,还是每次都返回同一实例,这一切由开发者自己决定。 因此,结合运用ListenerRegistry和监听器提供者,我们可以在事件发布者和观察者(或监听器)不存在的情况下,建立两者之间的关系。可以认为,这个优点很重要,它延迟了发布者和观察者的实例化。 具体实现 在这一部分,你将看到整个框架中所有组成部分的实现代码。我假定你已经了解必要的基础知识,比如EJB、同步,当然还有Java核心库。完整的源代码可以从本文最后下载。 下面是ListenerRegistry接口的代码: //ListenerRegistry.javapackage com.jwasp.listener;import java.util.EventListener;import java.rmi.RemoteException;import com.jwasp.listener.ListenerSupplier;/*** 框架的核心。实现事件发布者类和监听器提供者之间的映射*/public interface ListenerRegistry {void addListenerSupplier(ListenerSupplier listenerSupplier, Class publisherClass);void removeListenerSupplier(ListenerSupplier listenerSupplier, Class publisherClass);EventListener[] getListeners(Class publisherClass) throws RemoteException, ListenerActivationException;} 下面是ListenerSupplier接口: //ListenerSupplier.javapackage com.jwasp.listener; import java.util.EventListener; /** * 为方便起见而提供的“中介者”,负责创建/提取相应的监听器 */ public interface ListenerSupplier { /** * 返回和指定发布者类相对应的监听器 */ EventListener getListener(Class publisherClass) throws java.rmi.RemoteException, ListenerActivationException; } 下面是ListenerRegistry的缺省实现: //DefaultListenerRegistry.javapackage com.jwasp.listener; import java.util.*; import java.rmi.RemoteException; import com.jwasp.listener.ListenerRegistry; import com.jwasp.listener.ListenerSupplier; /** * ListenerRegistry的基本实现。该类是一个singleton(Singleton模 * 式的主要作用是保证在Java应用程序中,一个Class只有一个实 * 例存在)。 * 当发布者请求监听器时,这个注册器返回的不仅有显式为 * 指定发布者类所注册的监听器,而且还有为发布者所有父类 * 注册的监听器。例如: * 如果发布者B从发布者A扩展,而且已经有为A注册的监听 * 器提供者,那么,如果你把B类作为参数传递给getListeners方 * 法,你得到的不仅有显式为B注册的监听器,还有所有为B类的 * 父类(在本例中,它是A)所注册的监听器。 */ public class DefaultListenerRegistry implements ListenerRegistry{ private DefaultListenerRegistry(){} public static DefaultListenerRegistry getInstance(){ return instance; } public synchronized void addListenerSupplier(ListenerSupplier listenerSupplier, Class publisherClass) { assertNotNull("Publisher class is null", publisherClass); assertNotNull("ListenerSupplierr is null", listenerSupplier); Collection listenerSuppliers = (Collection)myListenerSuppliersMap.get(publisherClass); if ( listenerSuppliers == null ) { listenerSuppliers = new ArrayList(); myListenerSuppliersMap.put(publisherClass, listenerSuppliers); } listenerSuppliers.add(listenerSupplier); } public synchronized void removeListenerSupplier(ListenerSupplier listenerSupplier, Class publisherClass) { assertNotNull("Publisher class is null", publisherClass); assertNotNull("ListenerSupplierr is null", listenerSupplier); Collection listenerSuppliers = (Collection)myListenerSuppliersMap.get(publisherClass); if ( listenerSuppliers == null ) { return; } listenerSuppliers.remove(listenerSupplier); if ( listenerSuppliers.isEmpty() ) { myListenerSuppliersMap.remove(publisherClass); } } /** * 返回一个为指定发布者类注册的EventListener的数组。如果注册 * 器包含为该发布者注册的监听器提供者,它将依次访问每一个提供 * 者,调用其ListenerSupplier.getListener(publisherClass)方法。 * @param publisherClass发布者类 * @返回EventListener的数组 */ public EventListener[] getListeners(Class publisherClass) throws RemoteException,ListenerActivationException { //如最后一个参数设置成false,则禁止继承检查 Collection listenerSuppliers = getListenerSuppliersCopy(publisherClass, true); EventListener[] array = new EventListener[listenerSuppliers.size()]; Iterator i = listenerSuppliers.iterator(); int count = 0; while (i.hasNext()){ ListenerSupplier listenerSupplier = (ListenerSupplier)i.next(); array[count] = listenerSupplier.getListener(publisherClass); count++; } return array; } /** * 返回当前已经为指定发布者类注册的监听器提供者副本。 * 这是一个同步方法,从而允许getListeners方法保持非同 * 步。 * @param publisherClass * @param checkInheritance 如为true,则返回为指定发布者类和它的所有父类 * 注册的监听器提供者;如为flase,则只返回为指定发布者类注册的监听 * 器提供者 * @return 相应的监听器提供者的集合(永不为null) */ private synchronized Collection getListenerSuppliersCopy(Class publisherClass, boolean checkInheritance){ if ( checkInheritance ) { Collection publishers = myListenerSuppliersMap.keySet(); Iterator i = publishers.iterator(); Collection listenerSuppliers = new ArrayList(); while (i.hasNext()) { Class nextPublisherClass = (Class)i.next(); if ( nextPublisherClass.isAssignableFrom(publisherClass) ) { if ( myListenerSuppliersMap.get(nextPublisherClass) != null ) { listenerSuppliers.addAll((Collection) myListenerSuppliersMap.get(nextPublisherClass)); } } } return listenerSuppliers; } else { Collection listenerSuppliers = (Collection) myListenerSuppliersMap.get(publisherClass); if ( listenerSuppliers == null ) { return Collections.EMPTY_LIST; } else { //如果你决定不使用ArrayList,请改用clone支持的其他cast方式 return (ArrayList)((ArrayList)listenerSuppliers).clone(); } } } /** * 一个确保值非null的简单方法 */ protected void assertNotNull(String message, Object object){ if ( object == null ) { throw new IllegalArgumentException(message); } } //保存“发布者类 -> 监听器提供者的集合”对 protected HashMap myListenerSuppliersMap = new HashMap(); private static DefaultListenerRegistry instance = new DefaultListenerRegistry(); } 第二个提供者示例允许使用无状态会话Bean作为监听器。它用会话Bean的一个EJBHome构造,利用create()方法返回一个可用的无状态会话Bean。请注意这个提供者在WebLogic 5.1下运行,这是因为,该服务器串行化对无状态Bean的调用,不会因为同时使用同一无状态Bean而抛出RemoteException异常。 //StatelessSupplier.javapackage com.jwasp.listener; import java.util.EventListener; import javax.ejb.CreateException; import javax.ejb.EJBHome; import java.rmi.RemoteException; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; /** * 在getListener方法中,利用指定的监听器(无状态会话Bean) * 的EJBHome调用create()方法返回一个监听器。请确保EJB容 * 器串行化了对监听器的调用(或者在fireXXX方法中提供对监 * 听器的同步)。 */ public class StatelessSupplier implements ListenerSupplier { public StatelessSupplier(EJBHome ejbHome) throws RemoteException{ if ( ejbHome == null ) { throw new IllegalArgumentException("EJBHome is null"); } else if ( !ejbHome.getEJBMetaData().isStatelessSession() ) { throw new IllegalArgumentException ("EJBHome should belong to stateless session bean"); } myEjbHome = ejbHome; } public EventListener getListener(Class publisherClass) throws RemoteException, ListenerActivationException { try { Method createMethod = myEjbHome.getClass().getMethod("create", new Class[0]); Object object = createMethod.invoke(myEjbHome, new Object[0]); if ( object instanceof EventListener ) { return (EventListener)object; } else { throw new ListenerActivationException("Remote interface doesn't extend EventListener"); } } catch(NoSuchMethodException nsme) { throw new ListenerActivationException("Home interface doesn't define create() method"); } catch(SecurityException se) { throw new ListenerActivationException(se.getMessage()); } catch(IllegalAccessException iae) { throw new ListenerActivationException(iae.getMessage()); } catch(IllegalArgumentException iare) { throw new ListenerActivationException(iare.getMessage()); } catch(InvocationTargetException ite) { throw new ListenerActivationException(ite.getTargetException().getMessage()); } } private EJBHome myEjbHome; } ■ 结束语 本文描述的框架允许你使用分布式的观察者/监听器(不错,监听器也可以是EJB;提供者将负责创建/定位EJB)。但是,它的目标不是替代JMS或消息驱动的Bean,该框架的目标是补充那两种强大的通知机制。结合JMS、消息驱动的Bean,本文描述的框架允许你在面对分布式事件发布者和监听器时,正确地实现Observer模式。 注意发布者不必一定是EJB。当发布者是普通的类时,你同样可以方便地应用本文所描述的框架。 最后,我想要指出,该框架的本质是:在发布者和观察者当时不存在的情况下,建立两者之间的关系。因此,任何想要发布者在创建时配置自己的地方,都可以使用本文所介绍的框架(如果发布者是一个EJB,则配置应该在ejbCreate()/ejbActivate()方法里进行;如果发布者是一个普通的类,则应该在构造函数里进行)。按照这种方法,如果发布者不是一个singleton,你不必担心所有的实例都有一组同样的监听器(或一组同样的实现业务逻辑的功能)。 下载本文的源代码: http://www.ccidnet.com/tech/focus/java_little_t/ImplementObserverPattern.zip <

小小豆叮

SCJP Mock Exam 1

转载 对题目和答案谨做参考 Q1 A method is ... 1) an implementation of an abstraction. 2) an attribute defining the property of a particular abstraction. 3) a category of objects. 4) an operation defining the behavior for a particular abstraction. 5) a blueprint for making operations. Q2 An object is ... 1) what classes are instantiated from. 2) an instance of a class. 3) a blueprint for creating concrete realization of abstractions. 4) a reference to an attribute. 5) a variable. Q3 Which line contains a constructor in this class definition? public class Counter { // (1) int current, step; public Counter(int startValue, int stepValue) { // (2) set(startValue); setStepValue(stepValue); } public int get() { return current; } // (3) public void set(int value) { current = value; } // (4) public void setStepValue(int stepValue) { step = stepValue; } // (5) } 1) Code marked with (1) is a constructor 2) Code marked with (2) is a constructor 3) Code marked with (3) is a constructor 4) Code marked with (4) is a constructor 5) Code marked with (5) is a Constructor Q4 Given that Thing is a class, how many objects and reference variables are created by the following code? Thing item, stuff; item = new Thing(); Thing entity = new Thing(); 1) One object is created 2) Two objects are created 3) Three objects are created 4) One reference variable is created 5) Two reference variables are created 6) Three reference variables are created. Q5 An instance member… 1) is also called a static member 2) is always a variable 3) is never a method 4) belongs to a single instance, not to the class as a whole 5) always represents an operation Q6 How do objects pass messages in Java? 1) They pass messages by modifying each other's member variables 2) They pass messages by modifying the static member variables of each other's classes 3) They pass messages by calling each other's instance member methods 4) They pass messages by calling static member methods of each other's classes. Q7 Given the following code, which statements are true? class A { int value1; } class B extends A { int value2; } 1) Class A extends class B. 2) Class B is the superclass of class A. 3) Class A inherits from class B. 4) Class B is a subclass of class A. 5) Objects of class A have a member variable named value2. Q8 If this source code is contained in a file called SmallProg.java, what command should be used to compile it using the JDK? public class SmallProg { public static void main(String args[]) { System.out.println("Good luck!"); } } 1) java SmallProg 2) avac SmallProg 3) java SmallProg.java 4) javac SmallProg.java 5) java SmallProg main Q9 Given the following class, which statements can be inserted at position 1 without causing the code to fail compilation? public class Q6db8 { int a; int b = 0; static int c; public void m() { int d; int e = 0; // Position 1 } } 1) a++; 2) b++; 3) c++; 4) d++; 5) e++; Q10 Which statements are true concerning the effect of the >> and >>> operators? 1) For non-negative values of the left operand, the >> and >>> operators will have the same effect. 2) The result of (-1 >> 1) is 0. 3) The result of (-1 >>> 1) is -1. 4) The value returned by >>> will never be negative as long as the value of the right operand is equal to or greater than 1. 5) When using the >> operator, the leftmost bit of the bit representation of the resulting value will always be the same bit value as the leftmost bit of the bit representation of the left operand. Q11 What is wrong with the following code? class MyException extends Exception {} public class Qb4ab { public void foo() { try { bar(); } finally { baz(); } catch (MyException e) {} } public void bar() throws MyException { throw new MyException(); } public void baz() throws RuntimeException { throw new RuntimeException(); } } 1) Since the method foo() does not catch the exception generated by the method baz(), it must declare the RuntimeException in its throws clause. 2) A try block cannot be followed by both a catch and a finally block. 3) An empty catch block is not allowed. 4) A catch block cannot follow a finally block. 5) A finally block must always follow one or more catch blocks. Q12 What will be written to the standard output when the following program is run? public class Qd803 { public static void main(String args[]) { String word = "restructure"; System.out.println(word.substring(2, 3)); } } 1) est 2) es 3) str 4) st 5) s Q13 Given that a static method doIt() in a class Work represents work to be done, what block of code will succeed in starting a new thread that will do the work? CODE BLOCK A: Runnable r = new Runnable() { public void run() { Work.doIt(); } }; Thread t = new Thread(r); t.start(); CODE BLOCK B: Thread t = new Thread() { public void start() { Work.doIt(); } }; t.start(); CODE BLOCK C: Runnable r = new Runnable() { public void run() { Work.doIt(); } }; r.start(); CODE BLOCK D: Thread t = new Thread(new Work()); t.start(); CODE BLOCK E: Runnable t = new Runnable() { public void run() { Work.doIt(); } }; t.run(); 1) Code block A. 2) Code block B. 3) Code block C. 4) Code block D. 5) Code block E. Q14 Write a line of code that declares a variable named layout of type LayoutManager and initializes it with a new object, which when used with a container can lay out components in a rectangular grid of equal-sized rectangles, 3 components wide and 2 components high. Q15 public class Q275d { static int a; int b; public Q275d() { int c; c = a; a++; b += c; } public static void main(String args[]) { new Q275d(); } } 1) The code will fail to compile, since the constructor is trying to access static members. 2) The code will fail to compile, since the constructor is trying to use static member variable a before it has been initialized. 3) The code will fail to compile, since the constructor is trying to use member variable b before it has been initialized. 4) The code will fail to compile, since the constructor is trying to use local variable c before it has been initialized. 5) The code will compile and run without any problems. Q16 What will be written to the standard output when the following program is run? public class Q63e3 { public static void main(String args[]) { System.out.println(9 ^ 2); } } 1) 81 2) 7 3) 11 4) 0 5) false Q17 Which statements are true concerning the default layout manager for containers in the java.awt package? 1) Objects instantiated from Panel do not have a default layout manager. 2) Objects instantiated from Panel have FlowLayout as default layout manager. 3) Objects instantiated from Applet have BorderLayout as default layout manager. 4) Objects instantiated from Dialog have BorderLayout as default layout manager. 5) Objects instantiated from Window have the same default layout manager as instances of Applet. Q18 Which declarations will allow a class to be started as a standalone program? 1) public void main(String args[]) 2) public void static main(String args[]) 3) public static main(String[] argv) 4) final public static void main(String [] array) 5) public static void main(String args[]) Q19 Under which circumstances will a thread stop? 1) The method waitforId() in class MediaTracker is called. 2) The run() method that the thread is executing ends. 3) The call to the start() method of the Thread object returns. 4) The suspend() method is called on the Thread object. 5) The wait() method is called on the Thread object. Q20 When creating a class that associates a set of keys with a set of values, which of these interfaces is most applicable? 1) Collection 2) Set 3) SortedSet 4) Map Q21 What does the value returned by the method getID() found in class java.awt.AWTEvent uniquely identify? 1) The particular event instance. 2) The source of the event. 3) The set of events that were triggered by the same action. 4) The type of event. 5) The type of component from which the event originated. Q22 What will be written to the standard output when the following program is run? class Base { int i; Base() { add(1); } void add(int v) { i += v; } void print() { System.out.println(i); } } class Extension extends Base { Extension() { add(2); } void add(int v) { i += v*2; } } public class Qd073 { public static void main(String args[]) { bogo(new Extension()); } static void bogo(Base b) { b.add(8); b.print(); } } 1) 9 2) 18 3) 20 4) 21 5) 22 Q23 Which lines of code are valid declarations of a native method when occurring within the declaration of the following class? public class Qf575 { // insert declaration of a native method here } 1) native public void setTemperature(int kelvin); 2) private native void setTemperature(int kelvin); 3) protected int native getTemperature(); 4) public abstract native void setTemperature(int kelvin); 5) native int setTemperature(int kelvin) {} Q24 How does the weighty property of the GridBagConstraints objects used in grid bag layout affect the layout of the components? 1) It affects which grid cell the components end up in. 2) It affects how the extra vertical space is distributed. 3) It affects the alignment of each component. 4) It affects whether the components completely fill their allotted display area vertically. Q25 Which statements can be inserted at the indicated position in the following code to make the program write 1 on the standard output when run? public class Q4a39 { int a = 1; int b = 1; int c = 1; class Inner { int a = 2; int get() { int c = 3; // insert statement here return c; } } Q4a39() { Inner i = new Inner(); System.out.println(i.get()); } public static void main(String args[]) { new Q4a39(); } } 1) c = b; 2) c = this.a; 3) c = this.b; 4) c = Q4a39.this.a; 5) c = c; Q26 Which is the earliest line in the following code after which the object created on the line marked (0) will be a candidate for being garbage collected, assuming no compiler optimizations are done? public class Q76a9 { static String f() { String a = "hello"; String b = "bye"; // (0) String c = b + "!"; // (1) String d = b; b = a; // (2) d = a; // (3) return c; // (4) } public static void main(String args[]) { String msg = f(); System.out.println(msg); // (5) } } 1) The line marked (1). 2) The line marked (2). 3) The line marked (3). 4) The line marked (4). 5) The line marked (5). Q27 Which methods from the String and StringBuffer classes modify the object on which they are called? 1) The charAt() method of the String class. 2) The toUpperCase() method of the String class. 3) The replace() method of the String class. 4) The reverse() method of the StringBuffer class. 5) The length() method of the StringBuffer class. Q28 Which statements, when inserted at the indicated position in the following code, will cause a runtime exception when attempting to run the program? class A {} class B extends A {} class C extends A {} public class Q3ae4 { public static void main(String args[]) { A x = new A(); B y = new B(); C z = new C(); // insert statement here } } 1) x = y; 2) z = x; 3) y = (B) x; 4) z = (C) y; 5) y = (A) y; Q29 Which of these are keywords in Java? 1) default 2) NULL 3) String 4) throws 5) long Q30 It is desirable that a certain method within a certain class can only be accessed by classes that are defined within the same package as the class of the method. How can such restrictions be enforced? 1) Mark the method with the keyword public. 2) Mark the method with the keyword protected. 3) Mark the method with the keyword private. 4) Mark the method with the keyword package. 5) Do not mark the method with any accessibility modifiers. Q31 Which code fragments will succeed in initializing a two-dimensional array named tab with a size that will cause the expression tab[3][2] to access a valid element? CODE FRAGMENT A: int[][] tab = { { 0, 0, 0 }, { 0, 0, 0 } }; CODE FRAGMENT B: int tab[][] = new int[4][]; for (int i=0; i CODE FRAGMENT C: int tab[][] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; CODE FRAGMENT D: int tab[3][2]; CODE FRAGMENT E: int[] tab[] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; 1) Code fragment A. 2) Code fragment B. 3) Code fragment C. 4) Code fragment D. 5) Code fragment E. Q32 What will be the result of attempting to run the following program? public class Qaa75 { public static void main(String args[]) { String[][][] arr = { { {}, null }, { { "1", "2" }, { "1", null, "3" } }, {}, { { "1", null } } }; System.out.println(arr.length + arr[1][2].length); } } 1) The program will terminate with an ArrayIndexOutOfBoundsException. 2) The program will terminate with a NullPointerException. 3) 4 will be written to standard output. 4) 6 will be written to standard output. 5) 7 will be written to standard output. Q33 Which expressions will evaluate to true if preceded by the following code? String a = "hello"; String b = new String(a); String c = a; char[] d = { 'h', 'e', 'l', 'l', 'o' }; 1) (a == "Hello") 2) (a == b) 3) (a == c) 4) a.equals(b) 5) a.equals(d) Q34 Which statements concerning the following code are true? class A { public A() {} public A(int i) { this(); } } class B extends A { public boolean B(String msg) { return false; } } class C extends B { private C() { super(); } public C(String msg) { this(); } public C(int i) {} } 1) The code will fail to compile. 2) The constructor in A that takes an int as an argument will never be called as a result of constructing an object of class B or C. 3) Class C has three constructors. 4) Objects of class B cannot be constructed. 5) At most one of the constructors of each class is called as a result of constructing an object of class C. Q35 Given two collection objects referenced by col1 and col2, which of these statements are true? 1) The operation col1.retainAll(col2) will not modify the col1 object. 2) The operation col1.removeAll(col2) will not modify the col2 object. 3) The operation col1.addAll(col2) will return a new collection object, containing elements from both col1 and col2. 4) The operation col1.containsAll(Col2) will not modify the col1 object. Q36 Which statements concerning the relationships between the following classes are true? class Foo { int num; Baz comp = new Baz(); } class Bar { boolean flag; } class Baz extends Foo { Bar thing = new Bar(); double limit; } 1) A Bar is a Baz. 2) A Foo has a Bar. 3) A Baz is a Foo. 4) A Foo is a Baz. 5) A Baz has a Bar. Q37 Which statements concerning the value of a member variable are true, when no explicit assignments have been made? 1) The value of an int is undetermined. 2) The value of all numeric types is zero. 3) The compiler may issue an error if the variable is used before it is initialized. 4) The value of a String variable is "" (empty string). 5) The value of all object variables is null. Q38 Which statements describe guaranteed behavior of the garbage collection and finalization mechanisms? 1) Objects are deleted when they can no longer be accessed through any reference. 2) The finalize() method will eventually be called on every object. 3) The finalize() method will never be called more than once on an object. 4) An object will not be garbage collected as long as it is possible for an active part of the program to access it through a reference. 5) The garbage collector will use a mark and sweep algorithm. Q39 Which code fragments will succeed in printing the last argument given on the command line to the standard output, and exit gracefully with no output if no arguments are given? CODE FRAGMENT A: public static void main(String args[]) { if (args.length != 0) System.out.println(args[args.length-1]); } CODE FRAGMENT B: public static void main(String args[]) { try { System.out.println(args[args.length]); } catch (ArrayIndexOutOfBoundsException e) {} } CODE FRAGMENT C: public static void main(String args[]) { int ix = args.length; String last = args[ix]; if (ix != 0) System.out.println(last); } CODE FRAGMENT D: public static void main(String args[]) { int ix = args.length-1; if (ix > 0) System.out.println(args[ix]); } CODE FRAGMENT E: public static void main(String args[]) { try { System.out.println(args[args.length-1]); } catch (NullPointerException e) {} } 1) Code fragment A. 2) Code fragment B. 3) Code fragment C. 4) Code fragment D. 5) Code fragment E. Q40 Which of these statements concerning the collection interfaces are true? 1) Set extends Collection. 2) All methods defined in Set are also defined in Collection. 3) List extends Collection. 4) All methods defined in List are also defined in Collection. 5) Map extends Collection. Q41 What is the name of the method that threads can use to pause their execution until signalled to continue by another thread? Fill in the name of the method (do not include a parameter list). Q42 Given the following class definitions, which expression identifies whether the object referred to by obj was created by instantiating class B rather than classes A, C and D? class A {} class B extends A {} class C extends B {} class D extends A {} 1) obj instanceof B 2) obj instanceof A && ! (obj instanceof C) 3) obj instanceof B && ! (obj instanceof C) 4) obj instanceof C || obj instanceof D 5) (obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D) Q43 What will be written to the standard output when the following program is run? public class Q8499 { public static void main(String args[]) { double d = -2.9; int i = (int) d; i *= (int) Math.ceil(d); i *= (int) Math.abs(d); System.out.println(i); } } 1) 12 2) 18 3) 8 4) 12 5) 27 Q44 What will be written to the standard output when the following program is run? public class Qcb90 { int a; int b; public void f() { a = 0; b = 0; int[] c = { 0 }; g(b, c); System.out.println(a + " " + b + " " + c[0] + " "); } public void g(int b, int[] c) { a = 1; b = 1; c[0] = 1; } public static void main(String args[]) { Qcb90 obj = new Qcb90(); obj.f(); } } 1) 0 0 0 2) 0 0 1 3) 0 1 0 4) 1 0 0 5) 1 0 1 Q45 Which statements concerning the effect of the statement gfx.drawRect(5, 5, 10, 10) are true, given that gfx is a reference to a valid Graphics object? 1) The rectangle drawn will have a total width of 5 pixels. 2) The rectangle drawn will have a total height of 6 pixels. 3) The rectangle drawn will have a total width of 10 pixels. 4) The rectangle drawn will have a total height of 11 pixels. Q46 Given the following code, which code fragments, when inserted at the indicated location, will succeed in making the program display a button spanning the whole window area? import java.awt.*; public class Q1e65 { public static void main(String args[]) { Window win = new Frame(); Button but = new Button("button"); // insert code fragment here win.setSize(200, 200); win.setVisible(true); } } 1) win.setLayout(new BorderLayout()); win.add(but); 2) win.setLayout(new GridLayout(1, 1)); win.add(but); 3) win.setLayout(new BorderLayout()); win.add(but, BorderLayout.CENTER); 4) win.add(but); 5) win.setLayout(new FlowLayout()); win.add(but); Q47 Which method implementations will write the given string to a file named "file", using UTF8 encoding? IMPLEMENTATION A: public void write(String msg) throws IOException { FileWriter fw = new FileWriter(new File("file")); fw.write(msg); fw.close(); } IMPLEMENTATION B: public void write(String msg) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("file"), "UTF8"); osw.write(msg); osw.close(); } IMPLEMENTATION C: public void write(String msg) throws IOException { FileWriter fw = new FileWriter(new File("file")); fw.setEncoding("UTF8"); fw.write(msg); fw.close(); } IMPLEMENTATION D: public void write(String msg) throws IOException { FilterWriter fw = FilterWriter(new FileWriter("file"), "UTF8"); fw.write(msg); fw.close(); } IMPLEMENTATION E: public void write(String msg) throws IOException { OutputStreamWriter osw = new OutputStreamWriter( new OutputStream(new File("file")), "UTF8" ); osw.write(msg); osw.close(); } 1) Implementation A. 2) Implementation B. 3) Implementation C. 4) Implementation D. 5) Implementation E. Q48 Which are valid identifiers? 1) _class 2) $value$ 3) zer@ 4) ¥ngstr 5) 2muchuq Q49 What will be the result of attempting to compile and run the following program? public class Q28fd { public static void main(String args[]) { int counter = 0; l1: for (int i=10; i<0; i--) { l2: int j = 0; while (j < 10) { if (j > i) break l2; if (i == j) { counter++; continue l1; } } counter--; } System.out.println(counter); } } 1) The program will fail to compile. 2) The program will not terminate normally. 3) The program will write 10 to the standard output. 4) The program will write 0 to the standard output. 5) The program will write 9 to the standard output. Q50 Given the following interface definition, which definitions are valid? interface I { void setValue(int val); int getValue(); } DEFINITION A: (a) class A extends I { int value; void setValue(int val) { value = val; } int getValue() { return value; } } DEFINITION B: (b) interface B extends I { void increment(); } DEFINITION C: (c) abstract class C implements I { int getValue() { return 0; } abstract void increment(); } DEFINITION D: (d) interface D implements I { void increment(); } DEFINITION E: (e) class E implements I { int value; public void setValue(int val) { value = val; } } 1) Definition A. 2) Definition B. 3) Definition C. 4) Definition D. 5) Definition E. Q51 Which statements concerning the methods notify() and notifyAll() are true? 1) Instances of class Thread have a method called notify(). 2) A call to the method notify() will wake the thread that currently owns the monitor of the object. 3) The method notify() is synchronized. 4) The method notifyAll() is defined in class Thread. 5) When there is more than one thread waiting to obtain the monitor of an object, there is no way to be sure which thread will be notified by the notify() method. Q52 Which statements concerning the correlation between the inner and outer instances of non-static inner classes are true? 1) Member variables of the outer instance are always accessible to inner instances, regardless of their accessibility modifiers. 2) Member variables of the outer instance can never be referred to using only the variable name within the inner instance. 3) More than one inner instance can be associated with the same outer instance. 4) All variables from the outer instance that should be accessible in the inner instance must be declared final. 5) A class that is declared final cannot have any inner classes. Q53 What will be the result of attempting to compile and run the following code? public class Q6b0c { public static void main(String args[]) { int i = 4; float f = 4.3; double d = 1.8; int c = 0; if (i == f) c++; if (((int) (f + d)) == ((int) f + (int) d)) c += 2; System.out.println(c); } } 1) The code will fail to compile. 2) 0 will be written to the standard output. 3) 1 will be written to the standard output. 4) 2 will be written to the standard output. 5) 3 will be written to the standard output. Q54 Which operators will always evaluate all the operands? 1) || 2) + 3) && 4) ? : 5) % Q55 Which statements concerning the switch construct are true? 1) All switch statements must have a default label. 2) There must be exactly one label for each code segment in a switch statement. 3) The keyword continue can never occur within the body of a switch statement. 4) No case label may follow a default label within a single switch statement. 5) A character literal can be used as a value for a case label. Q56 Which modifiers and return types would be valid in the declaration of a working main() method for a Java standalone application? 1) private 2) final 3) static 4) int 5) abstract Q57 What will be the appearance of an applet with the following init() method? public void init() { add(new Button("hello")); } 1) Nothing appears in the applet. 2) A button will cover the whole area of the applet. 3) A button will appear in the top left corner of the applet. 4) A button will appear, centered in the top region of the applet. 5) A button will appear in the center of the applet. Q58 Which statements concerning the event model of the AWT are true? 1) At most one listener of each type can be registered with a component. 2) Mouse motion listeners can be registered on a List instance. 3) There exists a class named ContainerEvent in package java.awt.event. 4) There exists a class named MouseMotionEvent in package java.awt.event. 5) There exists a class named ActionAdapter in package java.awt.event. Q59 Which statements are true, given the code new FileOutputStream("data", true) for creating an object of class FileOutputStream? 1) FileOutputStream has no constructors matching the given arguments. 2) An IOExeception will be thrown if a file named "data" already exists. 3) An IOExeception will be thrown if a file named "data" does not already exist. 4) If a file named "data" exists, its contents will be reset and overwritten. 5) If a file named "data" exists, output will be appended to its current contents. Q60 Given the following code, write a line of code that, when inserted at the indicated location, will make the overriding method in Extension invoke the overridden method in class Base on the current object. class Base { public void print() { System.out.println("base"); } } class Extention extends Base { public void print() { System.out.println("extension"); // insert line of implementation here } } public class Q294d { public static void main(String args[]) { Extention ext = new Extention(); ext.print(); } } Fill in a single line of implementation. Q61 Given that file is a reference to a File object that represents a directory, which code fragments will succeed in obtaining a list of the entries in the directory? 1) Vector filelist = ((Directory) file).getList(); 2) String[] filelist = file.directory(); 3) Enumeration filelist = file.contents(); 4) String[] filelist = file.list(); 5) Vector filelist = (new Directory(file)).files(); Q62 What will be written to the standard output when the following program is run? public class Q03e4 { public static void main(String args[]) { String space = " "; String composite = space + "hello" + space + space; composite.concat("world"); String trimmed = composite.trim(); System.out.println(trimmed.length()); } } 1) 5 2) 6 3) 7 4) 12 5) 13 Q63 Given the following code, which statements concerning the objects referenced through the member variables i, j and k are true, given that any thread may call the methods a, b and c at any time? class Counter { int v = 0; synchronized void inc() { v++; } synchronized void dec() { v--; } } public class Q7ed5 { Counter i; Counter j; Counter k; public synchronized void a() { i.inc(); System.out.println("a"); i.dec(); } public synchronized void b() { i.inc(); j.inc(); k.inc(); System.out.println("b"); i.dec(); j.dec(); k.dec(); } public void c() { k.inc(); System.out.println("c"); k.dec(); } } 1) i.v is guaranteed always to be 0 or 1. 2) j.v is guaranteed always to be 0 or 1. 3) k.v is guaranteed always to be 0 or 1 4) j.v will always be greater than or equal to k.v at any give time. 5) k.v will always be greater than or equal to j.v at any give time. Q64 Which statements concerning casting and conversion are true? 1) Conversion from int to long does not need a cast. 2) Conversion from byte to short does not need a cast. 3) Conversion from float to long does not need a cast. 4) Conversion from short to char does not need a cast. 5) Conversion from boolean to int using a cast is not possible. Q65 Given the following code, which method declarations, when inserted at the indicated position, will not cause the program to fail compilation? public class Qdd1f { public long sum(long a, long b) { return a + b; } // insert new method declaration here } 1) public int sum(int a, int b) { return a + b; } 2) public int sum(long a, long b) { return 0; } 3) abstract int sum(); 4) private long sum(long a, long b) { return a + b; } 5) public long sum(long a, int b) { return a + b; } Q66 The 8859-1 character code for the uppercase letter A is 65. Which of these code fragments declare and initialize a variable of type char with this value? 1) char ch = 65; 2) char ch = '\65'; 3) char ch = '\0041'; 4) char ch = 'A'; 5)char ch = "A"; 1) 4 2) 2 3) 2 4) 2, 6 5) 4 6) 3 7) 4 8) 4 9) 1, 2, 3, 5 10) 1, 5 11) 4 12) 5 13) 1 14) "LayoutManager layout = new GridLayout(2, 3);" or: "LayoutManager layout = new GridLayout(2, 3)" 15) 5 16) 3 17) 2, 4 18) 4, 5 19) 2 20) 4 21) 4 22) 5 23) 1, 2 24) 2 25) 1, 4 26) 3 27) 4 28) 3 (? no run-time exception) 29) 1, 4, 5 30) 5 31) 2, 5 32) 1 33) 3, 4 34) 2, 3 35) 2, 4 36) 3, 5 37) 2, 5 38) 3, 4 39) 1 40) 1, 2, 3 41) "wait" 42) 3 43) 3 44) 5 45) 4 46) 1, 2, 3, 4 47) 2 48) 1, 2, 4 49) 1 50) 2, 3 51) 1, 5 52) 1, 3 53) 1 54) 2, 5 55) 5 56) 2, 3 57) 4 58) 2, 3 59) 5 60) super.print(); 61) 4 62) 1 63) 1,2 64) 1,2,5 65) 1,5 66) 1,4 <

小小豆叮

如何读出保存在session变量中的数组

作者:崔冠宇 Java中,将数组保存在session变量后再读出似乎是一件令程序员头痛的事,其实只要稍做改动问题即可迎刃而解,本文将向大家介绍这一雕虫小技. 假设有一数组定义如下: String arr[] = new String[]{“abc”,”def”,”ghi”,”jkl”,”mno”}; 将数组arr存入session变量中是没有任何问题的 session.setAttribute(“sessionArr”,arr); 然而,当检索session变量时,却回出现问题 String targetArr[] = session.getAttribute(“sessionArr”); 错误提示信息如下: incompatible types; found: java.lang.String, required: java.lang.String[] 出错原因是类型不匹配,”=”左边是数组类型,而”=”右边是Object类型,解决办法是强制类型转换 String targetArr[] = (String[])session.getAttribute(“sessionArr”); 好了,问题解决了! <

小小豆叮

SCJP Mock Exam 3

转载,对答案和题目谨做参考 Question 1) What will happen when you attempt to compile and run this code? abstract class Base{ abstract public void myfunc(); public void another(){ System.out.println("Another method"); } } public class Abs extends Base{ public static void main(String argv[]){ Abs a = new Abs(); a.amethod(); } public void myfunc(){ System.out.println("My Func"); } public void amethod(){ myfunc(); } } 1) The code will compile and run, printing out the words "My Func" 2) The compiler will complain that the Base class has non abstract methods 3) The code will compile but complain at run time that the Base class has non abstract methods 4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to looove it Answer to Question 1 -------------------------------------------------------------------------------- Question 2) What will happen when you attempt to compile and run this code? public class MyMain{ public static void main(String argv){ System.out.println("Hello cruel world"); } } 1) The compiler will complain that main is a reserved word and cannot be used for a class 2) The code will compile and when run will print out "Hello cruel world" 3) The code will compile but will complain at run time that no constructor is defined 4) The code will compile but will complain at run time that main is not correctly defined Answer to Question 2 -------------------------------------------------------------------------------- Question 3) Which of the following are Java modifiers? 1) public 2) private 3) friendly 4) transient 5) vagrant Answer to Question 3 -------------------------------------------------------------------------------- Question 4) What will happen when you attempt to compile and run this code? class Base{ abstract public void myfunc(); public void another(){ System.out.println("Another method"); } } public class Abs extends Base{ public static void main(String argv[]){ Abs a = new Abs(); a.amethod(); } public void myfunc(){ System.out.println("My func"); } public void amethod(){ myfunc(); } } 1) The code will compile and run, printing out the words "My Func" 2) The compiler will complain that the Base class is not declared as abstract. 3) The code will compile but complain at run time that the Base class has non abstract methods 4) The compiler will complain that the method myfunc in the base class has no body, nobody at all to looove it Answer to Question 4 -------------------------------------------------------------------------------- Question 5) Why might you define a method as native? 1) To get to access hardware that Java does not know about 2) To define a new data type such as an unsigned integer 3) To write optimised code for performance in a language such as C/C++ 4) To overcome the limitation of the private scope of a method Answer to Question 5 -------------------------------------------------------------------------------- Question 6) What will happen when you attempt to compile and run this code? class Base{ public final void amethod(){ System.out.println("amethod"); } } public class Fin extends Base{ public static void main(String argv[]){ Base b = new Base(); b.amethod(); } } 1) Compile time error indicating that a class with any final methods must be declared final itself 2) Compile time error indicating that you cannot inherit from a class with final methods 3) Run time error indicating that Base is not defined as final 4) Success in compilation and output of "amethod" at run time. Answer to Question 6 -------------------------------------------------------------------------------- Question 7) What will happen when you attempt to compile and run this code? public class Mod{ public static void main(String argv[]){ } public static native void amethod(); } 1) Error at compilation: native method cannot be static 2) Error at compilation native method must return value 3) Compilation but error at run time unless you have made code containing native amethod available 4) Compilation and execution without error Answer to Question 7 -------------------------------------------------------------------------------- Question 8) What will happen when you attempt to compile and run this code? private class Base{} public class Vis{ transient int iVal; public static void main(String elephant[]){ } } 1)Compile time error: Base cannot be private 2)Compile time error indicating that an integer cannot be transient 3)Compile time error transient not a data type 4)Compile time error malformed main method Answer to Question 8 -------------------------------------------------------------------------------- Question 9) What happens when you attempt to compile and run these two files in the same directory? //File P1.java package MyPackage; class P1{ void afancymethod(){ System.out.println("What a fancy method"); } } //File P2.java public class P2 extends P1{ afancymethod(); } 1) Both compile and P2 outputs "What a fancy method" when run 2) Neither will compile 3) Both compile but P2 has an error at run time 4) P1 compiles cleanly but P2 has an error at compile time Answer to Question 9 -------------------------------------------------------------------------------- Question 10) You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it.? public class MyAr{ public static void main(String argv[]){ int[] i = new int[5]; System.out.println(i[5]); } } 1) An error at compile time 2) An error at run time 3) The value 0 will be output 4) The string "null" will be output Answer to Question 10 -------------------------------------------------------------------------------- Question 11) You want to loop through an array and stop when you come to the last element. Being a good java programmer and forgetting everything you ever knew about C/C++ you know that arrays contain information about their size. Which of the following can you use? 1)myarray.length(); 2)myarray.length; 3)myarray.size 4)myarray.size(); Answer to Question 11 -------------------------------------------------------------------------------- Question 12) What best describes the appearance of an application with the following code? import java.awt.*; public class FlowAp extends Frame{ public static void main(String argv[]){ FlowAp fa=new FlowAp(); fa.setSize(400,300); fa.setVisible(true); } FlowAp(){ add(new Button("One")); add(new Button("Two")); add(new Button("Three")); add(new Button("Four")); }//End of constructor }//End of Application 1) A Frame with buttons marked One to Four placed on each edge. 2) A Frame with buutons marked One to four running from the top to bottom 3) A Frame with one large button marked Four in the Centre 4) An Error at run time indicating you have not set a LayoutManager Answer to Question 12 -------------------------------------------------------------------------------- Question 13) How do you indicate where a component will be positioned using Flowlayout? 1) North, South,East,West 2) Assign a row/column grid reference 3) Pass a X/Y percentage parameter to the add method 4) Do nothing, the FlowLayout will position the component Answer to Question 13) -------------------------------------------------------------------------------- Question 14) How do you change the current layout manager for a container 1) Use the setLayout method 2) Once created you cannot change the current layout manager of a component 3) Use the setLayoutManager method 4) Use the updateLayout method Answer to Question 14) -------------------------------------------------------------------------------- Question 15) Which of the following are fields of the GridBagConstraints class? 1) ipadx 2) fill 3) insets 4) width Answer to Question 15) -------------------------------------------------------------------------------- Question 16) What most closely matches the appearance when this code runs? import java.awt.*; public class CompLay extends Frame{ public static void main(String argv[]){ CompLay cl = new CompLay(); } CompLay(){ Panel p = new Panel(); p.setBackground(Color.pink); p.add(new Button("One")); p.add(new Button("Two")); p.add(new Button("Three")); add("South",p); setLayout(new FlowLayout()); setSize(300,300); setVisible(true); } } 1) The buttons will run from left to right along the bottom of the Frame 2) The buttons will run from left to right along the top of the frame 3) The buttons will not be displayed 4) Only button three will show occupying all of the frame Answer to Question 16) -------------------------------------------------------------------------------- Question 17) Which statements are correct about the anchor field? 1) It is a field of the GridBagLayout manager for controlling component placement 2) It is a field of the GridBagConstraints class for controlling component placement 3) A valid setting for the anchor field is GridBagConstraints.NORTH 4) The anchor field controls the height of components added to a container Answer to Question 17) -------------------------------------------------------------------------------- Question 18) What will happen when you attempt to compile and run the following code? public class Bground extends Thread{ public static void main(String argv[]){ Bground b = new Bground(); b.run(); } public void start(){ for (int i = 0; i <10; i++){ System.out.println("Value of i = " + i); } } } 1) A compile time error indicating that no run method is defined for the Thread class 2) A run time error indicating that no run method is defined for the Thread class 3) Clean compile and at run time the values 0 to 9 are printed out 4) Clean compile but no output at runtime Answer to Question 18) -------------------------------------------------------------------------------- Question 19) 10)When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. Is this statement 1) true 2) false Answer to Question 19) -------------------------------------------------------------------------------- Question 20) Which most closely matches a description of a Java Map? 1) A vector of arrays for a 2D geographic representation 2) A class for containing unique array elements 3) A class for containing unique vector elements 4) An interface that ensures that implementing classes cannot contain duplicate keys Answer to Question 20) -------------------------------------------------------------------------------- Question 21) How does the set collection deal with duplicate elements? 1) An exception is thrown if you attempt to add an element with a duplicate value 2) The add method returns false if you attempt to add an element with a duplicate value 3) A set may contain elements that return duplicate values from a call to the equals method 4) Duplicate values will cause an error at compile time Answer to Question 21) -------------------------------------------------------------------------------- Question 22) What can cause a thread to stop executing? 1) The program exits via a call to System.exit(0); 2) Another thread is given a higher priority 3) A call to the thread's stop method. 4) A call to the halt method of the Thread class Answer to Question 22) -------------------------------------------------------------------------------- Question 23) For a class defined inside a method, what rule governs access to the variables of the enclosing method? 1) The class can access any variable 2) The class can only access static variables 3) The class can only access transient variables 4) The class can only access final variables Answer to Question 23) -------------------------------------------------------------------------------- Question 24) Under what circumstances might you use the yield method of the Thread class 1) To call from the currently running thread to allow another thread of the same or higher priority to run 2) To call on a waiting thread to allow it to run 3) To allow a thread of higher priority to run 4) To call from the currently running thread with a parameter designating which thread should be allowed to run Answer to Question 24) -------------------------------------------------------------------------------- Question 25) What will happen when you attempt to compile and run the following code public class Hope{ public static void main(String argv[]){ Hope h = new Hope(); } protected Hope(){ for(int i =0; i <10; i ++){ System.out.println(i); } } } 1) Compilation error: Constructors cannot be declared protected 2) Run time error: Constructors cannot be declared protected 3) Compilation and running with output 0 to 10 4) Compilation and running with output 0 to 9 Answer to Question 25) -------------------------------------------------------------------------------- Question 26) What will happen when you attempt to compile and run the following code public class MySwitch{ public static void main(String argv[]){ MySwitch ms= new MySwitch(); ms.amethod(); } public void amethod(){ int k=10; switch(k){ default: //Put the default at the bottom, not here System.out.println("This is the default output"); break; case 10: System.out.println("ten"); case 20: System.out.println("twenty"); break; } } } 1) None of these options 2) Compile time error target of switch must be an integral type 3) Compile and run with output "This is the default output" 4) Compile and run with output of the single line "ten" Answer to Question 26) -------------------------------------------------------------------------------- Question 27) Which of the following is the correct syntax for suggesting that the JVM performs garbage collection 1) System.free(); 2) System.setGarbageCollection(); 3) System.out.gc(); 4) System.gc(); Answer to Question 27) -------------------------------------------------------------------------------- Question 28) What will happen when you attempt to compile and run the following code public class As{ int i = 10; int j; char z= 1; boolean b; public static void main(String argv[]){ As a = new As(); a.amethod(); } public void amethod(){ System.out.println(j); System.out.println(b); } } 1) Compilation succeeds and at run time an output of 0 and false 2) Compilation succeeds and at run time an output of 0 and true 3) Compile time error b is not initialised 4) Compile time error z must be assigned a char value Answer to Question 28) -------------------------------------------------------------------------------- Question 29) What will happen when you attempt to compile and run the following code with the command line "hello there" public class Arg{ String[] MyArg; public static void main(String argv[]){ MyArg=argv; } public void amethod(){ System.out.println(argv[1]); } } 1) Compile time error 2) Compilation and output of "hello" 3) Compilation and output of "there" 4) None of the above Answer to Question 29) -------------------------------------------------------------------------------- Question 30) What will happen when you attempt to compile and run the following code public class StrEq{ public static void main(String argv[]){ StrEq s = new StrEq(); } private StrEq(){ String s = "Marcus"; String s2 = new String("Marcus"); if(s == s2){ System.out.println("we have a match"); }else{ System.out.println("Not equal"); } } } 1) Compile time error caused by private constructor 2) Output of "we have a match" 3) Output of "Not equal" 4) Compile time error by attempting to compare strings using == Answer to Question 30) -------------------------------------------------------------------------------- Question 31) 1) What will happen when you attempt to compile and run the following code import java.io.*; class Base{ public static void amethod()throws FileNotFoundException{} } public class ExcepDemo extends Base{ public static void main(String argv[]){ ExcepDemo e = new ExcepDemo(); } public static void amethod(){} protected ExcepDemo(){ try{ DataInputStream din = new DataInputStream(System.in); System.out.println("Pausing"); din.readChar(); System.out.println("Continuing"); this.amethod(); }catch(IOException ioe) {} } } 1)Compile time error caused by protected constructor 2) Compile time error caused by amethod not declaring Exception 3) Runtime error caused by amethod not declaring Exception 4) Compile and run with output of "Pausing" and "Continuing" after a key is hit Answer to Question 31) -------------------------------------------------------------------------------- Question 32) What will happen when you attempt to compile and run this program public class Outer{ public String name = "Outer"; public static void main(String argv[]){ Inner i = new Inner(); i.showName(); }//End of main private class Inner{ String name =new String("Inner"); void showName(){ System.out.println(name); } }//End of Inner class } 1) Compile and run with output of "Outer" 2) Compile and run with output of "Inner" 3) Compile time error because Inner is declared as private 4) Compile time error because of the line creating the instance of Inner Answer to Question to 32 -------------------------------------------------------------------------------- Question 33) What will happen when you attempt to compile and run this code //Demonstration of event handling import java.awt.event.*; import java.awt.*; public class MyWc extends Frame implements WindowListener{ public static void main(String argv[]){ MyWc mwc = new MyWc(); } public void windowClosing(WindowEvent we){ System.exit(0); }//End of windowClosing public void MyWc(){ setSize(300,300); setVisible(true); } }//End of class 1) Error at compile time 2) Visible Frame created that that can be closed 3) Compilation but no output at run time 4) Error at compile time because of comment before import statements Answer to Question 33) -------------------------------------------------------------------------------- Question 34) Which option most fully describes will happen when you attempt to compile and run the following code public class MyAr{ public static void main(String argv[]) { MyAr m = new MyAr(); m.amethod(); } public void amethod(){ static int i; System.out.println(i); } } 1) Compilation and output of the value 0 2) Compile time error because i has not been initialized 3) Compilation and output of null 4) Compile time error Answer to Question 34) -------------------------------------------------------------------------------- Question 35) Which of the following will compile correctly 1) short myshort = 99S; 2) String name = 'Excellent tutorial Mr Green'; 3) char c = 17c; 4)int z = 015; Answer to Question 35) -------------------------------------------------------------------------------- Question 36) Which of the following are Java key words 1)double 2)Switch 3)then 4)instanceof Answer to Question 36) -------------------------------------------------------------------------------- Question 37) What will be output by the following line? System.out.println(Math.floor(-2.1)); 1) -2 2) 2.0 3) -3 4) -3.0 Answer to Question 37) -------------------------------------------------------------------------------- Question 38) Given the following main method in a class called Cycle and a command line of java Cycle one two what will be output? public static void main(String bicycle[]){ System.out.println(bicycle[0]); } 1) None of these options 2) cycle 3) one 4) two Answer to Question 38) -------------------------------------------------------------------------------- Question 39) Which of the following statements are true? 1) At the root of the collection hierarchy is a class called Collection 2) The collection interface contains a method called enumerator 3) The interator method returns an instance of the Vector class 4) The set interface is designed for unique elements Answer to Question 39) -------------------------------------------------------------------------------- Question 40) Which of the following statements are correct? 1) If multiple listeners are added to a component only events for the last listener added will be processed 2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order 3) Adding multiple listeners to a comnponent will cause a compile time error 4) You may remove as well add listeners to a component. Answer to Question 40) -------------------------------------------------------------------------------- Question 41) Given the following code class Base{} public class MyCast extends Base{ static boolean b1=false; static int i = -1; static double d = 10.1; public static void main(String argv[]){ MyCast m = new MyCast(); Base b = new Base(); //Here } } Which of the following, if inserted at the comment //Here will allow the code to compile and run without error 1) b=m; 2) m=b; 3) d =i; 4) b1 =i; Answer to Question 41) -------------------------------------------------------------------------------- Question 42) Which of the following statements about threading are true 1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or implements runnable 2) You can obtain a mutually exclusive lock on any object 3) A thread can obtain a mutually exclusive lock on a synchronized method of an object 4) Thread scheduling algorithms are platform dependent Answer to Question 42) -------------------------------------------------------------------------------- Question 43) Your chief Software designer has shown you a sketch of the new Computer parts system she is about to create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is called LinuxPC and one is called WindowsPC. The main difference between the two is that one runs the Linux operating System and the other runs the Windows System (of course another difference is that one needs constant re-booting and the other runs reliably). Under the WindowsPC are two Sub classes one called Server and one Called Workstation. How might you appraise your designers work? 1) Give the goahead for further design using the current scheme 2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type 3) Ask for the option of WindowsPC to be removed as it will soon be obsolete 4) Change the hierarchy to remove the need for the superfluous Computer Class. Answer to Question 43) -------------------------------------------------------------------------------- Question 44) Which of the following statements are true 1) An inner class may be defined as static 2) There are NO circumstances where an inner class may be defined as private 3) An anonymous class may have only one constructor 4) An inner class may extend another class Answer to Question 44) -------------------------------------------------------------------------------- Question 45) What will happen when you attempt to compile and run the following code int Output=10; boolean b1 = false; if((b1==true) && ((Output+=10)==20)){ System.out.println("We are equal "+Output); }else { System.out.println("Not equal! "+Output); } 1) Compile error, attempting to peform binary comparison on logical data type 2) Compilation and output of "We are equal 10" 3) Compilation and output of "Not equal! 20" 4) Compilation and output of "Not equal! 10" Answer to Question 45) -------------------------------------------------------------------------------- Question 46) Given the following variables which of the following lines will compile without error? String s = "Hello"; long l = 99; double d = 1.11; int i = 1; int j = 0; 1) j= i < Answer to Question 46) -------------------------------------------------------------------------------- Question 47) What will be output by the following line of code? System.out.println(010|4); 1) 142) 03) 64) 12 Answer to Question 47) -------------------------------------------------------------------------------- Question 48) Given the following variableschar c = 'c'; int i = 10; double d = 10; long l = 1; String s = "Hello"; Which of the following will compile without error? 1)c=c+i; 2)s+=i; 3)i+=s; 4)c+=s; Answer to Question 48) -------------------------------------------------------------------------------- Question 49) Which of the following will compile without error? 1) File f = new File("/","autoexec.bat");2) DataInputStream d = new DataInputStream(System.in);3) OutputStreamWriter o = new OutputStreamWriter(System.out);4) RandomAccessFile r = new RandomAccessFile("OutFile"); Answer to Question 49) -------------------------------------------------------------------------------- Question 50) Given the folowing classes which of the following will compile without error?interface IFace{} class CFace implements IFace{} class Base{} public class ObRef extends Base{ public static void main(String argv[]){ ObRef ob = new ObRef(); Base b = new Base(); Object o1 = new Object(); IFace o2 = new CFace(); } } 1)o1=o2; 2)b=ob; 3)ob=b; 4)o1=b; Answer to Question 50) -------------------------------------------------------------------------------- Question 51) Given the following code what will be the output?class ValHold{ public int i = 10; } public class ObParm{ public static void main(String argv[]){ ObParm o = new ObParm(); o.amethod(); } public void amethod(){ int i = 99; ValHold v = new ValHold(); v.i=30; another(v,i); System.out.println(v.i); }//End of amethod public void another(ValHold v, int i){ i=0; v.i = 20; ValHold vh = new ValHold(); v = vh; System.out.println(v.i+ " "+i); }//End of another } 1) 10,0, 302) 20,0,303) 20,99,304) 10,0,20 Answer to Question 51) -------------------------------------------------------------------------------- Question 52) Given the following class definition, which of the following methods could be legally placed after the comment//Here public class Rid{ public void amethod(int i, String s){} //Here } 1)public void amethod(String s, int i){}2)public int amethod(int i, String s){} 3)public void amethod(int i, String mystring){} 4) public void Amethod(int i, String s) {} Answer to Question 52) -------------------------------------------------------------------------------- Question 53) Given the following class definition which of the following can be legally placed after the comment line//Here ?class Base{ public Base(int i){} } public class MyOver extends Base{ public static void main(String arg[]){ MyOver m = new MyOver(10); } MyOver(int i){ super(i); } MyOver(String s, int i){ this(i); //Here } } 1)MyOver m = new MyOver();2)super(); 3)this("Hello",10);4)Base b = new Base(10); Answer to Question 53) -------------------------------------------------------------------------------- Question 54) Given the following class definition, which of the following statements would be legal after the comment //Hereclass InOut{ String s= new String("Between"); public void amethod(final int iArgs){ int iam; class Bicycle{ public void sayHello(){ //Here }//End of bicycle class } }//End of amethod public void another(){ int iOther; } } 1)System.out.println(s); 2) System.out.println(iOther);3) System.out.println(iam);4) System.out.println(iArgs); Answer to Question 54) -------------------------------------------------------------------------------- Question 55) Which of the following are methods of the Thread class? 1) yield()2) sleep(long msec)3) go()4) stop() Answer to Question 55) -------------------------------------------------------------------------------- Question 56) Which of the following methods are members of the Vector class and allow you to input a new element 1) addElement2) insert3) append4) addItem Answer to Question 56) -------------------------------------------------------------------------------- Question 57) Which of the following statements are true? 1) Adding more classes via import statements will cause a performance overhead, only import classes you actually use.2) Under no circumstances can a class be defined with the private modifier3) A inner class may under some circumstances be defined with the protected modifier4) An interface cannot be instantiated Answer 57) -------------------------------------------------------------------------------- Question 58) Which of the following are correct event handling methods 1) mousePressed(MouseEvent e){}2) MousePressed(MouseClick e){}3) functionKey(KeyPress k){}4) componentAdded(ContainerEvent e){} Answer 58) -------------------------------------------------------------------------------- Question 59) Which of the following are methods of the Collection interface?1) iterator2) isEmpty3) toArray4) setText Answer 59) -------------------------------------------------------------------------------- Question 60) Which of the following best describes the use of the synhronized keyword? 1) Allows two process to run in paralell but to communicate with each other2) Ensures only one thread at a time may access a method or object3) Ensures that two or more processes will start and end at the same time4) Ensures that two or more Threads will start and end at the same time Answer 60) -------------------------------------------------------------------------------- Answers -------------------------------------------------------------------------------- Answer 1) Objective 1.2) 1) The code will compile and run, printing out the words "My Func" A class that contains an abstract method must be declared abstract itself, but may contain non abstract methods. -------------------------------------------------------------------------------- Answer 2) Objective 4.1) 4) The code will compile but will complain at run time that main is not correctly defined In this example the parameter is a string not a string array as needed for the correct main method -------------------------------------------------------------------------------- Answer 3) Objective 4.3) 1) public2) private4) transient The keyword transient is easy to forget as is not frequently used. Although a method may be considered to be friendly like in C++ it is not a Java keyword. -------------------------------------------------------------------------------- Answer 4) Objective 1.2) 2) The compiler will complain that the Base class is not declared as abstract. If a class contains abstract methods it must itself be declared as abstract -------------------------------------------------------------------------------- Answer 5) Objective 1.2) 1) To get to access hardware that Java does not know about3) To write optimised code for performance in a language such as C/C++ -------------------------------------------------------------------------------- Answer 6) Objective 1.2) 4) Success in compilation and output of "amethod" at run time. A final method cannot be ovverriden in a sub class, but apart from that it does not cause any other restrictions. -------------------------------------------------------------------------------- Answer 7) Objective 1.2) 4) Compilation and execution without error It would cause a run time error if you had a call to amethod though. -------------------------------------------------------------------------------- Answer 8) Objective 1.2) 1)Compile time error: Base cannot be private A top leve (non nested) class cannot be private. -------------------------------------------------------------------------------- Answer 9) Objective 1.2) 4) P1 compiles cleanly but P2 has an error at compile time The package statement in P1.java is the equivalent of placing the file in a different directory to the file P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot be found. -------------------------------------------------------------------------------- Answer 10) Objective 1.1) 2) An error at run time This code will compile, but at run-time you will get an ArrayIndexOutOfBounds exception. This becuase counting in Java starts from 0 and so the 5th element of this array would be i[4]. Remember that arrays will always be initialized to default values wherever they are created. -------------------------------------------------------------------------------- Answer 11) Objective 1.1) 2)myarray.length; The String class has a length() method to return the number of characters. I have sometimes become confused between the two. -------------------------------------------------------------------------------- Answer 12) Objective 8.2) 3) A Frame with one large button marked Four in the Centre The default layout manager for a Frame is the BorderLayout manager. This Layout manager defaults to placing components in the centre if no constraint is passed with the call to the add method. -------------------------------------------------------------------------------- Answer 13) Objective 8.2) 4) Do nothing, the FlowLayout will position the component -------------------------------------------------------------------------------- Answer 14) Objective 8.2) 1) Use the setLayout method -------------------------------------------------------------------------------- Answer 15) Objective 8.2) 1) ipadx2) fill3) insets -------------------------------------------------------------------------------- Answer 16) Objective 8.2) 2) The buttons will run from left to right along the top of the frameThe call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and so the buttons end up at the top rather than the bottom. -------------------------------------------------------------------------------- Answer 17) Objective 8.2) 2) It is a field of the GridBagConstraints class for controlling component placement3) A valid settting for the anchor field is GridBagconstraints.NORTH -------------------------------------------------------------------------------- Answer 18) Objective 7.1) 4) Clean compile but no output at runtime This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and call when running a thread. If the for loop were defined in a method calledpublic void run() and the call in the main method had been to b.start() The list of values from 0 to 9 would have been output. -------------------------------------------------------------------------------- Answer 19) Objective 8.2) 2) falseYou can re-use the same instance of the GridBagConstraints when added successive components. -------------------------------------------------------------------------------- Answer 20) Objective 10.1) 4) An interface that ensures that implementing classes cannot contain duplicates -------------------------------------------------------------------------------- Answer 21) Objective 10.1) 2) The add method returns false if you attempt to add an element with a duplicate value I find it a surprise that you do not get an exception. -------------------------------------------------------------------------------- Answer 22) Objective 7.1) 1) The program exits via a call to exit(0);2) The priority of another thread is increased3) A call to the stop method of the Thread class Java threads are somewhat platform dependent and you should be carefull when making assumptions about Thread priorities. On some platforms you may find that a Thread with higher priorities gets to "hog" the processor. You can read up on this in more detail at http://java.sun.com/docs/books/tutorial/essential/threads/priority.html -------------------------------------------------------------------------------- Answer 23) Objective 4.1) 4) The class can only access final variables -------------------------------------------------------------------------------- Answer 24) Objective 7.1) 1) To call from the currently running thread to allow another thread of the same or higher priority to run Option 3 looks plausible but there is no guarantee that the thread that grabs the cpu time will be of a higher priority. It will depend on the threading algorithm of the Java Virtual Machine and the underlying operating system -------------------------------------------------------------------------------- Answer 25) Objective 6.2) 4) Compilation and running with output 0 to 9 -------------------------------------------------------------------------------- Answer 26) Objective 2.1) 1) None of these optionsBecause of the lack of a break statement after the break 10; statement the actual output will be "ten" followed by "twenty" -------------------------------------------------------------------------------- Answer 27) Objective 3.1) 4) System.gc(); -------------------------------------------------------------------------------- Answer 28) Objective 4.4) 1) Compilation succeeds and at run time an output of 0 and falseThe default value for a boolean declared at class level is false, and integer is 0; -------------------------------------------------------------------------------- Answer 29) Objective 1.2) 1) Compile time error You will get an error saying something like "Cant make a static reference to a non static variable". Note that the main method is static. Even if main was not static the array argv is local to the main method and would thus not be visible within amethod. -------------------------------------------------------------------------------- Answer 30) Objective 5.2) 3) Output of "Not equal" Despite the actual character strings matching, using the == operator will simply compare memory location. Because the one string was created with the new operator it will be in a different location in memory to the other string. -------------------------------------------------------------------------------- Answer 31) Objective 2.3) 4) Compile and run with output of "Pausing" and "Continuing" after a key is hit An overriden method in a sub class must not throw Exceptions not thrown in the base class. In the case of the method amethod it throws no exceptions and will thus compile without complain. There is no reason that a constructor cannot be protected. -------------------------------------------------------------------------------- Answer 32) Objective 6.3) 4) Compile time error because of the line creating the instance of Inner This looks like a question about inner classes but it is also a reference to the fact that the main method is static and thus you cannot directly access a non static method. The line causing the error could be fixed by changing it to say Inner i = new Outer().new Inner(); Then the code would compile and run producing the output "Inner" -------------------------------------------------------------------------------- Answer 33) Objective 4.6) 1) Error at compile time If you implement an interface you must create bodies for all methods in that interface. This code will produce an error saying that MyWc must be declared abstract because it does not define all of the methods in WindowListener. Option 4 is nonsense as comments can appear anywhere. Option 3 suggesting that it might compile but not produce output is ment to mislead on the basis that what looks like a constructor is actually an ordinary method as it has a return type. -------------------------------------------------------------------------------- Answer 34) Objective 1.2) 4) Compile time error An error will be caused by attempting to define an integer as static within a method. The lifetime of a field within a method is the duration of the running of the method. A static field exists once only for the class. An approach like this does work with Visual Basic. -------------------------------------------------------------------------------- Answer 35) Objective 9.5) 4)int z = 015; The letters c and s do not exist as literal indicators and a String must be enclosed with double quotes, not single as in this case. -------------------------------------------------------------------------------- Answer 36) Objective 4.3) 1)double4)instanceofNote the upper case S on switch means it is not a keyword and the word then is part of Visual Basic but not Java. Also, instanceof looks like a method but is actually a keyword, -------------------------------------------------------------------------------- Answer 37) Objective 9.2) 4) -3.0 -------------------------------------------------------------------------------- Answer 38) Objective 4.2) 3) one Command line parameters start from 0 and fromt he first parameter after the name of the compile (normally Java) -------------------------------------------------------------------------------- Answer 39) Objective 10.1) 4) The set is designed for unique elements. Collection is an interface, not a class. The Collection interface includes a method called iterator. This returns an instance of the Iterator class which has some similarities with Enumerators.The name set should give away the purpose of the Set interface as it is analogous to the Set concept in relational databases which implies uniquness. -------------------------------------------------------------------------------- Answer 40) Objective 8.1) 2) If multiple listeners are added to a component the events will be processed for all but with no guarantee in the order4) You may remove as well add listeners to a component. It ought to be fairly intuitive that a component ought to be able to have multiple listeners. After all, a text field might want to respond to both the mouse and keyboard -------------------------------------------------------------------------------- Answer 41) Objective 5.1) 1) b=m;3) d =i; You can assign up the inheritance tree from a child to a parent but not the other way without an explicit casting. A boolean can only ever be assigned a boolean value. -------------------------------------------------------------------------------- Answer 42) Objective 7.3) 2) You can obtain a mutually exclusive lock on any object3) A thread can obtain a mutually exclusive lock on a synchronized method of an object4) Thread scheduling algorithms are platform dependent Yes that says dependent and not independent. -------------------------------------------------------------------------------- Answer 43) Objective 6.1) 2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than Class type This question is about the requirement to understand the difference between the "is-a" and the "has-a" relationship. Where a class is inherited you have to ask if it represents the "is-a" relationship. As the difference between the root and the two children are the operating system you need to ask are Linux and Windows types of computers.The answer is no, they are both types of Operating Systems. So option two represents the best of the options. You might consider having operating system as an interface instead but that is another story. Of course there are as many ways to design an object hierarchy as ways to pronounce Bjarne Strousjoup, but this is the sort of answer that Sun will proabably be looking for in the exam. Questions have been asked in discussion forums if this type of question really comes up in the exam. I think this is because some other mock exams do not contain any questions like this. I assure you that this type of question can come up in the exam. These types of question are testing your understanding of the difference between the is-a and has-a relationship in class design. -------------------------------------------------------------------------------- Answer 44) Objective 4.1) 1) An inner class may be defined as static4) An inner class may extend another class A static inner class is also sometimes known as a top level nested class. There is some debate if such a class should be called an inner class. I tend to think it should be on the basis that it is created inside the opening braces of another class. How could an anonymous class have a constructor?. Remember a constructor is a method with no return type and the same name as the class. Inner classes may be defined as private -------------------------------------------------------------------------------- Answer 45) Objective 5.3) 4) Compilation and output of "Not equal! 10" The output will be "Not equal 10". This illustrates that the Output +=10 calculation was never performed because processing stopped after the first operand was evaluated to be false. If you change the value of b1 to true processing occurs as you would expect and the output is "We are equal 20";. -------------------------------------------------------------------------------- Answer 46) Objective 5.1)2)j= i< -------------------------------------------------------------------------------- Answer 47) Objective 5.3) 4) 12 As well as the binary OR objective this questions requires you to understand the octal notaction which means that the leading letter zero (not the letter O)) means that the first 1 indicates the number contains one eight and nothing else. Thus this calculation in decimal mean8|4 To convert this to binary means1000 0100 ---- 1100 ---- Which is 12 in decimal The | bitwise operator means that for each position where there is a 1, results in a 1 in the same position in the answer. -------------------------------------------------------------------------------- Answer 48) Objective 5.1) 2)s+=i; Only a String acts as if the + operator were overloaded -------------------------------------------------------------------------------- Answer 49) Objective 10.1) Although the objectives do not specifically mention the need to understand the I/O Classes, feedback from people who have taken the exam indicate that you will get questions on this topic. As you will probably need to know this in the real world of Java programming, get familiar with the basics. I have assigned these questions to Objective 10.1 as that is a fairly vague objective. 1) File f = new File("/","autoexec.bat");2) DataInputStream d = new DataInputStream(System.in);3) OutputStreamWriter o = new OutputStreamWriter(System.out); Option 4, with the RandomAccess file will not compile because the constructor must also be passed a mode parameter which must be either "r" or "rw" -------------------------------------------------------------------------------- Answer 50) Objective 5.1)1)o1=o2; 2)b=ob; 4)o1=b; -------------------------------------------------------------------------------- Answer 51) Objective 5.4) 4) 10,0,20 In the call another(v,i); A reference to v is passed and thus any changes will be intact after this call. -------------------------------------------------------------------------------- Answer 52) Objective 6.2) 1) public void amethod(String s, int i){}4) public void Amethod(int i, String s) {} Overloaded methods are differentiated only on the number, type and order of parameters, not on the return type of the method or the names of the parameters. -------------------------------------------------------------------------------- Answer 53) Objective 6.2) 4)Base b = new Base(10); Any call to this or super must be the first line in a constructor. As the method already has a call to this, no more can be inserted. -------------------------------------------------------------------------------- Answer 54) Objective 4.1) 1)System.out.println(s); 4) System.out.println(iArgs); A class within a method can only see final variables of the enclosing method. However it the normal visibility rules apply for variables outside the enclosing method. -------------------------------------------------------------------------------- Answer 55) Objective 7.2) 1) yield()2) sleep4) stop() Note, the methods stop and suspend have been deprecated with the Java2 release, and you may get questions on the exam that expect you to know this. Check out the Java2 Docs for an explanation -------------------------------------------------------------------------------- Answer 56) Objective 10.1) 1) addElement -------------------------------------------------------------------------------- Answer 57) Objective 4.1) The import statement allows you to use a class directly instead of fully qualifying it with the full package name, adding more classess with the import statement does not cause a runtime performance overhad. I assure you this is true. An inner class can be defined with the private modifier. 3) An inner class can be defined with the protected modifier4) An interface cannot be instantiated -------------------------------------------------------------------------------- Answer 58) Objective 4.6) 1) mousePressed(MouseEvent e){}4) componentAdded(ContainerEvent e){} -------------------------------------------------------------------------------- Answer 59) Objective 10.1) 1) iterator2) isEmpty3) toArray -------------------------------------------------------------------------------- Answer 60) Objective 7.3) 2) 2) Ensures only one thread at a time may access a method or object -------------------------------------------------------------------------------- End of documentMarcus Green copyright 2000 <

小小豆叮

J2ME 循序渐进教程(IBM DW)

J2ME 循序渐进 Shari Jones 本教程详细审查了袖珍版 Java 2 平台 (J2ME),它主要面向在 Java 编程及面向对象设计与开发方面有深厚背景的中级开发者。 您可以首先了解 J2ME 的背景并研究 J2ME 的配置和简表。随后,逐步建立您的开发环境,用于开发 J2ME 应用程序。 本教程将向您介绍一些课题如 K 虚拟机 (KVM),和 KJava API -- 用于关联连接有限设备配置 (CLDC) 和使用 CLDC 的移动信息设备简表。之后您将构造一个简单的应用程序来看看您能用 J2ME 做些什么。您将使用 CLDC 和 KJava 开发一个基本绘图应用程序以及一个小型 MIDP 应用程序。 预备知识 要学习此教程最好具备较好的 Java 编程的背景知识,以及面向对象的设计与开发的概念。 系统需求 首先,需要支持 JavaScript 的浏览器。如果想运行教程中的例子,您还需以下环境: Java 2 SDK---推荐使用J2SE 1.3 SDK。您会用到Java 2 SDK 中的以下工具 : java javac jar javadoc (可选) The Connected Limited Device Configuration (CLDC) 参考实现 K 虚拟机 (KVM),已经被包含在 CLDC 参考实现中 Mobile Information Device Profile (MIDP) Palm OS Emulator (POSE),您可用它对您的 KJava 应用在发布到真正的 Palm OS 设备之前进行测试 Palm 手持设备 进入教程 <

小小豆叮

会话(Session)数据到底是什么?

通常,Web 环境中的会话是指用户/客户机的 Web 浏览器和一个特定的 Web 服务器之间的一组交互。会话从最初浏览器调用 Web 服务器的 URL 开始,到 Web 服务器结束会话,这个会话“超时”,或当用户关闭浏览器时结束。会话数据是指在永久保存之前用户提供的在多个页面上使用的信息。会话数据和事务数据(Transaction data)之间的区别在于,会话数据是暂时的 - 只用于一组相连接的页面 - 而事务数据是用于永久的存储。会话数据通常在一组 Web 页面之后被转换成事务数据(当用户选择“提交”事务,或为购物车“付帐”时)。 考虑下面的情节:我们的用户 Rob 输入了他最喜欢的(假定的)酒类购物站点的 URL,www. winesRus.com。Rob 浏览页面寻找要买的酒,并在购物车里添加了一些。与站点的所有交互发生在一个由 www.winesRus.com Web 服务器控制的单一会话中。当 Rob 逐屏浏览,购买更多酒时,他要购买的物品的信息、他的地址,还有 Rob 提供的其它任何信息都被保存为会话数据。站点给他要购买的物品定价,并请求他确认。当 Rob 确认时,会话数据被用来执行购买事务,然后数据变成永久性的。 Servlet 与特定的 HTTP URL 一一对应,这很象传统的 Web 编程中每个 URL 要有自己的 CGI 脚本一样。例如,http://winesRus/servlet/purchaseWinesServlet 脚本对应于 http://winesRus.com/servlet/purchaseWinesServlet。 就象 CGI 脚本一样,servlet 自己是无状态的。和 CGI 脚本相似,servlet 也从 HTTP 参数和 HTML 表单获得客户机数据。在一个特定的应用服务器上,每个 servlet 类的一个单独实例为它的特定 URL 处理所有的 doGet() 和 doPost() 请求。每一个 HTTP 请求都在一个运行该实例的 service() 方法的唯一线程上处理。因为每个 servlet 实例都是共享资源,您不能在 servlet 本身存储客户机会话数据(比如顾客的购物车)。会话数据必须存储在 servlet 之外。 <

小小豆叮

关闭和释放 JDBC 资源

适用读者:开发人员 产品:WebSphere Application Server 版本:版本 3.0.2.x、3.5.x 和 4.0 平台:所有平台 关键字:HttpSession、Servlet、JSP 摘要 为了确保 JDBC 资源不在出现异常或错误等情况下被不正常关闭,我们应该在使用完 JDBC 资源之后关闭且释放它们。JDBC 连接池提供了 JDBC 连接定义和数目有限的连接,如果数量不够,就需要长时间的等待。不正常关闭 JDBC 连接会导致等待回收无效的 JDBC 连接。只有正常的关闭和释放 JDBC 连接,JDBC 资源才可以被快速的重用使性能得到改善。 建议 失败的关闭和释放 JDBC 连接可能导致其它用户的连接经历长时间的等待。虽然超时的JDBC 连接会被 WebSphere Application Server 退回而被回收 ,但必须等待这种情形发生。 使用完 JDBC 资源后关闭它们,还可以显式关闭 JDBC ResultSets。如果没有显式关闭语句,则在完成了相关语句之后会释放 ResultsSets。 所以请确保您构建的代码在所有情况下,甚至在异常和错误条件下,都能关闭和释放 JDBC 资源。以下代码显示了 JDBC 资源的获得和使用都封装在“Try-Catch-Finally”结构中。其中,在 finally 子句中处理 JDBC 资源的关闭,使所有情况下关闭都将发生。 关闭 JDBC Connection 和 PreparedStatement 的正确方式 Connection conn = null; ResultSet rs = null; PreparedStatement pss = null; try { conn = dataSource.getConnection(USERID,PASSWORD); pss = conn.prepareStatement("SELECT SAVESERIALZEDDATA FROM SESSION.PINGSESSION3DATA WHERE SESSIONKEY = ?"); pss.setString(1,sessionKey); rs = pss.executeQuery(); pss.close(); conn.close(); } catch (Throwable t) { // Insert Appropriate Error Handling Here } finally { // The finally clause is always executed - even in error // conditions PreparedStatements and Connections will always be closed try { if (pss != null) pss.close(); } catch(Exception e) {} try { if (conn != null) conn.close(); } catch (Exception e){} } } 替代方法 以下代码显示了关闭 JDBC 资源的错误方法。它们将在异常情况中失去正常关闭方式。这里如果抛出异常,应用程序将无法关闭 JDBC 连接。 Connection conn = null; ResultSet rs = null; PreparedStatement pss = null; try { conn = dataSource.getConnection(USERID,PASSWORD); pss = conn.prepareStatement("SELECT SAVESERIALZEDDATA FROM SESSION.PINGSESSION3DATA WHERE SESSIONKEY = ?"); pss.setString(1,sessionKey); rs = pss.executeQuery(); pss.close(); conn.close(); } catch (Throwable t) { // If i reach this spot, I blew a JDBC Connection. } 参考资料 WebSphere Application Server Development Best Practices for Performance and Scalability 作者 Harvey W. Gunther 是位于美国北卡罗来纳州 Raleigh 的 IBM WebSphere 产品开发小组中的一名高级性能分析师。可以通过 hgunther@us.ibm.com 与 Harvey Gunther 联系。 <

小小豆叮

客户机如何存储会话数据?

对于在客户机而不是服务器上存储会话数据,有两种主要的解决方案 - cookie 和隐藏域(hidden field)- 每一种方案都有各自的优势和劣势。 隐藏域 出现的第一种保留会话数据的机制之一是使用“隐藏域”。这种选择依赖于 HTML 的一个特殊功能来保存会话信息。HTML INPUT 标记有几种不同的类型,可以让 Web 作者指定如何接收输入。例如,“TEXT”类型会导致浏览器显示一个文本域。然而,有一种输入类型不符合任何特定的 UI 部件:“HIDDEN” 类型。隐藏域没有 UI 表现形式,所以不能被浏览器用户改变。隐藏域的值可以在 Web 页面上由应用服务器设置,以后再通过 HTTPServletRequest 接口的 getParameter() 方法读取回来,就好像其它所有 HTML 域一样。这正是我们在客户机 HTML 中记录会话信息所需要的。使用隐藏域存储会话数据的一个主要缺点是,我们必须改写 HTML 使其包括这些新的信息。下面的 Java 代码指出要做下面的工作: out.print("input type=\"HIDDEN\"); out.print("NAME=\"FieldName\" value=\""); out.print(fieldValue); out.println("\"\>"); 隐藏域使用很简单,正因如此,它们也存在一些问题以至于对很多系统来说不适用。第一个问题是,JSDK 没有提供一种将任意对象移出和移入隐藏域的方法。在 JSDK 中,处理隐藏域的方法和处理其它 HTTP 参数的方法是一样的,也就是说隐藏域是作为字符串来处理的。如果您想在自己的程序中使用这些字符串里面的信息,就必须建立一个架构用来生成合适的 HTML 和重新解析信息。 另一个缺点是,您的会话信息最终会在网络上发送很多次。为了理解这是怎样发生的,考虑下面的情况: 我们的酒类购物站点有一个两页的“频繁顾客程序”。第一页接收用户信息(姓名、地址等),而第二页接收选择信息(您更喜欢加州酒还是法国酒?您喜欢夏敦埃酒还是墨尔乐红葡萄酒?诸如此类等等)。第一个 servlet 从前一个 HTML 表单中解析出用户信息,并将其记录在隐藏域中。第二个 servlet 不仅必须解析出新的 HTML 表单信息,还要解析出前一个 servlet 重新写入隐藏域的信息。这样,每一个后续的页面不断地增加要解析的信息,当您进一步继续处理时就会使下载时间变长。 使用隐藏域的一个最大的缺点存在于混合型的站点中。新的 servlet 实现必须与旧的 CGI 和 HTML 共存很多次。如果您不能修改这些页面,当用户在 servlet 和旧的页面之间遍历时,隐藏数据就会丢失。 假定我们的酒类购物站点一直是用 CGI 程序实现的。并且假定旧的购物车是作为 www.winesRus.com/cgi-bin/shoppingcart 来实现的。站点中目前所有的 HTML 页面都指向这个 URL。我们可以改变所有的页面让它们指向 www.winesRus.com/servlets/shoppingcart,或者我们可以简单地用旧的链接给 servlet 起一个别名。如果您有数百个目录页指向这个链接,这个别名可以省掉您很多时间。然而,如果您是用隐藏域遍历站点,这种解决方法就不起作用。隐藏域必须添加到旧的 HTML 中,而且您可能还要改变这些链接。 使用隐藏域还有其它的缺点(请参阅下面章节有关安全性的讨论),但是对于某些情况,他们还是不错的。在安全性不高的某些站点中可以考虑它们,那里旧页面浏览最少,而且页面不是大量地“建立”在彼此之上,还有在不能接受服务器亲缘关系的地方也可以考虑它们。在为隐藏域的生成而建立框架和解析这两个步骤上付出的一些简单的努力以后可能会带来很多好处。然而,正如我们所见到的,对于大多数情况,都会有更好的解决方案。 Cookie 我们要研究的下一个存储会话数据的方法是直接在 cookie 中存储数据。正如我们在 HTTPSessions 的讨论中已经看到的,cookie 也可以用于在客户机浏览器上存储信息。它们不仅可以用于存储客户机身份标识,还可以存储实际的会话数据本身。cookie 有巨大的优势。 首先,cookie 不需要 HTML 重写。您将会话数据转换成如隐藏域示例所示的字符串,然后将其添加到您的 HttpServletResponse 对象中,如下所示: package com.winesrus.tests; import javax.servlet.http.*; public class CookieTest { public CookieTest(HttpServletResponse resp, String state) { String warning = Please accept this Cookie or bad things will happen to you!" Cookie cookie = new Cookie("winecookie", state); cookie.setDomain(".winesrus.com"); cookie.setPath("/"); cookie.setComment(warning); cookie.setVersion(0); resp.addCookie(cookie); } } 您可以用以下语句检索 cookie: javax.servlet.http.HttpServletRequest.getCookies(); 就是这样。您没有必要重写 HTML 页面来获取和设置 cookie 数据。 关于 cookie 的另一个优点就是,您可以和非 Java 资源共享您的会话数据。您的 JavaScript 和 CGI 程序可以利用这种状态信息,因为它是通过每一个客户机请求发送的。 然而,容量限制可能是使用 cookie 存储会话数据的致命弱点。一个 cookie 头最多可以存储 4K 的文本。这就让存储大的数据集合很不实际。您还需要注意您决定在 cookie 中存储的内容。这个 cookie 头包括了您 Web 站点中的所有 cookie。如果超过了最大的 cookie 容量,就会出现不好的后果。例如,依照用户浏览器的不同,不是旧 cookie 会丢失就是新 cookie 不能写入。要避免这种情况,要确保您的 cookie 不接近 4K 的限制。您要给自己足够的空间,来应付用户在自己的浏览器中已经有别的来自您的域的 cookie 的情况。这样就必须编写代码检查 cookie 是否被成功写入。您当然不能盲目地将对象序列化后将它们放到 cookie 中去。您必须非常有选择性的组织例程。 另一个主要的缺点是用户可以随意关掉 cookie。现在大多数浏览器都支持 cookie。然而,有少数 Web 站点用户希望在自己的浏览器中禁用 cookie。这就强迫您要在 HTML 页面中编写 JavaScript 或在 servlet 中编码以检测用户浏览器中的 cookie 是否被打开。所以,如果您使用 cookie 作为会话数据存储机制,您就必须有另一种机制作为“退路”,或者通报您的用户该站点没有 cookie 无法正常运行。 cookie 还有另一个缺点,就是关于它们怎样在 Web 中传送是有限制的。它们不能传送给同级域名。 这么说吧,WinesRus 买了一个新的域名:BeerIsUs.com。我们希望用户能够使用同样的购物车付帐(www.winesRus.com/servlets/shoppingcart)。问题在于,使用 cookie 的话,我们站点的 WinesRus.com 部分无法看到 BeerIsUs.com 创建的 cookie,反过来也一样。注意,如果我们有一个名为 Commerce.WinesRus.com 的特定的商业服务器,它就能够看到在 WinesRus.com 创建的 cookie,但是 WinesRus.com 看不到 Commerce.WinesRus.com 创建的 cookie。 在单独域名上可以存在的 cookie 数目是有限制的。某些域名限制是与浏览器有关的,所以您必须用多个浏览器来作全面的测试以确保 cookie 按照设计运行。使用 cookie 会使域名问题非常复杂。 cookie 和隐藏域都有另一个主要的缺点:安全性。 在客户机上存储的状态信息是不安全的。除非您花时间将数据加密,您在因特网上来回发送的数据都是明文。即使您手工或使用 SSL 将数据加密,您仍然不会愿意在客户机上存储敏感的商业数据。 所以,使用客户机保存会话的不利情况可能会使会话数据存储机制的优势黯然失色。客户机端解决方案最初看起来可能很简单,但复杂性很快就会成倍增长。相反,我们需要寻找那些最初比较复杂但会带来更好的整体效果的解决方案。 <

小小豆叮