Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Passing Scanner Object as a Parameter in Java

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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!
My Personal Notes arrow_drop_up
Last Updated : 30 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials