Java Output

We know that displaying variables is an important part of a computer program. Our Java application can display the output data to the monitor using the standard output stream named System.out.

In Java, we mostly use the System.out.print() and System.out.println() methods to display the output data.

With print() method, the cursor stays at the same line; while with println(), the cursor moves to the next line.

But, using these two methods, it is really difficult to format the output data according to the requirements of programs.

That is why we may want to use the System.out.printf() method for getting the formatted output like what we did in C programming.

 

An Example

This example illustrates the difference between println() and printf() methods.

Let us suppose we have been asked to perform the summation of the following series up to two-decimal places:

S = 1 + 1/2 + 1/3 + · · · · · · · · · · + 1/n

 

The code solving the above programming problem is given below.

Series.java

public class Series {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit: ");
int a = sc.nextInt();
double t, sum = 0.0;
for (int i = 1; i <= a; i++) {
t = 1.0/(double)i;
sum += t;
}

// Displaying the result
System.out.println("The sum is: " + sum);

}

}

Output:

C:\testing>java Series
Enter the limit:
5
The sum is: 2.283333333333333

Observation: If we look at the output of the program, we could see that the result displayed here is not up to two-decimal places. That means the displayed result fails to meet the requirements of the program. We have used here println() method only.

 

The modified code using “printf()” method to display the result is given below.

Series_Modified.java

public class Series_Modified {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit: ");
int a = sc.nextInt();
double t, sum = 0.0;
for (int i = 1; i <= a; i++) {
t = 1.0/(double)i;
sum += t;
}
// Displaying the result
System.out.printf("Modified Sum = %.2f\n", sum);
}
}

Output:

C:\testing>java Series_Modified
Enter the limit:
5
Modified Sum = 2.28