804 pretest 解题
Answers with Explanations   
1. c)    
s1 and s2 not equal    
s1 and s3 equal    
JVM sets a constant pool in which it stores all the string constants used in the type. If two references are     
declared with a constant, then both refer to the same constant object. The == operator checks the similarity of     
objects itself (and not the values in it). Here, the first comparison is between two distinct objects, so we get s1     
and s2 not equal. On the other hand, since references of s1and s3refer to the same object, we get s1 and     
s3 equal.    
2. c) [0, 0]    
The assignment x = x;inside the construct reassigns the passed parameter; it does notassign the member     
xin Point2D. The correct way to perform the assignment is this.x = x;. Field yis not assigned, so its value     
remains 0.    
3. d) When executed, this program prints    
k == j is true    
k.equals(j) is true    
The Integerobjects are immutable objects. If there is an Integerobject for a value that already exists, then     
it does not create a new object again. In other words, Java uses sharing of immutable Integerobjects, so two     
Integerobjects are equal if their values are equal (no matter if you use == operators to compare the references or     
use equals()method to compare the contents).    
4. a) arr1 == arr2 is false    
arr1.equals(arr2) is false    
Arrays.equals(arr1, arr2) is true    
The first comparison between two array objects is carried out using the == operator, which compares object     
similarity so it returns false here. The equals()method, which compares this array object with the passed array     
object, does not compare values of the array since it is inherited from the Objectclass. Thus we get another false.     
On the other hand, the Arraysclass implements various equals()methods to compare two array objects of     
different types; hence we get true from the last invocation.    
5. d) When executed, this program will print the following: str is not Object.    
The variable strwas declared but not instantiated; hence the instanceof operator returns false.    
6. b) Side Object Tail Side    
Overloading is based on the static type of the objects (while overriding and runtime resolution resolves to the     
dynamic type of the objects). Here is how the calls to the overload()method are resolved:     
•     overload(firstAttempt);--> firstAttemptis of type Side, hence it resolves to     
overload(Side).    
•     overload((Object)firstAttempt);-> firstAttemptis casted to Object, hence it resolves to     
overload(Object).
•     overload(secondAttempt);-> secondAttemptis of type Tail, hence it resolves to    
overload(Tail).    
•     overload((Side)secondAttempt);-> secondAttemptis casted to Side, hence it resolves to     
overload(Side).    
7.  c) foo(long)    
For an integer literal, the JVM matches in the following order: int, long, Integer, int.... In other words, it     
first looks for an inttype parameter; if it is not provided, then it looks for longtype; and so on. Here, since the int     
type parameter is not specified with any overloaded method, it matches with foo(long).    
8.  b)    
In Base.foo()    
In Derived.bar()    
A static method is resolved statically. Inside the static method, a virtual method is invoked, which is resolved     
dynamically.    
9.  d) When executed, the program prints “walk cannot fly”.    
In order to override a method, it is not necessary for the overridden method to specify an exception. However, if     
the exception is specified, then the specified exception must be the same or a subclass of the specified exception     
in the method defined in the super class (or interface).    
10.  b) club none none none    
Here is the description of matches for the four enumeration values:     
“club” matches with the case “Club”. •    
For “Spade”, the case “spade” does not match because of the case difference (switch case  •    
match is case sensitive).    
does not match with “diamond” because case statements should exactly match and there are  •    
extra whitespaces in the original string.    
“hearts” does not match the string “heart”. •    
11.  a) new Outer.Inner().text    
The correct way to access fields of the static inner class is to use the inner class instance along with the outer     
class, so new Outer.Inner().textwill do the job.    
12.  a) for(Cards card : Cards.values())    
System.out.print(card + " ");    
The values()method of an enumeration returns the array of enumeration members.    
13.  d) class CI12 extends C implements I1, I2 {}    
A class inherits another class using the extendskeyword and inherits interfaces using the implementskeyword.    
14.  d) interface II extends I1, I2 {}    
It is possible for an interface to extend one or more interfaces. In that case, we need to use the extendskeyword     
and separate the list of super-interfaces using commas
15.  c) The program will not compile and will result in a compiler error “ambiguous reference to name” in LINE A.   
Since nameis defined in both the base interface and the abstractclass, any reference to the member nameis     
ambiguous. The first reference to nameis in the line marked with comment LINE A, so the error is flagged in this     
line by the compiler.    
16.  c) has-a    
Composition is a design concept that refers to the has-a relationship.     
17.  c) When executed, the program prints the following: Brazil China India Russia.    
When nullis passed as a second argument to the Arrays.sort()method, it means that the default Comparable    
(i.e., natural ordering for the elements) should be used. The default Comparatorresults in sorting the elements     
in ascending order. The program does not result in a NullPointerExceptionor any other exceptions or a     
compiler error.    
18.  b) When executed, this program prints the following: “The removed element is: 1”.    
The remove()method is equivalent to the removeFirst()method, which removes the first element (head of the     
queue) of the Dequeobject.     
19.  d) When executed, the program prints the following: 1 2.0 3.0.    
The List is a generic type that is used here in raw form; hence it allows us to put different types of values in list2.     
Therefore, it prints the following: 1 2.0 3.0.    
20.  e) When executed, this program will print    
SimpleCounter<Double> counter is 2    
SimpleCounter<Integer> counter is 2    
SimpleCounter counter is 2    
Countis a static variable, so it belongs to the classand not to an instance. Each time constructor is invoked,     
countis incremented. Since two instances are created, the count value is two.    
21.  f ) The program throws an exception for java.util.UnknownFormatConversionException: Conversion = 'l'    
There is no format specifier for long int, and the same %dformat specifier for int is used for long as well. So, the     
format specifier %ldresults in a runtime exception UnknownFormatConversionException.    
22.  b)     
Using String.split method: 10 01 2012    
Using regex pattern: 10 01 2012    
Using str.split(regex)is equivalent to using Pattern.compile(regex).split(str).    
23.  d) false true false true    
Here are the following regular expression matches for the character x:    
•     x*means matches with xfor zero or more times.    
•     x+means matches with xfor one or more times.    
•     x{n}means match xexactly ntimes.
The pattern a*b+c{3}means match azero or more times, followed by bone or more times, and cexactly    
three times.    
So, here is the match for elements in the stringsarray:    
For  •     "abc", the match fails, resulting in false.    
For  •     "abbccc", the match succeeds, resulting in true.    
For  •     "aabbcc", the match fails, resulting in false.    
For  •     "aaabbbccc", the match succeeds, resulting in true.    
24.  d) Severity 1 does not match.    
severity3 does not match.    
severity five does not match.    
Here is the meaning of the patterns used:     
[^xyz]   Any character except x, y, or z (i.e., negation)    
\s   A whitespace character    
[a-z]   from a to z    
So the pattern "^severity[\\s+][1–5]"matches the string “severity” followed by whitespace followed by one     
of the letters 1 to 5.    
For this pattern,    
“Severity 1” does not match because of the capital S in “Severity”. •    
“severity 2” matches. •    
“severity3” does not match since there is no whitespace between severity and 3. •    
“severity five” does not match since “five” does not match a numeral from 1 to 5. •    
25.  a) The program prints the following: InvalidKeyException.    
It is not necessary to provide an Exceptionthrown by a method when the method is overriding a method defined     
with an exception (using the throws clause). Hence, the given program will compile successfully and it will print     
InvalidKeyException.    
26.  e) The program prints the following: in catch -> in finally ->.    
The statement println("after throw -> ");will never be executed since the line marked with the comment     
LINE Athrows an exception. The catch handles ArithmeticException, so println("in catch -> ");will be     
executed. Following that, there is a return statement, so the function returns. But before the function returns, the     
finallystatement should be called, hence the statement println("in finally -> ");will get executed. So,     
the statement println("after everything");will never get executed.    
27.  f ) Does not print any output on the console    
By default, assertions are disabled. If -ea(or the -enableassertionsoption to enable assertions), then     
the program would have printed “Error” since the exception thrown in the case of assertion failure is     
java.lang.AssertionError, which is derived from the Errorclass.
28.   d) This program will create file1.txt and file3.txt directories in the root directory, and a file2.txt directory in the    
“subdir” directory in the root directory.    
The mkdirs()method creates a directory for the given name. Since the file names have / in them, the method     
creates directories in the root directory (or root path for the Windows drive based on the path in which you     
execute this program).    
29.   b) When serializing an object that has references to other objects, the serialization mechanism also includes the     
referenced objects as part of the serialized bytes.    
and    
c) When an object is serialized, the class members that are declared as transient will not be serialized (and hence    
their values are lost after deserialization).    
Option b) and c) are true regarding object serialization.    
Option a) is wrong because the Serializableinterface is a marker interface; in other words, the Serializable     
interface is an empty interface and it does not declare any methods in it.    
Option d) is wrong because the Externalizableinterface declares two methods, writeExternal()and     
readExternal().    
Option e) is wrong because there is no such exception as NotExternalizableException.    
30.  b) Body first head hello program world    
TreeSet<String>orders the strings in default alphabetical ascending order and removes duplicates. The     
delimiter \W is non-word, so the characters such as < act as separators.    
31.  b) beginIndex = 0 and endIndex = 1    
In the Pathclass’s method subpath(int beginIndex, int endIndex), beginIndexis the index of the first     
element (inclusive of that element) and endIndexis the index of the last element (exclusive of that element). Note     
that the name that is closest to the root in the directory hierarchy has index 0. Here, the string element "Program     
Files"is the closest to the root C:\, so the value of beginIndexis 0 and endIndexis 1.    
32.  d) Prints the following: Copy.class Copy.java Hello.class OddEven.class PhotoCopy.java.    
In the Glob pattern “*o*?{java,class,html}”, the character * matches any number of characters, so *o* matches     
any string that has “o” in it. The ? matches exactly one character. The pattern {java,class} matches files with the     
suffixes of “java” or “class”. Hence, from the given files, the matching file names are Copy.class, Copy.java,     
Hello.class, OddEven.class, PhotoCopy.java.    
33.  b) WatchService watcher = FileSystems.getDefault().newWatchService();    
The getDefault()method in FileSystemsreturns the reference to the underlying FileSystemobject. The     
method newWatchService()returns a new watch service that may be used to watch registered objects for     
changes and events in files or directories.    
34.  The correct options are    
c) You can get an instance of PreparedStatementby calling the preparedStatement()method in the Connection     
interface.    
e) The interface Statementand its derived interfaces implement the AutoCloseableinterface, hence they can be     
used with a try-with-resources statement.
Option c) and e) are correct statements. The other three are incorrect for the following reasons:   
Option a) Objects of type Statement can handle IN, OUT, and INOUT parameters; you need to  •    
use objects of CallableStatement type for that.    
Option b)  •     PreparedStatementis used for pre-compiled SQL statements; the     
CallableStatementtype is used for stored procedures.    
Option d)  •     CallableStatementimplements the PreparedStatementinterface; PreparedStatement     
in turn implements the Statementinterface. These three types are not classes.    
35.  e) The program will result in throwing a SQLExceptionbecause auto-commit is true.     
If you call methods such as commit()or rollback()when the auto-commit mode is set to true, the program will     
a SQLException.    
36.  b) RowSetFactory rowSetFactory = RowSetProvider.newFactory();    
JdbcRowSet rowSet = rowSetFactory.createJdbcRowSet();    
37.  b) When executed, the program prints "Worker"and then the program hangs (i.e., does not terminate).    
The statement Thread.currentThread()in the main()method refers to the “Master” thread. Calling the join()    
method on itself means that the thread waits itself to complete, which would never happen, so this program     
hangs (and does not terminate).    
38.  Options a) and d) are true:    
a) Takes milliseconds as the argument for time to sleep.    
d) Can throw the InterruptedExceptionif it is interrupted by another thread when it sleeps.    
In option b), the sleep()method takes milliseconds as an argument, not microseconds.    
In option), the sleep()method does not relinquish the lock when it goes to sleep; it holds the lock.    
39.  c) The program prints    
Starting to wait    
Caught Exception    
In this program, the wait()method is called without acquiring a lock; hence it will result in throwing an     
IllegalMonitorStateException, which will be caught in the catch block for the Exception.    
40.  a) The program prints    
[10, 5, 10, 20]    
[20, 5, 10]    
[5, 10, 20]    
[5, 10, 20]    
Here is the description of the containers that explain the output:    
•     Listis unsorted.    
•     HashSetis unsorted and retains unique elements.    
•     TreeSetis sorted and retains unique elements.    
•     ConcurrentSkipListSetis sorted and retains unique elements.
41.  c) The program does not compile and results in a compiler error in the line marked with comment LINE A.   
The class CopyOnWriteArrayListdoes not inherit from ArrayList, so an attempt to assign a     
CopyOnWriteArrayListto an ArrayListreference will result in a compiler error (the ArrayListsuffix in the class     
named CopyOnWriteArrayListcould be misleading as these two classes do not share an is-a relationship).    
42.  c) Prints    
E Gamma    
R Johnson    
R Helm    
J Vlissides    
and then the program terminates.    
The producerclass puts an author on the list and then sleeps for some time. In the meantime, the other thread     
(consumer) keeps checking whether the list is non-empty or not. If it is non-empty, the consumer thread removes     
the item and prints it. Hence, all four author names get printed.    
43.  b)    
from=von    
subject=betreff    
In the resource bundle property files, the key values are separated using the = symbol, with each line in the     
resource file separated by a newline character.    
44.  c) ResourceBundle_en.properties    
Java looks for candidate locales for a base bundle named ResourceBundleand locale French (Canada), and     
checks for the presence of the following property files:    
ResourceBundle_fr_CA.properties    
ResourceBundle_fr.properties    
Since both of them are not there, Java searches for candidate locales for the base bundle named     
ResourceBundleand a default locale (English - United States):    
ResourceBundle_en_US.properties    
ResourceBundle_en.properties    
Java finds that there is a matching resource bundle, ResourceBundle_en.properties. Hence it loads this     
resource bundle.    
45.  a) System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));    
In the format hh:mm:ss, his for the hour in am/pm (with values in 1–12 range), mis for minutes, and sis     
for seconds. The class for creating and using custom date or time pattern strings is SimpleDateFormat. The     
expression new Date()creates a Dateobject with the current date and time value.
804 pretest 解题的更多相关文章
- 【LeetCode】804. Unique Morse Code Words 解题报告(Python)
		作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述: 题目大意 解题方法 set + map set + 字典 日期 题目地 ... 
- LeetCode 804 Unique Morse Code Words 解题报告
		题目要求 International Morse Code defines a standard encoding where each letter is mapped to a series of ... 
- MYSQL——解题查询语句答题思路,再难的查询都不怕!
		select查询语句,作为测试人员,使用此语句是家常便饭,是必须掌握的部分,由开始学习mysql到网上搜索试题做,开始做题一塌糊涂,拿到题目就晕,无从下手,现在慢慢总结了一套自己做题的方式,很开森,嘿 ... 
- 用C++实现的数独解题程序 SudokuSolver 2.1 及实例分析
		SudokuSolver 2.1 程序实现 在 2.0 版的基础上,2.1 版在输出信息上做了一些改进,并增加了 runtil <steps> 命令,方便做实例分析. CQuizDeale ... 
- SCNU ACM 2016新生赛决赛 解题报告
		新生初赛题目.解题思路.参考代码一览 A. 拒绝虐狗 Problem Description CZJ 去排队打饭的时候看到前面有几对情侣秀恩爱,作为单身狗的 CZJ 表示很难受. 现在给出一个字符串代 ... 
- SCNU ACM 2016新生赛初赛 解题报告
		新生初赛题目.解题思路.参考代码一览 1001. 无聊的日常 Problem Description 两位小朋友小A和小B无聊时玩了个游戏,在限定时间内说出一排数字,那边说出的数大就赢,你的工作是帮他 ... 
- HDU 3791二叉搜索树解题(解题报告)
		1.题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=3791 2.参考解题 http://blog.csdn.net/u013447865/articl ... 
- 【BZOJ1700】[Usaco2007 Jan]Problem Solving 解题 动态规划
		[BZOJ1700][Usaco2007 Jan]Problem Solving 解题 Description 过去的日子里,农夫John的牛没有任何题目. 可是现在他们有题目,有很多的题目. 精确地 ... 
- CH Round #56 - 国庆节欢乐赛解题报告
		最近CH上的比赛很多,在此会全部写出解题报告,与大家交流一下解题方法与技巧. T1 魔幻森林 描述 Cortana来到了一片魔幻森林,这片森林可以被视作一个N*M的矩阵,矩阵中的每个位置上都长着一棵树 ... 
随机推荐
- Hibernate关联关系配置(一对多、一对一和多对多)
			第一种关联关系:一对多(多对一) "一对多"是最普遍的映射关系,简单来讲就如消费者与订单的关系. 一对多:从消费者角的度来说一个消费者可以有多个订单,即为一对多. 多对一:从订单的 ... 
- Hadoop on Docker
			最初接触Docker是在2013年初,当时Docker才刚起步不久,知之甚少.在不到一年的时间里,Docker已经家喻户晓,成为时下最热门的云计算技术之一,出现了许多围绕docker的新兴产品(仅供参 ... 
- Magicodes.WeiChat——利用纷纭打造云日志频道
			纷纭,是个免费的渠道集成工具.这里我就不多介绍了,右侧是飞机票:https://lesschat.com/ 在开发或者在运维情况下,我们经常需要查看并关注服务器端日志以确保程序是否健康运行.尤其是在微 ... 
- Windows7上搭建Cocos2d-x 3.1.1开发环境
			前言 现在,越来越多的公司采用Cocos2d-x 3.0来开发游戏了,但是现在这样的文章并不多,所以打算写一系列来帮助初学者快速掌握Cocos2d-x 3.0.首先就从开发环境的大家说起吧. 开发工具 ... 
- Linux 进程间通信(一)
			Linux 进程间通信 进程是一个独立的资源分配单位,不同进程之间的资源是相互独立的,没有关联,不能在一个进程中直接访问另一个进程中的资源.但是,进程不是孤立的,不同的进程之间需要信息的交换以及状态的 ... 
- [Java Web整合开发王者归来·刘京华] 2、 Java Web开发概述
			1.Web相关概念 1-1.胖客户与瘦客户 >_<" RCP的定义及优缺点: >_<"TCP的定义及优缺点: 1-2.B ... 
- [自娱自乐] 3、超声波测距模块DIY笔记(三)
			前言 上一节我们已经研究了超声波接收模块并自己设计了一个超声波接收模块,在此基础上又尝试用单片机加反相器构成生成40KHz的超声波发射电路,可是发现采用这种设计的发射电路存在严重的发射功率太低问题,对 ... 
- [外挂4] 用CE查找棋盘基址
			a.找棋盘数据基址 b.分析棋盘数据结构 综合使用搜索技巧,这要看你的聪明才智啦! [如本例:首先精确查找0,然后点一下左上角的一个,再次筛选出变化的,重开盘,再搜变化的,发现期盼规律为值为0表示没有 ... 
- iOS-常用的辅助工具软件
			1.Navicat Premium11.0.20破解版快速安装配置(附文件) Navicat Premium是当下非常好用的数据库管理软件,但是价格非常昂贵,并且还有某些小bug,感觉3000+的 ... 
- MyEclipse使用总结——MyEclipse文件查找技巧 ctrl+shift+R ctrl+H
			一.查找文件 使用快捷键[ctrl+shift+R]弹出弹出文件查找框,如下图所示: 二.查找包含某个字符串的文件 使用快捷键[ctrl+H]在弹出对话框中选File Search选项,然后在第一个文 ... 
