[Go to site: main page, start]

0% found this document useful (0 votes)
26 views8 pages

Java Variables: Types and Examples

The document discusses Java variables. There are three types of variables in Java: local variables, instance variables, and static variables. A variable is a container that holds a memory location and can have a value that changes. Variables must be declared with a data type like int or string.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views8 pages

Java Variables: Types and Examples

The document discusses Java variables. There are three types of variables in Java: local variables, instance variables, and static variables. A variable is a container that holds a memory location and can have a value that changes. Variables must be declared with a data type like int or string.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Variables

A variable is a container which holds the value while the java program is executed. A variable is assigned
with a [Link] is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in java: primitive and non-primitive.

Variable

Variable is name of reserved area allocated in memory. In other words, it is a name of memory location.
It is a combination of "vary + able" that means its value can be changed.

1.    int data=50;

2.    //Here data is variable  

Types of Variables

There are three types of variables in java:


local variable

instance variable

static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.

Example to understand the types of variables in java

class A{  

int data=50;//instance variable  

static int m=100;//static variable  

void method(){  

int n=90;//local variable  

}  

}//end of class  

Java Variable Example: Add Two Numbers

class Simple{  

public static void main(String[] args){  
int a=10;  

int b=10;  

int c=a+b;  

[Link](c);  

}}  

Output:

20

Java Variable Example: Widening

class Simple{  

public static void main(String[] args){  

int a=10;  

float f=a;  

[Link](a);  

[Link](f);  
}}  

Output:

10

10.0

Java Variable Example: Narrowing (Typecasting)

class Simple{  

public static void main(String[] args){  

float f=10.5f;  

//int a=f;

//Compile time error  

int a=(int)f;  

[Link](f);  

[Link](a);  

 }

}  
Output:

10.5

10

Java Variable Example: Overflow

class Simple{  

public static void main(String[] args){  

//Overflow  

int a=130;  

byte b=(byte)a;  

[Link](a);  

[Link](b);  

 }

}  

Output:
130

-126

Java Variable Example: Adding Lower Type

class Simple{  

public static void main(String[] args){  

byte a=10;  

byte b=10;  

//byte c=a+b;

//Compile Time Error:

// because a+b=20 will be int  

byte c=(byte)(a+b);  

[Link](c);  

}  
Output:

20

Common questions

Powered by AI

In Java, when two lower type variables like byte or short are added, the result is automatically promoted to an int. This implicit promotion requires casting the result back to the lower type (e.g., to byte), and failure to do so leads to a compile-time error, as the operation exceeds the storage limits defined for these lower types without explicit conversion .

Explicit type casting is crucial when narrowing conversion occurs, as it ensures the programmer is aware of and responsible for potential data loss. For example, casting a float to an int truncates the decimal part, which could lead to significant information loss if not handled carefully . This mechanism prevents inadvertent conversion and requires conscious decision-making, thus safeguarding data integrity.

Local variables are declared within a method and are only accessible within that method, meaning they cannot be static and do not retain values between calls . Instance variables are declared within a class but outside any method, meaning they are associated with an instance of the class and each object of the class has its own copy of the instance variable . Static variables, on the other hand, are declared with the static keyword and are shared across all instances of the class. They are allocated memory only once, during class loading .

Integer overflow occurs when a cast operation results in a value that exceeds the capacity of the destination type. In Java, if an int with a value of 130 is cast to a byte, the resulting value is -126 due to byte's range limits (-128 to 127). This overflow results in unpredictable and incorrect outcomes, potentially leading to bugs if not properly accounted for in the logic.

Widening conversion is when a smaller data type is converted to a larger data type. For example, in Java, an int can be converted to a float without explicit casting because it enlarges the storage . Narrowing conversion is when a larger data type is converted to a smaller data type. Explicit casting is required in this situation, as demonstrated by converting a float to an int, where the fractional part is truncated .

Java handles overflow during type casting by wrapping around the value in the target type’s range. For example, when an int value of 130 is cast to a byte, it results in -126 due to the byte's range limitation (-128 to 127). Such overflow can lead to unexpected behaviors and logical errors, requiring careful handling and understanding of casting results.

Instance variables are allocated in the heap, with each object having its own unique memory allocation. This ensures data encapsulation and information hiding, as instance variables are not shared among objects. Static variables, however, are stored in the method area's static memory and are shared across all instances of the class, offering a common memory space for all instances which can lead to better memory utilization for class-wide persistent data .

Static variables in Java are allocated memory only once, in the method area's static storage, when the class is loaded. This shared memory allocation ensures that static variables have a consistent value across all instances of the class, making them ideal for constants or class-wide settings that need uniformity and thread-safety, as they represent global state for the class .

Local variables are allocated on the stack where the method's call frame resides, and they exist only during the method's execution. Instance variables are allocated in the heap as part of the object to which they belong, hence each object has its own set of these variables . Static variables, however, have a unique allocation in the method area's static storage, shared across all instances of a class and initialized when the class is loaded into memory .

In Java, arithmetic operations result in at least an int type, regardless of the types of the operands. When performing arithmetic on bytes, the result is treated as an int, thus requiring explicit casting back to byte to avoid a compile-time error. For instance, when adding two bytes, the sum is an int, which must be cast back to byte using (byte)(a+b) to store it in a byte variable .

You might also like