Variables in Java


A variable in simple terms is a storage place which has some memory allocated to it. Basically, a variable used to store some form of data. Different types of variables require different amounts of memory, and have some specific set of operations which can be applied on them.

Syntax:
Datatype variable_name = variable_value;

Example:
To store the numeric value 25 in a variable named "a":
int a = 25;

Variables Rules:

  • Variable name don’t start variable name with digits.
  • Beginning with underscore is valid but not recommended.
  • Special character not allowed in the name of variable.
  • Blank or White spaces are not allowed.
  • Don’t use keywords to name of you variable.

This is a Java program that declares and initializes different types of variables and prints their values to the console.

  • The import java.lang.* ; line is not necessary as the java.lang package is automatically imported.
  • The class variables declares a class named variables.
  • The public static void main(String args[]) method is the entry point of the program.

The program declares and initializes the following variables:

  • String variable named name with the value "Tutor Joes"
  • int variable named age with the value 25
  • float variable named percent with the value 25.25f
  • char variable named gender with the value 'M'
  • boolean variable named married with the value false

The program then prints the values of these variables to the console using the System.out.println() method, along with a label for each variable.

Source Code

//04  
 
import java.lang.*;
 
class variables
{
	public static void main(String args[])
	{
		String name="Tutor Joes";
		int age=25;
		float percent=25.25f;
		char gender='M';
		boolean married=false;
		System.out.println("Name 		: "+name);
		System.out.println("Age  		: "+age);
		System.out.println("Percent     : "+percent);
		System.out.println("Gender      : "+gender);
		System.out.println("Married     : "+married);
	}
}

Output

Name        : Tutor Joes
Age         : 25
Percent     : 25.25
Gender      : M
Married     : false
To download raw file Click Here

Basic Programs