Taking Input and Printing Output
Site Admin
· 11 Sep 2026
· 10 views
Printing Output
System.out.println("one line"); // prints then moves to new line
System.out.print("same line "); // prints without new line
System.out.printf("Age: %d, Score: %.2f%n", 21, 87.5); // formattedThe format specifiers used in printf:
%dinteger,%fdecimal number,%sstring,%nnew line.
Reading Input with Scanner
import java.util.Scanner;
public class InputDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("Hello " + name + ", you are " + age);
sc.close();
}
}Common Scanner Methods
nextLine()- reads a whole line as a String.next()- reads the next word.nextInt(),nextDouble()- read numbers.hasNextInt()- checks whether the next token is an integer.
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
int number = sc.nextInt();
System.out.println("You entered " + number);
}
printlnadds a new line,printdoes not,printfformats.Scanner(System.in)is the standard way to read console input.- Call
close()on the scanner when done.