Variables, Constants & Operators Topic 4.3.5 / Core
Key points
  • basic Java vocabulary and syntax;
  • data types, operators and functions.
  • variable;
  • constant;
  • data type;
  • primitive;
  • integer and real number;
  • byte, int, long, double, boolean, char;
  • casting;
  • arithmetic operator;
  • assignment;
  • mathematical function.
  • Eck chapter 2, Names and Things.
  • Kjell chapters 5 to 11, Running Java Programs and Data.
Related topics


'The primary purpose of the DATA statement is to give names to constants; instead of referring to Pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of Pi change.'
Quote from an early FORTRAN manual for Xerox computers.
Do you think the value of pi likely to change?

  1. Download the HelloWorld project. Save and unzip it, then use it as a template to play with. There is a Getting Started with BlueJ document here. Make the program display your preferred message(s). Copy and paste the output line several times if you wish.
  2. Work through this presentation on Variables, Constants and Operators.
  3. Given two int variables, e.g. number1 and number2 , how would you go about swapping their contents? There is a BlueJ project called Swapper here for you to save and experiment on.
  4. Work out these expressions as if you were executing a program yourself:
    double answerA = 23.0 / (5.0 * 2.0);
    int answerB = 5 + 11 - 3 * 5;
    int answerC = 12 % 4 * (13 / 7);
    double answerD = -33.0 - (-9.0 + 4;
    and then use this test program called Answerer to enter the code and check your answers.
  5. As you did for HelloWorld, download, save, compile and execute AddingMachine. Then:
    a. make three copies and change their names to SubtractingMachine, MultiplyingMachine and DividingMachine [can you make the last one crash?];
    b. adapt it to create a program that, given a mass by the user, evaluates Einstein's famous equation E = mc2 [you may need to research what the letters stand for; call the new project and class Einstein].
  6. Similarly, make a project called Square that calculates the square and cube of the number that you choose. Be careful how you adapt the output line.
  7. Create a similar program that, given a temperature in degrees Fahrenheit, outputs the same temperature in Celsius. Call the project TempConverter. Research the formula for the conversion.
  8. (a) Trace the following algorithmic extract for an input of 34. [2 marks]
       input (i);
       k = i mod 6;
       m = i div 6;
       output (m*6+k);
    (b) Determine the output if any integer, n, is input. [1 mark]
    (May 2006 SL P1 q11)