×

Scanner in Java

Static way of Programming:

When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a value.

Program:

Import java.io.*;
class  A
{
  public static void main(String s[])
 {
    int var1=1;
// Here “var1” assigned to 1.
  System. out. print ln (“var1 = “+var1);
}
}

Input:

1

Output:

var1=1

Note: The above program is about considering static values of variables in programming.

To access input from the user or to access dynamic values of variables from the keyboard we use the Scanner class or BufferReader class.

Scanner class:

  • It is used to read input from the keyboard.
  • java. Util package contains Scanner class.
  • We should create an object for the scanner class.

The syntax for the Creation of an Object:

Classname objectname = new Classname();

To access variables of instance variables or instance methods we should create classes.

new: It is used to allocate memory in the heap area.

Constructor:

Classname() is a constructor used to initialize the instance variables before creating objects. If a constructor is not available in class then the java compiler provides the default constructor.

Note: These created objects are allocated memory in the heap area.

The object for Scanner:

  • Scanner object -new Scanner()
  • Scanner class  – Classname.
  • Object – object name for the created object.
  • Scanner() – Constructor.

To use the scanner class in java. We have to import the package java. util.

The syntax for Importing Package:

import package_name;

For example,

import java. util.Scanner;

Note: The above line of code indicates java. util package providing scanner class in the program.

For example,

import java. util.*;

Note: The above line of code indicates java. util.* package providing all classes and methods in the program.

Methods to take Input:

  • nextByte()
  • nextShort()
  • nextInt()
  • nextLong()
  • nextFloat()
  • nextDouble()
  • nextBoolean()
  • next()
  • nextLine()

nextByte():

  • It is used to read byte values from keyboard or user.
  • Size of byte is 8 bits or 1 byte.
  • Byte value range lies between -2^7 to 2^7 -1;

     Program:

import java.io.*;
      import java.util.*;
     Class B
     {
        public static void main(String s[])
         {
           Scanner obj1 = new Scanner(System.in);
            Byte var1= obj1.nextByte();
             System.out.prinln(“var1=”+var1);
           }
        }

Input:

2

Output:

Var1=2

Note: If the value is more than 127 or less than -128 then it shows an error-like value out of range.

next short():

  • It is used to read short values from the keyboard.
  • Size of short is 2 bytes.
  • Short value range lies between -2^15 to 2^15 -1.

Program:

import java.io.*;
import java.util.*;
class C
{
public static void main(String s[])
{     
Scanner obj1 = new Scanner(System.in);
short a=obj1.nextShort();
}
}

Input:

345

Output:

a=345

nextInt():

  • It is used to read Integer values from the keyboard.
  • Size of Integer is 2 bytes.
  • Integer value range lies between -2^31 to 2^31 -1.

Program:

import java.io.*;
import java.util.*;
class C
{
     public static void main(String args[])
     {
       Scanner obj1= new Scanner();
       Int a = obj1.nextInt();
       System . out . println(“a=”+a);
  }
}

Input:

567

Output:

a=567

nextLong():

  • It is used to read long values from the keyboard.
  • Size of long is 8 bytes.
  • Long value range lies between 2^63 to 2^63 -1.

Program:

import java.io.*;
import java.util.*;
class D
{
  public static void main(String s[])
    {
      Scanner obj1=new Scanner(System.in);
      long var1=sc.nextLong();
      System.out.println(“var1=”+var1);
}
}

Input:

10888888898

Output:

Var1=108888898

nextFloat():

  • It is used to read float values from the keyboard.
  • Size of the float is 4 bytes.

Program:

import java.io.*;
import java.util.*;
class E
{
public static void main(String s[])
 {
Scanner obj1= new Scanner(System.in);
float var1=obj1.nextFloat();
System.out.println(“var1=”+a);
}
}

Input:

2.55

Output:

Var1=2.55

nextDouble():

  • It is used to read double values from the user.
  • Size of double is 8 bytes.

Program:

import java.io.*;
import java.util.*;
class F
{
public static void main(String s[])
  {
Scanner obj1 = new Scanner(System.in);
Double var1 = obj1.nextDouble();
  System.out.println(“var1=”+var1);
}
}

Input:

34.55

Output:

Var1=34.55

nextBoolean(): It is used to read Boolean values from the keyboard i.e, true or false.Size of Boolean is 1 bit.

Program:

import java.io.*;
import java.util.*;
class G
{
public static void main(String s[])
{
Scanner obj1 = new Scanner(System.in);
boolean flag=obj1.nextBoolean();
System.out.println(“flag=”+aflag):
}
}

Input:

true

Output:

flag=true

next(): It is used to read strings from the keyboard.

Program:

import java.io.*;
import java.util.*;
class Str
{
public static void main(String s[])
{      
Scanner obj1= new Scanner(System.in);
 String s=obj1.next();
System.out.println(“s=”+s);
}
}

Input:

Java

Output:

S=Java

nextLine(): It is used to read an entire line from the keyboard.

Program:

import java.io.*;
import java.util.*;
class Str1
{
public static void main(String s[])
{
Scanner obj1 = new Scanner(System.in);
String s=obj1.nextLine();
System.out.println(“s=”+s);
}
}

Input:

Java Programming

Output:

s=Java Programming

Related Topics

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.