Data Types

Variable is the name of memory location that can hold a value. There are three types of variables in java: local, instance and static.

Data is the information that we work with. These could be in the form of characters, text, number digits or more complex forms.

The value that a variable is assigned to is the data. For example,

Int number = 1;

In the example above, the data is assigned a type of int. Therefore, data types specify the different values that can be stored in the variables.

Primitive data types

Primitive data types hold exactly one value of it’s declared type at a time.

There are eight primitive data types in Java namely byte, short, int, char, long, float, double and boolean.

byte, short, int, long, float and double represent number values of various formats.

char represent a letter value like A.

boolean represent only two possible values of true or false.

Each of these data types can hold different values.

To declare a primitive data type use the syntax containing the data type name, followed by the name you have given the data and finally a semicolon as shown below:

byte number1;  

short number2;  

int number3; 

char alphabet;  

long number4; 

float number5;  

double number6; 

boolean yesOrNo

NonPrimitive data types

Non primitive data types are String , Arrays and Classes.

An example of a String is a name such as ‘‘John’’ . Please note that String as a data type is written with a capital S. String is any group of letters written together to form a word. To represent a String in your code first declare it as shown below:

String name;

Array is a collection of values of any data type.

class is a specification from which an object is created.

Primitive data types and allowed values

Primitive data types can hold values assigned to them, but the range of values vary from one to the other.

Data type Size value
byte1byte Stores whole numbers from -128 to 127
short2byteStores whole numbers from -32,768 to 32,767
int4bytesStores whole numbers from -2,147,483,648 to 2,147,483,647
long8bytesStores whole numbers -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float4bytesStores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double8bytesStores fractional numbers. Sufficient for storing 15 decimal digits
boolean2bytesStores true or false valuesStores
char1byteStores a single character/letter or ASCII values

Working with Data types

Primitive data types are special data types built into the language. they are not objects created from a class.

A literal is the source code representation of a fixed value.

Primitive data types can be assigned to literals such as any fixed value shown below:

boolean result = true;

char capitalC = ‘C’;

 byte b = 100;

 short s = 10000;

 int i = 100000;

Let’s create a java file containing a byte data as shown

public class ByteData {   

      public static void main(String[] args) {

       byte eightBitsMinus128 = -128; 

       byte eightBits127 = 127;

System.out.println(“A byte of primitive data can hold whole numbers with a minimum of ” +     eightBitsMinus128 + ” and a maximum of ” + eightBits127);

  }

}

Compile with javac ByteData.java

Run with java ByteData

Short data

public class ShortData {

      public static void main(String[] args) {

       short sixteenBitsMinus32768  = -32768 ;   

       short sixteenBits32767  = 32767 ;

 System.out.println(“two bytes of primitive data can hold    whole numbers with a minimum of ” + sixteenBitsMinus32768  + ” and a maximum of ” + sixteenBits32767);              

  }

}

Compile and run as shown in the previous example.

Int Data

public class IntData {

      public static void main(String[] args) {

           int thirtyTwoBitsMinus  = -2147483648;     

            int thirtyTwoBits  = 2147483647;

System.out.println(“four bytes of primitive data can hold whole numbers with a minimum of ” + thirtyTwoBitsMinus  + ” and a maximum of ” + thirtyTwoBits);

      }

}

Long Data

When you declare a long data and give it a value, ensure the letter L is added to the end of the value as shown below:

public class LongData {

      public static void main(String[] args) {

           long sixtyFourBitsMinus  = -9223372036854775808L ;    

           long sixtyFourBits  = 9223372036854775807L;

           System.out.println(“four bytes of primitive data can hold whole numbers with a minimum of ” + sixtyFourBitsMinus   + ” and a maximum of ” + sixtyFourBits);

      }

}

Float Data

Stores fractional numbers of 6 to 7 decimal digits.

Ensure  ‘f’ is added to the end of the value as shown below.

public class FloatData {

      public static void main(String[] args) {

           float thirtyTwoBitsFloat  = 214.1234f;

           System.out.println(“Stores fractional numbers of 6 to 7 decimal digits such as ” + thirtyTwoBitsFloat);

      }

}

Double Data

Ensure  ‘d’ is added to the end of the value as shown below.

public class DoubleData {

      public static void main(String[] args) {

           double sixtyFourBitsDouble = 214.123456789101d;   

           System.out.println(“Stores fractional numbers upto 15 decimal digits such as ” + sixtyFourBitsDouble);

      }

}

Boolean Data

public class BooleanData {

      public static void main(String[] args) {

           boolean sixteenBitsFalseBoolean  = false;

           boolean sixteenBitsTrueBoolean  = true;

           System.out.println(“Stores ” + sixteenBitsTrueBoolean + ” or ” + sixteenBitsFalseBoolean + ” values.” );

      }

}

Char Data

public class CharData {

      public static void main(String[] args) {

           char eightBitsChar  = ‘c’;

           System.out.println(“Stores a single character/letter or ASCII values such as ” + eightBitsChar );

      }

}

**Note that the java compiler will underline  the value with red when a value is saved into the wrong data type.

To the left of the image below there is a red square that contains a white ‘x’. This is the java compiler telling you the value is not within the range for the data type.

Primitive Data Casting

When a value of one primitive data type is assigned to another type, you are casting one data type to another. There two ways to cast, namely Widening casting and Narrowing casting.

Widening casting is when passing a smaller size data type to a larger size data type. This is also referred to as  Type Promotion . This is done automatically.

public class WideningCasting {

      public static void main(String[] args) {

          int thirtyTwoBits127 = 127;

        System.out.println(“A byte value “+ thirtyTwoBits127 + ” of primitive data can be casted to an int data of higher value” );

      }

}

class CharCastedTOInt {

      public static void main(String[] args) {

           char c = ‘a’;

          int i = 50000;

          int result = i / c;

          System.out.println(“i / c is ” + result);

          char b = ‘b’;

          int valueOfB = b;

          System.out.println(“The value of b is ” + valueOfB);

}

}

Narrowing casting is when passing a higher size data type to a smaller size data type. This has to be done manually by adding the type in parentheses in front of the value.

public class NarrowingCasting {

public static void main(String[] args) {
    double thirtyTwoBits  = (int)214748;
    System.out.println("A double data of a higher value can be casted to "+ thirtyTwoBits + " of primitive data of a lower value" );
}

}

Wrapper Classes

Wrapper classes are objects encapsulating primitive data types. Each primitive data type has a wrapper that can be used to encapsulate it.

Generic classes enable types. when used in your code you will not need to cast your primitive data. Generic classes only work with objects and since primitive data types are not objects, generic classes don’t support them. Wrapper classes are used to convert primitive values to wrappers objects for the purpose of using them with generic classes.

 The primitive data types and their corresponding wrapper classes are shown below.

Primitive data   Wrapper class

booleanBoolean
byteByte
shortShort
charCharacter
intInteger
longLong
floatFloat
doubleDouble

Operators

Java provides many types of operators which can be used to perform various calculations and functions. Here are some of the operators:

  1. Arithmetic Operators

These are mathematical operators that can be used to perform various arithmetic operations on primitive data types referred to as the operands. Some arithmetic operators are

Addition(+): This operator is a binary operator and is used to add two operands. For example:

byte one = 1;

byte two = 2;

int three = one + two;

Subtraction(-):This operator is a binary operator and is used to subtract one operand from another operand.Example below:

byte one = 1;

byte two = 2;

int answer = two – one;

Multiplication(*): A binary operator used to multiply two operands.

byte one = 1;

byte two = 2;

int answer = two * one;

Division(/): A binary operator used to divide the first operand(dividend) by the second operand(divisor) and give the quotient as a result. 

  byte one = 1;

  byte two = 2;

  int result = two / one;

Modulus(%): A binary operator used to return the remainder when the first operand(dividend) is divided by the second operand(divisor). 

byte one = 1;

byte two = 2;

int remainder = two % one;

2. Unary Operators

Java unary operators perform an operation on only one operand. Operations performed may be increment, decrement, negation, etc.  Various arithmetic, logical and other operators are also unary operators. Examples are:

Unary minus(–)operator can be used to convert a positive value to a negative value. Define and initialise a positive data as shown below:

short positive_one = 1;

Convert this positive data to a negative data using unary minus(-):              

int negative_One = -one;           

NOT(!) is a unary operator is used to indicate true or false. It can also be used to reverse the logical state of an operand. NOT operatoris used in situations where you need to compare two values and come to a true or false decision which is saved in a boolean value. For example define a true or false data and initialise to true:   

boolean condition = true ;                                     

 Define and initialise a positive data as shown below    

       int one = 1;                                                   

Define another positive data

        int two = 2;                                                  

Compare a to b using > (greater) and save in the boolean condition       

         condition = !(one > two);

Increment(++) Operator is used to increment the value of a variable. example below shows when operator is placed before the variable, then it is incremented instantly.

         byte one = 1;   

increment instantly    

byte one_plus_one = ++one;

Post-increment operator is placed after the variable, the value of the variable is not incremented instantly but retained until after the execution of the statement that comes after it in the code.

byte two = 2;

byte two_then_add_one = two++;

Unary Decrement(–-) operatoris used to decrement the value of an integer variable . It can be used aspre decrement and post decrement. Pre-decrement places the operator before the variable resulting in instant increase of the variable as shown below:

short one = 1;

To decrement by one, save into another variable before use.

short one_minus_one = –one;

Using a variable with decrement directly such as –one will decrement by 2 not 1.

Post-decrement unary operator is placed after the variable. When decrement is access through a variable, decrement is delayed until after the full execution of the statement after it.

short two = 2;

short two_then_minus_one = two–;

Bitwise Not or Complement (~) is a unary Operator that is used to  perform conversion of integral types to their equivalent binary value, and then invert each bit. A bit that is 0 is converted to 1, and vice versa. The integral types are byte , short , int , and long , whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two’s-complement integers, respectively, and char , whose values are 16-bit unsigned integers.

Bitwise complement operator works at the bit level inverting every “0” to “1” and every “1” to “0”. A byte contains 8 bits; applying this operator to a value whose bit pattern is “00000000” would change its pattern to “11111111”. The example below illustrates// this:

Define and initialise a variable

byte one = 1;

Perform a bitwise operation

int bitwiseOne = ~one;

The result of this will be -2

3. Assignment Operators

Assignment (=) Operator is used with the “=” sign where the left side is the operand and the right side is the value. The value on the right must be of same data type as on the left side. Example is shown below:

byte one = 1;

addition assignment (+=) operator is a quick way to add a value to a variable. The code x+=y is equivalent to x = x+y. This can be used with any primitive data type:char, byte, short, int, long, and float. Example is shown below:

Define and initialise a variable

int one = 1;

add a value of 2 to the variable to get an answer of 3

one += 2;

Subtraction assignment (-=) operator is a quick way to subtract a value from a variable. The code x-=y is equivalent to x=x-y. This can be used with any primitive data type: char, byte, short, int, long, and float. Example is shown below:

Define and initialise a variable

int two = 2;

Subtract a value of 1 to the variable to get an answer of 1

two -= 1;

Multiplication assignment (*=) operator is a quick way to multiply a variable by a value. The code x*=y is equivalent to x= x*y. This can be used with any primitive data type: char, byte, short, int, long, and float. Example is shown below:

Define and initialise a variable

int two = 2;

Multiply the variable by a value of 2 to get 4

two *= 2;

Division assignment(/=) operator is a quick way to divide a variable by a value. The code x/=y is equivalent to x= x/y. This can be used with any primitive data type: char, byte, short, int, long, and float. Example is shown below:

Define and initialise a variable

int six = 6;

Divide the variable by a value of 2 to get 3

six /= 2;

Modulus assignment (%=) operator is a quick way to divide a    variable by a value to get the remainder. The code x%=y is equivalent to x= x%y. This can be used with any primitive data type: char, byte, short, int, long, and float. Example is shown below:

Define and initialise a variable

int seven = 7;

Divide the variable by a value of 2 to get reminder of 1

seven %= 2;

4. Relational Operators

Equal to(==) Binary operator is used to check if one operand in relation to another operand are equal to one another. The operator returns true if the operand at the left-hand side is equal to the right-hand side, else it will return false. Example is below: 

define and initialise variables to be compared:

byte six = 6;

byte fivePlusOne = 5+1;

comparing for equality will return true:

boolean yes = (six == fivePlusOne);

Not Equal to(!=) is a binary operator used to check if one operand in relation to another operand are not equal to one another. The operator returns true if the operand at the left-hand side is not equal to the right-hand side,else it will be false. Example below:  

   define and initialise variables to be compared:

byte six = 6;

byte fivePlusOne = 5+1;

compare the variables for non-equality will return false:

boolean yes = (six != fivePlusOne);

Greater than(>) is a binary operator used to check if first operand is greater than the second. The operator returns true if the operand on the left-hand side is greater than the right-hand side, else it will be false. Example below: 

Define and initialise variables to be compared:

byte six = 6;

byte fivePlusOne = 5+1;

Compare to know the greater will return false:

boolean no = (six > fivePlusOne);

Less than(<) is a binary operator used to check if first operand is less than the second.The operator returns true if the operand on the left-hand side is less than the right-hand sideelse it will be false. Example below: 

Define and initialise variables to be compared:

byte six = 6;

byte fivePlusOne = 5+1;

Compare to know the lesser variable will return false:

boolean no = (six < fivePlusOne);

Greater than or Equal to(>=) binary operator is used to check if one operand is greater than or equal to one another. The operator returns true if the operand on the left-hand side is greater than orequal to the right-hand side,else it will be false. Example below:

Define and initialise variables to be compared:

byte six = 6;

byte fivePlusOne = 5+1;

Comparing will return true:

boolean yes = (six >= fivePlusOne);

Less than or Equal to(<=) binary operator is used to check if one operand is less than or equal to one another. The operator returns true if the operand on the left-hand side is less than or equal to the right-hand side, else it will be false. Example below:

Define and initialise variables to be compared:

byte six = 6;

byte fivePlusOne = 5+1;

Comparing first operand to second operand will return true:

boolean yes = (six <= fivePlusOne);

5. Logical Operators

Logical OR (||) Operator returns true when one of the conditions under consideration is true.If both of the two returns false, the operator returns false. When using Logical OR with same variables above, see example shown below:

Using logical OR on both conditions will return true.

boolean trueOutcome = (yes || no);

Logical NOT (!) is a unary Operator returns true when the conditions under consideration is false or not true.See example below:

Define and initialise variables to be used in condition:

byte three = 3;

byte four = 4;        

condition testing if three is greater than four will returnfalse:

boolean no = (three > four);

Using logical NOT on the condition will return true.

boolean  yes = !no;

6. Ternary (?:) Operator ternary operator is the only operator that takes three operands. It can be used in place of if-else conditions or even switch conditions using nested ternary operators. See below:

Define the three variables

byte one = 1; byte two = 2; byte twoISgreater;

Use the (one > two)condition  return one if condition is true, otherwise return two

twoISgreater = (one > two)? one : two ;

7.Bitwise Operators and Shift Operators

Bitwise operators work on data at the bit level. They have more specialise usage and as such we shall not go into more details.

Java Operator Precedence

Operator precedence relates to the order in which an expression with two or more operators will evaluate. Some operators have higher precedence over others and so will be evaluated first, while some have equal precedence and so will evaluate from left to right. The example below will evaluate the multiplication first because it has higher precedence than addition:

Define and initialise variables                                                                      

int two = 2, three = 3, four = 4;

Multiplication will be evaluated first before addition

int eleven = three + two * four;

Associativity deals with operators with equal precedenceand how they are evaluated. Examples of operators and their precedence and associativity is shown in the table below. Row 15 has the highest precedence while Row 1 has the lowest precedence. Each row has operators with equal precedence and so has associativity relationship with each other, and how these operators evaluate is shown in Associativity column. 

We must follow associativity if an expression has more than two operators of the same precedence. In such a case, an expression can be evaluated either left-to-right or right-to-left, depending on the operators in question.

The following table describes the precedence and associativity of operators used in Java.

Precedence Operator TypeAssociativity
15()
[]
·
Parentheses
Array subscript
Member selection
Left to Right
14++
Unary post-increment
Unary post-decrement
Right to left
13++

+

!
~
(type)
Unary pre-increment
Unary pre-decrement
Unary plus
Unary minus
Unary logical negation
Unary bitwise complement
Unary type cast
Right to left
12*
/
%
Multiplication
Division
Modulus
Left to right
11+
Addition
Subtraction
Left to right
10<<
>>
>>>
Bitwise left shift
Bitwise right shift with sign extension
Bitwise right shift with zero extension
Left to right
9<
<=
>
>=
instanceof  
Relational less than
Relational less than or equal
Relational greater than
Relational greater than or equal
Type comparison (objects only)
Left to right
8==
!=
Relational is equal to
Relational is not equal to
Left to right
7&Bitwise ANDLeft to right
6^Bitwise exclusive ORLeft to right
5|Bitwise inclusive ORLeft to right
4&&Logical ANDLeft to right
3||Logical ORLeft to right
2? :Ternary conditionalRight to left
1=
+=
-=
*=
/=
%=
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Modulus assignment
Right to left

Examples below:

An operator of higher precedence will evaluate first as shown here –  

Define and initialise variables

 int two = 2, three = 3, four = 4;  

Division will evaluate first before the addition to returning an output of 5

int five = three + four / two ;

Operators with same precedence have associativity and will evaluate according to the operators in question. An example below:

Define and initialise variables

int two = 2, three = 3, four = 4;

Division and subtraction have same precedence and so their associativity always evaluate from left to right. Therefore first addition will be evaluated first and then subtraction to return an output of 5.

int five = three + four – two;

Parentheses ()

Parentheses can be used in two scenarios: The first scenario is to control the order in which an expression operates, and the second scenario is to supply parameters to a constructor or a method.  Example shown below:

Define and initialise variables as double b/c a division will return a double.

double two = 2d, four = 4d, three = 3d;

Division has precedence over addition, so to change the order of evaluation use parentheses around two + three, in order to evaluate the expression from right to left returning an answer of 0.8

double five = four/(two + three);

If same expression is evaluated without parentheses, it will return an answer of 5. 

double without = four / two + three;

                                    

Math API

Math class provides mathematical functions used to perform basic numeric operations such as exponential, logarithm, square root, andtrigonometric functions. cosh, sin, tan, abs, multiply and many more. Some examples of frequently used methods are shown below:

Math.cbrt(int a) method returns the cube root of the  passed argument . Example below:

Define and initialise a variable                     

double twoOne6 = 216;

Applying the method returns 6.0 

double cbrtTwoOne6 = Math.cbrt(twoOne6);

Math.floor(int a) method returns the floor value of an argument which is the closest integer value which is either less or equal to the passed argument. For example, 101.23 floor value = 101.  Example below:

Define and initialise a variable                                   

double thirtyPoint56 = 30.56;

Apply method returns a lower figure of 30.0                         

thirtyPoint56 = Math.floor(thirtyPoint56);

Math.max(int a, int b) method returns the greater value out of the two values passed as argument.This method just compares using magnitude without considering any sign. see example below:

Define and initialise two variables                             

double onePoint34 = 1.34d;                                                    

double twoPoint40 = 2.40d;                                                      

Apply Math.max to variables to return 2.4                                  

double max = Math.max(onePoint34, twoPoint40);

Math.pow(int b, int e) method returns the value of b to the power of e. Example below:

Define and initialise variables

double b = 10d, e = 2d;

Apply Math.pow to raise b to power of e 

double bToPowerE = Math.pow(b, e);

Scope of Variables

The scope of a declared entity is the region of the program within which the entity is visible and can be referred to using a simple name.

Class Variables must be declared inside class, but outside a method.  Class variables have class level scope. They can be directly referenced anywhere in class using the simple variable name

public class ClassScope {

//Class variable declared
static int number;

public static void main(String[] args) {

    //referenced statically using class name as identifier inside a method and //initialised with a value
    ClassScope.number = 4;
    System.out.println(ClassScope.number);

}

}

public class LocalVariable {

//Class variable declared outside a method
private static int number;

//Local variable declared as a parameter in the method below.           
public static int amethod(int number){

//local variable referenced without an identifier. It is then used in the calculation below.
int answer = number * 10;

//Class variable of same name referenced using the class name as verifier.
LocalVariable.number = 4;
System.out.println(LocalVariable.number);
return answer;
}

public static void main(String[] args) {

System.out.println(amethod(5)); 
}

}

Local Variable Type Inference

Starting from JDK 10 and later, you can declare local variables with non-null initializers with the var identifier. This can help you write code that’s easier to read. An example is shown below:

public class TypeInference {

public static void main(String[] args) {

    // Local variable type in inferred using var identifier
    var number = 4;
    var name = "John Brown";
}

}

For a complete knowlege of Java see the book preview below:

Preview Java Beginner Reference Book

One thought on “Data Types

Leave a Reply

Your email address will not be published. Required fields are marked *