Java Data Types: primitive and non-primitive
Java has features for handling data or variable, every data must have a declared type, in this tutorial, we will discuss different types of data, there are two groups of a data type in Java, primitive and non-primitive, and the primitive has subgroups that categorized into different kinds of data type, see the tree diagram below for subgroups and data types:
Table of Contents
Variables
Java variables should have a data type, to declare a variable you must place data type first before the variable name, and after the declaration, the variables should initialize its value before using it, you can never use the value of an uninitialized variable, here is the example error that you will encounter:
public class DataType {
public static void main(String[] args) {
int contactNumber;
System.out.println(contactNumber);
}
}
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The local variable contactNumber may not have been initialized at DataType.main(DataType.java:4)
To avoid the error you must initialize the value:
public class DataType {
public static void main(String[] args) {
int contactNumber = 81234567;
System.out.println(contactNumber);
}
}
Output:
81234567
Naming conventions
Java has naming format for variables which is called camel case, here is the list of sample variables:
String givenName = "John";
int contactNumber = 81234567;
boolean isDeveloper = true;
float weight = 64.2;
Keep reading and you will find out more examples in the other sections.
Integer Data Types
Integer data types are used to declare a numeric variable, there are four types of integer(shown in the table below), each type has its storage size and input range, and a negative input value is allowed.
Java has wrapper class for additional properties of primitive data types, it can be used to apply an extra function to data type, check out the table below for the equivalent wrapper for each data type.
here is the table for the list of integer types with details:
Type | Storage Size | Valid Range | Wrapper Class |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 | Integer |
long | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Long |
short | 2 bytes | -32,768 to 32,767 | Short |
byte | 1 bytes | -128 to 127 | Byte |
int type
int
type is very common or practical data type used for numeric variable, it takes 32 bits of memory, and the default value is 0.
Here is the example int
variable in java, Integer
wrapper class was used to get the maximum and minimum constant value:
public class DataType {
public static void main(String[] args) {
int max_range = Integer.MAX_VALUE;
int min_range = Integer.MIN_VALUE;
System.out.println("max integer: " + max_range);
System.out.println("min integer: " + min_range);
}
}
Output:
max integer: 2147483647
min integer: -2147483648
The other thing you can do in wrapper class is, you can convert the variable to another primitive data type or non-primitive data type, for example:
int intNumber = 23;
Integer wrapInt = intNumber;
System.out.println("Convert integer to double: " + wrapInt.doubleValue());
Output:
Convert integer to double: 23.0
long type
long
is the larger data type of the integer, it takes 64-bit memory, this data type has a suffix upper case L or lower case l, and the default value is 0.
To accept a large amount of value, you must put L
or l
at the end of the number, and if not and the number is larger than int
max value the java will throw exception error, Here is the example long
declaration:
Invalid:
long number = 9223372036854775807;
Valid:
long number1 = 9223372036854775807L;
long number2 = 9223372036854775807l;
long number3 = 100;// less than int maximum value and greater than int minimum value
short type
short
takes 16-bit of memory, it is two times smaller than the int type, if you want to save some memory, you can use this data type but be careful not to exceed the range limit(32,768 to 32,767), which is shown in the table above, and the default value is 0.
Here is the example short declaration:
short number = 32767;
byte type
The byte
is the smaller type in integer data types, it takes 8-bit memory, and the value should not greater than 127 or less than -128.
here is the example byte declaration:
byte number = 127;
Floating-point Data Types
The floating-point refers to the numeric value the has a decimal number, for example, 1.0, 0.23, 0.001, and more, Java fallows the standard of IEEE 754 specification for floating-point computations, and these data types are not suitable for currency computations since there are some problems in decimal round-off computation.
Later in this section, you will find out more why you should not use it for currency.
There are two types of floating point in java which is shown below:
Type | Storage Size | Valid Range | Wrapper Class |
float | 4 bytes | approximately ±3.40282347E+38F (6-7 significant decimal digits) | Float |
double | 8 bytes | approximately ±1.79769313486231570E+308 (15 significant decimal digits) | Double |
float type
The float
type is smaller than double
, and it has suffix F
or f
to declare its valid value in java, below is the example float
declaration:
float number1 = 3.0f;
float number2 = 2.1f;
System.out.println(number1 - number2);
As this section mentioned above, the round-off have some problem if we use it for financial computation, the code above output will be 0.9000001
instead of 0.9
, and these round-off errors are caused when the floating-point numbers are represented in the binary number system.
If you like to precise financial number computation without round-off errors, you can use BigDecimal
like the example below:
float number1 = 3.0f;
float number2 = 2.1f;
System.out.println(new BigDecimal(number1 - number2).round(new MathContext(1)));
double type
The double
is the same as float
data type, it also is used for decimal values, however, it is larger than float, and you can add D
or d
at the end of the value for its suffix, but double
works whether with or without its suffix.
Here is the example double declaration:
double decNumber = 1.1d;
Character Data Type
Character Data Type or char
type in Java is originally intended for a single character. But, this is no longer the case, and nowadays, char
value can be described using Unicode.
Unicode
Unicode is character encoding standard used to define character value, and the Unicode character value requires two char values, \u
which is used for escape sequences and hexadecimal values that run from \u0000
to \uFFFF
. For example '\u0024'
for dollar sign, '\u0025'
for percent sign and more.
You should use single quote to enclose the char value. For example 'a'
, but it is different from "a"
. (“) double quote is used to describe String characters.
Here is the example char type declaration:
public class DataType {
public static void main(String[] args) {
double score = 80.9;
char percendSigm = '\u0024';
System.out.println(score+""+percendSigm);
}
}
Output:
80.9$
boolean type
boolean
type have two possible value its either true or false, and it is used for logical condition. For example control statement like if
statement, while
, switch
, etc.
Here is the example boolean
type declaration:
public class DataType {
public static void main(String[] args) {
boolean condition = true;
if(condition == true) {
System.out.println("Condition is True");
}else {
System.out.println("Condition is False");
}
}
}
Output:
Condition is True
Non-primitive
These kinds of data types are referring to the object, they used reference of an objects to store as a value.
Classes and Objects
The classes and objects are the basic concept of object-oriented programming (OOP) which is used to build a real life entities. In the next tutorial we will discuss more about OOP topic.
The class is a user-defined blueprint or prototype that used to create objects, and it includes the methods and properties of an object.
In the previous section, we already used wrapper classes which are also included in non-primitive data types.
Let’s use String class in java to create a string data type object. For example, we want to print “Hello World
“, we can use primitive data type char, however it takes lot of effort to complete the “Hello world
” since it can only allow a single character.
Here is the declaration for String and char data type:
public class DataType {
public static void main(String[] args) {
char h = 'H';
char e = 'e';
char l = 'l';
char w = 'W';
char o = 'o';
char r = 'r';
char d = 'd';
System.out.println("char Data Type: "+ h + e + l + l + o +" "+ w + o + r + l + d);
String greetings = new String("Hello World");
System.out.println("String Data Type: "+ greetings);
}
}
Output:
char Data Type: Hello World
String Data Type: Hello World
In String class, we just put the value in the string object to print the “Hello world”.
Arrays
The array is a kind of data type that can store multiple value, this is also known as one of the basic of data structure, refer to the next tutorial for more information about data structure.
Here is the example declaration of array data type:
public class DataType {
public static void main(String[] args) {
int[] numbers = {1,2,3,4,5,6};
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i]);
}
}
}
Output:
1
2
3
4
5
6
As you can see above, we declared int array which have 1 to 6 value, to print it, we must use for statement. Refer to the link below for more information about for loop statement:
Conclusion
The difference between primitive and non-primitive
- Primitive
- Predefined in Java.
- Value based data types.
- Requires value
- Starts with lowercase
- Have limited and different storage size for each data type
- Non-primitive
- Created by programmers or can be defined by Java libraries,
- Object or reference based data types.
- Can be null
- Starts with uppercase
- Have same storage size for each data type