Data Types (or simply Types) in Java are a way of telling what certain data is. It is seen as a way of declaring allowed values for certain data, the structure of such data and operations associated with it. Any data, be it numeric or a sentence of words, can have a different data type. For instance, just to define different types of numbers in Java, there are about six simple types available to programmers – some define whole numbers (integers numbers) and others define numbers with a decimal values (floating point numbers). Java also gives freedom to programmers to create complex and customizable data types. We will deal with complex data types in later chapters.
Java is considered a strongly typed programming language in that it is obligatory for all data, expressions and declarations within the code to have a certain type associated with it. This is either declared or inferred and the Java language only allows programs to run if they adhere to type constraints.
As we have discussed above, you can have types that define a number, or types that define textual content within your program. If you present a numeric type with data that is not numeric, say textual content, then such declarations would violate Java’s type system. This gives Java the unique ability of type safety. Java checks if an expression or data is encountered with an incorrect type or none at all. It then automatically flags this occurrence as an error at compile time. Most type-related errors are caught by the Java compiler, hence making a program more secure and safe once compiled completely and successfully.
In the Java language, there are three broad categories of data types:
- Primitives
- Object Reference Types
- Arrays
In the following section, we will discuss these three categories in detail.
Primitives
Primitives are the most basic data types available within the Java language. These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose – containing pure, simple values of a kind. Because these data types are defined into the Java type system by default, they come with a number of operations predefined. You can not define a new operation for such primitive types. In the Java type system, there are three further categories of primitives:
- Numeric PrimitivesThese primitive data types hold only numeric data. Operations associated with such data types are those of simple arithmetic (addition, subtration, etc.) or of comparions (is greater than, is equal to, etc.)
- Textual PrimitivesThese primitive data types hold characters (which can be alphabets or even numbers), but unlike numbers, they do not have operations that serve arithmetic purposes. Rather, operations associated with such types are those of textual manipulation (comparing two words, joining characters to make words, etc.)
- Boolean and Null Primitives
About Java Types
some type errors can still occur at runtime because Java supports a cast operation which is a way of changing the type of one expression to another. However, Java performs run time type checking when doing such casts, so an incorrect type cast will cause a runtime exception rather than succeeding silently and allowing data corruption.
Java is also known as a hybrid language. While supporting object oriented (OO) programming, Java is not a pure OO language like Smalltalk or Ruby. Instead, Java offers both object types and primitive types. Primitive types are used for boolean, character, and numeric values and operations. This allows relatively good performance when manipulating numeric data, at the expense of flexibility. For example, you cannot subclass the primitive types and add new operations to them.
Examples of Types
Below are two examples of Java types and a brief description of the allowed values and operations for these types. Additional details on each are available in other modules.
Example: int
The primitive type
int
represents a signed 32 bit integer value. The allowed data values for int
are the integers between -2147483648 to 2147483647 inclusive.The set of operations that may be performed on
int
values includes integer arithmetic such as +, -, *, /, %
, comparison operations (==, !=, <, >, <=, >=
), assignments (=, ++, --, +=, -=
), bit-wise operations such as logical and, logical or, logical xor, negation (&, |, ^, ~
), bit shift operations (<<, >>, >>>
), conversions to other numeric types and promotion to other integer types.For example, to declare a
private
integer instance field named length
, one would use the declarationprivate int length;
Example: String
You use
class
and interface
definition in Java to define new types. Class and interface types are associated with object references also sometime refered to as Reference types. An object reference has two main attributes:- Its type associated with a class or an interface
- A java object it references, that is created by instantiating a class
The
String
class is one such example. String values are a sequence of 0 or more Unicode characters. The null
reference is another valid value for a String expression.The operations on a String reference variable are those available for all reference types, such as comparison operations
==, !=
and assignment =
.The allowed operations on String object, however are the set of methods in the
java.lang.String
class, which includes length()
, toString()
, toLowerCase()
, toUpperCase()
,compareTo(String anotherString)
and more... .In addition, String objects also inherit the set of operations from the base class that String extends from, which is
java.lang.Object
. These operations include methods such as equals()
,hashCode()
, wait()
, notifyAll()
, and getClass()
.private
String
name = "Dehan Vithana";
In the above example the name object reference's attributes are:
- Type is :
String
- The referenced object is also :
String
Both the
java.lang.String
class methods and java.lang.Object
class methods are available for the object reference name.private
Object
name = "Dehan VIthana";
In the above example the name object reference's attributes are:
- Type is :
Object
- The referenced object is :
String
Only the
java.lang.Object
class methods are available for the object reference name.Array Types
Arrays in Java are represented as a built-in Array object. As with object types, they behave as a reference but have a few differences allowing them to allow easy access to sub elements.
When one declares an array, the data type is changed to include square brackets. (While you can instead place these square brackets next to the variable name, this is not recommended.) To create an array, you will need to use the new operator to have it create the Array with the specified number of elements:
/* Declares an array named data1, and has it assigned to an array with 25 elements. */
private int[] data1 = new int[25];
/* Declares an array named data2 that contains these three elements. */
private int[] data2 = new int[] { 1, 99, -2 }
Arrays are described in more detail in the Arrays section.
Primitive Data Types
The Java primitive data types contain pure values, no operations. It is basically data types similar to what other non-object-oriented languages have.
There are arrays of primitive types in Java; but because they are not objects, primitive values can not be put in a collection.
For this reason object wrappers are defined in JDK 'java.lang.*' package for all the primitive types.
Size (bits) | Example | Minimum Value | Maximum Value | Wrapper Class | |
---|---|---|---|---|---|
Integer types | |||||
byte | 8 | byte b = 65; | -128 | 127 | Byte |
char | 16 | char c = 'A'; char c = 65; | 0 | 216-1 | Character |
short | 16 | short s = 65; | -215 | 215-1 | Short |
int | 32 | int i = 65; | -231 | 231-1 | Integer |
long | 64 | long l = 65L; | -263 | 263-1 | Long |
Floating-point types | |||||
float | 32 | float f = 65f; | Float | ||
double | 64 | double d = 65.55; | Double | ||
Other | |||||
boolean | 1 | boolean b = true; | -- | -- | Boolean |
void | -- | -- | -- | -- | Void |
The types
short
, int
, long
, float
, and double
are usually used in arithmetic operations; byte
and char
can also be used, but less commonly.The character type
char
is used for text processing. The type byte
is commonly used in binary file input output operations.String
objects representing literal character strings in Java, in the java.lang.* package. java.lang.String is not a primitive type, but instead is a special class built into the Java language. For further info, see String
.Data Conversion (Casting)
Data conversion (casting) can happen between two primitive types. There are two kinds:
- Implicit : casting operation is not required; the magnitude of the numeric value is always preserved. However, precision may be lost when converting from integer to floating point types
- Explicit : casting operation required; the magnitude of the numeric value may not be preserved
Example for implicit casting:
int
i = 65;
long
l = i; // --- int is converted to long, casting is not needed
Example for explicit casting:
long
l = 656666L;
int
i = (int
) l; // --- long is converted to int, casting is needed
The following table shows the conversions between primitive types, it shows the casting operation for explicit conversions:
from byte | from char | from short | from int | from long | from float | from double | from boolean | |
---|---|---|---|---|---|---|---|---|
to byte | - | (byte) | (byte) | (byte) | (byte) | (byte) | (byte) | N/A |
to char | - | (char) | (char) | (char) | (char) | (char) | N/A | |
to short | (short) | - | (short) | (short) | (short) | (short) | N/A | |
to int | - | (int) | (int) | (int) | N/A | |||
to long | - | (long) | (long) | N/A | ||||
to float | - | (float) | N/A | |||||
to double | - | N/A | ||||||
to boolean | N/A | N/A | N/A | N/A | N/A | N/A | N/A | - |
Autoboxing/unboxing
- Autoboxing/unboxing
- Autoboxing and unboxing, language features since Java 1.5, make the programmer's life much easier when it comes to working with the primitive wrapper types. Consider this code fragment:
int
age = 23;
Integer ageObject = new Integer(age);
Primitive wrapper objects were Java's way of allowing one to treat primitive data types as though they were objects. Consequently, one was expected to 'wrap' one's primitive data type with the corresponding primitive wrapper object, as shown above.
- Autoboxing
- Since Java 1.5, one may write as below and the compiler will automatically create the wrap object. The extra step of wrapping the primitive is no longer required. It has been 'automatically boxed up' on your behalf.
int
age = 23;
Integer ageObject = age;
- Unboxing
- Uses the same process in reverse. Study the following code for a moment. The
if
statement requires aboolean
primitive value, yet it was given a Boolean wrapper object. No problem! Java 1.5 will automatically 'unbox' this.
Boolean canMove = new Boolean(true);
if ( canMove )
{
System.out.println( "This code is legal in Java 1.5" );
}
0 comments:
Post a Comment