Passing Scanner Object as a Parameter in Java

There are different ways to input data from the user using Scanner Class. Every time when we need input from the user a Scanner object is declared. Sometimes there is a possibility of getting a restriction on the number of objects that can be created. So we may not get a chance to create another object in order to input data from the user. In such a situation, we can pass a Scanner object that is already created as a parameter to the method where you need to input the data. The below code helps you to get a clear idea about it!

Example Code:

Java




import java.util.*;
  
public class Sample {
    public void examplemethod(Scanner sc)
    {
        System.out.println("What is your name? ");
        String name = sc.next();
        System.out.println("Your name is " + name + "!");
    }
    public static void main(String args[])
        throws IOException
    {
        // Instantiating the Scanner class
        Scanner sc = new Scanner(System.in);
        Sample ob = new Sample();
        // Calling the method and
        // Passing the Scanner Object
        ob.examplemethod(sc);
    }
}
// Contributed by PL VISHNUPPRIYAN


Output:

What is your name?
VISHNUPPRIYAN
Your name is VISHNUPPRIYAN!