Variable, Identifiers and Data Types
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.
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.
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 |
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.
No comments:
Post a Comment