More Ways to Create Variables
There are several ways we can create and give values to variables.
Create and Assign Values
You can also combine the two steps of declaring a variable and assigning a variable into one step. This is called initializing. The syntax is as follows :
data_type variable_name = value_to_assign;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MoreVariablesDemo {
public static void main (String[] args) {
//We can declare and assign to a variable in one line
//Instead of declaring a variable
//And then assigning a value in another line
int total = 100;
//Now, try declaring and assigning the price variable into one line
//As we have done for the total variable
double price;
price = price = 105.80;
//You can save an extra line of code
//By declaring and assigning in one line
System.out.println("Total is " + total);
System.out.println("Price is " + price);
}
}