Consider the following code:public void displayNames(){ int i = 5; String[] names = new String[10]; System.out.println(names[i]);}What will be the output when displayNames executes?
Question
Consider the following code:public void displayNames(){ int i = 5; String[] names = new String[10]; System.out.println(names[i]);}What will be the output when displayNames executes?
Solution
When the displayNames method executes, it will output null.
Here's the step-by-step explanation:
-
An integer
iis declared and initialized with the value5. -
An array of Strings
namesis declared with a size of10. Since no values are assigned to the array elements, they are automatically initialized with the default value for object references, which isnull. -
The
System.out.println(names[i]);statement attempts to print the value of thenamesarray at index5. Since this value has not been assigned, it isnull.
So, the output of this code will be null.
Similar Questions
Given the following method: static String saySomething(String name) { String output = ""; if (name.length() < 5) { output = name + ", your name is short."; } else { output = name + ", your name is long."; } return output; } What would the output be to the screen after following statement? System.out.println(saySomething("Randy"));Randy, your name is long.Randy, your name is short.RandysaySomething("Randy")
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); }}
What will be the output of the following Java code? public class array_output { public static void main(String args[]) { int array_variable [] = new int[10]; for (int i = 0; i < 10; ++i) { array_variable[i] = i; System.out.print(array_variable[i] + " "); i++; } } }
What will be printed when the following code is executed? String firstname = "John"; String surname = "Smith"; surname.toUpperCase(); System.out.print(fir
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.