Consider the given code: class String_demo { public static void main(String args[]) { char arr[] = {'Q','W','E','R','T','Y}; } }Which among the following option will print QWERTYA) System.out.println(arr);B) System.out.println(arr.toString());C) new String(arr); System.out.println(str);D) System.out.println(Arrays.toString(arr));
Question
Consider the given code: class String_demo { public static void main(String args[]) { char arr[] = {'Q','W','E','R','T','Y}; } }Which among the following option will print QWERTYA) System.out.println(arr);B) System.out.println(arr.toString());C) new String(arr); System.out.println(str);D) System.out.println(Arrays.toString(arr));
Solution
The correct option is C. However, the code is not written correctly. Here is the correct version:
class String_demo {
public static void main(String args[]) {
char arr[] = {'Q','W','E','R','T','Y'};
String str = new String(arr);
System.out.println(str);
}
}
In this corrected code, we first create a character array arr[] with the elements 'Q','W','E','R','T','Y'. Then, we create a new String str from the character array using the String(char[] value) constructor. Finally, we print the string using System.out.println(str);. This will output QWERTY to the console.
Option A, B, and D will not work because they either directly print the character array (which will not give the desired output) or they use methods that do not exist for character arrays in Java.
Similar Questions
Select the correct answerWhat will be the output of the following Java program?class String_demo { public static void main(String args[]) { char chars[] = {'f', 'o', 'r'}; String s = new String(chars); System.out.println(s); }}Optionsfrforo
public class Test { public void m1(String arg1) { arg1="Test"; } public static void main(String[] args) { Test test1= new Test(); String s= "Hello"; test1.m1(s); System.out.println(s); }}
Analyze the following code carefully. Please select the one that applies.public class Test { public static void main(String[] args) { A a = new A(); a.print(); }}class A { String s; A(String s) { this.s = s; }void print() { System.out.println(s); }}
Consider the following program.public class Main { public static void main(String args[]) { String[] names = new String[2]; names[0] = "Alice"; names[1] = "Bob"; names[2] = "Charlie"; System.out.println(names[2]); }}Which of the following is an output of the above program? a. Charlie b. Bob c. Alice d. Compilation Error
What will be the output of the following program?class string_class {public static void main(String args[]){String obj = "hello";String obj1 = "world"; String obj2 = obj;obj2 = " world";System.out.println(obj + " " + obj2); }}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.