Passing Scanner Object as a Parameter in Java
Last Updated :
30 Dec, 2022
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
{
Scanner sc = new Scanner(System.in);
Sample ob = new Sample();
ob.examplemethod(sc);
}
}
|
Output:
What is your name?
VISHNUPPRIYAN
Your name is VISHNUPPRIYAN!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...