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
- class SimpleVariables {
- public static void main(String args[]) {
- // Lets save memory and use short for smaller numbers that
- // range between -32,768 and a maximum value of 32,767
- short age = 30;
- // 32-bit, minimum value of -2^31 and a maximum value of 2^31
- int invoiceNumber = 100000;
- // 64-bit, minimum value of -2^63 and a maximum value of 2^63
- long fileSizeInBytes = 1934567890;
- // Ttrue or false.
- boolean isSuperUser = true;
- //32-bit single-precision
- float pi = 3.14f;
- String txt = "Hello World";
- }
- }
No comments:
Post a Comment