简体   繁体   中英

How can is initialize all variables in a Java class at once to zero

I have some Java code with class variables and rather than set them to a particular value, I'd just like to initialize everything to zero. In C/C++, I can just do a memset() on the size of the structure, but how do I do the same thing in Java?

Primitives will default to zero. Objects will default to null. See https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html . However, as that article mentions, relying on the default value in Java is considered bad practice. The better practice is to set them all either when you declare them or in the constructor.

All primitive data types default to zero, only objects (and therefore Strings as well) default to null. As long as you do not specify a value, all int, long, float, double etc. are 0 / 0.0 and all object and string variables are null.

Java initializes everything to 0 and null. But you should do this in constructor yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM