Java Arrays Tutorial (3)

Java Arrays Tutorial (3)

Data types have a specific set of values. A byte cannot hold a value larger than 127 and an int cannot hold a value larger than 2,147,483,647. You can also create your own data types that have a finite set of legal values. A programmer created data type with a fixed set of values is an enumerated data type.

In Java, you create an enumerated data type in a statement that uses the keyword enum, an identifier for the type, and a pair of curly braces that contain a list of the enum constants, which are the allowed values for the type. For example, the following code creates an enumerated type named Month that contains 12 values:

Enum Month{JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};

After you create an enumerated data type, you can declare variables of that type. For example, you might declare the following:

Month birthMonth;

You can assign any of the enum constants to the variables. Therefore, you can code a statement such as the following:

birthMonth = Month.MAY;

An enumeration type like Month is a class, and its enum constants act like instantiated from the class, including having access to the methods of the class.

Creating an enumeration type provides you with several advantages:

(1). If you did not create an enumerated type for month values, you could use another type, for example, ints or Strings. The problem is that any value could be assigned to an int or String variable, but only the 12 allowed values can be assigned to a Month.

(2). If you did not create an enumerated type for month values, you could create another type to represent months, but invalid behavior could be applied to the values. For example, you could add or substract two months, which is not logical. Programmers say using enums makes the values type-safe. Type-safe describes a data type for which only appropriate behaviors are allowed.

(3). The enum constants provide a form of self-documentation. Someone reading your program might misinterpret what 9 means as a month value, but there is less confusion when you use the identifier OCT.

(3). As with other classes, you can also add methods and other fields to an enum type.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值