+ 6
What's is the use of "new" in Java
why we write "new" . example :- Scanner sc= new Scanner (System.in); can we use it for several time . What is the use of making "new".
9 Answers
+ 12
Using 'new' you create an instance of the Scanner class, which is further used to scan user inputs ( in your case )
To make multiple instances of a class, you can use new several times
+ 11
TheĀ newĀ operator creates an object by allocating memory for a new object and returning a reference to that memory. It also invokes the object constructor.
In your example, Scanner is a class in the java.util package and you create "sc" (object) of that class. The new operator obtains the memory for it.
+ 10
@Ethan Once you create an object, you can use it as many times as you want (within it's scope). For example:
Scanner sc = new Scanner(System.in);
System.out.print(sc.nextLine());
System.out.print(sc.nextInt());
You can create different objects, too. Though it's unnecessary with the Scanner class!
+ 8
@Ethan here, new allocates memory for storing 10 integers. You have an array of int data type. Is Scanner a data type? :)
+ 6
"new" keyword is used to allocate memory in java
+ 5
The "new" keyword creates an object of class so basically you have just created a object of class Scanner which you can use multiple times without having to create another like so..
Scanner scn = new Scanner(System.in);
int interger = scn.nextInt();
String str = scan.nextLine();
+ 3
You are creating a new instance of that class e.g. an object.
You are telling the class that you want an object to be created in a certain way via the parameters ( if it has any)
In this case you are saying create an object of the Scanner class that can be used for receiving input from the keyboard (System.in).
You can create as many objects of you like but some things may only need one instance but can be used in several ways such the Scanner class or the Random class.
+ 3
is it possible to use it several time.
+ 2
@Dev why it is use of new in array
example :- int a[]=new int[10];
why can't it be like scanner