+ 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".

15th Jan 2018, 8:56 AM
šŸ¦‹FEATHERšŸ¦‹
šŸ¦‹FEATHERšŸ¦‹ - avatar
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
15th Jan 2018, 9:07 AM
777
777 - avatar
+ 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.
15th Jan 2018, 9:03 AM
Dev
Dev - avatar
+ 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!
15th Jan 2018, 9:14 AM
Dev
Dev - avatar
+ 8
@Ethan here, new allocates memory for storing 10 integers. You have an array of int data type. Is Scanner a data type? :)
15th Jan 2018, 9:30 AM
Dev
Dev - avatar
+ 6
"new" keyword is used to allocate memory in java
15th Jan 2018, 6:47 PM
Shreya
Shreya - avatar
+ 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();
15th Jan 2018, 10:03 AM
D_Stark
D_Stark - avatar
+ 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.
15th Jan 2018, 9:00 AM
Tarantino
Tarantino - avatar
+ 3
is it possible to use it several time.
15th Jan 2018, 9:05 AM
šŸ¦‹FEATHERšŸ¦‹
šŸ¦‹FEATHERšŸ¦‹ - avatar
+ 2
@Dev why it is use of new in array example :- int a[]=new int[10]; why can't it be like scanner
15th Jan 2018, 9:23 AM
šŸ¦‹FEATHERšŸ¦‹
šŸ¦‹FEATHERšŸ¦‹ - avatar