Java class 10th Chapter 2
Java class 10th Chapter 2
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
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;
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;
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.
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);
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);
}
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).
Complete Program
Program: Accept name, age and marks using the Scanner class
import [Link];
Output:
Enter your name : Ishaan
Enter your age : 15
Enter your marks: 88.5
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.
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.
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
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.
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.
Types of Packages
● Built-in (predefined) packages — supplied by Java itself.
● User-defined packages — created by the programmer using the keyword 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
Note: [Link] is the only package that need not be imported explicitly, since it is loaded automatically by the
JVM for every Java program.
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));
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.
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
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.
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
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.
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.
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
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]();
Output:
Enter marks : 82
Grade B
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.
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)
Output:
Enter three numbers : 12 45 30
Largest = 45
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.
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.
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
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.
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.
1. Infinite Loop
A loop whose condition never becomes false, so it keeps repeating forever (until stopped externally, e.g. by a
break statement).
Example:
for ( ; ; )
{
[Link]("This runs forever!");
}
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
Example:
int i;
for (i = 1; i <= 100; i++); // empty body — counts silently till 100
[Link]("Final i = " + i);
Output:
Final i = 101
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
for → while
// for loop
for (int i = 1; i <= 5; i++)
{
[Link](i);
}
while → do-while
// while loop
int i = 1;
while (i <= 5)
{
[Link](i);
i++;
}
do-while → for
// do-while loop
int i = 1;
do
{
[Link](i);
i++;
} while (i <= 5);
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.
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
{
[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).
Guess Paper — 1
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.
int x = 1, sum = 0;
do
{
if (x % 2 == 0)
{
x++;
continue;
}
sum += x;
x++;
} while (x <= 8);
[Link]("Sum = " + sum);
[4]
int m = 3;
switch(m)
{
case 1: [Link]("One");
case 2: [Link]("Two");
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:
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]
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]
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.
int a = 2, b = 3, c;
c = a++ + ++b;
[Link]("a="+a+" b="+b+" c="+c);
[4]
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
{
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]
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]