Given the following code:
public class Main { public static void main(String[] args) { Object[][] twoDimArray = {//from w w w . j ava 2 s . com {"SQL", -100.678, 44, 'X', true}, {"Java", 50.88, 777, 'Y', false}, {"Array", -20.4455, 5151, 'Z', false} }; // (1) INSERT DECLARATION HERE for (Object[] oneDimArray : twoDimArray) { System.out.format(formatStr, oneDimArray); } } }
Which declarations, when inserted at (1), will print the following:
|X| SQL|t|(100.68)| 44| |Y| Java|f| +50.88| 777| |Z|Array|f| (20.45)| 5151|
Select the two correct answers.
(a) String formatStr = "|%4$-1c|%5s|%5$1.1b|%(+8.2f|%6d|%n"; (b) String formatStr = "|%4$c|%5s|%5$.1b|%(+8.2f|%6s|%n"; (c) String formatStr = "|%4$c|%5s|%5$.1b|%2$(+-8.2f|%3$6s|%n"; (d) String formatStr = "|%4$c|%1$5s|%5$.1b|%2$(+8.2f|%3$,6d|%n";
(a) and (b)
First, note that the Object[] array oneDimArray
is passed as varargs Object... to the format()
method.
(a) In the format %4$-1c, -1 is superfluous if we only want to print 1 character.
4$ here indicates the fourth value in the oneDimArray
that represents a row in the twoDimArray
.
%5s implicitly refers to the first value in the oneDimArray
, which is printed with a width of 5 characters right-justified.
In %5$1.1b, %5$ indicates the fifth value (boolean) in the oneDimArray
.
The precision .1 indicates that only the first character should be printed.
The width of 1 is superfluous in 1.1.
%(+8.2f corresponds to the second value (float) in the oneDimArray
, indicating that negative values should be enclosed in () and positive values should have the + sign.
The width is 8 and the precision is 2 decimals.
%6d corresponds to the third value (int) in the oneDimArray
, indicating that the width is 6 characters.
(b) The superfluous -1 in (a) is missing in (b) for formatting a character.
The int value is formatted with %6s, giving the same result as %6d in (a).
(c) In the format specification %2$(+-8.2f, the - sign indicates that the value should be printed left-justified, not right-justified as in the output.
The format %3$6s in (c) only indicates the third argument (int value) explicitly.
(d) Arguments are made explicit.
The format %3$,6d specifies the locale-specific grouping separator (,), which is used for the value 5151, formatting it as 5,151.
This is not so in the output.