Formatting: It is important to format the output before display the results to end user. Proper formatting makes the user more understandable about program results.
We always display results in String format. To format the output, we concatenate the values such as int, char, double, boolean with messages (string type) as follows:
Syntax | Example |
int + int = int | 10 + 20 = 30 |
String + String = String | “Java” + “Book” = JavaBook “10” + “20” = 1020 |
String + int = String | “Book” + 1 = Book1 “123” + 456 = 123456 |
String + int + int = String | “Sum = “ + 10 + 20 = Sum1020 |
String + (int + int) = String | “Sum = “ + (10 + 20) = Sum30 |
String + double = String | “Value = “ + 23.45 = Value = 23.45 |
String – int = Error |
public class Code { public static void main(String[] args) { int a=10; System.out.println(a); } } Output: 10 |
public class Code { public static void main(String[] args) { int a=10, b=20; System.out.println(a + “ , “ + b); } } Output: 10, 20 |
public class Code { public static void main(String[] args) { int a=10, b=20; System.out.println(“a = ” + a); System.out.println(“b = ” + b); } } Output: a = 10 b = 20 |
public class Code { public static void main(String[] args) { int a=10, b=20; System.out.println(“a = ” + a + “ , “ + “b = ” + b); } } Output: a = 10, b = 20 |
public class Code { public static void main(String[] args) { int a=10, b=20; int c=a+b; System.out.println(“Sum of ” + a + ” and ” + b + ” is ” + c); } } Output: Sum of 10 and 20 is 30 |
public class Code { public static void main(String[] args) { int a=10, b=20; int c=a+b; System.out.println(a + ” + ” + b + ” = ” + c); } } Output: 10+20=30 |