Model G20 2027 at FLAME University, registrations now open

Revision of Class IX Syllabus | ICSE Class 10 Computer Applications Notes

30 min read

On this page

This note covers object oriented programming, classes and objects, Java compilation, values and data types, operators, input and output, mathematical methods, conditional statements, loops and nested for loops.

What are the principles of object oriented programming?

A program is an ordered set of instructions for carrying out a task. A programming language provides the rules for writing those instructions. Java is a high-level language, meaning that its instructions are expressed in a form more manageable for people than machine instructions.

Property: Objects combine state and behaviour

Object oriented programming, abbreviated OOP, organises a program around objects that combine data and operations. An object represents an entity through its state and behaviour. State means its stored attributes, or properties; behaviour means the operations it can perform through methods, which are named units of executable code.

A class specifies the attributes and methods of its objects. An interface here means the operations exposed for use. A derived class is a class based on an existing class.

How do the four principles differ?

PrincipleMeaning
Data abstractionPresenting essential features while hiding unnecessary implementation details, meaning details of how an operation is performed.
EncapsulationCombining related data and methods within a class and controlling access to that data.
InheritanceDeriving a class from an existing class so that accessible features can be inherited and extended.
PolymorphismAllowing the same operation name or interface to support different forms of behaviour in an appropriate context.

Abstraction concerns what a user needs to know. Encapsulation concerns how related data and operations are grouped and protected. They support each other, but they describe different ideas.

Procedure oriented programming organises a solution primarily around procedures, or routines that perform tasks. Object oriented programming places the associated data and behaviour together in objects. A Java solution still uses sequential instructions, decisions and repetition inside its methods.

When identifying a principle, explain the relevant relationship. Reuse through a derived class points to inheritance. Different forms of an operation point to polymorphism. Hiding unnecessary detail points to abstraction. Combining data with the methods that act on it points to encapsulation.

How do classes, objects and Java execution fit together?

Property: A class specifies its objects

A class specifies the attributes and methods for its objects. A class may be regarded as a blueprint to create objects. It may be viewed as a factory that produces similar objects. A class may also be considered as a new data type created by the user.

An instance is a particular object of a class. The class description and the objects created from it are different: the description sets out the structure, while each object has its own state. A method call requests execution of a method.

What happens between source code and execution?

Source code is the program text written in a programming language. A compiler translates source code into a target representation. In Java, compilation produces bytecode, instructions for the Java Virtual Machine, abbreviated JVM.

  1. Write the Java source code in a source file.
  2. Compile the source; correct any reported compilation errors.
  3. Obtain the generated class file containing Java bytecode.
  4. Run the bytecode through a suitable JVM on the computer.

Object code is translated code produced by a compiler. Java bytecode should not be confused with processor-specific machine instructions. Platform independence describes the ability of the same Java bytecode to run through suitable JVM implementations on different platforms, meaning combinations of hardware and operating system.

Java is described as simple, robust, secure and object oriented. Robustness concerns features that help detect or manage errors. Security concerns protection mechanisms; it does not mean that every Java program is free from vulnerabilities. These features do not remove the need to check program logic.

A Java application is a standalone program. An applet is a Java program designed for execution within a supporting host, traditionally a compatible browser or applet viewer. This distinction describes program organisation and execution context; an applet requires a supporting environment.

How do characters and tokens form a Java program?

A character set is a collection of characters available for representing text. ASCII means American Standard Code for Information Interchange, a character coding scheme. Unicode is a character encoding standard that represents characters from many writing systems.

A variable is a named storage location whose value can change. A string is text represented as a sequence of characters.

A token is a basic meaningful unit recognised in program text. Java tokens include keywords, identifiers, literals, punctuators and operators. Understanding their different roles helps separate names chosen by the programmer from words and symbols that already have a defined purpose.

Token categoryMeaning and Java form
KeywordA reserved word with a language-defined purpose, such as class for declaring a class or int for the integer data type.
IdentifierA name for a program entity, such as a variable, class or method.
LiteralA value written directly in code, including a number, character or string.
PunctuatorA symbol that separates or groups program elements, such as a semicolon or brace.
OperatorA symbol that specifies an operation on values, such as addition or assignment.

Java identifiers are case-sensitive: changing letter case can change the name. A name cannot be a keyword or begin with a digit. Use meaningful names to make the role of a variable visible.

How are special characters represented?

An escape sequence uses a backslash to introduce a special character inside a literal. A character literal uses single quotation marks. A string literal, representing text, uses double quotation marks. Quotation marks delimit the literal; they are not automatically part of the displayed text.

Escape sequenceMeaning
\nNewline
\tHorizontal tab
\\Backslash
\"Double quotation mark
\'Single quotation mark

A constant represents a value intended to remain fixed. Java uses the keyword final to prevent reassignment of a variable after it has been assigned. Distinguish that restriction from a literal, which is the written value itself.

How do data types and conversions control values?

A data type specifies the kind of value a variable can hold and the operations available for it. Java has primitive types for basic values and reference types for references to objects. A boolean value is either true or false. A reference is a value used to refer to an object.

A bit is a binary digit, and a byte consists of eight bits. The following sizes describe primitive value representations. They do not describe the total memory occupied by an object, nor the size of a reference variable.

A signed integer is a whole-number value that can be positive, negative or zero. A floating-point type represents numbers using a form that supports fractional values. A Unicode code unit is a unit used in encoding text; a char does not necessarily hold an entire visible symbol.

Primitive typeKind of valueSize
byteSigned integer8 bits, 1 byte
shortSigned integer16 bits, 2 bytes
intSigned integer32 bits, 4 bytes
longSigned integer64 bits, 8 bytes
floatFloating-point number32 bits, 4 bytes
doubleFloating-point number64 bits, 8 bytes
charUnicode code unit16 bits, 2 bytes
booleantrue or falseNo language-specified storage size

Implicit conversion happens automatically where Java permits it. Explicit conversion, or casting, requests a conversion by writing the target type in parentheses before an expression. An expression produces a value. Narrowing a floating-point value to an integer can discard its fractional part.

How is a complete application written?

In the programs below, Revision is the class identifier. The main method is the application entry point. In its declaration, public permits access, static makes the method belong to the class, and void means that the method returns no value.

String is Java's text class; String[] denotes an array, a sequence of elements, of strings. The identifier args names command-line arguments, values supplied when starting the application. A parameter declares an input; an argument supplies its value. Parentheses enclose method parameters or arguments; braces enclose blocks, groups of statements; a semicolon terminates a simple statement. The equals sign assigns a value; giving a variable its first value is initialisation.

System.out.println displays a value and then ends the line. System names a library class, out refers to its standard output stream, and println names the printing method. A stream is a flow of data. The dot selects a member of a class or object.

Worked example 1. Calculate the area of a rectangle of length 10 units and breadth 20 units. Here area means length multiplied by breadth; * is multiplication.

class Revision {
public static void main(String[] args) {
int length = 10;
int breadth = 20;
int area = length * breadth;
System.out.println(area);
}
}

Answer: Output:
200

  1. Line 1 opens the class declaration; line 2 opens the main method, which runs the calculation.
  2. Line 3 declares length as an int and assigns the given length, 10.
  3. Line 4 declares breadth as an int and assigns the given breadth, 20.
  4. Line 5 declares area and stores the product of length and breadth.
  5. Line 6 prints 200, representing the area in square units. Lines 7 and 8 close the method and class.

How should Java operators and expressions be evaluated?

An operand is a value on which an operator acts. A unary operator has one operand, a binary operator has two, and a ternary operator has three. The conditional operator has the form condition ? firstValue : secondValue.

Here condition is a boolean expression, firstValue supplies the result when it is true, and secondValue supplies the result when it is false. The question mark and colon separate these parts. Exactly one of the two value expressions is selected for evaluation.

GroupSymbols and meanings
Arithmetic+ adds; - subtracts; * multiplies; / divides; % gives a remainder.
Relational and equality< means less than; > greater than; <= less than or equal to; >= greater than or equal to; == equal to; != not equal to.
Logical&& is true when both operands are true; || is true when at least one is true; ! reverses a boolean value.
Assignment= stores a value; +=, -=, *=, /= and %= combine an operation with assignment.
Increment and decrement++ increases a variable by one; -- decreases it by one.

Precedence determines how operators group in an expression. Associativity resolves grouping among operators at the same precedence. Multiplication, division and remainder take precedence over addition and subtraction. Parentheses make the intended grouping explicit. Assignment groups from right to left.

Prefix increment updates the variable before yielding its value. Postfix increment yields the old value and then updates the variable. A counter records a count; an accumulator stores a running total. Both require suitable initial values before repeated updates.

Rule: For the operators listed here, read precedence from higher to lower: postfix increment/decrement; prefix increment/decrement and unary operators; multiplication/division/remainder; addition/subtraction; ordered comparisons; equality; logical AND; logical OR; conditional operator; assignment.

Short-circuit evaluation means that && skips its right operand when the left operand is false, while || skips its right operand when the left operand is true. With integer operands, / produces an integer quotient, discarding any fractional part towards zero.

Note: Assignment and equality testing have different purposes. A compound assignment also includes conversion back to the left variable's type, so its behaviour is not fully described by simply expanding the arithmetic symbols.

Worked example 2. Add the given integer values 10 and 20. num1 and num2 store the operands; result stores their sum.

class Revision {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
int result = num1 + num2;
System.out.println(result);
}
}

Answer: Output:
30

  1. Line 1 begins the class; line 2 begins the main method.
  2. Line 3 declares num1 and initialises it to 10.
  3. Line 4 declares num2 and initialises it to 20.
  4. Line 5 adds the stored integer values and assigns 30 to result.
  5. Line 6 prints the sum. Lines 7 and 8 close the method and class blocks.

How are input, comments and errors handled?

Input supplies data to a program. Values can be assigned in initialisation statements, passed as arguments when a method is called, or read during execution. A parameter is a named input in a method declaration; an argument is the value supplied in a call.

A package groups related classes. The Scanner class in java.util reads and interprets input. An import declaration allows its short class name to be used. The new operator creates an object; System.in supplies the standard input stream to the Scanner object.

Scanner methodValue read
nextShort(), nextInt(), nextLong()An integer of the corresponding short, int or long type.
nextFloat(), nextDouble()A floating-point value of the corresponding type.
next()The next input token as a string, using whitespace as the usual separator.
nextLine()The rest of the current line as a string, excluding the line separator.
next().charAt(0)The first char of the next input token; charAt selects a character position and position numbering starts at zero.

Note: After a numeric token is read, a following nextLine() may read only the remainder of that line. Check whether a pending line separator needs consuming before reading the intended next line of text.

How can a program's mistakes be classified?

A syntax error violates the language's grammar. A runtime error occurs during execution, for instance when an input token cannot be interpreted as the requested numeric type. A logical error makes a program produce an unintended result despite being able to run.

Debugging means finding and correcting errors. A comment documents code without acting as an executable instruction. Java uses // for a comment continuing to the line's end and /* followed by */ to enclose a block comment. Document variable purposes and input assumptions.

Worked example 3. Read two integers and subtract the second from the first. Input is 5 followed by 7. The variable diff stores the difference; input names the Scanner reference.

import java.util.Scanner;
class Revision {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
int diff = num1 - num2;
System.out.println(diff);
}
}

Answer: Output for input 5 7:
-2

  1. Line 1 imports Scanner. Lines 2 and 3 open the class and main method.
  2. Line 4 creates a Scanner connected to standard input and stores its reference in input.
  3. Line 5 reads the first given integer, 5, into num1; line 6 reads 7 into num2.
  4. Line 7 subtracts num2 from num1, storing -2 in diff.
  5. Line 8 prints the difference. Lines 9 and 10 close the method and class.

How do mathematical library methods simplify calculations?

A library method is a ready-made operation supplied by a library class. Java's Math class belongs to java.lang, whose classes are available without an explicit import of that package. Call these methods using Math followed by a dot and the method name.

In the notation below, x is the supplied numerical argument; y is an exponent, meaning the power to which a base is raised. The symbols a and b represent the two numerical arguments being compared. Empty parentheses mean that no argument is supplied.

Pseudorandom means generated algorithmically to behave like a random selection. Overflow means that an arithmetic result exceeds a type's representable range. Positive infinity here indicates the direction towards larger values when a rounding tie is resolved.

MethodMeaning
Math.pow(x, y)Raises x to the power y; returns double.
Math.sqrt(x)Returns the square root as double for a non-negative argument.
Math.cbrt(x)Returns the cube root as double.
Math.ceil(x)Returns the least integer-valued double greater than or equal to x.
Math.floor(x)Returns the greatest integer-valued double less than or equal to x.
Math.round(x)Returns the nearest integer, with ties towards positive infinity; float gives int and double gives long.
Math.abs(a)Returns absolute value, the magnitude without a negative sign, except for the minimum signed integer overflow case.
Math.max(a, b)Returns the greater of the two supplied values.
Math.min(a, b)Returns the smaller of the two supplied values.
Math.random()Returns a pseudorandom double at least 0.0 and less than 1.0.

Which details matter when predicting output?

Distinguish the mathematical value from the returned data type. An integer-valued double remains a double. Also distinguish rounding from casting: a cast to an integer discards the fractional part towards zero, while round chooses the nearest integer with its stated tie rule.

Rule: Give every mathematical method the required arguments, and account for its return type when storing or printing its result. A random result belongs to an interval; it does not have a fixed predictable output.

Worked example 4. Find the greater of 5 and 6 using Math.max. num1 and num2 store these integer values.

class Revision {
public static void main(String[] args) {
int num1 = 5;
int num2 = 6;
System.out.println(Math.max(num1, num2));
}
}

Answer: Output:
6

  1. Line 1 opens the class; line 2 opens its main method.
  2. Line 3 stores 5 in num1. Line 4 stores 6 in num2.
  3. Line 5 calls Math.max with both int arguments. The int form returns their greater value, 6, which println displays.
  4. Lines 6 and 7 close the main method and the class. No Math object or explicit java.lang import is needed.

How do conditional statements choose what executes?

Flow of control means the order in which statements execute. Selection chooses a path according to a condition. Java's if statement executes its controlled statement or block when its boolean condition is true. An if-else statement provides an alternative for a false condition.

An else-if ladder tests conditions in order and selects the first true branch. A final else supplies a fallback if no condition succeeds. A nested if places one if statement inside another controlled part, making the inner test depend on reaching that part.

How does switch differ from an if-else ladder?

A switch statement selects a starting branch by matching a selector value against case labels. A case label identifies a candidate matching value. The optional default label provides a starting branch when no case matches.

In the traditional colon-style switch, break exits the switch. Without an intervening exit, execution can continue into statements after subsequent labels; this is fall-through. Separate labels do not themselves stop execution. An if-else ladder can test ranges and combinations of conditions directly.

A menu-driven program reads a choice and performs the corresponding operation. Define what every accepted choice means and handle unrecognised choices. System.exit(0) requests termination of the running JVM; the zero status conventionally indicates normal termination. It is different from leaving one switch.

Syntax: In if (condition) { firstBlock } else { secondBlock }, condition is a boolean expression; firstBlock denotes statements selected when true, and secondBlock denotes statements selected when false. These descriptive names stand for the statements to be written.

Worked example 5. For the distinct integer inputs 5 and 6, subtract the smaller from the larger. num1 and num2 hold the inputs, and diff holds the result.

class Revision {
public static void main(String[] args) {
int num1 = 5, num2 = 6;
int diff;
if (num1 > num2) {
diff = num1 - num2;
} else {
diff = num2 - num1;
}
System.out.println(diff);
}
}

Answer: Output:
1

  1. Lines 1 and 2 open the class and main method. Line 3 declares both inputs; the comma separates the two declarations of the same type.
  2. Line 4 declares diff without assigning it yet. Both decision branches assign it before printing.
  3. Line 5 tests whether 5 is greater than 6. It is false, so line 6 is skipped.
  4. Line 7 opens the alternative branch. Line 8 calculates 6 minus 5 and stores 1; line 9 closes the selection.
  5. Line 10 prints 1. Lines 11 and 12 close the method and class.

How do for, while and do-while loops repeat work?

Iteration means repetition of a set of statements. A loop body contains the repeated work. A control variable helps determine whether repetition continues. Initialisation establishes its starting value, the condition tests whether to continue, and the update changes its value.

Property: for and while are entry-controlled; do-while is exit-controlled

The for and while statements are entry-controlled: they test before executing the body. The do-while statement is exit-controlled: it tests after the body, which therefore executes at least once when control enters the loop normally.

Syntax: for (initialisation; condition; update) { body } runs initialisation once, then repeats condition testing, body execution and updating. In while (condition) { body }, place the necessary initialisation before the loop and arrange updates within its repeated work.

A finite loop finishes after a limited number of iterations. An infinite loop continues without reaching a normal exit. A delay loop performs repeated work to introduce a delay, but its elapsed time depends on the execution environment. Multiple counters can be updated within one for loop.

How can the same counting task use three loop forms?

Each following program prints the first five natural numbers, meaning the positive counting numbers beginning at one. The variable count is the current number. The condition count <= 5 includes five; count++ increases the current value by one after each printed number.

Worked example 6. Print the first five natural numbers using for.

class Revision {
public static void main(String[] args) {
for (int count = 1; count <= 5; count++) {
System.out.println(count);
}
}
}

Answer: Output:
1
2
3
4
5

  1. Lines 1 and 2 open the class and main method.
  2. Line 3 declares count, starts it at 1, tests the upper bound and specifies the update.
  3. Line 4 prints the current count. Line 5 ends the body; the update then runs before the next condition test.
  4. After 5 is printed, count becomes 6 and the condition is false. Lines 6 and 7 close the method and class.

Worked example 7. Print the same five numbers using while.

class Revision {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
}
}

Answer: Output:
1
2
3
4
5

  1. Lines 1 and 2 open the class and main method; line 3 initialises count before the loop.
  2. Line 4 checks whether count is at most 5 before permitting each iteration.
  3. Line 5 prints count. Line 6 increments it so the condition can eventually become false.
  4. Line 7 closes the loop body and control returns to the condition. Lines 8 and 9 close the method and class.

Worked example 8. Print the same five numbers using do-while.

class Revision {
public static void main(String[] args) {
int count = 1;
do {
System.out.println(count);
count++;
} while (count <= 5);
}
}

Answer: Output:
1
2
3
4
5

  1. Lines 1 and 2 open the class and main method; line 3 establishes the starting value.
  2. Line 4 enters the body without a preliminary test. Line 5 prints the current number.
  3. Line 6 increments count. Line 7 tests the updated value and includes the required ending semicolon.
  4. The test becomes false when count reaches 6. Lines 8 and 9 close the method and class.

Loop conversion must preserve the initial state, order of printing, update and exit test. Replacing an entry-controlled loop with do-while without considering an initially false condition can change the result. Identical output for these inputs does not prove equivalence for every starting condition.

How do nested for loops, break and continue work?

A nested loop is a loop placed inside another loop. The outer loop controls the enclosing repetition, while the inner loop completes its work for each reached outer iteration. In a printed pattern, the outer loop can select rows and the inner loop can select entries within a row.

For a rectangular pattern, the number of entries can remain fixed across rows. For a right-angled triangular pattern, the number can depend on the current row. Reinitialise the inner control variable whenever the inner loop is entered for a new row.

Where should printing and line changes occur?

System.out.print writes without automatically ending the line; println() with no argument ends the current line. Put entry printing inside the inner loop and the line change after that loop but inside the outer loop. This placement separates entries from rows.

Worked example 9. Print five rows of the pattern shown in the output. num is the row limit, i is the current row, and j is the current entry. The string " " supplies a space after each entry; + joins it to the printed number.

class Revision {
public static void main(String[] args) {
int num = 5;
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Answer: Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

  1. Lines 1 and 2 open the class and main method. Line 3 sets the given row limit to 5.
  2. Line 4 starts each row with i increasing from 1 through num.
  3. Line 5 resets j to 1 for each row and allows entries up to the current i.
  4. Line 6 prints j and a space without ending the row. Line 7 closes the inner loop.
  5. Line 8 ends the completed row. Line 9 closes the outer loop; lines 10 and 11 close the method and class.

An unlabelled break exits the nearest enclosing loop or switch. An unlabelled continue skips the remainder of the current iteration of the nearest enclosing loop. In a for loop, continue proceeds to the update before the next condition test.

In nested loops, an unlabelled break in the inner loop does not automatically terminate the outer loop. Similarly, continue in the inner loop advances that inner loop. Trace which enclosing construct receives control before deciding which statements execute next.

When checking a nested-loop output, record the current outer value, the inner starting value, each inner test and each print operation. Keep spaces and line endings separate from the numeric sequence. This prevents correct entry values from being arranged into an incorrect pattern.

Glossary

  • Class — A specification defining the attributes and methods available to its objects.
  • Object — An instance of a class that combines state with behaviour.
  • Abstraction — Presenting essential features while hiding unnecessary details of their implementation.
  • Encapsulation — Grouping related data and methods within a class and controlling access.
  • Bytecode — Instructions generated by Java compilation for execution through a Java Virtual Machine.
  • Token — A basic meaningful unit recognised within the text of a program.
  • Data type — A classification specifying supported values and the operations permitted on them.
  • Type casting — Explicitly requesting conversion of a value to a specified target type.
  • Precedence — Rules determining how operators group when an expression contains different operators.
  • Accumulator — A variable that stores a running total updated during repeated processing.
  • Parameter — A named input declared by a method to receive an argument.
  • Iteration — One repetition of the statements forming the body of a loop.
  • Nested loop — A loop placed within the body of another enclosing loop.
  • Logical error — A mistake in reasoning that makes a running program produce unintended results.

Common errors and misconceptions

  • Misconception: A class and an object are interchangeable terms. Correct: A class specifies attributes and methods; an object is a particular instance with its own state.
  • Misconception: Bytecode is the original Java source text. Correct: The compiler translates the source into bytecode, which is executed through a suitable JVM.
  • Misconception: The equals sign tests equality. Correct: = performs assignment; == tests equality. Read their roles separately when evaluating a condition or tracing stored values.
  • Misconception: Integer division automatically preserves a fractional quotient. Correct: Division with integer operands produces an integer result, with the fractional part discarded towards zero.
  • Misconception: Casting and rounding have the same effect. Correct: A floating-point to integer cast truncates towards zero; Math.round follows a nearest-integer rule with ties towards positive infinity.
  • Misconception: Every loop tests before executing its body. Correct: for and while test first; do-while executes its body before its first condition test.
  • Misconception: continue exits the entire loop just like break. Correct: continue skips remaining work in the current iteration; break leaves the nearest enclosing loop or switch.
  • Misconception: An inner loop automatically resumes its previous counter value on every row. Correct: Its initialisation runs again each time execution reaches that inner for loop.

Exam-style questions with model answers

Q1. Distinguish between a class and an object. [2 marks]
  1. A class specifies the attributes and methods for the objects created from it; it may be regarded as their blueprint.
  2. An object is a particular instance of a class, combining its stored state with the behaviour supplied through methods.
Q2. Define abstraction, encapsulation, inheritance and polymorphism in object oriented programming. [4 marks]
  1. Abstraction presents the essential features needed to use an operation while hiding unnecessary details of how that operation is implemented.
  2. Encapsulation groups related data and methods within a class and provides a basis for controlling access to that data.
  3. Inheritance allows a derived class to obtain accessible features from an existing class and extend those features where required.
  4. Polymorphism allows the same operation name or interface to support different forms of behaviour in an appropriate programming context.
Q3. For the Java statements int length = 10; int breadth = 20; int area = length * breadth; System.out.println(area); state what each statement does and give the output. The variables represent rectangle length, breadth and area in consistent units; * means multiplication. [4 marks]
  1. The first statement declares the integer variable length and initialises it to the given length of 10 units.
  2. The second statement declares the integer variable breadth and initialises it to the given breadth of 20 units.
  3. The third statement multiplies the stored length and breadth, then assigns their product, 200, to the integer variable area.
  4. The fourth statement displays 200 and ends the line. This numerical value represents the rectangle area in square units.
Q4. For int num1 = 5, num2 = 6; int diff; if (num1 > num2) { diff = num1 - num2; } else { diff = num2 - num1; } System.out.println(diff); identify the condition result, the selected calculation and the output. num1 and num2 are the input integers; diff stores their difference. [3 marks]
  1. The condition compares num1 with num2, asking whether 5 is greater than 6. Its boolean result is false.
  2. The else branch therefore executes and calculates num2 minus num1, giving 6 minus 5. The value 1 is assigned to diff.
  3. The final println statement displays 1 and ends the line. The subtraction in the first branch is skipped for these supplied values.
Q5. Trace this complete loop fragment: for (int count = 1; count <= 5; count++) { System.out.println(count); } Here count is the current integer, <= means less than or equal to, and ++ increases it by one. Explain initialisation, testing, printing, updating and termination, including the full output. [5 marks]
  1. Initialisation declares the integer control variable count and gives it the starting value 1. This initialisation runs once when the loop begins.
  2. The condition tests whether count is at most 5 before each iteration. It permits the body to execute for each value from 1 through 5.
  3. The body prints the current count followed by a line ending. The full output is 1, 2, 3, 4 and 5 on separate lines.
  4. After each completed body execution, count++ increases count by one. Control then returns to the condition before another execution of the body.
  5. After printing 5, the update makes count equal to 6. The next condition is false, so execution leaves the loop without printing 6.
Q6. Explain six features of this Java fragment and give its full output: int num = 5; for (int i = 1; i <= num; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(); } num is the row limit, i the row number and j the entry. ++ increments by one; + joins the number to a space. [6 marks]
  1. The statement before the outer loop sets num to 5, establishing the given number of rows to generate in the printed pattern.
  2. The outer loop starts i at 1 and includes each row number through 5, increasing i by one after each completed row.
  3. The inner loop starts j at 1 afresh whenever a new row begins. Its upper bound is the current value of i.
  4. The print statement displays each j followed by a space. It does not end the line, so entries remain on their current row.
  5. The println statement after the inner loop ends the completed row. Its placement inside the outer loop produces one line ending per row.
  6. The full output, with a space after each entry, is:
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
Q7. Distinguish a syntax error, a runtime error and a logical error. [3 marks]
  1. A syntax error breaks the grammar of the language. The compiler reports such an error, which must be corrected before successful compilation.
  2. A runtime error arises while a program executes, such as when input cannot be interpreted as the numeric type requested by Scanner.
  3. A logical error lies in the intended reasoning or calculation. The program may compile and run, yet its actual output differs from the required result.
Q8. State two differences between an entry-controlled while loop and an exit-controlled do-while loop. [2 marks]
  1. A while loop tests its condition before executing the body, whereas a do-while loop tests after executing the body.
  2. A while body may execute zero times; a do-while body executes at least once when control enters that loop normally.

Key takeaways

  • Objects combine state and behaviour, while classes specify the attributes and methods available to their instances.
  • Java compilation produces bytecode, which executes through a suitable Java Virtual Machine on the target platform.
  • Identify each value's data type before tracing arithmetic, conversions, comparisons or calls to mathematical library methods.
  • Assignment stores a value; equality compares values. Precedence and associativity determine the grouping of operators within expressions.
  • Choose Scanner methods to match the intended input type, and distinguish token reading from reading the remaining line.
  • An if-else ladder selects the first true branch; a traditional switch may fall through without an intervening exit.
  • Trace each loop's initialisation, condition, body and update, checking whether the first test precedes or follows the body.
  • For nested patterns, track rows and entries separately, resetting the inner counter and placing line changes deliberately.

Test yourself

What is the difference between state and behaviour?

State is an object's stored attribute values; behaviour consists of operations provided through its methods.

What does the dot in a Java member access do?

The dot selects a member of a class or object, such as a field or method.

What is the difference between prefix and postfix increment?

Prefix increment updates before yielding a value; postfix increment yields the old value and then updates the variable.

Why can nextLine() appear to read an empty line after nextInt()?

It reads the remainder of the current line, which may be empty before the pending line separator.

What does Math.max return for the integer arguments 5 and 6?

It returns the greater integer argument, 6; the integer form of the method returns an int.

What distinguishes break from continue in a for loop?

An unlabelled break exits the nearest loop or switch; continue skips to the loop update and then the next test.

Why is println() outside the inner loop in a row-printing pattern?

It ends the line after all entries in the current row have been printed by the inner loop.

Why should a loop conversion be checked with an initially false condition?

An entry-controlled loop then skips its body, while a do-while loop executes its body before testing the condition.