User Input and Output In Java

input output in java

In this article, you will learn how to take input using Scanner and print output using System.out.print() in Java. The tutorial also involves building a simple interactive program at the end using the concepts you have learned. To understand today’s concepts, you must be clear about data types, variables, and streams.

User interactions are an important part of programming to make applications interactive and user-friendly. Java’s libraries facilitate handling user input and output.

Understanding System.out in Java

In Java, System is a class, out is an object of the standard output stream that is connected to the standard output device i-e monitor. The out class contains methods like print(), println(), and printf() to show data on the screen. These methods can print different types of data, like text, numbers, and objects, making it easy to display information in your programs.

Print Output on Console in Java using System.out.print()

There are a few different methods for displaying information on the screen in Java but the article will focus on System.out.print() and System.out.println().

The print() and println() Methods

The print() method in Java prints the string passed to it without adding a new line at the end. This means that any print statements that come after will appear on the same line.

Example for print()

public class HelloWorld {

    public static void main(String[] args) {
        System.out.print("Hello, ");
        System.out.print("world!");
    }

}

Output

Hello, world!

On the other hand, the println() method prints the string and then moves the cursor to a new line. Hence, the next print statement starts on the following line.

Example for println()

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, ");
        System.out.println("world!");
    }

}

Output

Hello,
world!

Print a Single Variable on the Console

You can also print variables using print() and println(). Some commonly used data types are int, string, and float. The same syntax is applied to all other data types as well.

Print an Int

To display an int variable you can use the following syntax:

int VariableName = 42; // your value
System.out.println(VariableName);

Print a Float

For a float variable, use the following syntax:

float VariableName = 3.14f;  // your value
System.out.println(VariableName);

Print a String

Similarly, for a String variable, use the following syntax:

string VariableName = "Your Message"; 
System.out.println(VariableName)

Now you can look at a simple example that uses all the variables listed above in a single code.

Example

public class SimpleProgram {

    public static void main(String[] args) {

        // Variables declaration and initialization
        String productName = "Laptop";
        int quantity = 3;
        float price = 1299.99f;

        // Calculating total price
        float totalPrice = quantity * price;

        // Displaying information using println()
        System.out.println("Product: " + productName);
        System.out.println("Quantity: " + quantity);
        System.out.println("Price per unit: $" + price);
        System.out.println("Total price: $" + totalPrice);
    }

}

Output

Product: Laptop
Quantity: 3
Price per unit: $1299.99
Total price: $3899.97

Print Multiple Variables Using a Single Statement

To print multiple variables of different data types in a single statement, you can concatenate (combinate) them with a string. In Java, the + operator is used to concatenate (join together) strings and other values into a single string. Remember that “Anything concatenated to a string becomes a string”.

Example Code

public class PersonDetails {

    public static void main(String[] args) {

        // Variables declaration and initialization
        int age = 25;
        float height = 5.9f;
        String name = "John";

        // Printing person's details
        System.out.println("Name: " + name + ", Age: " + age + ", Height: " + height);
    }

}

Output

Name: John, Age: 25, Height: 5.9

Scanner Class

Initially, let’s forget about technical explanation and think of the scanner in Java as a real-life barcode scanner. A device that takes the product code as input from barcodes on the product. Just like the real world scanner can read barcodes of different types of products, the Java scanner works in the same way. It can read different types of data types (values) from the user.

In Java programming, the Scanner class is used for reading input from various sources like files, strings, and the keyboard. When you connect it to the System.in (standard input stream), it’s ready to receive the input from the standard input device i-e keyboard. This class contains methods including nextInt(), nextFloat(), and nextLine() etc, that convert the input string to data types like integers, floats, etc. 

Input Methods for Commonly Used Data Types

Some of the input methods for the commonly used data types are discussed below including int, float, and also string. 

Input an Int

To read an int value from the user, use the following syntax:

Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();

Input a Float

To input a float, use the following syntax:

Scanner scanner = new Scanner(System.in);
float fnum = scanner.nextFloat();

Input a String

Similarly, for a reading a string from the user (including spaces), use the following syntax:

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

Below is an example that inputs the various data types from the user in a single program.

Example Code

import java.util.Scanner;

public class InputExample {

    public static void main(String[] args) {

        // Creating a Scanner object attached to System.in
        Scanner scanner = new Scanner(System.in);

        // Input an integer
        System.out.print("Enter an integer: ");
        int num = scanner.nextInt();

        // Input a float
        System.out.print("Enter a float: ");
        float fnum = scanner.nextFloat();

        // Consume the newline character left by nextFloat()
        scanner.nextLine(); // needed because nextFloat() does not consume the newline character

        // Input a string
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        // Display inputs
        System.out.println("You entered:");
        System.out.println("Integer: " + num);
        System.out.println("Float: " + fnum);
        System.out.println("String: " + input);

        // Closing the scanner
        scanner.close();
    }

}

Sample Output

Enter an integer: 5
Enter a float: 5.5
Enter a string: hello
You entered:
Integer: 5
Float: 5.5
String: hello

There are other methods to input values in Java. Here is a table that sums up the remaining for you.

Data TypeInput Method
booleannextBoolean()
bytenextByte()
doublenextDouble()
floatnextFloat()
IntnextInt()
StringnextString()
LongnextLine()
shortnextShort()

Conclusion

To sum up, you have studied how the system.in with Scanner class is used to take input from the user. Also, how the System.out.print() and System.out.println() are used to display data on the console. Combining them results in a user-friendly and interactive applications as an end product.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top