Strings

Practice Questions

Computer Science › Strings

Questions
7
1

Which of the following blocks of code converts an array of characters into a string?

2

Consider the following code:

int\[\] vals = {5,4,2};

String s = "Hervaeus";

String s2 = "";

for(int i = 0; i < s.length(); i++) {

for(int j = 0; j < vals\[i % vals.length\]; j++) {

s2 += s.charAt(i);

}

}

System.out.println(s2);

What is the output for the code above?

3

String\[\] books = {

"Logica sive Ars Rationalis",

"Kritik der reinen Vernunft",

"Cursus Philosophicus Thomisticus",

"Happy words for happy people",

"Insane words for an insane world"

};

String str = "Kittens in a cart";

ArrayList vals = new ArrayList();

for(int i = 0; i < books.length; i++) {

if(books\[i\].compareTo(str) > 0) {

vals.add(books\[i\]);

}

}

System.out.println(vals);

What is the output for this method?

4

See code below:

String\[\] books = {

"De Secundis Intentionibus",

"Leviathan",

"Averrois Commentaria Magna in Aristotelem De celo et mundo",

"Logica Docens for Idiots",

"Logica Utens for Tuba Players"

};

String userInput;

// In code excised from here, a person inputs the value "Logica Utens for Tuba Players" ...

for(int i = 0; i < books.length; i++) {

if(books\[i\] == userInput) {

System.out.println("This is a wonderful book!!");

}

}

What is the error in the code above?

5

Consider the following code:

char\[\] values = {'I',' ','l','o','v','e',' ','y','o','u','!','!'};

String s = "";

for(int i = 0; i < values.length / 2; i++) {

char temp = values\[i\];

values\[i\] = values\[values.length - i-1\];

values\[values.length - i-1\] = temp;

}

for(int i = 0; i < values.length; i++) {

s += values\[i\];

}

System.out.println(s);

What is the output for the code above?

6

String greet = "Hello ";
String sub;
int len = greet.length();
sub = greet.substring(0, (len/2));
System.out.println (sub);

What is printed?

7

Which of the following blocks of code makes every other character in the string s to be upper case, starting with the second character?

Return to subject