Java object array Initialization Method

Source: Internet
Author: User

The problem is as follows:

 
Class filestruct {int intpara; filestruct () {intpara = 0;} public void setintpara (int I) {intpara = I;} public int getintpara () {return intpara ;}} class read {public void main (string [] ARGs) {filestruct [] FS = new filestruct [10]; for (INT I = 0; I <10; I ++) system. out. println (FS [I]. getintpara );}

In this caseProgramWill throw an exception: Java. Lang. nullpointerexception

There are two errors in the above program: 1. the initialization of the array is not over 2. In the filestruct class, the constructor function is not released to the public.

Cause of error: 1. When initializing non-basic data in Java, new must be used. After using new to create an array, the array is still a reference array. Only after a new object is created and the object is assigned to the array for reference, initialization ends.

2. If the new object is used in the above program to assign values to the array reference, an exception will still be thrown: the constructor filestruct () is not visible

Based on this, the above procedures should be changed:

 
Class filestruct {int intpara; Public filestruct () {intpara = 0;} public void setintpara (int I) {intpara = I;} public int getintpara () {return intpara ;}} class read {public void main (string [] ARGs) {filestruct [] FS = new filestruct [10]; for (Int J = 0; j <10; j ++) FS [J] = new filestruct (); For (INT I = 0; I <10; I ++) system. out. println (FS [I]. getintpara );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.