Java Variables, Identifiers and Data Types

Java Variables:

Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.

    public class localVariableEx
     {
        public static int a;
        public static void main(String[] args)
         {
            int b; System.out.println("a : "+a);             System.out.println("b : "+b); //Compilation error
        }
    }

 

Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.

Java Data Types:

The data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.

Java has four main primitive data types built into the language. We can also create our own data types.

Integer: byte, short, int, and long.
Floating Point: float and double
Character: char

Boolean: variable with a value of true or false.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.

Data Type Default Value (for fields) Range
byte 0 -127 to +128
short 0 -32768 to +32767
int 0
long 0L
float 0.0f
double 0.0d
char ‘\u0000′ 0 to 65535
String (object) null
boolean false
When we declare a variable we assign it an identifier and a data type.

For Example:
String message = “hello world”
In the above statement, String is the data type for the identifier message. If you don’t specify a value when the variable is declared, it will be assigned the default value for its data type.

Identifier Naming Rules:
Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
Must begin with a letter, dollar sign, or an underscore Are case sensitive Keywords cannot be used as identifiers Within a given section of your program or scope, each user defined item must have a unique identifier Can be of any length.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More