Basic Input and Output in Java

Input in Java :

When we have to take input of any data type we must import a Java package java.util.Scanner. 

import java.util.Scanner;

This package contains a class Scanner, by creating an object of class Scanner input from the user can be taken.

Code:

Java Code

class Main {
  public static void main(String args[]) {

    // creating an object of Scanner class
    Scanner input = new Scanner(System.in);

    int number = input.nextInt(); // taking input from user
  }
}

Taking input of different Data types :

  • Integer input 

Java Code

import java.util.Scanner;

class Main {
	public static void main(String args[]) {
		
	// creating an object of Scanner class
	Scanner input = new Scanner(System.in);

	int n = input.nextInt(); // taking input from user
	
	System.out.println(n);
	}
}

Input: 9

Output: 9

  • Float input:

Java Code

import java.util.Scanner;

class Main {
	public static void main(String args[]) {
		
	// creating an object of Scanner class
	Scanner input = new Scanner(System.in);

	float n = input.nextFloat(); // taking input from user
	System.out.println(n);
	}
}

Input: 9.121

Output: 9.121

  • Double input :

Java Code

import java.util.Scanner;

class Main {
	public static void main(String args[]) {
		
	// creating an object of Scanner class
	Scanner input = new Scanner(System.in);

	double n = input.nextDouble(); // taking input from user
	System.out.println(n);
	}
}

Input: 9.2121

Output: 9.2121

  • String input :

Java Code

import java.util.Scanner;

class Main {
	public static void main(String args[]) {
		
	// creating an object of Scanner class
	Scanner input = new Scanner(System.in);

	String str = input.next(); // taking input from user
	System.out.println(str);
	}
}

Input: Takeuforward

Output: Takeuforward

Output in Java :

There are two ways in which we can display output to users.

System.out.println();
System.out.print();

System is a class, out is a public static field that accepts output data.

  • When you have to display another output on the next line use. It is like pressing enter after you output something.
System.out.println();

Java Code

import java.util.Scanner;

class Main {
  public static void main(String args[]) {

    System.out.println("Takeuforward");

  }
}
  • When you don’t want the cursor to move to the next line. The next print statement prints output on the same line.
System.out.print();

Java Code

import java.util.Scanner;

class Main {
  public static void main(String args[]) {

    System.out.print("Takeuforward");

  }
}

Special thanks to Rushikesh Aadav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article