0% found this document useful (0 votes)
49 views

Chapter II.9

This document contains 18 practice problems related to working with selected classes from the Java API, specifically String, StringBuilder, and related methods. Each problem presents a code snippet or scenario and asks for the expected output or result. This includes problems about manipulating and comparing strings, using StringBuilder methods, concatenation vs reassignment, and other common string and StringBuilder tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Chapter II.9

This document contains 18 practice problems related to working with selected classes from the Java API, specifically String, StringBuilder, and related methods. Each problem presents a code snippet or scenario and asks for the expected output or result. This includes problems about manipulating and comparing strings, using StringBuilder methods, concatenation vs reassignment, and other common string and StringBuilder tasks.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

*******************************************************************

* NAILING 1Z0-808:
* PRACTICAL GUIDE TO ORACLE JAVA SE8 PROGRAMMER I CERTIFICATION
* BY IGOR SOUDAKEVITCH
* www.igor.host
*******************************************************************
* Practice questions to
* CHAPTER II.9, Working with Selected Classes from Java API
*******************************************************************

Problem 9.1
Given:
class Hello {
public static void main(String[] args) {
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
str.replace("o", "");
System.out.print(str + " ");
System.out.print(str.replace("o","") + " ");
System.out.print(sb.append("?").equals(sb.append("!")) + " ");
System.out.println(str.replace("o","").equals(str.replace("o","")));
}
}
What is the result?
A. Hell Hell false false
B. Hell Hell true true
C. Hello Hell false false
D. Hello Hell true true
E. Hello Hell false true
F. Hello Hell true false

*******************************************************************

Problem 9.2
Given:
class OurPets {
static String checkPets(StringBuilder myPet, StringBuilder yourPet){
return myPet == yourPet ? "same" : "different";
}
static String checkNames(StringBuilder myPet, StringBuilder yourPet){
return myPet.equals(yourPet) ? "same" : "different";
}
public static void main(String[] args) {
StringBuilder myPet = new StringBuilder("Fluffy");
StringBuilder yourPet = new StringBuilder("Fluffy");
System.out.print(checkPets(myPet, yourPet) + " pets, ");
System.out.println(checkNames(myPet, yourPet) + " names");
}
}
What is the result?
A. same pets, same names
B. different pets, same names
C. same pets, different names
D. different pets, different names
E. Compilation fails
*******************************************************************

Problem 9.3
Given:
class TheFifthElement {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("1"); // earth
sb.append("2"); // water
sb.append("3"); // air
sb.append("4"); // fire
sb.replace(4,4,"Leeloo"); // line t1
System.out.println(sb);
}
}
What is the result?
A. 1234Leeloo
B. Compilation fails
C. The code throws a run-time exception

*******************************************************************

Problem 9.4
Given the following class:
class Test {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
String str = null;
for(int e : arr){ str += e; }
System.out.println(str);
}
}
What is the result:
A. _12345 (where _ denotes an empty space)
B. 12345
C. null12345
D. Compilation fails
E. A NullPointerException is thrown

*******************************************************************

Problem 9.5
Hoping to land a job as a junior programmer at a local bank, you came to a Java
interview and were asked to complete the following class that masks 20-digit
account numbers so that only the last five digits will be visible to the user while
each of the first 15 digits is replaced with an asterisk:
public class AccountMasker {
public static String maskAccount(String accNum) {
String lead = "***************"; // contains 15 asterisks in a row

// your code goes here

public static void main(String[] args) {


String accNum = args[0];
System.out.println(maskAccount(accNum.replace(" ","")));
}
}
Specifically, your task is to finish up the method maskAccount(String accNum) so
that the class AccountMasker will output ****************67541 when run with the
following command:
java AccountMasker "34296 01853 49820 67541"
Which two LOCs, when used independently, will achieve this requirement?
A. return (new StringBuilder(accNum)).substring(15, 20).toString();
B. return lead + accNum.substring(15, 20);
C. return new StringBuilder(accNum).append(lead, 15, 20).toString();
D. return new StringBuilder(accNum).insert(0, lead).toString();
E. return new StringBuilder(lead).append(accNum, 15, 20).toString();

*******************************************************************

Problem 9.6
Which statement initializes a StringBuilder to a capacity of 256?
A. StringBuilder sb = new StringBuilder(new String(256));
B. StringBuilder sb = StringBuilder.setCapacity(256);
C. StringBuilder sb = StringBuilder.setLength(256);
D. StringBuilder sb = new StringBuilder(256);

*******************************************************************

Problem 9.7
Given the code fragment:
StringBuilder sb = new StringBuilder();
String exam = "1Z0";
int code = 808;
Which two options will output the following:
I’ll pass 1Z0-808
A. System.out.println(sb.append("I’ll pass " + exam + "-" + code));
B. System.out.println(sb.insert("I’ll pass ").append(exam + "-" + code));
C. System.out.println(sb.insert("I’ll pass
").insert(exam).insert("-").insert(code));
D. System.out.println(sb.append("I’ll pass
").append(exam).append("-").append(code));

*******************************************************************

Problem 9.8
Given:
public static void main(String[] args) {
String a = "B ";
a = a.concat("U ");
String b = "L ";
a = a.concat(b);
a.replace('U', 'A');
a = a.concat(b);
System.out.println(a);
}
What is the result?
A. B A L L
B. B L A
C. B U L L
D. B U A
E. B U A L

*******************************************************************

Problem 9.9
Given:
public class Simple{
public static void main (String[] args){
char c = 6;
System.out.println("Hello".charAt(c));
}
}
What is the result?
A. There is no output
B. Compilation fails
C. The code throws an IndexOutOfBoundsException
D. The code throws a NullPointException

*******************************************************************

Problem 9.10
Given:
StringBuilder bucket = new StringBuilder("Empty me!");
Which statement(s) will empty the contents of the bucket object?
A. bucket.empty();
B. bucket.clear();
C. bucket.delete(0, bucket.size());
D. bucket.delete(0, bucket.length());
E. bucket.deleteAll();
F. bucket.remove(0, bucket.length());
G. bucket.removeAll();

*******************************************************************

Problem 9.11
Given:
class PoorGirl {
public static void main(String[] args) {
String name = "Javeline";
System.out.println("Hi! I’m " + name.replace("e", "a"));
}
}
What is the result?
A. Hi! I’m Javaline
B. Hi! I’m Javalina
C. Hi! I’m Jevaline
D. Hi! I’m Jeveline
*******************************************************************

Problem 9.12
Given the following main() method:
public static void main(String[] args) {
String str = " ";
str.trim();
System.out.println(str.equals("") + " " + str.isEmpty());
}
What is the result?
A. true true
B. true false
C. false true
D. false false

*******************************************************************

Problem 9.13
Given:
StringBuilder sb = new StringBuilder();
sb.append("Duke");
And the following LOCs:
System.out.println(sb.insert(0, "Hello "));
System.out.println(sb.append(0, "Hello "));
System.out.println(sb.add(0, "Hello "));
System.out.println(sb.set(0, "Hello "));
How many of them print Hello Duke?
A. None
B. One
C. Two
D. Three

*******************************************************************

Problem 9.14
Given the following code fragment:
String str1 = "null";
String str2 = new String("NULL");
System.out.println(str1.equalsIgnoreCase(str2.toLowerCase()));
System.out.println(str2 == str2.replace('L','l').toLowerCase());
System.out.println(str1 == str1.replace('L','l').toLowerCase());
How many times the code prints true?
A. Not a single time
B. Once
C. Twice
D. Three times

*******************************************************************

Problem 9.15
Given:
public class TheMatrix {
public static void main(String[] args) {
String movie = "The";
movie.concat(" ").concat("MATRIX".toLowerCase());
System.out.print(movie.substring(5,6));
}
}
What is the result?
A. a
B. at
C. Compilations fails
D. An exception is thrown at run time

*******************************************************************

Problem 9.16
Given:
public class TheMatrixReloaded {
static void reload(StringBuilder sb) {
sb.append(" Matrix");
sb.insert(" Reloaded", sb.length());
}
public static void main (String[] args) {
StringBuilder sb = new StringBuilder("The");
reload(sb);
System.out.println(sb);
}
}
What is the result?
A. The
B. The Matrix Reloaded
C. Compilation fails
D. An exception is thrown at run time

*******************************************************************

Problem 9.17
Given the code fragment:
public static void main (String[] args) {
String[] str = new String[2];
int i = 0;
for (String e : str)
System.out.print(e.concat(" " + i++).trim());
}
What is the result?
A. 01
B. 0 1
C. 0 1
D. Compilation fails
E. An exception is thrown at run time

*******************************************************************
Problem 9.18
Given:
public class Exam {
String str = "";
static void pass(String str) {
str.concat("Passed");
}
public static void main(String[] args) {
String str = "Failed ";
pass(str);
System.out.println(str);
}
}
What is the result?
A. Passed
B. Failed
C. Failed Passed
D. Compilation fails
E. An exception is thrown at runtime

*******************************************************************

Problem 9.19
Given:
public class AnotherExam {
public static void main (String[] args) {
StringBuilder sb = new StringBuilder("Passed");
System.out.print(sb + ": ");
System.out.println(sb.replace(0,4,"Fail") ==
sb.delete(0,666).insert(0,"Failed"));
}
}
What is the result?
A. Passed: false
B. Passed: true
C. Failed: false
D. Failed: true
E. Compilation fails
F. The code throws IndexOutOfBoundsException

*******************************************************************

Problem 9.20
Given:
public class Capricchio {
public static void main (String[] args) {
Object obj = null;
StringBuilder sb = new StringBuilder();
sb.append(obj);
System.out.println(sb.length());
}
}
What is the result?
A. 1
B. 4
C. 16
D. Compilations fails
E. A NullPointerException is thrown at run time

*******************************************************************

Problem 9.21
Given:
public class HowAboutThisOne {
public static void main (String[] args) {
String str = null;
StringBuilder sb = new StringBuilder(str += str);
sb.delete(0,sb.length());
System.out.println(sb.capacity());
}
}
What is the result?
A. 8
B. 16
C. 24
D. Compilations fails
E. A NullPointerException is thrown at run time

*******************************************************************

Problem 9.22
Given:
class Slogan {
public static void main(String[] args) {
String str = "String Beans Forever!";
// line XXX: only a single LOC goes in here!
}
}
And the following LOCs:
System.out.println(str.delete(6,11));
str = str.delete(6,11); System.out.println(str);
str.replace(" Bean",""); System.out.println(str);
System.out.println(new StringBuilder(str).remove(" Bean").toString());
How many LOCs, when inserted independently at line XXX, will make the code print
Strings Forever!?
A. None
B. One
C. Two
D. Three

*******************************************************************

Problem 9.23
Given:
final String str = "";
while(str.equals("")) System.out.print(str+1);
What is the result?
A. 1
B. No visible output at all
C. Code compiles but enters endless loop at run time
D. Compilation fails because of an unreachable statement
E. Compilation fails because str+1 creates a new object but str is final
F. Compilation fails because the expression str+1 is illegal

*******************************************************************

Problem 9.24
Given:
"a".replace("a","b");
"a".replace('a','b');
"a".replace(0,"a".length(),"b");
"a".replace(new StringBuilder('a'),"");
"a".replace(new StringBuilder('a'), new StringBuilder("b"));
new StringBuilder("a").replace("","b");
new StringBuilder("a").replace('a','b');
new StringBuilder("a").replace(0,1,"b");
How many LOCs fail compilation?
A. Two
B. Three
C. Four
D. Five

*******************************************************************

Problem 9.25
Given:
public class Dissonance{
public static void main(String[] args) {
Object obj = "Quartet No. 19 in C Major, K. 465"; // line D1
System.out.println(obj.getClass().getSimpleName() + " " + obj); }
}
Is it true that the code prints String Quartet No. 19 in C Major, K. 465?
A. true
B. false

*******************************************************************

Problem 9.26
Given the following code fragment:
LocalDate today = LocalDate.of(2016, Month.JUNE, 13);
today.plusHours(24);
System.out.println(today);
What is the result?
A. 2016-06-14
B. 2016-06-13
C. Compilation fails
D. An exception is thrown at run time

*******************************************************************
Problem 9.27
Given:
public static void main(String[] args) {
String date = LocalDate.parse("2016-07-13")
.plusDays(31)
.format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(date); }
What is the result?
A. 2016-07-13
B. 2016-07-14
C. 2016-07-15
D. Compilation fails
E. An exception is thrown at run time

*******************************************************************

Problem 9.28
Given:
LocalDate ld = LocalDate.of(2016, 6, 13);
ld.plusMonths(6).format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(ld);
What is the result?
A. December 13, 2016
B. June 13, 2015
C. 2016-12-13
D. 2016-06-13

*******************************************************************

Problem 9.29
Which two LOCs fail compilation?
A. LocalDateTime.of(2016,6,13);
B. LocalDate.of(2016, Month.JUNE, 50);
C. LocalDateTime.of(2016,06,13,14,15);
D. LocalDate ld = new LocalDate(2016,6,13);
E. LocalTime.now().format(DateTimeFormatter.ISO_DATE);

*******************************************************************

Problem 9.30
Given:
System.out.println(LocalDate.now().plus(Period.of(0,0,0)));
System.out.println(LocalDate.of(2016, Month.JUNE, 13)
.format(DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println(LocalDate.parse("2016-06-13", DateTimeFormatter.ISO_DATE));
What is the result if the system date is June 13, 2016?
A. 2016-06-13
2016-06-13
2016-06-13
B. Compilation fails.
C. A DateParseException is thrown at runtime.
*******************************************************************

Problem 9.31
Given the full contents of the file JavaBirthday.java:
1 package birthday;
2 import java.time.LocalDate;
3 import java.time.format.DateTimeFormatter;
4
5 public class JavaBirthday {
6 public static void main(String[] args) {
7 LocalDate birthday = LocalDate.of(1995, Month.MAY, 23);
8 DateTimeFormatter formatter =
9 DateTimeFormatter.ofPattern("MMM dd, YYYY");
10 System.out.println("Java was born on " + birthday.format(formatter));
11 }
12 }
One of the LOCs fails compilation. Which two modifications, used independently,
will make the code print Java was born on May 23, 1995?
A. Replace line 2 with import java.time.*;
B. Replace line 3 with import java.time.format.*;
C. Replace Month.MAY on line 7 with Month.May
D. Replace Month.MAY on line 7 with 05

*******************************************************************

Problem 9.32
Given the following class definition:
class LangsToLearn {
public static void main(String[] args) {
List<String> langs = new ArrayList<>();
langs.add("Ruby");
langs.add("Perl");
langs.add("Perl");
langs.add("Closure");
if (langs.remove("Perl")) langs.add("Emacs Lisp");
System.out.println(langs);
}
}
What is the result?
A. [Ruby, Perl, Closure, Emacs Lisp]
B. [Ruby, Closure, Emacs Lisp, Emacs Lisp]
C. [Ruby, Closure, Emacs Lisp]
D. Compilation fails

*******************************************************************

Problem 9.33
Given:
ArrayList<String> someTypes = new ArrayList<>();
someTypes.add("byte");
someTypes.add("long");
someTypes.add("int");
Which two expressions evaluate to 3?
A. someTypes.size();
B. someTypes.capacity();
C. someTypes.length();
D. someTypes.get(2).size;
E. someTypes.get(2).length;
F. someTypes.get(2).length();

*******************************************************************

Problem 9.34
Given the following code fragment:
ArrayList<Integer> list = new ArrayList(); // a1
list.add(1); // a2
System.out.println(list.get(list.size())); // a3
What is the result?
A. 1
B. Compilation fails on line a1
C. Compilation fails on line a2
D. Compilation fails on line a3
E. An IndexOutOfBoundsException is thrown at run time

*******************************************************************

Problem 9.35
Given:
class TestingArrayList {
public static void main (String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 5; i++) list.add("" + i);
System.out.println(list.remove(list.indexOf("4")));
}
}
What is the result?
A. true
B. 4
C. [0, 1, 2, 3, 4]
D. Compilation fails

*******************************************************************

Problem 9.36
Given:
public class MutatisMutandis {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new StringBuilder(""));
list.add("");
for (Object e : list )
if (e instanceof StringBuilder) ((StringBuilder)e).append("OK");
else ((String)e).concat("OK");
System.out.println(list);
}
}
What is the result?
A. [OK, OK]
B. [OK, ]
C. Compilations fails
D. A RuntimeException is thrown

*******************************************************************

Problem 9.37
Given:
class Birdies{
public static void main(String[] args) {
List aviary = new ArrayList<>(); // line b1
aviary.add("kinglet");
aviary.add("finch");
aviary.add("titmouse");
aviary.add(aviary.set(0,"jay")); // line b2
System.out.println(aviary);
}
}
What is the result?
A. [jay, finch, titmouse, kinglet]
B. [jay, finch, titmouse, true]
C. Compilation fails on line b1
D. Compilation fails on line b2

*******************************************************************

Problem 9.38
Given:
class Sweet16 {
public static void main(String[] args) {
List<Integer> ages = new ArrayList<>();
ages.add(16);
ages.add(null);
for (int i = 0; i < ages.size(); i++) System.out.print(ages.get(i));
for (int i : ages) System.out.println(i);
}
}
What is the result?
A. 16null16
B. 16null16null
C. 16null16 and a NullPointerException
D. Compilation fails

*******************************************************************

Problem 9.39
Given the following class definitions:
class Examinee {
private String name;
private int score;
public Examinee(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() { return name; }
public int getScore() { return score; }
}

class ReleasingResults{
public static void checkScore(List<Examinee> list, Predicate<Examinee> p){
for (Examinee e : list) {
if (p.test(e)) {
System.out.print(e.getName() + ", ");
}
}
}

public static void main(String[] args) {


List<Examinee> list = Arrays.asList(new Examinee("Alice", 98),
new Examinee("Bob", 48),
new Examinee("Charlie", 62),
new Examinee("Doug", 88));
System.out.print("Passed: ");

// line r1

}
}
Which LOC, when inserted at line r1, enables the code to print Passed: Alice,
Doug,?
A. checkScore(list, () -> e.getScore() > 65);
B. checkScore(list, Examinee e -> e.getScore() > 65);
C. checkScore(list, e -> e.getScore() > 65);
D. checkScore(list, (Examinee e) -> { e.getScore() > 65; });

*******************************************************************

Problem 9.40
Let sb refer to a StringBuilder object. Which of the following fail(s) compilation?
A. sb -> sb.toString()
B. StringBuilder sb -> sb.toString()
C. (StringBuilder sb) -> return sb.length();
D. (StringBuilder sb) -> { return sb.length(); }

*******************************************************************

Problem 9.41
Given:
class Test {
String check(List list, Predicate p){ // line t1
return p.test(list)? "Empty" : "Populated";
}
void run() {
ArrayList list = new ArrayList(); // line t2
System.out.println(
check(list, list -> list.isEmpty())); // line t3
}
public static void main(String[] args) {
new Test().run();
}
}
Which two options can make the code compile and run successfully?
A. Replace line t3 with check(list, myList -> list.isEmpty()));
B. Replace line t2 with List list = new ArrayList();
and replace line t3 with check(list, myList -> myList.isEmpty()));
C. Replace line t1 with String check(List list, Predicate<ArrayList> p){
and line t3 with check(list, myList -> myList.isEmpty()));
D. Replace line t1 with String check(ArrayList list, Predicate<ArrayList> p){
line t2 with List mist = new ArrayList();
and line t3 with check(mist, list -> list.isEmpty()));
E. Replace line t1 with String check(List list, Predicate<List> p){
and line t3 with check(list, myList -> myList.isEmpty()));

*******************************************************************

Problem 9.42
Given:
class Suspect {
private String name;
private boolean statement;

public Suspect (String name) {


this.name = name;
this.statement = Math.random() < 0.5 ? false : true;
}

public boolean getStatement() { return statement; }


public String getName() { return name; }
}

class Interrogation {
private static void interrogate(List<Suspect> perps){
for(Suspect e : perps)
if (e.getStatement() != true)
System.out.println(e.getName() + " is lying!");
}
public static void main(String[] args) {
List<Suspect> roundUp = new ArrayList();
roundUp.add(new Suspect("Alice"));
roundUp.add(new Suspect("Bob"));
roundUp.add(new Suspect("Charlie"));
roundUp.add(new Suspect("Doug"));
roundUp.add(new Suspect("Eugine"));
roundUp.add(new Suspect("Frances"));

interrogate(roundUp);
}
}
Which modification will achieve the same result?
A. Overload the method interrogate() with the following code fragment:
private static void interrogate(List<Suspect> perps, Predicate p){
for(Suspect s : perps)
if(!p.test(s))
System.out.println(s.getName() + " is lying");
}
and replace the call to interrogate() with the following LOC:
interrogate(roundUp, perps -> perps.getStatement());
B. Overload the method interrogate() with the following code fragment:
private static void interrogate(List perps, Predicate<Suspect> p){
for(Suspect s : perps)
if(!p.test(s))
System.out.println(s.getName() + " is lying");
}
and replace the call to interrogate() with the following LOC:
interrogate(roundUp, perps -> perps.getStatement());
C. Add the following interface:
interface LieDetector {
default boolean test(Suspect s){ return s.getStatement(); }
}
then overload the method interrogate() with the following code fragment:
private static void interrogate(List<Suspect> perps, LieDetector ld){
for(Suspect s : perps)
if(!ld.test(s))
System.out.println(s.getName() + " is lying");
}
and replace the call to interrogate() with the following LOC:
interrogate(roundUp, perps -> perps.getStatement());
D. Add the following interface:
interface LieDetector { boolean analyze(Suspect s); }
then overload the method interrogate() with the following code fragment:
private static void interrogate(List<Suspect> perps, LieDetector ld){
for(Suspect s : perps)
if(!ld.analyze(s))
System.out.println(s.getName() + " is lying");
}
and replace the call to interrogate() with the following LOC:
interrogate(roundUp, perps -> perps.getStatement());

*******************************************************************

Problem 9.43
Which one is true?
A. Functional interface may not contain more than one method.
B. Any interface that has a single abstract method is therefore functional.
C. Functional interface cannot have superinterfaces.
D. Functional interface cannot be extended.
E. None of the above.

You might also like