Note- Variable is declared followed by semi-colon (;)
There are two types of variable as
Note- Static keyword is applied to global variable and it will become a static variable.
How to print the value of local variable
1. System.out.print(x); // Here passing variable x.
2. System.out.println (“Value of X is=”+x); // Here we are writing message in double quotes then passing variable x. Both statements indicates that output is 0.
Note- Static keyword is not applied to local variable.
How to print the value of Global variable
How to access the global variable outside of class.
public class GlobalDemo {
int x ; //declaration of global variable
int y=10; //initalization of global variable
public static void main(String[] args) {
GlobalDemo globalDemo= new GlobalDemo(); //this is the way to create the object of class-globalDemo this is the object name
//how to print the value of variable- objectname.variablename
System.out.println("value of y variable is>>"+globalDemo.y);
}
}
public class Test {
public static void main(String[] args) {
GlobalDemo globalDemo= new GlobalDemo();
System.out.println(globalDemo.y);
}
}
Output
value of y variable is>>10
Example- Declaring variable for different data types
int a;
byte b;
short s;
long l;
float f;
boolean b1;
char ch='v';
Example- Initialize variable for different data types
int a=5000;
byte b=50;
short s=500;
long l=50000;
float f=2.5f;
boolean b1=false;
char ch='v';