Skip to content
Related Articles
Open in App
Not now

Related Articles

Passing Scanner Object as a Parameter in Java

Improve Article
Save Article
  • Last Updated : 30 Dec, 2022
Improve Article
Save 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:


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


What is your name?
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!