Skip to content
Computer ApplicationsICSE Class 8 · Chapter 4

Program Coding ICSE Class 8: Identifiers, Data Types, Operators and if-else in Java

Updated 15 October 2026 · Fact-checked

ICSE Class 8 Program Coding introduces programming: identifiers and their naming rules, literals, data types such as int, char and float, declaring and initialising variables, arithmetic, relational, logical and assignment operators, compiling and running a program, and decision making with if, if-else and the if-else-if ladder.

What Program Coding is about

A program is a set of instructions, written in a programming language, that a computer carries out. Program coding (programming) means turning an algorithm into such instructions.

The CISCE Class VIII curriculum says programming can be introduced using any programming language. This page uses Java (as in the BlueJ environment many ICSE schools use, and the language of ICSE Computer Applications from Class IX). If your school uses another language, the ideas are the same; only the spelling of the code changes. Every program on this page was compiled and run, and the outputs shown are the actual outputs.

The curriculum asks you to learn:

  • an introduction to programming and the components of a program: identifiers and their naming rules;
  • literals (integer, real, string) and data types (int, char, float and so on) and why different types are needed;
  • declaring and initialising variables;
  • arithmetic (+ - * / %), relational and logical operators, and the assignment operator;
  • compiling and executing programs;
  • the concept, use and syntax of if, if-else and the if-else-if ladder, and designing programs with them.

Weightage: CISCE publishes no question paper, marking scheme or chapter weightage for Class VIII Computer Studies: your school sets and marks the exam. Program Coding sits in the Theme: Program Coding theme of the CISCE Curriculum for Upper Primary Classes (VI-VIII).Source: CISCE Curriculum for Upper Primary Classes (VI-VIII), RDCD 2016

Key concepts

Structure of a program; compiling and executing

A simple Java program:

// My first Java program
class Welcome
{
    public static void main(String args[])
    {
        System.out.println("Welcome to Java");
        System.out.println("I am in Class 8");
    }
}

Output (as run):

Welcome to Java
I am in Class 8
  • class Welcome names the program; the code goes between the curly braces { }.
  • main is where the program starts running.
  • System.out.println(...) prints and moves to a new line; System.out.print(...) prints and stays on the same line.
  • Every statement ends with a semicolon ;.
  • // starts a comment, which the computer ignores; it explains code to people.

Compiling and executing:

  • The program you write is the source code. A compiler checks it for syntax errors (spelling and grammar mistakes in code) and translates it. In Java, the compiler (javac) produces bytecode, which the Java Virtual Machine (JVM) then executes (runs).
  • In BlueJ: write the class, click Compile; if there are no errors, right-click the class and choose void main(String[] args) to run it.
  • Errors: syntax errors (missing semicolon, wrong spelling) are caught when compiling; logical errors (wrong formula) give wrong answers and must be found by testing.

Worked example

A student types System.out.println("Hello") without a semicolon and also writes Println with a capital P. When are these errors found, and what kind are they?

Try it first, then show the solutionSolution
  1. Both are syntax errors: Java needs a semicolon after each statement, and it is case-sensitive, so Println is not the same as println.
  2. The compiler reports them when the program is compiled, before it can run.

Answer: Syntax errors, found at compile time.

Identifiers, literals and data types

Identifiers are the names given to variables, classes and other parts of a program, such as age, totalMarks, Welcome.

Naming rules (Java):

  • May contain **letters, digits, underscore _ and dollar sign**.
  • Must not start with a digit (2marks is invalid; marks2 is valid).
  • No spaces or other symbols (total marks, marks% are invalid).
  • Must not be a keyword (reserved word such as int, class, if).
  • Case-sensitive: Age and age are different.
  • Good practice: meaningful names such as area, studentName.

Literals are fixed values written directly in the program:

LiteralExamples
Integer25, -7, 0
Real (floating-point)3.14, -0.5, 152.5f
Character'A', '7' (one character in single quotes)
String"Riya", "Class 8" (text in double quotes)
Booleantrue, false

Data types tell the computer what kind of value a variable holds and how much memory it needs:

TypeHoldsSizeExample
intwhole numbers4 bytesint age = 13;
floatdecimal numbers (less precise)4 bytesfloat height = 152.5f;
doubledecimal numbers (more precise)8 bytesdouble pi = 3.14159;
chara single character2 byteschar grade = 'A';
booleantrue or false(1 bit of information)boolean passed = true;
Stringtext (a class, not a basic type)variesString name = "Riya";

Why different data types? To save memory (no need for 8 bytes to store an age), to store values correctly (decimals need float or double; text needs String), and to let the computer check errors (you cannot store "ten" in an int).

Worked example

Which identifiers are valid? (i) total_marks (ii) 2ndTerm (iii) class (iv) my name (v) area1

Try it first, then show the solutionSolution
  1. Valid: (i) letters and underscore; (v) letters then a digit.
  2. Invalid: (ii) starts with a digit; (iii) keyword; (iv) contains a space.

Answer: Valid: (i) and (v)

Declaring and initialising variables

A variable is a named memory location whose value can change while the program runs.

  • Declaration: telling the computer the variable's type and name: int age;
  • Initialisation: giving it its first value: age = 13;
  • Both together: int age = 13;
  • Several of one type: int a = 17, b = 5;

Program (as run):

class DataTypes
{
    public static void main(String args[])
    {
        int age = 13;
        float height = 152.5f;
        double pi = 3.14159;
        char grade = 'A';
        boolean passed = true;
        String name = "Riya";
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height);
        System.out.println("Pi: " + pi);
        System.out.println("Grade: " + grade);
        System.out.println("Passed: " + passed);
    }
}

Output:

Name: Riya
Age: 13
Height: 152.5
Pi: 3.14159
Grade: A
Passed: true

The + between text and a value joins them into one string. A float literal needs an f at the end (152.5f); without it Java treats the number as a double.

Worked example

Write statements to declare and initialise a variable for (i) the number of students, 40 (ii) the price of a pen, ₹12.50 (iii) a section letter, B.

Try it first, then show the solutionSolution
  1. (i) Whole number: int students = 40; (ii) Decimal: double price = 12.50;
  2. (iii) One character: char section = 'B';

Answer: int students = 40; double price = 12.50; char section = 'B';

Arithmetic, relational, logical and assignment operators

Program (as run) with int a = 17, b = 5;:

System.out.println(a + b);          // 22
System.out.println(a - b);          // 12
System.out.println(a * b);          // 85
System.out.println(a / b);          // 3   (int / int drops the decimal part)
System.out.println(a % b);          // 2   (remainder)
System.out.println(17.0 / 5);       // 3.4 (a decimal operand gives a decimal answer)
System.out.println(a > b);          // true
System.out.println(a == b);         // false
System.out.println(a != b);         // true
System.out.println(a > 10 && b > 10); // false
System.out.println(a > 10 || b > 10); // true
System.out.println(!(a > b));       // false
GroupOperatorsResult
Arithmetic+ - * / %a number; % gives the remainder
Relational> < >= <= == (equal to) != (not equal to)true or false
Logical&& (AND: both true), OR, written as two vertical bars (at least one true), ! (NOT: reverses)true or false
Assignment=stores the value on the right in the variable on the left

Assignment (as run): int x = 10; x = x + 5; makes x 15; then x = x * 2; makes it 30. x = x + 5 is not an equation; it means 'take x, add 5, store the result back in x'.

Do not confuse = (assign) with == (compare).

Order: *, /, % before +, -; brackets first. With int y = 7;, y % 3 + y / 2 = 1 + 3 = 4 (as run).

Joining strings (as run): "Sum = " + 3 + 4 prints Sum = 34 (text first, so each number is joined as text), but "Sum = " + (3 + 4) prints Sum = 7.

Worked example

Give the output (as run): int p = 25, q = 4; then print p / q and p % q on one line, p / q stored in a double, and p + q * 2.

Try it first, then show the solutionSolution
  1. p / q = 6 (integer division), p % q = 1: prints 6 1.
  2. double d = p / q; stores 6 first, so prints 6.0. p + q * 2 = 25 + 8 = 33.

Answer: 6 1, then 6.0, then 33

Taking input with Scanner

To make programs work for any values, read input from the keyboard using the Scanner class.

import java.util.Scanner;
class Interest
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter principal: ");
        double p = sc.nextDouble();
        System.out.print("Enter rate: ");
        double r = sc.nextDouble();
        System.out.print("Enter time in years: ");
        double t = sc.nextDouble();
        double si = p * r * t / 100;
        double amt = p + si;
        System.out.println("Simple interest = " + si);
        System.out.println("Amount = " + amt);
    }
}

Run with 5000, 8 and 3: Simple interest = 1200.0 and Amount = 6200.0.

  • import java.util.Scanner; makes the Scanner class available.
  • sc.nextInt() reads an int; sc.nextDouble() a double; sc.next() one word; sc.nextLine() a whole line.
  • A double result is printed with .0 when it is a whole number.

Worked example

Which Scanner method would you use to read (i) a number of students (ii) a temperature like 36.6 (iii) a one-word city name?

Try it first, then show the solutionSolution
  1. (i) Whole number: nextInt(). (ii) Decimal: nextDouble().
  2. (iii) One word: next().

Answer: nextInt(), nextDouble(), next()

Decision making: if, if-else and the if-else-if ladder

if: runs a statement only when the condition is true.

if (n > 0)
    System.out.println("Positive");

if-else: chooses between two paths (as run: 27 → 27 is odd, −4 → -4 is even).

if (n % 2 == 0)
    System.out.println(n + " is even");
else
    System.out.println(n + " is odd");

if-else-if ladder: chooses one of many; conditions are checked from the top, the first true one runs and the rest are skipped.

if (m >= 90)
    g = 'A';
else if (m >= 75)
    g = 'B';
else if (m >= 60)
    g = 'C';
else
    g = 'D';

As run: 82 → B, 90 → A, 59 → D.

Rules:

  • The condition goes in brackets and must be true or false.
  • No semicolon after if (condition).
  • Without braces, only the first statement after if or else belongs to it. Use { } for more than one statement.

Braces trap (as run): int m = 10; if (m > 5) m = m + 1; m = m * 2; prints 22: only m = m + 1 belongs to the if; m = m * 2 always runs. Similarly, with n = -4, if (n > 0) System.out.println("Positive"); System.out.println("Done"); prints only Done.

Worked example

In the grade ladder above, why is the second condition written as m >= 75 and not m >= 75 && m < 90?

Try it first, then show the solutionSolution
  1. The ladder reaches else if (m >= 75) only when m >= 90 was false, so m is already below 90.
  2. Repeating m < 90 is unnecessary (though not wrong).

Answer: Because the earlier condition has already ruled out 90 and above.

Program Coding in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

if-else-if ladder for prices

Suppose a museum charges nothing for children under 5, ₹100 for ages 5 to 17, ₹200 for ages 18 to 59 and ₹120 for ages 60 and above.

Write the ladder and give the price for ages 4, 18, 59 and 60 (outputs as run).

Try it first, then show the solutionSolution
  1. if (age < 5) price = 0; else if (age < 18) price = 100; else if (age < 60) price = 200; else price = 120;
  2. Age 4 → Rs 0; 18 → Rs 200; 59 → Rs 200; 60 → Rs 120.

Answer: Rs 0, Rs 200, Rs 200, Rs 120

Memory hook: Test every boundary: 4, 5, 17, 18, 59, 60.

if-else for a bill

Imagine an electricity board that charges ₹5 per unit for the first 100 units and ₹7 per unit above 100.

Write the if-else and give the bill for 80 and 150 units (as run).

Try it first, then show the solutionSolution
  1. if (u <= 100) bill = u * 5; else bill = 100 * 5 + (u - 100) * 7;
  2. 80 → Bill = Rs 400; 150 → Bill = Rs 850.

Answer: Rs 400 and Rs 850

Memory hook: Two slabs, two branches.

Choosing data types

Suppose you are writing a school library program that stores a book's title, number of copies, price and whether it is available.

Choose a data type for each and give a declaration.

Try it first, then show the solutionSolution
  1. Title: String title = "Wings of Fire"; Copies: int copies = 3;
  2. Price: double price = 250.75; Available: boolean available = true;

Answer: String, int, double, boolean

Memory hook: Text → String; count → int; money → double; yes/no → boolean.

Topics in this chapter

Program Coding: syntax and key facts

Program skeleton
class Name { public static void main(String args[]) { statements; } }
Execution starts in main.
Declaration and initialisation
type name = value; e.g. int age = 13;
float literals need f: 152.5f.
Integer division and remainder
17 / 5 gives 3; 17 % 5 gives 2; 17.0 / 5 gives 3.4
int / int drops the fraction.
Relational and logical
> < >= <= == != give true/false; && AND, || OR, ! NOT
= assigns; == compares.
Selection
if (c) s1; / if (c) s1; else s2; / if (c1) s1; else if (c2) s2; else s3;
First true condition wins in a ladder.

Program Coding: diagrams to practise

Practise each one on paper: draw it from the checklist, then tick off every label.

From source code to output

Show the steps from writing a Java program to getting its output.

Draw

  1. A box: Source code (Welcome.java) written by the programmer.
  2. An arrow labelled 'compile (javac)' to a box: Bytecode (Welcome.class); a side arrow to 'syntax errors listed' if any.
  3. An arrow labelled 'execute (JVM)' to a box: Output on screen.

Label

  • Source code
  • Compiler
  • Syntax errors
  • Bytecode
  • Java Virtual Machine
  • Output

Watch out: In BlueJ, the Compile button does the first arrow; running main does the second.

How the school exam asks Program Coding

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Identifiers and data typesValid or invalid names; choose a data type; classify literals.Check the four naming rules; match value to type.
Operators and outputPredict outputs of expressions, especially /, % and string joining.Work out each operator in order; int / int drops decimals.
if-else tracingGive the output of a code fragment for given values; braces traps.Mark which statements belong to each if; test boundaries.
Write a programPrograms with Scanner input and if, if-else or a ladder (bills, grades, largest, tickets).import, class, main, input, decision, output with labels.

Tricks to remember Program Coding

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • No digit first, no space, no keyword

    The three 'no's of naming identifiers (and remember: case matters).

    Use it when: Identifier rules.

  • % is the leftover

    17 % 5: five goes three times into 17, leftover 2.

    Use it when: Remainder operator.

  • One = gives, two == ask

    = gives a value; == asks 'are these equal?'.

    Use it when: Assignment versus comparison.

  • Ladder: first true wins

    Climb from the top; stop at the first true rung.

    Use it when: if-else-if ladder.

  • No braces, one statement

    Without { }, if controls just the next statement.

    Use it when: Avoiding the braces trap.

Program Coding: exam-level solved questions

Ordered from exam level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: Remainder operator · 1 mark · MCQExam level

What is the value of 23 % 4?
(a) 5
(b) 3
(c) 5.75
(d) 4

Try it first, then show the solutionSolution
  1. 4 goes into 23 five times (20), leaving 3.
  2. % gives the remainder.

Answer: (b)

Example 2: Declaration and initialisation · 2 marks · Short answerExam level

Differentiate between declaration and initialisation of a variable with an example.

Try it first, then show the solutionSolution
  1. Declaration states the type and name: int marks;
  2. Initialisation gives the first value: marks = 85; (or together: int marks = 85;).

Answer: As above

Example 3: Predict the output · 3 marks · Short answerHarder exam level

Give the output (all verified by running):

int x = 8;
x = x + 4;
System.out.println(x);
x = x * 3;
System.out.println(x);
int y = 11;
int z = y % 4 + y / 3;
System.out.println(z);
System.out.println("Sum = " + 5 + 6);
System.out.println("Sum = " + (5 + 6));
System.out.println(5 + 6 + " is the sum");
Try it first, then show the solutionSolution
  1. x = 12, then 36. z = 11 % 4 + 11 / 3 = 3 + 3 = 6.
  2. "Sum = " + 5 joins first, giving Sum = 5, then 6 is joined: Sum = 56.
  3. Brackets add first: Sum = 11. In 5 + 6 + " is the sum", 5 + 6 = 11 is added before the text: 11 is the sum.

Answer: 12
36
6
Sum = 56
Sum = 11
11 is the sum

Example 4: Even or odd program · 4 marks · Long answerHarder exam level

Write a program to input a number and print whether it is even or odd. Give the output for 27.

Try it first, then show the solutionSolution
  1. import java.util.Scanner;
    class EvenOdd
    {
        public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int n = sc.nextInt();
            if (n % 2 == 0)
                System.out.println(n + " is even");
            else
                System.out.println(n + " is odd");
        }
    }
  2. Input with Scanner and nextInt().
  3. A number is even if its remainder on division by 2 is 0.
  4. As run with 27: 27 is odd.

Answer: 27 is odd

Example 5: Largest of three · 3 marks · Short answerHarder exam level

Write the decision part of a program to find the largest of three integers a, b and c using logical operators, and give the output for (15, 25, 20) and (8, 8, 3).

Try it first, then show the solutionSolution
  1. if (a >= b && a >= c)
        big = a;
    else if (b >= c)
        big = b;
    else
        big = c;
    System.out.println("Largest = " + big);
  2. (15, 25, 20): first condition false; 25 >= 20 true → Largest = 25 (as run).
  3. (8, 8, 3): 8 >= 8 && 8 >= 3 true → Largest = 8 (as run); >= handles equal values.

Answer: Largest = 25; Largest = 8

Example 6: Leap year with logical operators · 4 marks · Long answerHOTS / competency

Write a program to test whether a year is a leap year using one if-else with logical operators. Give the output for 1900, 2000 and 2024.

Try it first, then show the solutionSolution
  1. A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.
  2. import java.util.Scanner;
    class Leap
    {
        public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter year: ");
            int y = sc.nextInt();
            if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
                System.out.println(y + " is a leap year");
            else
                System.out.println(y + " is not a leap year");
        }
    }
  3. 1900: divisible by 100 and not by 400 → 1900 is not a leap year.
  4. 2000 → 2000 is a leap year; 2024 → 2024 is a leap year (all as run).

Answer: 1900 not leap; 2000 leap; 2024 leap

Example 7: Integer division trap · 3 marks · Short answerHOTS / competency

Predict the output and explain each line (verified by running):

int p = 20, q = 6;
double d = p / q;
double e = (double) p / q;
System.out.println(d);
System.out.println(e);
System.out.println(p > q && q > 10);
Try it first, then show the solutionSolution
  1. p / q is int / int = 3; storing it in a double gives 3.0.
  2. (double) p turns 20 into 20.0 first, so the division is decimal: 3.3333333333333335.
  3. 20 > 6 is true but 6 > 10 is false; AND needs both, so false.

Answer: 3.0
3.3333333333333335
false

Case-study practice (Section B style)

Read the situation, then answer every part. In a school exam set on the board pattern this is a 6-mark question split into 2 + 2 + 2 marks.

The school canteen billing program

Suppose the canteen wants a program that inputs the total bill and prints the amount to pay: no discount up to ₹200, 5% off for bills above ₹200 up to ₹500, and 10% off above ₹500. A student has written the ladder below.

if (bill > 200)
    pay = bill - bill * 5 / 100;
else if (bill > 500)
    pay = bill - bill * 10 / 100;
else
    pay = bill;
  1. (i) · 2 marks

    What does the program print as the amount to pay for a bill of ₹600, and why is this wrong?

    Answer

    Answer: 570.0 instead of 540.0

    600 > 200 is true, so the first branch runs and gives 5% off: 600 − 30 = 570.0 (with bill and pay as double). The 10% branch is never reached for any bill above 500, because those bills are also above 200.

  2. (ii) · 2 marks

    Correct the ladder.

    Answer

    Answer: Test the larger limit first

    if (bill > 500)
        pay = bill - bill * 10 / 100;
    else if (bill > 200)
        pay = bill - bill * 5 / 100;
    else
        pay = bill;

    Now 600 → 540.0, 400 → 380.0, 150 → 150.0.

  3. (iii) · 2 marks

    Which data type should bill and pay have, and why?

    Answer

    Answer: double

    Bills and discounts can have paise (decimal values), so double is suitable; int would drop the decimal part.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

State two rules for naming identifiers in Java and give one valid and one invalid example. (2 marks)

StepMarks
Cannot start with a digit; no spaces or special symbols except _ and the dollar sign; not a keyword (any two)1
Valid: totalMarks; invalid: 2marks (or total marks, class)1

Program (15 marks): Write a Java program to input the units of electricity used and print the bill: ₹5 per unit for the first 100 units and ₹7 per unit for units above 100. Show the output for 80 and 150 units. (15 marks)

StepMarks
import java.util.Scanner;, class declaration and main method3
Scanner object, prompt and int u = sc.nextInt();3
Correct if-else: if (u <= 100) bill = u * 5; else bill = 100 * 5 + (u - 100) * 7;5
Output with a label: System.out.println("Bill = Rs " + bill);2
Outputs: 80 → Bill = Rs 400; 150 → Bill = Rs 8502

Where students lose marks in Program Coding

The slips examiners see most often, and what to write instead.

  • Mistake: Using = instead of == in a condition

    = assigns; in Java if (x = 5) does not compile for an int x.

    Wrong working

    if (n % 2 = 0)

    Right working

    if (n % 2 == 0)

    Do this: One = gives, two == ask.

    Usually costs: 1 mark, and the program will not compile.

  • Mistake: Putting a semicolon after if (condition)

    if (a > b); ends the if at once; the next statement always runs.

    Do this: Never put ; straight after the condition's bracket.

    Usually costs: 1-2 marks.

  • Mistake: Forgetting integer division

    7 / 2 is 3 in Java when both are int.

    Wrong working

    7 / 2 = 3.5

    Right working

    7 / 2 = 3; 7.0 / 2 = 3.5

    Do this: Make one operand a decimal if you need a decimal answer.

    Usually costs: 1 mark.

  • Mistake: Wrong order in an if-else-if ladder

    A wide condition at the top hides narrower ones below it.

    Do this: Put the most restrictive condition first (bill > 500 before bill > 200).

    Usually costs: Logic marks in programs.

  • Mistake: Missing quotes or the f in literals

    char c = A; and float h = 152.5; do not compile.

    Do this: char c = 'A'; and float h = 152.5f;

    Usually costs: 1 mark.

Practice questions on Program Coding

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · MCQExam level

    Which is a valid identifier?
    (a) 1stName
    (b) first name
    (c) first_name
    (d) int

    Hint

    Digit first, space, keyword.

    Answer

    (c)

  2. Q2 · 1 mark · Very short answerExam level

    Name the data type for (i) 25 (ii) 'Y' (iii) true.

    Hint

    Whole number, character, yes/no.

    Answer

    (i) int (ii) char (iii) boolean.

  3. Q3 · 2 marks · Short answerExam level

    What is a variable? Write a statement to declare and initialise a variable for the temperature 36.6.

    Hint

    Named memory location.

    Answer

    A variable is a named memory location whose value can change during the program. double temp = 36.6;

  4. Q4 · 2 marks · Short answerExam level

    Classify the literals: 45, "45", 4.5, '4'.

    Hint

    Quotes matter.

    Answer

    45 integer; "45" string; 4.5 real; '4' character.

  5. Q5 · 1 mark · Assertion-reasonHarder exam level

    Assertion (A): In Java, 9 / 2 evaluates to 4.
    Reason (R): When both operands are integers, Java drops the decimal part of the quotient.
    (a) (A) is true and (R) is false.
    (b) (A) is false and (R) is true.
    (c) Both (A) and (R) are true, and (R) is the correct explanation for (A).
    (d) Both (A) and (R) are true, but (R) is not the correct explanation for (A).

    Hint

    Integer division.

    Answer

    (c)

  6. Q6 · 2 marks · Short answerHarder exam level

    With int a = 29, b = 4;, give the value of (i) a % b (ii) a / b (iii) a > 25 || b > 10 (iv) !(a != b).

    Hint

    int / int drops the decimal part; || needs only one true side.

    Answer

    (i) 1 (ii) 7 (iii) true (iv) false.

  7. Q7 · 2 marks · Short answerHarder exam level

    Give the output (as run):

    int m = 7;
    if (m % 2 == 0)
        m = m / 2;
        m = m + 10;
    System.out.println(m);
    Hint

    Indentation does not decide which lines belong to the if.

    Answer

    17: without braces only m = m / 2 belongs to the if, and it is skipped because 7 is odd; m = m + 10 always runs despite its indentation, giving 17.

  8. Q8 · 2 marks · Short answerHarder exam level

    Distinguish between syntax errors and logical errors with an example of each.

    Hint

    Compile versus wrong answer.

    Answer

    A syntax error breaks the language rules and is caught by the compiler, e.g. a missing semicolon. A logical error lets the program run but gives a wrong result, e.g. writing area = l + b instead of l * b.

  9. Q9 · 4 marks · Long answerHarder exam level

    Write a program to input marks and print the grade: A for 90 and above, B for 75 to 89, C for 60 to 74, D below 60. Give the output for 82.

    Hint

    if-else-if ladder.

    Answer
    import java.util.Scanner;
    class Grade
    {
        public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter marks: ");
            int m = sc.nextInt();
            char g;
            if (m >= 90)
                g = 'A';
            else if (m >= 75)
                g = 'B';
            else if (m >= 60)
                g = 'C';
            else
                g = 'D';
            System.out.println("Grade: " + g);
        }
    }

    As run with 82: Grade: B.

  10. Q10 · 3 marks · Short answerHarder exam level

    Write the expressions in Java: (i) a is between 10 and 20 inclusive (ii) ch is a vowel 'a' or 'e' (iii) n is not equal to 0.

    Hint

    &&, ||, !=.

    Answer

    (i) a >= 10 && a <= 20 (ii) ch == 'a' || ch == 'e' (iii) n != 0.

  11. Q11 · 3 marks · Short answerHarder exam level

    Write a program to input the length and breadth of a rectangle (whole numbers), print its area and perimeter, and print 'It is a square' if they are equal, otherwise 'It is a rectangle'. Give the output for 6 and 4, and for 5 and 5.

    Hint

    Area = l × b; perimeter = 2 × (l + b); then one if-else.

    Answer
    import java.util.Scanner;
    class Rectangle
    {
        public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter length and breadth: ");
            int l = sc.nextInt();
            int b = sc.nextInt();
            System.out.println("Area = " + (l * b));
            System.out.println("Perimeter = " + (2 * (l + b)));
            if (l == b)
                System.out.println("It is a square");
            else
                System.out.println("It is a rectangle");
        }
    }

    As run with 6 and 4: Area = 24, Perimeter = 20, It is a rectangle. With 5 and 5: Area = 25, Perimeter = 20, It is a square.

  12. Q12 · 3 marks · Short answerHOTS / competency

    A museum ticket program uses: if (age < 5) price = 0; else if (age < 18) price = 100; else if (age < 60) price = 200; else price = 120;. Give the price for ages 4, 17, 18 and 60, and explain what would go wrong if the first two conditions were swapped.

    Hint

    Ages under 5 are also under 18.

    Answer

    4 → 0; 17 → 100; 18 → 200; 60 → 120. If age < 18 came first, children under 5 would also satisfy it and be charged 100, so the free-entry branch could never run.

  13. Q13 · 3 marks · Short answerHOTS / competency

    Predict the output and explain: System.out.println("Total: " + 10 + 20); and System.out.println(10 + 20 + " is the total");

    Hint

    Left to right; text changes + into joining.

    Answer

    Total: 1020 and 30 is the total. In the first, the text comes first, so 10 and 20 are joined as text one after another. In the second, 10 + 20 are added as numbers (30) before meeting the text.

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.What is an identifier?Show answer

    A name given to a variable, class or other program element.

  2. 2.Give an example of a string literal.Show answer

    "Hello".

  3. 3.Which data type stores a single character?Show answer

    char.

  4. 4.What does % do?Show answer

    Gives the remainder of a division.

  5. 5.What is the value of !(5 > 3)?Show answer

    false.

  6. 6.What does a compiler do?Show answer

    Checks source code for syntax errors and translates it (into bytecode in Java).

  7. 7.In a ladder, which branch runs?Show answer

    The first one whose condition is true (else, if none is).

Best order to study it

  1. Type and run the Welcome program; learn the skeleton and compiling.
  2. Learn identifier rules, literals and data types.
  3. Practise declaring and initialising variables.
  4. Predict outputs with arithmetic, relational, logical and assignment operators.
  5. Learn Scanner input.
  6. Write and test programs with if, if-else and ladders, checking boundary values.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • Can you write the skeleton of a Java program from memory?
  • Can you spot invalid identifiers?
  • Can you choose the right data type for any value?
  • Can you predict /, % and string-joining outputs?
  • Can you write an if-else-if ladder in the right order?
  • Can you explain compile-time (syntax) and logical errors?

Program Coding: frequently asked questions

My school uses a different language. Is this page still useful?

Yes. The CISCE Class VIII curriculum allows any programming language. Identifiers, literals, data types, operators and if-else exist in every language; only the exact spelling of the code changes.

What is the difference between float and double?

Both store decimals. double uses 8 bytes and is more precise; float uses 4 bytes and needs an f after the literal (152.5f). Most programs use double.

Why does Java print 3 for 17 / 5?

When both operands are int, Java performs integer division and drops the decimal part. Use 17.0 / 5 (or cast to double) to get 3.4.

Is String a data type?

String is a class in Java used to store text. It is used like a data type, but it is not one of the basic (primitive) types such as int and char.

Based on: CISCE Curriculum for Upper Primary Classes (VI-VIII), Computer Studies (Class VIII); CISCE RDCD: Curriculum Pre-School to Class VIII