In Java, variables are used to store data values. They act as placeholders for the values. Variable needs to be declared before it can be used. They have a name, a type and a value. For example:
int age = 30;
Here, age is the name of the variable, int is the type (data type) and 30 is the value.
Data types specify the size and type of values that can be stored in the variable. Java is a statically typed language, which means that the type is specified during variable declaration and it cannot change later. Some of the commonly used data types in Java are:
Integers
byte: 1 byte, -128 to 127
short: 2 bytes, -32,768 to 32,767
int: 4 bytes, -2,147,483,648 to 2,147,483,647
long: 8 bytes, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Decimals
float: 4 bytes, up to 38 digits of precision
double: 8 bytes, up to 308 digits of precision
Characters
- char: 2 bytes, Unicode character set
Booleans
- boolean: true or false
Strings
- String: a sequence of characters
Variable names in Java must follow the following rules:
They must start with a letter, underscore or dollar sign.
After the first character, they can contain letters, numbers, underscores and dollar signs.
They cannot contain spaces.
Keywords cannot be used as variable names. Some examples of keywords are: public, class, void, int, etc.
Variable names should be meaningful. Age is a good name, a is not.
Case sensitivity - age and AGE are two different variables.
Conventions - variable names start with a lowercase letter, class names start with an uppercase letter.
Variables can be:
Local variables: Defined inside a method. They can be used only within that method and lose scope once the method finishes execution.
void method() { int num = 10; // local variable }
Instance variables: Defined inside a class, outside any method. They are initialized when an object is instantiated and destroyed when the object is discarded. They can be accessed from anywhere within the class.
class Person { String name; // instance variable }
Static variables: Belong to the class rather than the instance. They are initialized when the class is loaded and destroyed only when the program exits. They can be accessed without instantiating an object, using the class name.
class Person { static int count = 0; // static variable }
Final variables: Cannot be reassigned. They have to be initialized during the declaration. Useful for constants.
final double PI = 3.14; // final variable
In Java, you can declare variables anywhere in a method, but before using them. The scope of a variable is from its declaration until the end of the block it is declared in. For example:
{
int x = 10; // scope of x is from here to end of block
}
// x cannot be used here - out of scope
That's a high-level overview of variables and data types in Java. Let me know if you would like me to elaborate on any part of the summary.