Learn Java Variables
Java Variables are containers that are used to store data values.
In Java, there are various types of variables, as given below:
- String: It stores text, for example, “Hello”. String values are provided using double quotes.
- Int: It stores integers, all whole numbers, without decimals, such as 145 or -145.
- Float: It is used to store floating point numbers with decimals, such as 29.99 or -29.99.
- Char: It is used to store single characters, such as ‘a’ or ‘B’. Char values are provided using a single quote.
- Boolean: It is used to store values with two states: true or false.
Creating or Declaring Variables
If you want to create or declare a variable, you must specify your variable type & assign some specific value to it:
Syntax
type variable_Name = value;
Example
String Name = "Ram";
Where type is one of Java’s types. In the above, the code sample type is String, variable_Name is Name, and Value is Ram. To assign some value to variable_name, we use the equal sign “=”.
We can use type java variable for int, float, char and boolen and we will give you sample codes below.
/* Code Sample for int */
type variable_Name = value;
//Example for int
int number= "10";
/* Code Sample for float*/
type variable_Name = value;
//Example for float
int number= "10.25";
/* Code Sample for char*/
type variable_Name = value;
//Example for char
char myLetter = 'H';
/* Code Sample for Boolean*/
type variable_Name = value;
//Example for Boolean
boolean myBool = true;
Now Let’s create a variable that should store text; look at the following example:
Examples
Create a variable called the name of type String and assign it the value “Ram”:
/* Example for String*/
public class First{
public static void main(String[] args) {
String name = "Ram";
System.out.println(name);
}
}
/* Example for Int*/
public class First{
public static void main(String[] args) {
int number = 256;
System.out.println(number);
}
}
/* Example for Float*/
public class First{
public static void main(String[] args) {
float number = 256.5465f;
System.out.println(number);
}
}
/* Example for Double*/
public class First{
public static void main(String[] args) {
double number = 256.5465569856546;
System.out.println(number);
}
}
/* Example for Boolean*/
public class First{
public static void main(String[] args) {
boolean myBool = true;
System.out.println(myBool);
}
}
/* Example for Char*/
public class First{
public static void main(String[] args) {
char myLetter = 'H';
System.out.println(myLetter);
}
}
Learn Java Non-Primitive Data Type