Java Variables
A variable is a holder which holds the esteem while the java
program is executed. A variable is alloted with a datatype.
Variable is a name of memory area. There are three kinds of
factors in java: neighborhood, occurrence and static.
There are two kinds of information types in java: crude and
non-crude.
Variable
Variable is name of held zone assigned in memory. As such,
it is a name of memory area. It is a mix of "fluctuate + capable"
that implies its esteem can be changed.
int data=50;//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
announced inside the body of the strategy is called neighborhood variable. You
can utilize this variable just inside that strategy and different strategies in
the class aren't even mindful that the variable exists.
A nearby factor
can't be characterized with "static" watchword.
2 Instance Variable
A variable
pronounced inside the class however outside the body of the strategy, is called
case variable. It isn't pronounced as static.
It is called
example variable since its esteem is occasion explicit and isn't shared among
occurrences.
3 Static Variable
A variable
which is proclaimed as static is called static variable. It can't be
neighborhood. You can make a solitary duplicate of static variable and offer
among every one of the examples of the class. Memory allotment for static
variable happens just once when the class is stacked in the memory.
Example to
understand the type of variable 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 Number
class Simple{
public static void
main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}
|
OutPut :-
20
|
Java Variable
Example :- Widening
class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(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;
System.out.println(f);
System.out.println(a);
}}
|
OutPut :-
10.5
10
|
Java Variable
Exmple :- Overflow
class
Simple{
public static void
main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
|
OutPut :-
130
-126
|
Java Variable
Exmple :- 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);
System.out.println(c);
}}
|
OutPut :-
20
|
No comments:
Post a Comment