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;
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);

results matching ""

    No results matching ""