Java - Variables And Primitive Data Types

In this code snippet we take a look at primitive data types with example code snippets.
Java is a statically-typed language, which means that all variables must be declared before they can be used. This means that a variable's data type must be declared before it can be used. A variables data type helps to determine the values it can hold and the types of operations that can be done. For example, consider 1 + 1. If this was an equation you would expect the answer to be 2. However Java uses the + symbol for concatenation as well, which means 1+1 can also result in 11. By defining the data type of a variable such situations can be avoided. If two variables are of type String, then the + operation will result in a concatenation where as if two variables were defined as an int then an arithmetic operation is performed. It is worth noting that some programming languages such as PHP are dynamically typed where the data type is determined at run-time and therefore a data type does not need to be declared.
The following is a list of Primitive Data Types that are supported by Java.
  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char
A primitive type is predefined by the language and is named by a reserved keyword. Primitive values don't share state with other primitive values. You will notice that the data type string is not listed above, this is because string's are actually objects of type String. Java gives string's special treatment so that you don't need to create an instance of the String class every time you want to declare a string.
  1. class SimpleVariables {   
  2.   
  3.     public static void main(String args[]) {   
  4.   
  5.         // Lets save memory and use short for smaller numbers that    
  6.         // range between -32,768 and a maximum value of 32,767   
  7.         short age = 30;   
  8.            
  9.         // 32-bit, minimum value of -2^31 and a maximum value of 2^31   
  10.         int invoiceNumber = 100000;   
  11.            
  12.         // 64-bit, minimum value of -2^63 and a maximum value of 2^63   
  13.         long fileSizeInBytes = 1934567890;   
  14.            
  15.         // Ttrue or false.   
  16.         boolean isSuperUser = true;   
  17.            
  18.         //32-bit single-precision   
  19.         float pi = 3.14f;   
  20.   
  21.         String txt =  "Hello World";   
  22.     }   
  23. }  

No comments:

Post a Comment