Java Ouput

Java Printing / Output

In this tutorial, we'll explore how to display output in Java. Output and printing are essential aspects of programming as they allow us to communicate with users, debug our code, and test our programs. We'll cover the following topics in this tutorial:

Using System.out.println()

The most common way to display output in Java is by using the System.out.println() method. This method prints the provided data to the console followed by a newline character, which moves the cursor to the next line. Let's look at some examples:

Example
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.println("Java is fun to learn!");
    }
}
Output
Hello, World!
Java is fun to learn!

Using System.out.print()

If you want to print text without moving to the next line, you can use System.out.print(). This method does not add a newline character, so subsequent output will be on the same line:

Example
public class PrintExample {
    public static void main(String[] args) {
        System.out.print("This ");
        System.out.print("is ");
        System.out.print("one ");
        System.out.print("line.");
    }
}
Output
This is one line.

Formatting Output

You can format your output using placeholders and the printf method. This method allows you to control the alignment, precision, and data types of your output:

Example
public class FormatExample {
    public static void main(String[] args) {
        int num = 42;
        double pi = Math.PI;
        System.out.printf("The number is %d and the value of pi is %.2f%n", num, pi);
    }
}
Output
public class FormatExample {
    public static void main(String[] args) {
        int num = 42;
        double pi = Math.PI;
        System.out.printf("The number is %d and the value of pi is %.2f%n", num, pi);
    }
}

Escape Sequences

Java supports escape sequences to include special characters in your output. Common escape sequences include \n (newline), \t (tab), \" (double quote), and \\ (backslash):

Example
public class EscapeExample {
    public static void main(String[] args) {
        System.out.println("This is a newline.\nThis is a tab:\tThis is a backslash: \\");
    }
}
Output
This is a newline.
This is a tab:    This is a backslash: \

You can concatenate strings and variables using the + operator:

System.out.println("Name : " + " Abhiyantrik tutorials " );

These fundamental concepts will help you display output effectively in Java programs. As you become more proficient in Java, you'll use these techniques extensively to provide feedback and information to users or for debugging purposes.

Contact Us

Name
Email
Mobile No:
subject:
Message: