Sunday, May 31News That Matters
Shadow

Java Variable

Variable is a memory storage that serves as a placeholder for identifiers. Identifiers are then the name that is assigned to data that is meant for manipulation. When working with java variables, the datatype of a particular variables meant to be observed unless error will erupt.

Ways of declaring a variable:

[Datatype Variable_name = variable;]

Example: int a = 10; or 

String a,b,c;
a = “Tonna”;
b = “Romanus”;

Types of variable

Local Variables: These are variable that are inserted or defined inside any method in Java class and destroys when the method is completed.

Instance variables: These are variables that are inserted or initialized within a class but not inside a method. It can be called up by any method.

Class variables: These are variable that are initialized within a class, outside any method but with a static keyword. The main difference of Class Variable and. Instance variable is that Instance variable is static while Class variable is not.

Code:

 1
2
3
4
5
6
7
8
9
10
11
12
13
public class JavaVariables {

public static int age = 20; //this a class variable because it's is outside a method
public static String name = "Tonna"; //This is also a Class variable
public static void main(String[] args){

int a = 21; //this is a local variable

System.out.println(name + " is " + age + " years old");
System.out.println(name + " will soon turn " + a + " soon");

}
}


Output:

Tonna is 20 years old
Tonna will soon turn 21 soon

Leave a Reply

Your email address will not be published.