Java Variable and Constant
- A variable is a location in your computer's memory in which you can store a value and from which you can later retrieve that value.
- Your computer's memory is normally Random Access Memory (RAM).
- A variable must always be defined inside a Java class.
- When you define a variable in Java, you must tell the compiler what kind of variable it is. (this is usually referred to as variable type).
Java Primitive variable types
- Java works with Primitive variable types, which represent simple values that have built-in functionality in the language.
They are fixed elements, such as characters, integers and floating-point.
Primitive types in Java:
Type Definition boolean true or false char 16-bit, Unicode character byte 8-bit, signed, two's complement integer short 16-bit, signed, two's complement integer int 32-bit, signed, two's complement integer long 64-bit, signed, two's complement integer double 64-bit, 1.7e-308 – 1.7e+308, floating point value float 32-bit, 3.4e-38 -- 3.4e+38, floating-point valueVariable declaration example:
... int foo; double d1, d2; boolean isFun; ...Variable declaration with initialization example:
... int foo = 42; double d1 = 3.14, d2 = 2 * 3.14; boolean isFun = true; ...Integer literals example:
... int i1 = 1230; // specified in decimal (base 10) int i2 = 01230; // specified in octal (base 8) // i2 = 664 decimal int i3 = 0xFFFF; // specified in hexadecimal (base 16) // i3 = 65535 decimal ...Automatic casting/converting example:
... long l = 13L; // Int. literals are of type int // unless they are suffixed with an L long l = 13; // Equivalent: 13 is converted from type int byte b = 42; // Works fine as long as values < 255 int i = 43; int result = b * i; // b is promoted to int before multiplication int x = 13; byte b = x; // Compile-time error, explicit cast needed byte b = (byte) x; // OK - as x is casted to byte ...Floating-point literals example:
... double d = 8.31; // Floating-point values can be specified in decimal double e = 3.00e+8; // or specified in scientific notation float f = 8.31F; // Default of type double unless they // are suffixed with an f or F float g = 3.00e+8F;; ...Character literals example:
... char a = 'a'; // Specified either as a single-quoted character // or char newline = '\n'; // as an escaped ASCII // or char smiley = '\u263a'; // written with special Unicode escape sequences ...
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the
correctness in the pages or source codes.
The risk of using this web-site pages or any program
codes from this website is entirely at the individual user.