variables java
// instance variable in java example
public class InstanceVariableDemo
{
// instance variable declared inside the class and outside the method
int c;
public void subtract()
{
int x = 100;
int y = 50;
c = x - y;
System.out.println("Subtraction: " + c);
}
public void multiply()
{
int m = 10;
int n = 5;
c = m * n;
System.out.println("Multiplication: " + c);
}
public static void main(String[] args)
{
InstanceVariableDemo obj = new InstanceVariableDemo();
obj.subtract();
obj.multiply();
}
}
3.88
8
// static variable in java example
public class StaticVariableExample
{
// static variable
static int a = 0;
public void add()
{
a++;
}
public static void main(String[] args)
{
StaticVariableExample obj1 = new StaticVariableExample();
StaticVariableExample obj2 = new StaticVariableExample();
obj1.add();
obj2.add();
// both objects are sharing same copy of static variable
System.out.println("Object 1 value is: " + a);
System.out.println("Object 2 value is: " + a);
}
}
Thank you!
8
0
3.86
7
int myVariable = 42; //This is the most commonly used variable. Only use other variables if you have a good reason to.
Thank you!
7
0
4
5
/* Depending on what variables you want to declare */
String hello = "hello"; //characters
short one = 12;//shorter integers
int two = 2000; //complete integer up too 32 bits
long number = 2000000; //complete integer up to 64 bits
float decimal = 1.512 //up to 7 decimal digits
double million = 1.387892847395 //up tp 16 decmial digits
Bool condition = true; // true or false
char a = "a"; // unicode character
Thank you!
5
0
5
1
/*
## Variable
- Container which holds the value while the Java program is executed.
- Assigned with a data type.
- Name of memory location.
## There are three types of variables in java:
1) Local variable
2) Static (or class) variable
3) Instance variable
*/
Thank you!
1
0
4.4
10
// local variable in java example
public class LocalVariableExample
{
public void employeeDetails()
{
// local variable empAge and name
int empAge = 22;
String name = "Sachin";
}
public static void main(String[] args)
{
LocalVariableExample obj = new LocalVariableExample();
// name and empAge cannot
// be resolved to a variable
System.out.println("Employee name is : " + name + ", and age : " + empAge);
}
}
Thank you!
10
0
Are there any code examples left?
New code examples in category Java