5 Minutes of Java (2. Declaring and Initialising Variables)

Declaring and Initialising Variables

In Python, you can declare and initialise variables in the following formats:

  • age = 5
  • height = 1.75
  • name = “john”

Python is smart enough to know that the data type for age is int, height is float and name is str.

In Java, you declare and initialise variables in the following formats:

  • int age = 5;
  • double height = 1.75;
  • String name = “john”;

You have to state the data type of the variable as part of variable declaration. (Take note of the semi-colon at the end of each statement).

 One Important point to note:
For python, you can change the data type of a variable. For example,the same variable a can be used to store the value 1 (an integer) and the value “john” (a string).

This is not allowed in Java. If you have declared the variable a as an integer.

  • int a = 1;

You will get an error if you attempt to do the following:

  • a = “john”;

2 thoughts on “5 Minutes of Java (2. Declaring and Initialising Variables)

  1. int a = 1;
    cannot be change by typing
    a = “john”;

    but can it be done if i change to another int?
    int a = 1;
    a = 2;
    so that the a would be changed from 1 to 2

  2. Yes, it can be done. Basically, the data type of the variable cannot be changed after you have declared it. Therefore, if you declare the variable xyz as int, xyz must always be an int.
    int xyz = 10;
    xyz = 20;
    The above code is allowed.

Leave a Reply