Reputation: 693
So, now I know that for integers I can use
System.out.println("Name: %d", Name);
So, how do I print out other values in Java? Things like Strings, Boolean, Dates, and Doubles? Do I use %d for integers only?
Upvotes: 0
Views: 564
Reputation: 676
Anything you put inside the parenthesis of System.out.println() or System.out.print() is formatted and printed as a string. However, you can control how variables are printed out inside your string (as you did using %d) using Java's printf() method.
The printf() method takes two parameters: the string to print and a list of variable names. You insert the format flags (%d, %f, etc) in the string and you list the variables you want formatted in the string second.
System.out.printf("Your total is %d", 29.99);
This means that Java will format 29.99 as a decimal rather than a string when it outputs "Your total is 29.99".
You can check out the other types of formatting in the "conversion type character" table here.
Upvotes: 0
Reputation: 285430
Regarding:
System.out.println("Name: %d", Name);
No, that won't work for println, for printf, yes, but not for println:
System.out.printf("Name: %d", Name);
or if you want a new line:
System.out.printf("Name: %d%n", Name);
For booleans, %b, for doubles, %f, for Strings %s .... Dates would require a combination of specifiers (or I would just use a SimpleDateFormat object myself). Note that these specifiers can take width constants to give them more power at formatting the output. e.g.,
System.out.printf("Pi to four places is: %.4f%n", Math.PI);
Please check the Formatter API for more of the details.
Upvotes: 3
Reputation: 7
You can do System.out.println("something");
if you want to skip a line after printing, but if you want to print something, then continue on the same line, then you should just do System.out.print("something");
You can also just print out Strings, boolean values (t/f) and doubles just by doing something like
System.out.println(booleanname);
or
System.out.println(Stringname;
or
System.out.println(doublevariablename);
Upvotes: 0
Reputation: 281958
System.out.println(whatever);
whatever
can be a String, boolean, int, Point, whatever. Check out the docs.
Upvotes: 0