0% found this document useful (0 votes)
4 views33 pages

Java class 10th Chapter 2

This document provides comprehensive revision notes for Java programming targeted at Class IX students. It covers essential topics such as data types, input methods, error types, comments, and packages, along with complete example programs for practical understanding. Additionally, it includes guess papers to aid in exam preparation.

Uploaded by

azhaanansari9411
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

Java class 10th Chapter 2

This document provides comprehensive revision notes for Java programming targeted at Class IX students. It covers essential topics such as data types, input methods, error types, comments, and packages, along with complete example programs for practical understanding. Additionally, it includes guess papers to aid in exam preparation.

Uploaded by

azhaanansari9411
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Sachin Tripathi Java Programming — Class IX Revision Notes

Sachin Tripathi | Java Self-Study Notes | Page 1 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Table of Contents
Table of Contents .......................................................................................................................................................2
How to Use These Notes............................................................................................. Error! Bookmark not defined.
2.1 Initialising and Assigning Data Values ................................................................................................................5
Key Terms ...............................................................................................................................................................5
Types of Data Values (Primitive Data Types) ........................................................................................................5
Methods of Assigning Values ................................................................................................................................5
Complete Program .................................................................................................................................................6
2.2 Input using Parameters.......................................................................................................................................6
Types of Parameters ..............................................................................................................................................6
Ways of Passing Parameters .................................................................................................................................7
Complete Program .................................................................................................................................................7
2.3 Input using the Scanner Class .............................................................................................................................7
Steps to use the Scanner Class ..............................................................................................................................7
Important Methods of the Scanner Class .............................................................................................................8
Complete Program .................................................................................................................................................8
2.4 Types of Errors ....................................................................................................................................................9
Classification of Errors ...........................................................................................................................................9
2.5 Comments in Java ............................................................................................................................................ 10
Types of Comments ............................................................................................................................................ 10
2.6 Packages in Java ............................................................................................................................................... 11
Types of Packages ............................................................................................................................................... 11
Commonly Used Built-in Packages ..................................................................................................................... 11
How to Import a Package ................................................................................................................................... 11
2.7 Mathematical Functions in Java ...................................................................................................................... 12
Important Methods of the Math Class............................................................................................................... 12
Complete Program .............................................................................................................................................. 12
2.8 Java Expressions ............................................................................................................................................... 13
Types of Expressions ........................................................................................................................................... 13
Operator Precedence (High to Low) ................................................................................................................... 13
Type Conversion in Expressions ......................................................................................................................... 14
2.9 Decision Making Statements ........................................................................................................................... 14
2.10 if Statement ................................................................................................................................................... 15
Syntax .................................................................................................................................................................. 15
Flow of Execution................................................................................................................................................ 15
Complete Program .............................................................................................................................................. 15

Sachin Tripathi | Java Self-Study Notes | Page 2 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.11 if-else Statement ............................................................................................................................................ 16


Syntax .................................................................................................................................................................. 16
Complete Program .............................................................................................................................................. 16
2.12 if-else-if Statement (Ladder) ......................................................................................................................... 17
Syntax .................................................................................................................................................................. 17
Complete Program .............................................................................................................................................. 17
2.13 Nested if Statement ....................................................................................................................................... 18
Syntax .................................................................................................................................................................. 18
Complete Program .............................................................................................................................................. 18
2.14 switch-case Statement................................................................................................................................... 19
Syntax .................................................................................................................................................................. 19
Important Rules .................................................................................................................................................. 19
Complete Program .............................................................................................................................................. 20
2.15 Difference between if-else and switch-case ................................................................................................. 20
2.16 Looping Statements ....................................................................................................................................... 21
Essential Components of a Loop ........................................................................................................................ 21
2.17 Classification of Loops ................................................................................................................................... 21
Based on Condition Testing ................................................................................................................................ 21
Based on Number of Iterations .......................................................................................................................... 21
2.18 for Loop .......................................................................................................................................................... 22
Syntax .................................................................................................................................................................. 22
Flow of Execution................................................................................................................................................ 22
Complete Program .............................................................................................................................................. 22
2.19 while Loop ...................................................................................................................................................... 23
Syntax .................................................................................................................................................................. 23
Complete Program .............................................................................................................................................. 23
2.20 do-while Loop ................................................................................................................................................ 24
Syntax .................................................................................................................................................................. 24
Complete Program .............................................................................................................................................. 24
2.21 Special Loops .................................................................................................................................................. 24
2.22 Jump Statements ........................................................................................................................................... 25
Types of Jump Statements ................................................................................................................................. 25
2.23 Interconversion of Loops ............................................................................................................................... 26
2.24 Comparison of Various Types of Loops ......................................................................................................... 28
2.25 Nested Loops .................................................................................................................................................. 28
Syntax .................................................................................................................................................................. 28
Complete Program .............................................................................................................................................. 28

Sachin Tripathi | Java Self-Study Notes | Page 3 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Guess Paper — 1 ..................................................................................................................................................... 30


SECTION A (40 Marks) — Answer all questions ................................................................................................. 30
SECTION B (40 Marks) — Attempt any four questions ...................................................................................... 31
Guess Paper — 2 ..................................................................................................................................................... 32
SECTION A (40 Marks) — Answer all questions ................................................................................................. 32
SECTION B (40 Marks) — Attempt any four questions ...................................................................................... 33

Sachin Tripathi | Java Self-Study Notes | Page 4 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.1 Initialising and Assigning Data Values


In Java, before a variable can be used, it must be declared with a data type. A variable can then be given a value
either at the time of declaration (initialisation) or afterwards (assignment).

Key Terms
● Declaration: Telling the compiler the name and data type of a variable, e.g. int marks;
● Initialisation: Declaring a variable and giving it a value in the same statement, e.g. int marks = 95;
● Assignment: Giving a value to a variable that has already been declared, e.g. marks = 88;

Types of Data Values (Primitive Data Types)


Data Type Size Default Value Example
byte 1 byte 0 byte b = 10;
short 2 bytes 0 short s = 200;
int 4 bytes 0 int n = 1000;
long 8 bytes 0L long l = 100000L;
float 4 bytes 0.0f float f = 5.5f;
double 8 bytes 0.0 double d = 99.99;
char 2 bytes '\u0000' char c = 'A';
boolean 1 bit false boolean flag = true;

Methods of Assigning Values


1. Assigning a literal value directly
Example:
int age = 15;
double price = 499.50;
char grade = 'A';
boolean isPass = true;

2. Assigning value through an expression


Example:
int a = 10, b = 20;
int sum = a + b; // sum is assigned the result of a + b

3. Assigning value using another variable


Example:
int x = 50;
int y = x; // y now also holds 50

Sachin Tripathi | Java Self-Study Notes | Page 5 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

4. Assigning value through user input (Scanner class)


This is discussed in detail in Section 2.3 (Input using the Scanner Class).

Complete Program
Program: Declare, initialise and display data values
public class DataValues
{
public static void main(String args[])
{
int rollNo = 21; // initialisation
String name; // declaration only
name = "Aarav"; // assignment
double marks = 92.5;
char grade = 'A';
boolean pass = true;

[Link]("Roll No : " + rollNo);


[Link]("Name : " + name);
[Link]("Marks : " + marks);
[Link]("Grade : " + grade);
[Link]("Pass : " + pass);
}
}

Output:
Roll No : 21
Name : Aarav
Marks : 92.5
Grade : A
Pass : true

Note: A variable that is only declared (not initialised) cannot be used in an expression until it is assigned a value,
otherwise the compiler gives a "variable might not have been initialized" error.

2.2 Input using Parameters


Instead of taking input from the keyboard, a method can receive input directly through parameters (arguments)
passed to it when it is called. This is a common way of supplying data to methods in Java.

Types of Parameters
Term Meaning
The variable listed in the method definition/heading,
Formal Parameter
e.g. int a, int b in void add(int a, int b)
The real value passed while calling the method, e.g.
Actual Parameter
add(10, 20);

Sachin Tripathi | Java Self-Study Notes | Page 6 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Ways of Passing Parameters


1. Pass by Value (used for primitive data types in Java)
A copy of the actual value is passed to the method. Any change made to the formal parameter inside the method
does NOT affect the original variable.

2. Passing multiple parameters


A method can accept more than one parameter, separated by commas, and each parameter must have its own
data type mentioned.

Complete Program
Program: Find the sum of two numbers using parameters
public class ParamDemo
{
void sum(int a, int b) // a, b are formal parameters
{
int total = a + b;
[Link]("Sum = " + total);
}

public static void main(String args[])


{
ParamDemo obj = new ParamDemo();
[Link](15, 25); // 15, 25 are actual parameters
}
}

Output:
Sum = 40
Note: In Java, primitive types are always passed by value. Only objects/arrays are passed by reference of the
object (the reference itself is copied).

2.3 Input using the Scanner Class


The Scanner class (found in the package [Link]) is the most common way of taking input from the keyboard in
Java programs. It must be imported at the top of the program before it can be used.

Steps to use the Scanner Class


● Step 1: Import the package → import [Link];
● Step 2: Create an object → Scanner sc = new Scanner([Link]);
● Step 3: Call the appropriate method to read the required data type.

Sachin Tripathi | Java Self-Study Notes | Page 7 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Important Methods of the Scanner Class


Method Purpose Return Type
nextInt() Reads an integer value int
nextLong() Reads a long value long
nextFloat() Reads a float value float
nextDouble() Reads a double value double
Reads a single word (stops at
next() String
whitespace)
Reads an entire line, including
nextLine() String
spaces
nextBoolean() Reads a boolean value (true/false) boolean

Complete Program
Program: Accept name, age and marks using the Scanner class
import [Link];

public class ScannerDemo


{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter your name : ");
String name = [Link]();
[Link]("Enter your age : ");
int age = [Link]();
[Link]("Enter your marks: ");
double marks = [Link]();
[Link]("\n--- Details ---");
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("Marks : " + marks);
}
}

Output:
Enter your name : Ishaan
Enter your age : 15
Enter your marks: 88.5

--- Details ---


Name : Ishaan
Age : 15
Marks : 88.5

Sachin Tripathi | Java Self-Study Notes | Page 8 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Note: If nextInt(), nextDouble(), etc. is followed immediately by nextLine(), the nextLine() will read an empty string
because the newline character left in the buffer is consumed first. Use an extra [Link]() to clear the buffer, or
use next()/nextLine() consistently.

2.4 Types of Errors


An error is a mistake in a program that prevents it from compiling or running correctly, or that produces a wrong
result. Errors in Java are broadly classified into three types.

Classification of Errors
Type When it Occurs Example Detected By
Violates the grammar int a = 10 (missing
Syntax Error Compiler
rules of Java semicolon)
Occurs while the program Dividing a number by
Runtime Error JVM (at run time)
is executing zero: int x = 5/0;
Program runs but gives a Using + instead of * to Programmer (on checking
Logical Error
wrong result find area output)

1. Syntax Errors
These occur when the rules of the Java language are not followed, such as missing semicolons, unmatched braces,
misspelled keywords, or undeclared variables. The program will not compile until these are fixed.

Example (contains a syntax error):


int marks = 90
[Link](marks); // Error: ';' expected after 90

2. Runtime Errors
These occur while the program is running, even though it compiled successfully. Common causes include division
by zero, invalid array index, or trying to use a null reference.

Example:
int a = 10, b = 0;
[Link](a / b); // ArithmeticException: / by zero

3. Logical Errors
The program compiles and runs without any error message, but the output is incorrect because the logic used by
the programmer is wrong.

Example:
int length = 5, breadth = 4;
int area = length + breadth; // should be length * breadth
[Link]("Area = " + area); // gives 9 instead of 20

Sachin Tripathi | Java Self-Study Notes | Page 9 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Note: Syntax and runtime errors stop the program, but a logical error does not — it silently produces a wrong
answer, which makes it the hardest to detect.

2.5 Comments in Java


Comments are non-executable statements used to explain code. They are completely ignored by the compiler and
are meant only for programmers to understand or document the program.

Types of Comments
Type Symbol Usage
Used for short, one-line
Single-line comment //
explanations
Used to comment out several lines
Multi-line comment /* .... */
at once
Used to generate official
Documentation comment /** .... */ documentation using the javadoc
tool

Example:
// This program calculates the area of a circle
public class Circle
{
/* The following method
computes area = pi * r * r */
public static void main(String args[])
{
/** Documentation comment
* @author Sachin Tripathi
*/
double r = 7, area;
area = 3.14 * r * r; // formula used
[Link]("Area = " + area);
}
}

Output:
Area = 153.86
Note: Comments do not affect the size of the compiled .class file's execution speed; they are removed before
compilation begins.

Sachin Tripathi | Java Self-Study Notes | Page 10 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.6 Packages in Java


A package in Java is a grouping (folder/namespace) of related classes and interfaces. Packages help organise code,
avoid naming conflicts, and provide access control.

Types of Packages
● Built-in (predefined) packages — supplied by Java itself.
● User-defined packages — created by the programmer using the keyword package.

Commonly Used Built-in Packages


Package Purpose
Contains fundamental classes (String, Math, Integer,
[Link] System). Imported automatically — no need to import
explicitly.
Contains utility classes such as Scanner, ArrayList,
[Link]
Random, Date.
Contains classes for input and output operations, e.g.
[Link]
BufferedReader.
[Link] Contains classes to create applets.
Contains classes for building Graphical User Interfaces
[Link]
(GUI).

How to Import a Package


Syntax:
import [Link]; // imports a single class
import packageName.*; // imports all classes of the package

Example:
import [Link];
public class PackageDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number : ");
int n = [Link]();
[Link]("Square root = " + [Link](n));
}
}

Output:
Enter a number : 81
Square root = 9.0

Sachin Tripathi | Java Self-Study Notes | Page 11 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Note: [Link] is the only package that need not be imported explicitly, since it is loaded automatically by the
JVM for every Java program.

2.7 Mathematical Functions in Java


Java provides a built-in class called Math (from the package [Link]) which contains many ready-made methods
(functions) for performing common mathematical calculations.

Important Methods of the Math Class


Method Description Example Result
Returns the absolute
[Link](x) [Link](-7) 7
(positive) value
Returns x raised to the
[Link](x,y) [Link](2,3) 8.0
power y
Returns the square root
[Link](x) [Link](25) 5.0
of x
[Link](x) Returns the cube root of x [Link](27) 3.0
Returns the greater of a
[Link](a,b) [Link](4,9) 9
and b
Returns the smaller of a
[Link](a,b) [Link](4,9) 4
and b
Rounds x to the nearest
[Link](x) [Link](4.6) 5
whole number
Returns the smallest
[Link](x) [Link](4.2) 5.0
integer ≥ x (as double)
Returns the largest
[Link](x) [Link](4.8) 4.0
integer ≤ x (as double)
Returns the natural
[Link](x) [Link](1) 0.0
logarithm of x
Returns a random double,
[Link]() [Link]() e.g. 0.732…
0.0 ≤ value < 1.0

Complete Program
Program: Demonstrate common Math class functions
public class MathDemo
{
public static void main(String args[])
{
[Link]("abs(-15) = " + [Link](-15));
[Link]("pow(5,2) = " + [Link](5, 2));
[Link]("sqrt(64) = " + [Link](64));
[Link]("max(12,20) = " + [Link](12, 20));
[Link]("round(7.5) = " + [Link](7.5));

Sachin Tripathi | Java Self-Study Notes | Page 12 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

[Link]("ceil(3.1) = " + [Link](3.1));


[Link]("floor(3.9) = " + [Link](3.9));
}
}

Output:
abs(-15) = 15
pow(5,2) = 25.0
sqrt(64) = 8.0
max(12,20) = 20
round(7.5) = 8
ceil(3.1) = 4.0
floor(3.9) = 3.0

Note: All Math class methods are called using the class name directly ([Link]), because they are
static methods — no object of the Math class needs to be created.

2.8 Java Expressions


An expression is a valid combination of operators, constants and variables that evaluates to produce a single value.

Types of Expressions
Type Description Example
Uses arithmetic operators (+, -, *, /,
Arithmetic Expression a+b*c
%) to perform calculations
Uses relational operators (<, >, <=,
Relational Expression a>b
>=, ==, !=) and returns a boolean
Combines relational expressions
Logical Expression using &&, ||, ! and returns a (a>b) && (b>c)
boolean
Assigns the result of the right-hand
Assignment Expression x=a+b
side to a variable

Operator Precedence (High to Low)


Order Operators Description
1 () Parentheses
2 ++ -- (unary) Increment / Decrement, unary +/-
3 * / % Multiplication, Division, Modulus
4 + - Addition, Subtraction
5 < <= > >= Relational operators
6 == != Equality operators
7 && Logical AND

Sachin Tripathi | Java Self-Study Notes | Page 13 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Order Operators Description


8 || Logical OR
9 = += -= etc. Assignment operators

Type Conversion in Expressions


● Implicit Conversion (Widening): Automatically done by the compiler when a smaller data type is
converted to a larger one, e.g. int to double.
● Explicit Conversion (Type Casting / Narrowing): Done manually by the programmer to convert a larger
type to a smaller one, e.g. (int) 9.8

Example:
public class ExprDemo
{
public static void main(String args[])
{
int a = 15, b = 4;
double result = a / b; // implicit conversion, int/int first
double correct = (double) a / b; // explicit cast before division
[Link]("a/b as double = " + result);
[Link]("(double)a/b (correct) = " + correct);
[Link]("a % b = " + (a % b));
boolean check = (a > b) && (b > 0);
[Link]("check = " + check);
}
}

Output:
a/b as double = 3.0
(double)a/b (correct) = 3.75
a % b = 3
check = true

Note: int a / int b performs integer division and truncates the decimal part BEFORE the result is stored in a
double. Casting one operand to double before the division gives the correct decimal answer.

2.9 Decision Making Statements


Decision making (conditional/selection) statements allow a program to choose between different paths of
execution depending on whether a given condition is true or false. Java provides the following decision-making
constructs, each explained in detail in the sections that follow.

Statement Use
if Executes a block only when the condition is true
if-else Executes one block if true, another if false
if-else-if ladder Tests multiple conditions one after another

Sachin Tripathi | Java Self-Study Notes | Page 14 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Statement Use
Nested if An if statement written inside another if statement
Selects one of many blocks based on the value of an
switch-case
expression

2.10 if Statement
The if statement is the simplest decision-making statement. It executes a block of code only if the given condition
evaluates to true. If the condition is false, the block is simply skipped.

Syntax
if (condition)
{
statement(s); // executes only when condition is true
}

Flow of Execution
● The condition is evaluated first.
● If it is true, the statements inside the block execute.
● If it is false, control jumps to the statement immediately after the if block.

Complete Program
Program: Check if a number is positive
import [Link];
public class IfDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number : ");
int n = [Link]();

if (n > 0)
{
[Link](n + " is a positive number");
}
[Link]("Program ends.");
}
}

Output:
Enter a number : 8
8 is a positive number
Program ends.

Sachin Tripathi | Java Self-Study Notes | Page 15 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Note: If the block contains only a single statement, the curly braces { } are optional — but using them is always
recommended for clarity and to avoid logical errors.

2.11 if-else Statement


The if-else statement provides two paths of execution: one block runs when the condition is true, and another
block runs when the condition is false. Exactly one of the two blocks will always execute.

Syntax
if (condition)
{
statement(s); // executes when condition is true
}
else
{
statement(s); // executes when condition is false
}

Complete Program
Program: Check whether a number is even or odd
import [Link];
public class IfElseDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number : ");
int n = [Link]();

if (n % 2 == 0)
{
[Link](n + " is Even");
}
else
{
[Link](n + " is Odd");
}
}
}

Output:
Enter a number : 7
7 is Odd

Sachin Tripathi | Java Self-Study Notes | Page 16 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.12 if-else-if Statement (Ladder)


When more than two possibilities need to be tested, the if-else-if ladder is used. Conditions are tested one after
another from top to bottom, and as soon as one condition is found true, its block executes and the rest are
skipped.

Syntax
if (condition1)
{
statement(s);
}
else if (condition2)
{
statement(s);
}
else if (condition3)
{
statement(s);
}
else
{
statement(s); // executes when none of the above are true
}

Complete Program
Program: Assign a grade based on marks obtained
import [Link];
public class GradeDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter marks : ");
int marks = [Link]();

if (marks >= 90)


[Link]("Grade A");
else if (marks >= 75)
[Link]("Grade B");
else if (marks >= 60)
[Link]("Grade C");
else
[Link]("Grade D");
}
}

Output:
Enter marks : 82
Grade B

Sachin Tripathi | Java Self-Study Notes | Page 17 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Note: The order of conditions matters. Since conditions are tested top to bottom, they must be arranged from the
most specific/highest range to the lowest, otherwise the ladder gives a wrong result.

2.13 Nested if Statement


A nested if is an if (or if-else) statement placed inside the body of another if or else block. It is used when a decision
depends on the result of another decision, i.e. one condition needs to be checked only after another condition is
already true.

Syntax
if (condition1)
{
if (condition2)
{
statement(s); // executes only when BOTH condition1 and condition2 are true
}
else
{
statement(s); // condition1 true, condition2 false
}
}
else
{
statement(s); // condition1 false
}

Complete Program
Program: Find the largest of three numbers using nested if
import [Link];
public class NestedIfDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter three numbers : ");
int a = [Link](), b = [Link](), c = [Link]();

if (a >= b)
{
if (a >= c)
[Link]("Largest = " + a);
else
[Link]("Largest = " + c);
}
else
{
if (b >= c)

Sachin Tripathi | Java Self-Study Notes | Page 18 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

[Link]("Largest = " + b);


else
[Link]("Largest = " + c);
}
}
}

Output:
Enter three numbers : 12 45 30
Largest = 45

2.14 switch-case Statement


The switch statement is a multi-way branch statement that compares the value of an expression against a list of
case values, and executes the matching block. It provides a cleaner alternative to a long if-else-if ladder when
comparing a single variable against several fixed values.

Syntax
switch (expression)
{
case value1:
statement(s);
break;
case value2:
statement(s);
break;
...
default:
statement(s);
}

Important Rules
● The expression must evaluate to byte, short, int, char, String, or an enum (not float/double/boolean).
● Case values must be constants and must all be unique.
● The break statement is used to exit the switch after a matching case executes; without it, execution 'falls
through' into the next case.
● The default case is optional and executes when no case matches; it can be placed anywhere but is
usually written last.

Sachin Tripathi | Java Self-Study Notes | Page 19 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Complete Program
Program: Display the day of the week using switch-case
import [Link];
public class SwitchDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter day number (1-7) : ");
int day = [Link]();

switch (day)
{
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid day number");
}
}
}

Output:
Enter day number (1-7) : 3
Wednesday

Note: Since Java 7, switch also works with String values, e.g. case "Monday": — this is frequently asked in board
examinations.

2.15 Difference between if-else and switch-case

Basis if-else Statement switch-case Statement


Can test any type of condition Tests only equality against fixed
Condition Type
(relational, logical, range) constant values
Works with all data types including Works only with byte, short, int,
Data Type
boolean, float, double char, String, enum
Becomes complex/hard to read Cleaner and easier to read for
Readability
with many conditions multiple fixed choices
Tests conditions sequentially, one Directly jumps to the matching case
Execution
at a time using the value
Can check a range, e.g. marks >= 60 Cannot directly check a range of
Range Checking
&& marks <= 75 values
Relatively slower for many Generally faster for many fixed
Speed
conditions choices

Sachin Tripathi | Java Self-Study Notes | Page 20 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.16 Looping Statements


A loop is a control structure that repeats a block of statements again and again as long as a given condition remains
true. Loops are used to avoid writing the same code multiple times and to perform repetitive tasks efficiently.

Essential Components of a Loop


● Initialisation — setting the starting value of the loop control (counter) variable.
● Condition (Test Expression) — checked before/after each repetition to decide whether to continue
looping.
● Update (Increment/Decrement) — changes the counter variable after each iteration so that the loop
eventually ends.
● Body of the loop — the statement(s) that get repeated.
Note: A loop that never satisfies its terminating condition is called an infinite loop, and must generally be avoided
unless intentionally created (see Section 2.21).

2.17 Classification of Loops


Loops in Java are classified in two important ways: based on when the condition is tested, and based on whether
the number of repetitions is known in advance.

Based on Condition Testing


Type Description Loops in this category
The condition is tested BEFORE the
loop body executes. If false at the
Entry-controlled Loop for loop, while loop
very start, the body may not
execute even once.
The condition is tested AFTER the
Exit-controlled Loop loop body executes. The body do-while loop
always executes at least once.

Based on Number of Iterations


Type Description Example
The number of iterations is known for loop, e.g. running exactly 10
Definite / Counter-controlled Loop
in advance times
The number of iterations depends
Indefinite / Condition-controlled while loop reading input until user
on a condition and is not fixed in
Loop enters 0
advance

Sachin Tripathi | Java Self-Study Notes | Page 21 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.18 for Loop


The for loop is an entry-controlled, definite loop that combines initialisation, condition testing and updating in a
single line, making it the most commonly used loop when the number of iterations is known.

Syntax
for (initialisation; condition; update)
{
statement(s);
}

Flow of Execution
● Initialisation is executed once, at the very beginning.
● Condition is checked; if true, the loop body executes.
● After the body runs, the update statement executes.
● Control goes back to check the condition again — this repeats until the condition becomes false.

Complete Program
Program: Print the first 10 natural numbers and their sum using a for loop
public class ForDemo
{
public static void main(String args[])
{
int sum = 0;
for (int i = 1; i <= 10; i++)
{
[Link](i + " ");
sum = sum + i;
}
[Link]("\nSum = " + sum);
}
}

Output:
1 2 3 4 5 6 7 8 9 10
Sum = 55

Sachin Tripathi | Java Self-Study Notes | Page 22 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.19 while Loop


The while loop is an entry-controlled loop used when the number of iterations is not known in advance and
depends on a condition. The condition is checked before every iteration.

Syntax
initialisation;
while (condition)
{
statement(s);
update;
}

Complete Program
Program: Print the multiplication table of a number using a while loop
import [Link];
public class WhileDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number : ");
int n = [Link]();

int i = 1;
while (i <= 10)
{
[Link](n + " x " + i + " = " + (n * i));
i++;
}
}
}

Output:
Enter a number : 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

Note: If the update statement (i++) is forgotten, the condition never becomes false and the program runs into an
infinite loop.

Sachin Tripathi | Java Self-Study Notes | Page 23 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

2.20 do-while Loop


The do-while loop is an exit-controlled loop — the body of the loop is executed first, and the condition is checked
afterwards. This guarantees that the loop body runs at least once, even if the condition is false from the start.

Syntax
initialisation;
do
{
statement(s);
update;
} while (condition); // note the semicolon at the end

Complete Program
Program: Display numbers from 1 to 5 using a do-while loop
public class DoWhileDemo
{
public static void main(String args[])
{
int i = 1;
do
{
[Link]("Value of i = " + i);
i++;
} while (i <= 5);
}
}

Output:
Value of i = 1
Value of i = 2
Value of i = 3
Value of i = 4
Value of i = 5

Note: A do-while loop always requires a semicolon after the while(condition), unlike the for and while loops.

2.21 Special Loops


These are variations of loops used in specific situations frequently tested in the ICSE board examination.

1. Infinite Loop
A loop whose condition never becomes false, so it keeps repeating forever (until stopped externally, e.g. by a
break statement).

Sachin Tripathi | Java Self-Study Notes | Page 24 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Example:
for ( ; ; )
{
[Link]("This runs forever!");
}

2. for Loop with Multiple Initialisations and Updates


A single for loop can initialise and update more than one variable at a time, separated by commas.

Example:
for (int i = 1, j = 10; i <= 5; i++, j--)
{
[Link]("i = " + i + " j = " + j);
}

Output:
i = 1 j = 10
i = 2 j = 9
i = 3 j = 8
i = 4 j = 7
i = 5 j = 6

3. Loop with an Empty Body


Occasionally used to consume time or count without performing any repeated action; the body is simply a
semicolon.

Example:
int i;
for (i = 1; i <= 100; i++); // empty body — counts silently till 100
[Link]("Final i = " + i);

Output:
Final i = 101

2.22 Jump Statements


Jump statements are used to alter the normal flow of control inside a loop or switch block.

Types of Jump Statements


Statement Purpose
Terminates the loop or switch statement completely and transfers control to the
break
statement immediately after it
Skips the remaining statements of the current iteration and moves to the next
continue
iteration of the loop
return Exits from the current method and optionally returns a value to the caller

Sachin Tripathi | Java Self-Study Notes | Page 25 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

break statement
Example:
for (int i = 1; i <= 10; i++)
{
if (i == 6)
break; // loop stops completely when i becomes 6
[Link](i + " ");
}

Output:
1 2 3 4 5

continue statement
Example:
for (int i = 1; i <= 6; i++)
{
if (i == 3)
continue; // skips printing only when i is 3
[Link](i + " ");
}

Output:
1 2 4 5 6

return statement
Example:
public class ReturnDemo
{
static int square(int n)
{
return n * n; // exits the method with a value
}
public static void main(String args[])
{
[Link]("Square = " + square(6));
}
}

Output:
Square = 36

2.23 Interconversion of Loops


Any for, while, or do-while loop can be rewritten as any other type of loop, since they all share the same three
components: initialisation, condition, and update. This is a favourite board question.

Sachin Tripathi | Java Self-Study Notes | Page 26 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

for → while
// for loop
for (int i = 1; i <= 5; i++)
{
[Link](i);
}

// equivalent while loop


int i = 1;
while (i <= 5)
{
[Link](i);
i++;
}

while → do-while
// while loop
int i = 1;
while (i <= 5)
{
[Link](i);
i++;
}

// equivalent do-while loop (add a check for the initial condition)


int i = 1;
if (i <= 5)
{
do
{
[Link](i);
i++;
} while (i <= 5);
}

do-while → for
// do-while loop
int i = 1;
do
{
[Link](i);
i++;
} while (i <= 5);

// equivalent for loop


for (int i = 1; i <= 5; i++)
{
[Link](i);
}

Sachin Tripathi | Java Self-Study Notes | Page 27 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Note: When converting a do-while to a for/while loop, remember that do-while executes at least once even if the
condition is initially false — this must be handled separately if an exact equivalent is required.

2.24 Comparison of Various Types of Loops

Basis for Loop while Loop do-while Loop


Control Type Entry-controlled Entry-controlled Exit-controlled
1 (always executes at
Minimum Executions 0 (may not execute at all) 0 (may not execute at all)
least once)
When body must run at
Definite/counter- Indefinite iterations,
Best Suited For least once, e.g. menu-
controlled iterations condition-based
driven programs
Written separately;
Initialisation, Condition, Written separately,
All three in a single line condition checked at the
Update outside/inside the loop
end
Required —
Semicolon after condition Not required Not required
while(condition);

2.25 Nested Loops


A nested loop is a loop written inside the body of another loop. The inner (nested) loop completes ALL of its
iterations for every single iteration of the outer loop. Nested loops are extensively used for pattern printing
programs in the ICSE board examination.

Syntax
for (initialisation; condition; update) // outer loop
{
for (initialisation; condition; update) // inner loop
{
statement(s);
}
}

Complete Program
Program: Print a right-angled triangle pattern of stars using nested for loops
public class NestedLoopDemo
{
public static void main(String args[])
{
int rows = 5;
for (int i = 1; i <= rows; i++) // outer loop -> controls rows
{
for (int j = 1; j <= i; j++) // inner loop -> controls columns

Sachin Tripathi | Java Self-Study Notes | Page 28 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

{
[Link]("* ");
}
[Link](); // move to next line after each row
}
}
}

Output:
*
* *
* * *
* * * *
* * * * *

Note: For a pattern with n rows, the outer loop generally controls the number of rows, while the inner loop's limit
is typically expressed in terms of the outer loop's counter (here, j <= i).

Sachin Tripathi | Java Self-Study Notes | Page 29 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Guess Paper — 1

SPECIMEN BOARD-PATTERN QUESTION PAPER


Subject: Computer Applications (Java) | Class: X
Time: 2 Hours Maximum Marks: 80

General Instructions: Answer all questions in Section A and any four questions from Section B. The intended outputs must be
shown wherever a program is written.

SECTION A (40 Marks) — Answer all questions


Question 1. Answer briefly:
(a) Differentiate between formal parameters and actual parameters with a suitable example. [2]
(b) State two differences between the Scanner class methods next() and nextLine(). [2]
(c) What is a logical error? Give one example. [2]
(d) Name the package that is imported automatically in every Java program. Give one class from it. [2]
(e) Write the output of [Link](-4.3) and [Link](-4.3). [2]

Question 2. Answer briefly:


(a) What do you understand by type casting? Differentiate between implicit and explicit type conversion. [2]
(b) State the value of x after execution: int x = 5 + 4 * 2 % 3; [2]
(c) Give two differences between an if-else statement and a switch-case statement. [2]
(d) What is meant by an entry-controlled loop? Name two such loops in Java. [2]
(e) Rewrite the following using a while loop: for(int i=1;i<=5;i++) [Link](i); [2]

Question 3. Find the output of the following code:

int x = 1, sum = 0;
do
{
if (x % 2 == 0)
{
x++;
continue;
}
sum += x;
x++;
} while (x <= 8);
[Link]("Sum = " + sum);
[4]

Question 4. Find the output of the following code:

int m = 3;
switch(m)
{
case 1: [Link]("One");
case 2: [Link]("Two");

Sachin Tripathi | Java Self-Study Notes | Page 30 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

case 3: [Link]("Three");
case 4: [Link]("Four"); break;
default: [Link]("Other");
}
[4]

Question 5. Find the output of the following nested loop and also state how many times the inner loop executes in
total:

for (int i = 1; i <= 3; i++)


{
for (int j = 1; j <= i; j++)
[Link](j + " ");
[Link]();
}
[4]

Question 6. Rewrite the following program segment after removing all syntax errors, underlining each correction:

Class Test
{
public static void Main(String args[])
(
int a = 10, b = 20
[Link]("Sum = " a+b);
}
}
[4]

SECTION B (40 Marks) — Attempt any four questions


Question 7. Write a Java program using the Scanner class to input two numbers and display their sum, difference,
product and quotient using appropriate methods of the Math class where required. [10]

Question 8. Write a Java program to input the age of a person and display whether the person is a Child (age < 13), a
Teenager (13–19) or an Adult (age > 19) using an if-else-if ladder. [10]

Question 9. Write a Java program to input a number and check whether it is prime or not, using a for loop. [10]

Question 10. Write a Java program using a switch-case statement to input a number from 1 to 5 and print the
corresponding name of the day it represents, considering 1 as Monday. [10]

Question 11. Write a Java program to print the sum of the following series using a loop: 1 + 1/2 + 1/3 + 1/4 + ... + 1/n
(accept the value of n from the user). [10]

Question 12. Using a nested for loop, write a Java program to print the following pattern for n = 5 rows:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
[10]

Sachin Tripathi | Java Self-Study Notes | Page 31 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

Guess Paper — 2
SPECIMEN BOARD-PATTERN QUESTION PAPER
Subject: Computer Applications (Java) | Class: X
Time: 2 Hours Maximum Marks: 80

General Instructions: Answer all questions in Section A and any four questions from Section B. The intended outputs must be
shown wherever a program is written.

SECTION A (40 Marks) — Answer all questions


Question 1. Answer briefly:
(a) Differentiate between a syntax error and a runtime error, with one example of each. [2]
(b) Name the three types of comments used in Java and give the symbol used for each. [2]
(c) Give two points of difference between the break and continue statements. [2]
(d) What is meant by an exit-controlled loop? Name the loop in Java that is exit-controlled. [2]
(e) What is the default value of a boolean and a char variable in Java? [2]

Question 2. Answer briefly:


(a) State the number of times the following loop will execute: for(int i=10;i>0;i-=2) [Link](i); [2]
(b) Convert the following if-else-if ladder into an equivalent switch-case structure (only state the case labels used):
if(ch=='a')...else if(ch=='b')...else if(ch=='c')... [2]
(c) What is the purpose of the default keyword in a switch statement? [2]
(d) Write a single Java statement to find the cube of 5 using the Math class. [2]
(e) Why is the Scanner class said to belong to the [Link] package? How is it imported? [2]

Question 3. Find the output of the following code:

int a = 2, b = 3, c;
c = a++ + ++b;
[Link]("a="+a+" b="+b+" c="+c);
[4]

Question 4. Find the output of the following code:

int n = 20;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
[Link](i + " ");
}
[4]

Question 5. Find the output of the following code and mention which type of loop is being demonstrated (entry or
exit-controlled):

int x = 15;
do
{

Sachin Tripathi | Java Self-Study Notes | Page 32 of 33


Sachin Tripathi Java Programming — Class IX Revision Notes

[Link]("x = " + x);


x += 5;
} while (x < 10);
[4]

Question 6. Rewrite the following program segment using a for loop instead of a while loop, without changing its
output:

int i = 1, fact = 1;
while (i <= 5)
{
fact = fact * i;
i++;
}
[Link]("Factorial = " + fact);
[4]

SECTION B (40 Marks) — Attempt any four questions


Question 7. Write a Java program to input the length and breadth of a rectangle using the Scanner class and display
its area and perimeter. [10]

Question 8. Write a Java program to input three sides of a triangle and check whether a valid triangle can be formed.
If valid, further check if it is Equilateral, Isosceles or Scalene, using nested if statements. [10]

Question 9. Write a Java program to input a number and print whether it is a palindrome or not, using a while loop.
[10]

Question 10. Using switch-case, write a menu-driven Java program that inputs the choice of a simple calculator (1-
Add, 2-Subtract, 3-Multiply, 4-Divide) along with two numbers, and displays the result. [10]

Question 11. Write a Java program to input 10 numbers using a for loop and display the sum of all even numbers and
the count of odd numbers among them. [10]

Question 12. Using a nested for loop, write a Java program to print the following pattern for n = 5 rows:

A
B B
C C C
D D D D
E E E E E
[10]

Sachin Tripathi | Java Self-Study Notes | Page 33 of 33

You might also like