codingstreets
Search
Close this search box.
java-variables

Get Started: Java Variables

In This Article, You Will Learn about Java Variables.
Before moving ahead, let’s know a bit about Java Comments.

Table of Contents

Java Variables

Variable: Variable is the object that stores values itself and reserved location in the computer memory.

 There are different types of variables –

  • String – A string stores values inside quotation marks. E.g., “Hello World.”
  • int – An int stores the without decimal numerical value such as 11029.
  • float – A float stores the decimal numerical value such as 11.2.
  • char – A char stores a single character such as ‘J’ and ‘A’. Note that a single quotation mark surrounds the char value.
  • boolean – A boolean defines true or false based on the given condition.

Creating a variable

In Java, to create a variable, first must define the variable type, then the variable’s name.

Syntax

				
					type variableName = value;
				
			

Where type is one of Java’s variable types such as String, int and variableName is the variable’s name such as name, age. The equal sign is used to assign values to the variable.

Example: Create a variable called firstName of String type and assign it the value String “Hello World”

				
					String firstName = "Hello World";
System.out.println(firstName);
				
			

Example: Create a variable called firstInteger of int type and assign it the value String 1000.

				
					int firstInteger = 1000;
System.out.println(firstInteger);
				
			

Example: Create a variable but assign value later on after declaring a variable.

				
					int firstInteger; 
firstInteger = 1000;
System.out.println(firstInteger);
				
			

Note: Assigning a new value to an existing variable will overwrite the previous value.

Example: Change the existing value of variable called firstInteger to 2000.

				
					int firstInteger = 1000; 
firstInteger = 2000;
System.out.println(firstInteger);
				
			

Final Variables

Use the final keyword to prevent the values from being overwritten. The final keyword will declare the variable as “final” or “constant“, which means unchangeable and read-only.

Example: Create a variable with using final keyword.

				
					final String Name = "John";
Name = "Johnny";
System.out.println(Name);
				
			

If you find anything incorrect in the above-discussed topic and have further questions, please comment below.

Connect on:

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on