Home > Java > javaTutorial > What is the usage of new in java

What is the usage of new in java

王林
Release: 2020-05-25 10:44:47
Original
12872 people have browsed it

What is the usage of new in java

1. Use new to input data - instantiate the object and create memory

Example:

Scanner reader = new Scanner(System.in);
Copy after login

Scanner is A class, reader is a Scanner object created, new creates this instance and assigns variables to it.

Input basic type data: nextBoolean(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble().

The usage is:

Scanner reader = new Scanner(System.in);//先创建对象
Copy after login

Then use

int x = reader.nextInt();
Copy after login

(Video tutorial recommendation: java video)

2. Allocate elements to the array

1. Declare the array

One-dimensional array: int a[] or int [] a; declare multiple at one time, int a[ ], b[] or int [] a, b;

Two-dimensional array: int a[][] or int [][] a; declare multiple at one time, int a[][], b [][] ;

Note: Java does not allow specifying the number of array elements within square brackets in the array declaration!

2. Allocate elements to the array

Array name = new array element type [number of elements];

For example: boy = new float [4]; (Prerequisite is that you have declared a float type boy variable! You can also declare and create it at the same time, for example: float boy = new float [4];)

Java allows you to use the value of an int type variable to specify the elements of an array. number. For example:

int size = 30;

double number = new double[size];

3. Use of length

For one-dimensional arrays, The value of "array name.length" is the number of elements in the array. For a two-dimensional array, the value of "array name.length" is the number of one-dimensional arrays it contains.

Recommended tutorial: Getting started with java development

The above is the detailed content of What is the usage of new in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template