All posts by admin

5 Minutes of Java (3. User Input and Display Result)

Getting User Input

In Python, you get user input using the raw_input() function:

  • age = int(raw_input(“Enter your age: “))
  • weight = float(raw_input(“Enter your weight: “))
  • name = raw_input(“Enter your name: “))

In Java, getting user input is more complicated. We have provided a Helper class to simplify the process of getting user input. These are some of the methods that you will commonly use.

  • int age = Helper.readInt(“Enter your age: “);
  • double weight = Helper.readDouble(“Enter your weight: “);
  • String name = Helper.readString(“Enter your name: “);

Display Result

In python, the print() function is used to display result.

  • print (“Hello World”)

In Java, you will need to use the following function to display result.

  • System.out.println(“Hello World”);


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

5 Minutes of Java (1. Variable and Data Type)

Variable and Data Type

You have learnt about the following data type in Python.

  • int – Used for whole numbers (e.g. 1, 10, 100)
  • float – Used for decimal numbers (e.g 1.4, 2.5, 3.0)
  • str – Used for any textual data (e.g. ‘John, “Peter”, “Male”)
    You can use both single quote (‘john’) or double quote (“john”)

In Java, there is similar concept of data type as well.

  • int – Used for whole numbers as well
  • float, double – Used for decimal numbers
    In this course, for simplicity, we will always use double to store decimal numbers.
  • String – Used for textual data. Take note that only double quote is allowed (“john”)