Primitive Data Types

suggest change

Introduction

The 8 primitive data types byte, short, int, long, char, boolean, float, and double are the types that store most raw numerical data in Java programs.

Syntax

Remarks

Java has 8 primitive data types, namely boolean, byte, short, char, int, long, float and double. (All other types are reference types. This includes all array types, and built-in object types / classes that have special significance in the Java language; e.g. String, Class and Throwable and its subclasses.)

The result of all operations (addition, subtraction, multiplication, etc) on a primitive type is at least an int, thus adding a short to a short produces an int, as does adding a byte to a byte, or a char to a char. If you want to assign the result of that back to a value of the same type, you must cast it. e.g.

byte a = 1;
byte b = 2;
byte c = (byte) (a + b);

Not casting the operation will result in a compile error.

This is due to the following part of the Java Language Spec, §2.11.1:

A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. [..]. Thus, most operations on values of actual types boolean, byte, char, and short are correctly performed by instructions operating on values of computational type int.

The reason behind this is also specified in that section:

Given the Java Virtual Machine’s one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine’s run-time data types, there would be more instructions than could be represented in a byte. […] Separate instructions can be used to convert between unsupported and supported data types as necessary.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Primitive Data Types:
* Primitive Data Types

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
26 Primitive Data Types
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap