Basic Input and Output in Java

Java output and input play a crucial role in creating interactive programs. Java provides several mechanisms to capture user input and display output, allowing your programs to communicate with users effectively. In this tutorial, we will explore how to obtain user input and perform output operations in Java.



Basic Output in Java

In Java, displaying output to the screen is a fundamental aspect of programming. There are several ways to achieve this, such as using System.out.println(), System.out.print(), or System.out.printf() methods. All these methods come from out object from System class in Java. These methods allow you to send output to the standard output, which is typically the screen.

When you use System.out.println(), it prints the string inside the parentheses and automatically moves the cursor to the beginning of the next line. On the other hand, System.out.print() prints the string without moving the cursor to a new line, allowing subsequent output to appear on the same line.

 

To demonstrate this, consider the following example:

 

class PrintExamples {

    public static void main(String[] args) {

              

               System.out.println("Hello, Java!"); // Output with a line break

               System.out.print("Welcome "); // Output without a line break

               System.out.print("to "); // Output without a line break

               System.out.println("the world of Java!"); // Output with a line break

    }

}

 

When you run this program, the output will be:

Hello, Java!

Welcome to the world of Java!

As you can see, the println() method prints the strings inside the quotes on separate lines, while the print() method prints them on the same line.

 

Furthermore, you can use the + operator to concatenate strings and display them together. For example:

class StringConcatenation {

    public static void main(String[] args) {

              

               int age = 25;

               double salary = 5000.0;

              

               System.out.println("Employee Details:");

               System.out.println("Name: John Doe");

               System.out.println("Age: " + age);

               System.out.println("Salary: $" + salary);

    }

}

 

When you run this program, the output will be:

Employee Details:

Name: John Doe

Age: 25

Salary: $5000.0

 

In the above example, the + operator is used to concatenate strings and variables. The value of the age variable is automatically converted to a string, allowing it to be appended to the output string. In the example above, the value of the number variable is evaluated first. Since its value is of type double, the compiler automatically converts it to a string. Then, the strings are concatenated using the + operator.

It's important to note that when displaying integers, variables, or other non-string values, you should not enclose them in quotation marks. The compiler will handle the conversion and formatting accordingly.

Understanding these output techniques allows you to effectively display information to the user and create more dynamic and interactive Java programs.


Formatting output in Java

When it comes to formatting output in Java using System.out.printf(), you have the flexibility to control the appearance of your output by specifying format specifiers. Format specifiers are placeholders that define how different data types should be displayed. Let's explore the common format specifiers and their usage:

  1. %d - Integer:
    • Use %d to represent integer values in the output.
    • For example, System.out.printf("Count: %d", count); will display the value of the count variable as an integer.
  2. %f - Floating-Point:
    • %f is used to format floating-point numbers.
    • For instance, System.out.printf("Price: %.2f", price); will display the price variable with two decimal places.
  3. %s - String:
    • Use %s to format string values.
    • For example, System.out.printf("Name: %s", name); will display the name variable as a string.
  4. %c - Character:
    • %c is used to format single characters.
    • For instance, System.out.printf("First initial: %c", initial); will display the initial variable as a character.
  5. %b - Boolean:
    • %b is used to format boolean values.
    • For example, System.out.printf("Is valid: %b", isValid); will display the isValid variable as a boolean value (either true or false).
  6. %e - Scientific Notation:
    • %e is used to display numbers in scientific notation.
    • For instance, System.out.printf("Scientific notation: %e", value); will display the value variable in scientific notation.


These are just a few examples of format specifiers, but there are many more available to cater to specific formatting requirements. Additionally, you can combine format specifiers with additional formatting options, such as width, precision, and alignment, to further customize the output.

Here's an example demonstrating multiple format specifiers and additional formatting options:

 

class FormattedOutput {

    public static void main(String[] args) {

              

               String name = "Alice";

               int score = 95;

              

               System.out.printf("Student Name: %s\n", name);

               System.out.printf("Score: %d\n", score);

               System.out.printf("Percentage: %.2f%%\n", (score / 100.0) * 100);

    }

}

 

When you run this program, the output will be:

Student Name: Alice

Score: 95

Percentage: 95.00%

In this example, System.out.printf() is used for formatted output. The %s is a placeholder for the name variable, %d for the score variable, and %.2f for the calculated percentage. The format specifier %d is used for integers, %s for strings, and %.2f for floating-point numbers with two decimal places.

 

User Input in Java

In the dynamic world of Java programming, user interaction is key to creating engaging and interactive applications. Fortunately, Java provides various methods to gather input from users. In this section, we will explore the power of user input using the Scanner object. Prepare yourself for an exciting journey into the world of user input in Java!


The Scanner Class

1.1 Importing the Scanner Class: To begin our quest for user input, we must first import the Scanner class into our Java program. By including the following line at the beginning of your code, you unlock a world of input possibilities:

 

import java.util.Scanner;


Creating the Scanner Object

Once we have imported the Scanner class, it's time to create an instance of the Scanner object. This object acts as our trusty companion, helping us capture input from the user. Let's summon the Scanner object by adding the following line to our code:

 

import java.util.Scanner;

Let us take an interger from user to understand the game of user input with the help Scanner class.

 

class UserInput {

    public static void main(String[] args) {

              

               Scanner input = new Scanner(System.in);

              

               System.out.print("Enter an integer: ");

               int number = input.nextInt();

               System.out.println("You entered: " + number);

    }

}

 

As we run this program, an intriguing prompt awaits us:

Enter an integer: 23

Ah, the magic of user input! The moment you enter the number 23 and press enter, our program captures your input using the Scanner object, a versatile tool for gathering information from the user.

But remember, user input is not limited to integers alone. The Scanner class offers a lot of methods to capture various data types, such as strings, doubles, and more. With each new input, a world of possibilities unfolds before us.


Input Types in Java

In the previous example, we demonstrated how to capture user input as a string using the nextLine() method. But did you know that the Scanner class offers a multitude of methods to capture different data types? Prepare to dive into the world of input types as we explore the treasures that await you. Refer to the following table for a glimpse into the diverse input methods available:

 

Method

Description

nextBoolean(  )

Takes a boolean value from the user

nextByte( )

Takes a byte value from the user

nextDouble( )

Takes a double value from the user

nextFloat( )

Takes a float value from the user

nextInt( )

Takes a int value from the user

nextLine( )

Takes a String value from the user

nextLong( )

Takes a long value from the user

nextShort( )

Takes a short value from the user

 

Let us understand these methods with the help of following example:

 

import java.util.Scanner;

class UserInput {

    public static void main(String[] args) {

              

               Scanner scanner = new Scanner(System.in);

              

               // Obtaining float input

               System.out.print("Enter a decimal number: ");

               float decimalNumber = scanner.nextFloat();

               System.out.println("Input received: " + decimalNumber);

              

               // Obtaining double input

               System.out.print("Enter a large decimal number: ");

               double largeDecimalNumber = scanner.nextDouble();

               System.out.println("Input received: " + largeDecimalNumber);

              

               // Obtaining String input

               System.out.print("Enter a word: ");

               String word = scanner.next();

               System.out.println("Input received: " + word);

    }

}


This program showcases the power of capturing user input in a simple yet captivating way.  As you run the program, it eagerly awaits your input. You will have the opportunity to provide a decimal number, a large decimal number, and even a word.

 

Enter a decimal number: 5.64

You entered: 5.64

Enter a large decimal number: -23.4

You entered: -23.4

Enter a word: Hey!

You entered: Hey!


Practice Programs on Java Input and Output

 

1.      Write a Java program that inputs two numbers from user and print their quotient and remainder on screen.

 

import java.util.Scanner;

public class QuotientAndRemainder {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter the first number: ");

        int number1 = scanner.nextInt();

 

        System.out.print("Enter the second number: ");

        int number2 = scanner.nextInt();

 

        int quotient = number1 / number2;

        int remainder = number1 % number2;

 

        System.out.println("Quotient: " + quotient);

        System.out.println("Remainder: " + remainder);

 

        scanner.close();

    }

}

 

Explanation:

1.      We start by importing the java.util.Scanner class to read user input.

2.      In the main method, we create an instance of the Scanner class to read input from the console.

3.      The program prompts the user to enter the first number, reads it using nextInt(), and stores it in the number1 variable.

4.      Similarly, the program prompts the user to enter the second number, reads it using nextInt(), and stores it in the number2 variable.

5.      We calculate the quotient by dividing number1 by number2 using the division operator / and store it in the quotient variable.

6.      We calculate the remainder by using the modulus operator % on number1 and number2 and store it in the remainder variable.

7.      Finally, we print the quotient and remainder on the screen using System.out.println().

Sample Output:

plz enter first num = 5.0

plz enter second num = 2.0

Quotient = 2.5

Remiander = 1.0

 

2.      Write a Java program that inputs base and height of triangle from user and display area of triangle.

Hint: area = 1/2 x base x height

 

import java.util.Scanner;

public class TriangleArea {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter the base of the triangle: ");

        double base = scanner.nextDouble();

 

        System.out.print("Enter the height of the triangle: ");

        double height = scanner.nextDouble();

 

        double area = 0.5 * base * height;

 

        System.out.println("The area of the triangle is: " + area);

 

        scanner.close();

    }

}

 

Explanation:

 

1.      We start by importing the java.util.Scanner class to read user input.

2.      In the main method, we create an instance of the Scanner class to read input from the console.

3.      The program prompts the user to enter the base of the triangle, reads it using nextDouble(), and stores it in the base variable.

4.      Similarly, the program prompts the user to enter the height of the triangle, reads it using nextDouble(), and stores it in the height variable.

5.      We calculate the area of the triangle using the formula: area = 0.5 * base * height and store it in the area variable.

6.      Finally, we print the area of the triangle on the screen using System.out.println().

Now, when you run the program, it will ask you to enter the base and height of the triangle. After you provide the input, it will calculate the area of the triangle using the formula and display the result on the screen.

 

Sample Output:

Please enter base of triangle = 8.2

Please enter height of triangle = 5.2

Area of triangle = 21.32

 

3.      Write a Java program that converts a person height from inches to centimeter using formula 2.5 * height.

 

import java.util.Scanner;

public class HeightConverter {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.print("Enter the height in inches: ");

        double heightInInches = scanner.nextDouble();

 

        double heightInCentimeters = 2.54 * heightInInches;

 

        System.out.println("The height in centimeters is: " + heightInCentimeters);

 

        scanner.close();

    }

}

 

Explanation:

1.      We start by importing the java.util.Scanner class to read user input.

2.      In the main method, we create an instance of the Scanner class to read input from the console.

3.      The program prompts the user to enter the height in inches, reads it using nextDouble(), and stores it in the heightInInches variable.

4.      We calculate the height in centimeters by multiplying the heightInInches with the conversion factor 2.54 and store it in the heightInCentimeters variable.

5.      Finally, we print the height in centimeters on the screen using System.out.println().

Now, when you run the program, it will ask you to enter the height in inches. After you provide the input, it will calculate the equivalent height in centimeters using the given formula and display the result on the screen.

Sample Output

Please enter inches = 20

Height in centimeter = 50.0


By leveraging user input and output operations in your Java programs, you can create engaging and interactive applications that cater to user interactions and provide valuable feedback. Experiment with different input techniques, format your output for clarity and unlock the power of user-driven experiences in your Java projects. This article is a part of Java series.
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !