📐Variables & Types
Although Java is object-oriented, not all types are objects. It is built on top of basic variable types called primitives.
Primitive Types
byte
(number, 1 byte)short
(number, 2 bytes)int
(number, 4 bytes)long
(number, 8 bytes)float
(float number, 4 bytes)double
(float number, 8 bytes)char
(a character, 2 bytes)boolean
(true or false, 1 byte)
Java is a strongly typed language, which means variables need to be defined before we use them.
ASSIGNMENT COMPATIBILITIES
A value of one type can be assigned to a variable of any type further to the right
But not to a variable of any type further to the left. You can assign a value of type char to a variable of type int.
Example : float var = 5;
Numbers
To declare and assign a number use the following syntax:
Or you can combine them:
To define a double floating point number, use the following syntax:
If you want to use float, you will have to cast:
Or, You can use this:
Characters and Strings
In Java, a character is its own type and it's not simply a number, so it's not common to put an ASCII value in it, there is a special syntax for chars:
String
is not primitive. It's a real type, but Java has special treatment for String.
Here are some ways to use a string:
There is no operator overloading in Java but there is the exception that proves the rule - string is the only class where operator overloading is supported. We can concat two strings using + operator. The operator +
is only defined for strings, you will never see it with other objects, only primitives.
You can also concat string to primitives:
boolean
Every comparison operator in Java will return the type boolean. Unlike other languages, it only accepts two special values: true
or false
.
Quick Reference:
Data Type | Type | Default Value | Sample Code |
---|---|---|---|
byte | Primitive | 0 | byte myByte = 0; |
short | Primitive | 0 | short myShort = 0; |
int | Primitive | 0 | int myInt = 0; |
long | Primitive | 0L | long myLong = 0L; |
float | Primitive | 0.0f | float myFloat = 0.0f; |
double | Primitive | 0.0d | double myDouble = 0.0d; |
char | Primitive | '\u0000' | char myChar = '\\u0000'; |
boolean | Primitive | false | boolean myBoolean = false; |
String | Non-Primitive | null | String myString = null; |
Array | Non-Primitive | null | int[] myArray = null; |
Class | Non-Primitive | null | Class myClass = null; |
Object | Non-Primitive | null | Object myObject = null; |
HashMap | Non-Primitive | null | HashMap<String, Integer> myHashMap = null; |
Last updated