Blue-J: ICSE Class - 10
Blue-J: ICSE Class - 10
Blue-J: ICSE Class - 10
Blue-J
FEATURES:
✓ Well Planned Notes
✓ Mini Test Papers
ICSE Class – 10th ✓ Smart Practice Notes
Computer Application (JAVA) ✓ Tricky Worksheets
✓ Group Classes with
Personal Attention
https://www.youtube.com/c/YPComputerClasses ✓ One to One Classes
https://www.instagram.com/yogesh.verma27/ ✓ YT Videos for Revision
✓ Sharing Student’s Progress
https://www.facebook.com/yogesh.verma.79219 with Parents
https://www.YPComputerClasses.in/
Contents
2. Library Classes 87 – 90
3. Arrays 93 – 107
Private members are available to only own class and not accessible to function outside the class.
Private member data & function cannot be accessed outside the class. It is known as Data Hiding. They can be accessed
only through public members of the class.
Public members are the members which accessible from anywhere either inside or outside.
Or
A class is a blueprint or a prototype that defines characteristics & behaviour common to all objects of a certain kind. It is
the fundamental building block of Object Oriented Programming. How To Create A Class : Syntax:
Eg: class - Student public class class_name
characteristics: name, roll, std, marks. {
Behaviour: calc_tot(), calc_per(). private Data members declaration;
public Member functions declaration;
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→5
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
new: It is a keyword which is use to create an object and helps to allocate memory to an object.
Object can access the public member data & function of class using dot(.) operater.
How To Access : Example:
Syntax: S1.input();
ObjectName . publicMemberName; S1.x;
Data Encapsulation
Wrapping up of data members and member methods together in a single unit which is known as Data Encapsulation.
Abstraction:
Abstraction is the act of representing essential features without getting in to complexity of the system.
Eg: We know how to drive a car. But we don’t know the mechanism that makes the car move.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→6
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Inheritance: It is an ability of object of one class to acquire properties of object of another class. It follows the concept of
hierarchy.
Benefits: It helps in code re-usability. Allows less time in writing a program. Enables program execution faster.
Polymorphism: It means one thing many forms. It is an ability of one object to respond to same message in one or more
different ways.
Benefits: Function Overloading & Overriding.
Components of OOP
The major components of Object Oriented Programming are as follows:
1. Class 2. Object 3. Data Members & Methods 4. Access Specifier and Visibility Modes
Objects related to a class:
A class is a blueprint or prototype that defines variables & methods common to objects of same kind. It combines objects &
methods for manipulating the data in to one neat package.
Object factory:
A class is known as object factory as you can create numerous objects of similar characteristics & behaviour from a class. A
class determines the nature of an object.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→7
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Class encapsulate: A class encapsulates state & behaviour of an object i.e. data members & member methods.
8
Differentiate class & objects:
Class Objects
A class is a template for an object. A object is an instance of a class.
Class does not exist in the computer memory. Object exist in the computer memory.
Types of Java
9
Developers
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→9
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Java Byte Code → Java source code is converted in to an intermediate code after compilation. This code is known as Byte
12
code. It is stored in file with .class extension & is same across all platforms. It can be executed only by Java Virtual Machine.
(source code is the code which is written by the programmer).
API → API stands for Application Programming Interface. It is the java library with pre-written classes and methods for easy
programming.
JDK → Java Development Kit (JDK) is an environment for building java application and applets. It includes tools for
developing & testing programs written in java.
JDK 1.1 → JDK 1.2 → JDK 1.3 → JDK 1.4 → JDK 1.5 → JDK 1.6 → JDK 1.7
Blue J → Blue J is an Integrated Development Environment (IDE) for executing programs written in Java. It has a viewer,
editor & debugger.
Data Types
Token: Token is a smallest individual unit of a program. Tokens are building blocks of Java. Types of tokens are:
16 Types of tokens:
a) Keywords
b) Identifiers
c) Literals
d) Separators
e) Operators
f) Punctuators
(KILSOP)
Keyword
Keywords are reserved words provide by Java which convey special meaning to the compiler. They cannot be used as
identifiers. E.g. int, void, while, case, do, int, double, if, else, final, void, char, for, while, switch, case etc.
Literal (constants)
Literals are data items which do not change its value during the execution of the program.
Type of literals: Integer Literal → 20
Floating point / Real Literal → 2.5
Character Literal → ‘a’
String Literal → “Java”
Boolean Literal → false
Null Literal → null
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→16
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Token→ Literals
17
Differentiate String literal & Character literal.
String Literal Character Literal
It is a set of characters enclosed within double quotes. It is a single character enclosed within single quote.
It stored in a variable with String datatype. It stored in a variable with char datatype.
E.g. String s = “hello”; E.g. char ch = ‘a’;
Separators → Separators are the special characters in Java, which are used to separate the variables or characters.
Eg: ( ) (Brackets) – used to enclose any arithmetical or relational expressions.
{ } (Curly brackets) – used to enclose a group of statements which is called as compound/block statement
[ ] (Square brackets) – used to enclose subscript(index) or the cell number of a dimensional array.
, (Comma) – used to separate multiple variable under the same declaration.
Punctuators → Punctuators are the punctuation signs used as special characters in Java.
Eg: ? (question mark) – It is used in ternary operator.
; (semicolon) – It is a statement terminator. It indicates the end of a statement. Any line continued after semi colon
is treated as the next statement.
. (dot) - It is used to call the function with an object and used to access instance variables by using an object.
Variable
18 Variable is a name given to memory location to store data by user. On the other hand, It is the quantity which can change
during program execution. A variable must be declared before its use. It cannot be declared again in the same scope.
Identifier → Identifiers are the symbolic names given to various parts of program like variable, function, class & object etc.
Variable / Identifier Naming Rules
➢ A variable name is any combination of alphabets, digits, underscores(_) or dollar symbol ($) .
➢ The first character in the variable name must be an alphabet(a/A – z/Z), underscore ( _ ) or dollar( $ ). It can not be a
number. It is case sensitive & can be of any length.
➢ Blank spaces, commas, keywords (reserved words) or special symbol except an underscore or dollar are not allowed
within a variable name.
➢ E.g.: Correct variables → si_int , m_hra , pop_e_89 , $a , _b etc.
➢ Wrong variables → 1a, emp sal, no., if etc.
Variable Declaration
Syntax: Data type variable_name1, var2…….; final keyword / constant variable
Ex: int a; char ch; float per, sal; When a variable is declared using
Variable Initialization final keyword it becomes a constant
a. Static Initialization → Variable is initialized during the compile time. i.e. its value cannot be changed
Eg: int a = 10; during execution of the program.
char ch = ‘b’; double per = 66.5; E.g. final double pi = 3.14;
b. Dynamic Initialization → Variable is initialized during the runtime.
Eg: int a = 10, b=20; int c = a + b ; here c variable is initialized dynamically.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→18
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→22
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→23
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Q7→ Find addition and product of given numbers. Q9→ WAP to swap to numbers.
class Swap
class FirstPro {
{ public static void main(int A, int B)
public static void main(int a, int b) {
{ int C;
int sum, prod; System.out.println(“Before Swapping”);
sum = a + b; System.out.println(“A = " + A);
prod = a * b; System.out.println(“B = " + B);
System.out.println("addition = " + sum);
System.out.println("product = " + prod);
System.out.println(sum + “ is an addition ");
}
} System.out.println(“After Swapping”);
System.out.println(“A = " + A);
Q8→ Write the SOP line to print 10 + 20 = 30 System.out.println(“B = " + B);
in above Program. }
}
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→24
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Q10→ WAP to input employee name and his salary of a month and print his annual salary.
25 class Employee
{
public static void main(String name, int salary, int asal)
{
int asal = salary*12;
System.out.println(“Employee Name = " + name);
System.out.println(“Annual Salary is = " + salary);
System.out.println(“Annual Salary is = " + asal);
}
}
Exercise→(Input using function arguments)
Q1→ Write a program (WAP) to input two numbers and calculate their sum, product, subtraction and division.
Q2→ WAP to input your name, gender and age and print these details.
Q3→ WAP to input rollno, name, marks of four subjects and calculate total & percentage.
Q4→ WAP to input distance in Meters and convert it into CM, KM, inch and feet.
(Hint cm = m*100, km = m/1000, inch = cm*2.5, feet = inch/12)
(1m=100cm, 1km=1000m, 1feet=12 inches, 1 inches=2.5cm)
Q5→ Temperature of a city in Fahrenheit degrees is input. Write a program to convert this temperature into Centigrade
degrees. T(°C) = (T(°F) - 32) × 5/9
Q6→ The length & breadth of a rectangle and radius of a circle are input. Write a program to calculate the area &
perimeter of the rectangle, and the area & circumference of the circle.
Q7→ If the total selling price of 15 items and the total profit earned on them is input, write a program to find the cost price
of one item.
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→25
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→26
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Type Conversion → Conversion of one datatype to another datatype is called type conversion.
27
There are two types of type conversions:
1. Implicit type conversion / type coercion 2. Explicit type conversion / narrowing conversion / type casting
Type Conversion
28
Explicit Conversion of Literals
Examples
float f = 0.123F
double d = 23.34D
int a = 12;
long b = 12L
Operators:- Operators are special symbols which represents computation. They are applied on operand(s), which can be
29 values or variables.
Operand:- Operands are variables or constants on which operations are performed by the operator.
Unary Operator: The Operators which are associated with only one operand are unary operators. Eg: ++, --, +, -, !.
Binary Operator: The Operators which are associated with only two operands are unary operators.
Eg: /, %, *, + , -, <, >, etc. (Arithmetical and Relational Operators)
Ternary Operator: The Operators which are associated with only three operands are unary operators. Eg: ( ? : ) .
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→29
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Arithmetic Operators:
30 They are used for various mathematical calculations. They are /, % (Modulus / Remainder Op), *, +, -.
These operators are also called Binary Arithmetic Operator.
The result depends on the largest data type present in expression or left hand side variable.
a) System.out.println(11/2);
b) System.out.println(11.0/2); i) double a = 10 + 11/2;
c) System.out.println(11%2); System.out.println(a);
d) System.out.println(10%2); ii) double b = 10 + 11.0/2;
e) System.out.println(4%10); System.out.println(b);
f) System.out.println(4/10); iii) int c = (int)(10 + 11.0/2);
g) System.out.println(‘A’ + 10); System.out.println(c);
h) System.out.println(‘b’ + ‘B’); iv) int ch = ‘d’ + 10;
i) System.out.println(‘1’ + 10); System.out.println(ch);
j) System.out.println(“A” + ‘b’ + 10);
k) System.out.println(‘b’ + 10 + “A”);
Relational Operators:
They are used for comparisons between two operands(values). It returns boolean value. They are >, <, >=, <=, ==, !=.
Assignment Operator: Assignment operators are used to assigning value to a variable. The left side operand of the
assignment operator is a variable and right side operand of the assignment operator is a value. Eg. A=10 10 = A
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→30
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Logical Operators: They are used for combining various ! (NOT) Operator: The not operator works by
31 conditions together using an operator. It returns a boolean inverting (or negating) the value of its operand.
value comparing two or more boolean values. ! Condition1 Result
Logical operators are &&(And), ||(Or), !(Not). T F
F T
&& (AND) Operator : It returns true if both conditions are true.
It doesn’t check second condition if first condition is false. Logical Operators Symbol Format
Condition1 && Condition2 Result
T T T NOT ! !(a==b)
T F F
AND && (a>b)&&(a>c)
F T F
F F F OR || (a==b)||(a==c)
|| (OR) Operator : It returns true if either first condition or Precedence of logical operators is NOT (!), AND (&&) and OR (||).
second condition or both are true. It doesn’t check second If a statement contains all the three logical operators then NOT is
condition if first condition is true. operated first.
Condition1 || Condition2 Result
T T T
T F T
F T T
F F F
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→31
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Precedence of Operators:
33
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→33
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Operators ++ and --
35
Increment(++) / Decrement(--)
Pre-Operator Post-Operator
++a, --a a++, a--
Note:
➢ ++ increases value by 1 and - - decreases value by 1.
➢ Pre-Operator uses/transfers always updated value.
➢ Post-Operator uses/transfers always original value then update itself.
Ternary operator(?:)
38 Ternary operator or conditional operator requires 3 operands. It is an alternative to if-else statement. In ternary operator the
first operand must be a conditional expression. If the condition is true then operand 2(true expr) is executed otherwise
operand 3(false expr) is executed. It is also called the conditional assignment statement.
Syntax : var = condition ? true expr : false expr;
Different ways to input in Java Q3→ WAP to find and display the simple interest
39 There are various ways to input the data values in Java. They areand amount by using function argument when
given below. principal, Interest and time are input from console.
1) By using a Function Argument class Swap
2) By using a Scanner Class {
3) By using a InputStreamReader Class public void main(int p, int r, int t)
4) By using Command Line Argument {
1) Programs using function arguments and without static keyword double si, amt;
si = (p*r*t)/100.0;
Q1→ Find Subtraction and Division of given numbers. amt = p+si;
class FirstPro System.out.println(“The Simple interest = “+si);
{ System.out.println(“The amount = “+amt);
public void main(int a, int b) }
{ }
int sub, div;
sub = a - b;
div = a / b;
System.out.println(“Subtraction = " + sub);
System.out.println(“Division = " + div);
System.out.println(sub + “ is a subtraction ");
}
}
Q2→ Write the SOP line to print 10 - 20 = -10 in above Program.
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→39
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→40
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Q7→ WAP to input the time in seconds. Display the time after converting them into hours, minutes and seconds.
41 Sample input: Time in seconds 5430
Sample output: 1 Hour 30 Minutes 20 Seconds
class Time
{
public static void main(int sec)
{
int min, hr;
min = sec/60;
sec = sec%60
hr = min/60;
min = min%60;
System.out.println(hr + “ Hour " +min +” Minutes “+sec+” Seconds”);
}
}
Exercise→(Input using function arguments) Programs
Q8→ Temperature of a city in Fahrenheit degrees is input. Write a program to convert this temperature into Centigrade
degrees. T(°C) = (T(°F) - 32) × 5/9
Q9→ The length & breadth of a rectangle and radius of a circle are input. Write a program to calculate the area &
perimeter of the rectangle, and the area & circumference of the circle.
Q10→ If the total selling price of 15 items and the total profit earned on them is input, write a program to find the cost price
of one item.
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→41
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→42
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Unit 5: Input in Java 2) Input Data at run time using scanner Class
Q1→ Find addition, subtraction, product and division of given Q2→ WAP to swap to numbers.
43 numbers. import java.util.Scanner;
import java.util.Scanner; class Swap
class FirstPro {
{ public static void main(String args[ ])
public static void main() {
{ Scanner sc = new Scanner (System.in);
Scanner sc = new Scanner (System.in); int a, b, c;
int a, b, sum, sub, prod,div; System.out.println("Enter two Numbers ");
System.out.println("Enter two Numbers "); a = sc.nextInt();
a = sc.nextInt(); b = sc.nextInt();
b = sc.nextInt(); System.out.println(“Before Swapping”);
sum = a + b; System.out.println(“a = " + a);
sub = a-b; System.out.println(“b = " + b);
prod = a * b;
div = a/b;
System.out.println("addition = " + sum);
System.out.println(“Subtraction = “ + sub); System.out.println(“After Swapping”);
System.out.println("product = " + prod); System.out.println(“a = " + a);
System.out.println(“Division = “ + div); System.out.println(“b = " + b);
} } }
} Q3→ Write the SOP line to print 10 * 20 = 200
if a=10 and b=20; c=a+b;
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→43
Ch1: Revision of class 9th
JMD HGGM
ICSE Class 10th Sub: Computer Applications
Unit 5: Input in Java 2) Input Data at run time using scanner Class
Q1→ WAP to input your name, gender and age and print these details.
44 Q3→ WAP to input two numbers in A and B and swap these two numbers with using extra variable and without using
extra variable.
Q4→ WAP to input rollno, name, marks of four subjects and calculate total & percentage.
Q5→ WAP to input distance in Meters and convert it into CM, KM, inch and feet.
(Hint cm = m*100, km = m/1000, inch = cm*2.5, feet = inch/12)
(1m=100cm, 1km=1000m, 1feet=12 inches, 1 inches=2.5cm)
Q6→ WAP to input employee name and Basic Salary (BS).
Calculate TA(travelling Allowance), DA(Dearness Allowance), HRA(House Rent Allowance), Total Salary(TS),
IT(income tax), PF(profit & funds) and Net Salary(NS).
TA = 35%of BS, DA = 30%of BS, HRA = 25% of BS, TS = BS + TA + DA + HRA;
IT = 5.6%of TS, PF = 7.5%of TS), NS = TS – ( IT + PF );
Q7→ Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this
temperature into Centigrade degrees. T(°C) = (T(°F) - 32) × 5/9
Q8→ The length & breadth of a rectangle and radius of a circle are input through the keyboard. Write a program to
calculate the area & perimeter of the rectangle, and the area & circumference of the circle.
Q9→ If a four-digit number is input through the keyboard, write a program to obtain the sum of the first and last digit of
this number.
Q10→ If the total selling price of 15 items and the total profit earned on them is input through the keyboard, write a
program to find the cost price of one item.
JMD-HGGM
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→44
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
3) Input Data at run time using InputStreamReader Class, use the following steps:
45
a) Import a package java.io because, because InputStreamReader class is available in it.
b) In main method, create objects of InputStreamReader and BufferedReader classes.
Eg: InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Or
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
readLine()
It is a method which helps to get a string at run time using object of BufferedReader class. Its return type is String.
Syntax: String readLine();
Eg:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter String”);
String a = br.readLine(); parseXXX() is used to convert
System.out.print(“Enter all numeric values”); string into numeric datatype.
int b = Integer.parseInt(br.readLine()); a) Byte.parseByte()
double c = Double.parseDouble(br.readLine()); b) Short.parseShort()
byte d = Byte.parseByte(br.readLine()); c) Integer.parseInt()
short e = Short.parseShort(br.readLine()); d) Long.parseLong()
long f = Long.parseLong(br.readLine()); e) Float.parseFloat()
float g = Float.parse Float(br.readLine()); f) Double.parseDouble()
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→45
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
read() → It is used to get a character from keyboard but it returns ASCII Eg: System.out.print(“Enter a character”);
46
value of a inputted character at run time. Its return type is int. int a = br.read(); // B
Syntax: int read(); System.out.print(a); // 66
char ch = (char) br.read(); // B
Q7→ WAP to input employee name and his salary of a month
System.out.print(a); // B
and print his annual salary.
import java.io.*;
class Employee Character ASCII Code
{ A to Z 65 to 90
public static void main() throws IOException
{ A to z 97 to 122
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 0 to 9 48 to 57
System.out.println("Enter Employee name and his salary");
String name = br.readLine(); import java.util.Scanner;
int salary = Integer.parseInt(br.readLine()); class Employee
int asal = salary*12; { public static void main()
System.out.println(“Annual Salary is="+asal); { Scanner sc = new Scanner (System.in);
} System.out.println("Enter Employee name & his salary");
} String name = sc.nextLine();
int salary = sc.nextInt();
int asal = salary*12;
System.out.println(“Annual Salary is = " + asal);
} }
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→46
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
This is one of the ways to accept the data values from the user and pass the arguments (known as command line
arguments) to the main function like main(String args[ ]). The arguments tp the main function are passed through args[0],
args[1]. Args[2] and so on.
Q1→ Write a program in java to find the value of the given expression.
p = (a2 + b2 )/(a - b) Q2→ WAP in java to accept the
number of days using command line
public class Expression
argument and display the result after
{
converting it into number of years,
public static void main(String args [ ]) // (String [ ] args)
number of months and the remaining
{
numbers of days.
int a, b;
double p;
a = Integer.parseInt(arg[0]);
b = Integer.parseInt(arg[1]); Q3→ WAP in java to accept time in
p = (double)(a*a + b*b)/(a-b); seconds using command line argument
System.out.println(“The value of expression = " + p); and display the time after converting
System.out.println(“Division = " + div); them into hours, minutes and seconds.
} Eg: input Time in second = 5430
} Output: 1 Hour 30 Minutes 30 Seconds
Types of Errors in Java → There are three types of errors that occur in a computer program.
48 1. Syntax Error / Compile time Error
2. Logical Error
3. Runtime Error / Execution Error
1. Syntax Error / Compile time Error: These errors occur when the rules of the programming language are not followed.
They encountered during the compilation of a program.
Eg: missing semicolon, incorrect variable name, undefined terms etc.
2. Logical Error: The errors which occur due to wrong logic which gives incorrect results.
Eg: WAP to program to take three numbers. Divide the sum of first two numbers by the third number and display result.
int a=180,b =240, c=60,p;
p= a+b/c // wrong logic
p=(a+b)/c // correct logic
3. Runtime Error / Execution Error: The errors the occur during the execution of the program are runtime errors. They
may occur due to incorrect mathematical operations or by entering incorrect data values at the time of inputs.
Eg: dividing a number by zero, trying to find out the square root of a negative number.
Comments in Java→ Comments are remarks given by the programmer to explain aspect of the code to the program reader.
They are ignored by the compiler. They are also used for debugging purpose.
There are three (types) styles of writing comments:
✓ Single line comment: //………………………
✓ Multiple line comment: /*……………………*/
✓ Documentation comment: /**………………………………*/ used for a brief document or produce an HTML file that
documents your program.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→48
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Methods/Functions are subprograms or small block of code which perform specific action. Or
49 A large program can be divided into smaller subprograms. These subprograms are called as function.
Advantages of function:-
➢ Complexity of program is reduced.
➢ Debugging (error checking) can be done easily.
➢ Memory is saved. As only a single copy of the function is present in
the memory but it can be called many times in a program.
Categories Of Functions / Methods:
There are two Categories of functions.
1. Built-in methods/ Library methods / Pre-defined methods
Functions/Methods which are pre-defined in ‘JAVA’ language.
Or The methods which are created by the system developers
are said to be library methods or built-in methods.
Example → Math.pow(), Math.abs(), Math.sqrt(), etc.
2. User defined function → Methods are defined by the users itself.
Functions/Methods Answers
1. Math.ceil( 3.4 );
2. Math.ceil( 8 );
3. Math.ceil(4.2);
4. Math.ceil(-0.95);
5. Math.ceil(65.5);
6. Math.ceil(654);
7. Math.ceil(2.9);
8. Math.ceil(12.01);
1. Math.floor(-4.7);
2. Math.floor(16.3);
3. Math.floor(2.9);
4. Math.floor(-99.51);
5. Math.floor(-0.84);
6. Math.floor(64.6);
7. Math.floor(456);
8. Math.floor(-12.01);
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→52
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Math.random( )
53 This function returns a random number between 0 and 1. It returns a double data type value.
Syntax – double Math.random( );
1. To get an integer random number between 1 and n:
int rd = (int) (Math.random( )*n) + 1;
2. To get an integer random number between max and min:
int rd = (int) (Math.random( )*( max – min ) ) + min );
3. To get 0 and 1 as head and tail of a coin randomly.
int n = (int) (Math.random( ) * 2 );
Math.round()
This method returns the value of the argument rounded to the nearest int value.
0.5 and above is rounded to nearest higher int value & below 0.5 is rounded off to nearest lower int value.
Syntax - long Math.round(double a), or int Math.round(float a)
Math.rint()
This method is used to round the argument to nearest integer in floating point.
In case of 0.5 at decimal places it will round off to nearest even double value.
Syntax - double Math.rint(double a)
If statement - Questions
59
Q1→ WAP to input a number and find out whether it is an odd number or even number.
Q2→ WAP to input a number and determine whether the year is a leap year or not.
Q3→ WAP to input a number and check the number is +ve number, –ve number or zero.
Q4→ WAP to input two numbers and find out the greatest number.
Q5→ WAP to input three numbers and find out the smallest number.
Q6→ WAP to input an alphabet and check whether it is vowel or not.
Q7→ WAP to input a character and check whether it is capital alphabet, small alphabet, number or symbol.
Q8→ WAP to input a three-digit number to obtain the reversed number and to determine whether the original and reversed
numbers are equal or not.
Q9→ Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through
the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.
Q10→ WAP to input length and breadth of a rectangle and to find whether the area of the rectangle is greater than its
perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.
Q11→ WAP to input to a number and check the number is buzz number or not.
( Buzz is the number which is divisible by 7 or ends with 7 ).
System.exit(0)
61 When System.exit(0) function is invoked(called), it terminates the execution of the program at that moment. Thus, the
execution of remaining statements of the program is ignored.
Syntax: System.exit(0);
Eg: Q13→ WAP to display the square and cube of a positive number. If entered number is not positive then program terminates
automatically by printing appropriate massage.
import java.util.Scanner;
class Pro_exit
{
public static void main(String args[])
{
Scanner sc = new Scanner (System.in);
int n;
System.out.println("Enter a Number: ");
n = sc.nextInt();
if(n<0)
{
System.out.println(“It is a negative number. So the program terminates”);
System.exit(0);
}
System.out.println(“Square of a number = ”+(n*n));
System.out.println(“Cube of a number = ”+(n*n*n));
} }
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→61
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Syntax: Note:
switch(variable / expression) ➢ Break statement is used to exit from case.
{ ➢ Default statement is executed when no case value is satisfied.
case value: ➢ Case values must be an integer or character. It can not be float and
statements string values.
break; // it is optional ➢ Cases can never have variable expressions.
case value: (for example case a +3: is wrong)
statements ➢ Multiple cases cannot use same expressions.
break; (case 2: case 1+1 is wrong)
case value: ➢ Multiple cases can use different expressions.
statements (case 2: case 1+2 is correct)
break; ➢ A switch with 10 cases would work faster than an equivalent if-else
---------- ladder
---------- ➢ A switch with two cases would work slower than an equivalent if-else.
default : // it is optional The limitations of switch are as follows:
statements o It doesn't allow ranges, Eg. case 90-100.
} o It requires either integers or characters and doesn't allow Strings & double.
Q1→ WAP to input a number and print week days name according to inputted number. 1 for Monday, 2 for Tuesday, … ...
7 for Sunday. If number is not between 1 to 7 then print invalid number.
A → Import java.util.*;
Class Weekdays case 3:
{ System.out.println(“Wednesday”);
public static void main(String args[]) break;
{ case 4:
int n; System.out.println(“Thursday”);
Scannner sc = new Scanner(System.in); break;
System.out.println(“Enter a number ”); case 5:
n = sc.nextInt(); System.out.println(“Friday”);
switch(n) break;
{ case 6:
case 1: System.out.println(“Saturday”);
System.out.println(“Monday”); break;
break; case 7:
case 2: System.out.println(“Sunday”);
System.out.println(“Tuesday”); break;
break; default:
System.out.println(“Invalid number”); } } }
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→63
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Switch - Questions
66
Q3→ WAP to input an alphabet and check whether it is vowel or not using switch.
Q4→ WAP to input a number and find out whether it is an odd number or even number using switch.
Q5→ WAP to input a month number and print month names like 1 for January, 2 for February……………..12 for December.
Q6→ WAP to input a month number and print season names like (12, 1, 2) for Winter, (3, 4, 5) for Spring, (6, 7, 8) for
Summer, (9, 10, 11) for Fall Season.
Q7→ WAP to print following menu.
1. Addition
2. Subtraction
3. Multiplication Q8→ WAP to input two numbers and one operator
4. Division and print result according to given operator.
5. Exit Eg: Enter two nos. 10 20 +
Enter your choice __ Result = 30
Enter two number ___ ____
Result is ___
Fall through:
If there is no break after a matching case construct, the statements of all the cases after a matching case are executed till
a break is encountered or the switch block is over. This is known as fall through.
These statements are used to perform a set of instructions repeatedly while the condition is true. iteration statements are
67 also called looping statements.
Types of Loop
1. Entry controlled loop (for, while loop)
➢ In this construct the test expression is evaluated first & then executes the statements (body of the loop.
➢ The loop is not executed if the condition is false for first time. Eg. for, while loop.
2. Exit controlled loop (do – while loop)
➢ In this construct the test expression is evaluated after the execution of the body of the loop
➢ The loop is executed if the condition is false for first time. Eg. do - while loop.
The loop has four different elements that have different purposes. These elements are:
i. initialization expression: Before entering in a loop, its variables must be initialized.
ii. Test Expression (Condition): The test expression decides whether the loop body will be executed or not. if
the test condition is true, the loop body gets executed Otherwise the loop is terminated. it means loop is
executed till the condition is true.
iii. The Body of the loop: The statements, which are executed repeatedly while the test expression evaluates to
true form the body of the loop.
iv. Modifier / increment / Decrement(++,- -) Expression: The increment/Decrement expression changes the
value of the loop variable.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→67
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
For loop
68
For loop is an entry controlled loop with all the expressions in one line. It is used for fixed number of iterations.
Syntax: for(initialization; Condition; ++/--) Block or compound statement
{ it is a set of two or more statements enclosed within a pair of curly
// loop body braces “{ }”.
} Eg. for(i=1;i<=4;i++)
{
Eg1: Print numbers from 1 to 10.
Block of statements;
for( int i = 1; i <= 10; i++)
}
{
System.out.print(i+ “ “); Eg4: Find outputs
} for( int i = 1; i <= 10; i+=2)
Eg2: Print numbers from 10 to 1. {
int i; System.out.print(i+ “ “);
for( i = 10; i >= 1; i- -) System.out.print(“Number”);
{ }
System.out.print(i+ “ “);
} Eg5: Find outputs
for( int i = 1; i <= 10; i+=2)
Note: System.out.print(i+ “ “);
System.out.print(“Number”);
There are different variations / types in the ‘for’ loop given below:
70 Infinite loop / Endless loop: We can specify more than one statements in a for loop
A loop that never terminates is known as infinite loop. for initialization and inc / dec. But they have to be comma
Eg1: for( int i = 1 ; ; i++ ) separated.
{ Eg1: int a, b;
System.out.println(“infinite loop”); for(a= 1, b= 10 ; a<=5 && b>=1; a++, b-- )
} {
Eg2: for( ; ; ) System.out.println(“Hello Java”);
{ }
System.out.println(“infinite loop”); Note: in loop, multiple conditions can be specified using
} logical operators (&&, || ) only.
Eg3: for( int i = 1 ; i<=10 ; )
System.out.println(“infinite loop”);
Null loop / Empty loop / Bodyless loop / Time Delay loop
A loop that doesn’t include any statement as body of the loop
is called null, delay, empty or bodyless loop. We can use semi
colon after the for loop to make empty loop.
Eg1: for( int i = 1 ; i<1000 ; i++ );
While loop
71
While loop is fundamental looping statement. All the expressions are written on separate lines. it is used when the
numbers of iterations are unknown. it is an entry control loop. The condition is checked and the loop executes till a
condition is true.
Syntax: How to get digits from given number:
Eg2: import java.util.*;
initialization Print 10 to 1
while(condition) class GetDigits
int i; {
{ i = 10;
Loop body public static void main()
while(i>=1) {
++/-- {
} Scannner sc = new Scanner(System.in);
System.out.print(i+” “); System.out.println(“Enter a number ”);
i--; int n = sc.nextInt();
Eg1:
} int dig;
Print 1 to 10
int i; while(n!=0) // while(n>0)
i = 1; {
while(i<=10) dig = n%10; // To get last digit
{ n = n/10; // To remove last digit
System.out.Print(i+” “); Note: System.out.println(dig);
i++; }
} }
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→71
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Do…While loop Q2→ WAP to input name and age of persons. Continue the
73
input process according to user’s choices(y/n). Calculate
Do-while loop is an exit controlled loop. It first executes the average age of persons.
statements & then checks the condition. Thus it executes the import java.util.*;
loop at least once. it is used when number of iterations is class User
unknown. {
Syntai public static void main()
initialization Eg2:
{ Scannner sc = new Scanner(System.in);
do int i = 1;
String name; int age, cnt=0, sum=0; char ch;
{ do
do
Loop body {
{
++/-- System.out.print(i+” “);
System.out.println(“Enter a name and age”);
}While(condition); i++;
name = sc.neitLine();
Eg1: }while(i <= 10);
age = sc.neitint();
int i = 1; Output will be: sum = sum + age;
do 1 2 3 4 5 6 7 8 9 10 cnt++;
{ System.out.println(“Do u want to continue(y/n)”);
System.out.print(i+” “); ch = sc.neit().charAt(0);
i++; } while(ch==‘y’ || ch==‘Y’);
}while(i >= 10); Q1→ WAP to input a number System.out.println(“Average age =”+(sum/cnt));
Output will be: and calculate factorial of given }
1 number. }
It is used when number of iterations are known. It is used when number of iterations is unknown.
All the expressions are written on same lines. All the expressions are written on different lines.
It first checks the condition & then executes the statements. It is used when number of iterations is unknown.
It will not execute if condition is false for first time. It executes once even if the condition is false.
Similarity: Both the loops are used when number of iterations is unknown.
Comparing Do…While and While - The difference between do-while and while is that do-while evaluates its test
expression at the end of the loop instead of at the beginning. Therefore, the statements within the do block are always
executed at least once. Do-while is an exit controlled loop and while is an entry controlled loop.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→74
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
NESTED LOOP
75
A loop placed inside another loop is known as nested Rules to make patterns
loop. For every iteration of outer loop, inner loop
executes for n times. 1) Count total number of rows and columns.
Syntax: 2) Execute Outer loop for Rows and inner loop for Columns.
Outer loop Output
3) Print OUTER loop variable when we have Same values in
{ //outer loop body x y rows like -
inner loop 1 1
{ 1 2 11111
//inner loop body 1 3 22222
} 1 4
} 33333 and set outer loop first then inner loop
Example & Find output: 2 1
System.out.println( “ x y “ ); 4) Print INNER loop variable when we have Different values in
2 2
for(int x = 1 ; x <= 3; x++ ) 2 3 rows like -
{ 2 4
for(int y = 1 ; y <= 4; y++ ) 12345
{ 3 1 12345
System.out.println(x + “ “ + y); 3 2
} 12345 and set inner loop first then outer loop
3 3
System.out.println(); 3 4
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→75
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Pattern Questions
76
Q4 → 4 4 4 4 4 4 Q7 → A A A A Q10 → 1 2 3 4 Q13 → 7 7 7 7 7 7 7
77
3 3 3 3 3 3 B B B B 5 6 7 8 6 6 6 6 6 6
2 2 2 2 2 2 C C C C 9 1 2 3 5 5 5 5 5
1 1 1 1 1 1 D D D D 4 5 6 7 4 4 4 4
3 3 3
2 2
1
Q5 → 5 4 3 2 1 0 Q8 → D C B A Q11 → 1 Q14 → 1 1 1 1 1
5 4 3 2 1 0 D C B A 2 2 2 2 2 2
5 4 3 2 1 0 D C B A 3 3 3 3 3 3
5 4 3 2 1 0 D C B A 4 4 4 4 4 4
5 4 3 2 1 0 D C B A 5 5 5 5 5 5
Q6 → @ @ @ @ Q9 → D D D Q12 → 6 Q15 → D
@ @ @ @ C C C 5 5 C C
@ @ @ @ B B B 4 4 4 B B B
@ @ @ @ A A A 3 3 3 3 A A A A
@ @ @ @ 2 2 2 2 2
1 1 1 1 1 1
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→77
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
Pattern Questions
78
Find Outputs
84
Q1→ for( i = 1; i <= 10; i++); Q4→ for( i = 1; i <= 20; i++)
System.out.print(i+” “); {
switch(i)
Output _________________ {
case 1: i += 3;
Q2→ int c = 0; case 2: i += 5; break;
for( i = 1; i <= 45; i++) default: i += 2;
{ }
c++; System.out.print( i + ” “);
} }
System.out.print(i+“ ”+c); output_________________
output__________________
Q5→ int s=0, k=10;
Q3→ int i = 1; do
while(i<=10) {
{ System.out.print( k + ” “);
System.out.print( i + ” “); s = s+5;
i++; }while(k<=20);
} output __________ A4→
output __________ 9 12 15 18 21
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→84
Ch1: Revision of class 9th Sub: Computer Application
JMD HGGM
ICSE Class 10th
85
Contents
2. Library classes
1. Character functions
2. Conversion methods
3. Auto boxing & Unboxing
4. Programs
Methods / Functions
Exercise: Outputs
Eg: → boolean b; Outputs
boolean b;
b = Character.isLetter(‘y’); char ch1 = ‘*’, ch2 = ‘D’ ;
System.out.print(b); b = Character.isLetter(ch1);
System.out.print(b);
b = Character.isLetter(‘5’);
System.out.print(b); b = Character.isLetter(ch2);
System.out.print(b);
Argument
Wrapper Class Method Name
Return Type
character Questions.
Q1→Character conversion into Opposite Case. Q2→WAP to input a character and check it is symbol or not.
90
91
Contents
3. Array in java
Array In Java
➢ Array is a collection of data having homogenous (similar) data Input data in array using scanner class
93
type values. Scanner sc = new Scanner (System.in);
➢ Continuous memory is allocated for array. int ar[ ] = new int[5];
There are two types of array for(int i = 0; i <= 4; i++)
1. Single Dimensional array (1 D Array) {
2. Two / Multi-Dimensional array (2 D Array) System.out.println("Enter data ");
ar[i] = sc.nextInt();
1. Single Dimensional array (1 D array)
}
Syntax: datatype arrayname[ ] = new datatype[size] ; Or
Printing an array elements
datatype [ ] arrayname = new datatype[size] ;
for(int i = 0; i <= 4; i++)
Eg: int ar[ ] = new int[5]; //20 bytes
{
double b[ ] = new double[5]; //40 bytes
System.out.println(ar[i] + “ ”);
char c[ ] = new char[5]; //10 bytes
}
Initialization of 1 Dimensional array
int ar[ ] = { 10, 20, 30, 40, 50}; Input data in array using BufferedReader class
double b[ ] = { 5.6, 10.45, 6.7, 8.5, 9.66}; BufferedReader br = new BufferedReader( new
char ch[ ] = { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’}; InputStreamReader (System.in));
String st[ ] = {“abc”, “xyz”, “aaa”}; ar[0] int ar[ ] = new int[5];
for(int i = 0; i <= 4; i++)
{
ar[ ]= 10 20 30 40 50 Array Index no./
System.out.println("Enter data ");
name subscript no.
ar[0] ar[1] ar[2] ar[3] ar[4] ar[i] = Integer.parseInt( br.readLine() );
It always starts
}
from zero(0)
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→93
Ch 3 : Arrays in Java (1d & 2d) Sub: Computer Application
JMD HGGM
ICSE Class 10th
Array Questions
Q1→ WAP to input 10 elements in an array and print array.
95 Q2→ WAP to input 5 numbers in an array and find sum and average of array elements.
Q3→ WAP to input 5 or N numbers in an array and find product of even numbers of array elements.
Q4→ WAP to input 5 numbers in an array and copy these numbers in another array.
Q5→ WAP to input 5 numbers in an array and reverse these numbers in another array.
Q6→ WAP to input 5 numbers in an array and reverse these numbers in same array.
Q7→ WAP to input 5 or N numbers in an array and find out maximum and minimum number.
Q8→ WAP to input 5 numbers in an array and find out standard deviation.
Q9→ Write a program to accept the year of graduation from school as an integer value from the user. Using the Binary
Search and linear Search technique on the sorted array of integers given below, output the message “record exists” if
the value input is located in the array. If not, output the message “Record does not exist”.
{1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010}
Q10→ Write a program to accept name and total marks of N number of students in two single subscript array name[ ] and
totalmarks[ ]. Calculate and print:
(i) The average of the total marks obtained by N number of students.
[average = (sum of total marks of all the students)/N]
(ii) Deviation of each student’s total marks with the average. [deviation = total marks of a student – average]
Q11→ Write a program to input integer elements into an array of size 20 and perform the following operations:
(i) Display largest number from the array.
(ii) Display smallest number from the array.
(iii) Display sum of all the elements of the array. (iv) Display product of all odd elements of the array.
Q5→ WAP to input 5 numbers in an array and reverse these numbers in another array.
97
Array Questions
Q12→ Write a program to input twenty names in an array. Arrange these names in descending order of alphabets,
98
using the bubble sort technique and selection sort technique. Print the sorted array.
Q13→ Write a program to initialize the seven wonders of the World along with their Locations in two different arrays.
Search for a name of the country input by the user. If found, display the name of the country along with its Wonder,
otherwise display “Sorry Not Found!”.
Seven wonders – CHICHEN ITZA, CHRIST THE REDEEMER, TAJMAHAL, GREAT WALL OF CHINA, MACHU
PICCHU, PETRA, COLOSSEUM.
Location - MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY
Example - Country Name : INDIA Output : INDIA – TAJMAHAL
Country Name : USA Output : Sorry Not Found!
Linear Search
Q→ WAP to input N numbers in an Array and find key element and also print index number. (Q9)
99
A→ import java.util.*;
public class Linear_Search
{ for( i = 0; i<n; i++)
public static void main() {
{ // Array Input String key; if(key == arr[ i ]) //if(key.equals(arr[i])==true)
int n, key, i, flag=0 ; {
Scanner sc = new Scanner(System.in); flag = 1;
System.out.println("Enter total number of elements of array:"); break;
n = sc.nextInt(); }
int arr[ ] = new int[n]; // String arr[] = new String[n]; } //end of while loop
for(i = 0; i < n; i++) if(flag == 1)
{ {
System.out.println("Enter array number :"); System.out.print(key+“ Number is found at ”+i);
arr[i] = sc.nextInt(); // arr[i] = sc.nextLine(); }
} else
{
System.out.println("Enter number to be searched :"); System.out.print(“Number is not found”);
key = sc.nextInt(); // key = sc.nextLine(); }
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→99
Ch 3 : Arrays in Java (1d & 2d) Sub: Computer Application
JMD HGGM
ICSE Class 10th
Binary Search
Q→ WAP to input N numbers in an Array and sort array in ascending order. (Using bubble sort). (Q12)
101
A→ import java.util.*;
public class Bubble_sort int temp; //String temp
{ for ( i = 0; i < n-1; i++)
public static void main() {
{ for ( j = 0; j < (n-1-i); j++)
int n, i, j; {
Scanner sc = new Scanner(System.in); if(arr[ j ] > arr[ j+1 ]) //if( arr[ j ].compareTo(arr[ j+1 ])>0)
System.out.print("Enter total number of element of array"); {
n = sc.nextInt(); temp = arr[ j ];
arr[ j ] = arr[ j+1 ];
int arr[] = new int[n]; //String arr[] = new String[n]; arr[ j+1 ] = temp;
}
for(i = 0; i<n; i++) }
{ }
System.out.println("Enter array number :"); System.out.println("sorted array is ");
arr[i] = sc.nextInt(); // arr[i] = sc.nextLine(); for ( i = 0; i < n; i++)
} {
System.out.println(arr[ i ]+ “ “ );
}
Selection Sort
Q→ Write a program to input twenty names in an array. Arrange int max = 0, index = 0; //String max
102
these names in descending order of alphabets, using the bubble sort for ( i = 0; i < n-2; i++)
technique and selection sort technique. Print the sorted array. (Q12) {
max = arr[ i ];
import java.util.*; for ( j = i+1; j < (n-1); j++)
public class Selection_sort {
{ if(arr[ j ] > max) // if( arr[ j ].compareTo(max)>0)
public static void main() {
{ max = arr[ j ] ;
int n, i; index = j ;
Scanner sc = new Scanner(System.in); }
System.out.print("Enter total number of element of array"); }
n = sc.nextInt(); arr[ index ] = arr[ i ];
arr[i] = max;
int arr[] = new int[n]; //String arr[] = new String[n]; }
System.out.println(“Sorted Array is ");
for(i = 0; i<n; i++) for ( i = 0; i < n; i++)
{ {
System.out.println("Enter array number :"); System.out.println(arr[ i ]+ “ ”);
arr[i] = sc.nextInt(); // arr[i] = sc.nextLine(); }
}
Linear Search:
Name the search or sort algorithm that:
104 The item is compare one by one with each element in an
a. Makes n-1 passes to sort the whole array checking the
array, which traverses sequentially to locate the item. It is
adjacent elements in every pass. Bubble Sort
time consuming for large no. of elements. Array need not
b. Compare the sought key with each key element of the
be sorted.
array. linear Search
The range of an array with 10 elements.
Binary Search:
Range of array is from 0 to (length of array – 1), i.e. 0 to 9.
The array has to be in sorted order. The array is divided
Sorting
into two halves and the middle element is compared. If the
Bubble Sort:
search value is not located on middle element then either
In bubble sort the adjacent elements are compared. For
of the two halves is checked depending upon the search
ascending order if the element is greater than it is
value. It is the faster processes for large no. of elements.
interchanged (swapped) with the adjacent element. This
process is repeated for all the elements for n-1 times. It goes
Array Instantiation
through all the loop cycles even if the array is sorted much
To instantiate (or create) an array, write the new keyword,
before.
followed by the square brackets containing the number of
Selection Sort:
elements you want the array to have.
The maximum or minimum value is found and is swapped
int ages[] = new int[100];
with the first element of the array, the same process is
repeated for 2nd , 3rd element and so on. It is faster than
You can also instantiate an array by directly initializing it
Bubble sort.
with data. For example: int arr[] = {1, 2, 3, 4, 5};
Q5: What will this code print ? [2] Q11: What is the difference between the linear search and the
106 int arr[] = new int[5]; binary search technique? [2]
System.out.println(arr); Q12: String x[] = {“Artificial intelligence”, “IOT”, “Machine learning”,
“Big data”};
(i) 0 (iii) 0000
Give the output of the following statements:
(ii) value stored in arr[0] (iv) garbage value (i) System.out.println(x[3]);
(ii) System.out.println(x.length);
Q6: If int x[] = {4, 3, 7, 8, 9,10};
what are the values of p and q ? [2]
Q13: What will this code print ? [2]
(i) p = x.length int arr[] = new int[5];
(ii) q = x[2] + x[5] * x[1] System.out.println(arr[0]);
Q7: Name any one reference data type. [2] (i) 0 (iii) 0000
Q8: String x[] = {“SAMSUNG”, “NOKIA”, “SONY”, “MICROMAX”, (ii) value stored in arr[0] (iv) garbage value
BLACKBERRY};
Give the output of the following statements: [2]
(i) System.out.println(x[1]); Q14: If int x[] = {4, 3, 7, 8, 9,10};
(ii) System.out.println(x[3].length()); what are the values of p and q?
Q9: Differentiate between searching and sorting? (i) p = x[1] % x[0] + ++x[3] * x[3] / x[5]++
Q10: Consider the following String array and give the output. (ii) q = x[2] + x[5] / x[1] * x[2]
String arr[] = {“DELHI”, “CHENNAI”, “MUMBAI”, “LUCKNOW”,
“JAIPUR”};
System.out.println(arr[0].length()>arr[3].length());
System.out.print(arr[4].substring(0,3);
Q15: String x[] = {“Artificial intelligence”, “IOT”, “Machine learning”, “Big data”}; [2]
107
Give the output of the following statements:
(i) System.out.println(x[2].length());
(ii) System.out.println(x[3].substring(2, x.length);
Q16: Consider the following String array and give the output. [2]
String arr[] = {“DELHI”, “CHENNAI”, “MUMBAI”, “LUCKNOW”, “JAIPUR”};
System.out.println(arr.length != arr[0].length());
System.out.print(arr[3].replace(‘N’, ‘m’));
Ans→ 1) a) 2, 3, 4,
3) value of arr are 1,2,3,5,5
value of k is 3
1 4) p = 11 q=28
108
Contents
4. String Handling
STRINGS IN JAVA
String initialization H e l l o J a v a .
str =
String str = "Hello Java.";
0 1 2 3 4 5 6 7 8 9 10
Character initialization
char ch = ‘A’; index / subscript number
It is always starts from zero (0)
Character String
A character is a single alphabet, a digit or a single String is a set of characters in java.
special symbol. It is primitive datatype. It is non-primitive datatype.
It must have only one character. It encloses within single It encloses within double quotes.
inverted quotes.
Eg : Characters → 'A' , 'i' , '5' , '=' , ‘$‘, etc. Eg: Strings → “Hello Java.”, “computer1”, etc.
String & character input using scanner String & character input using BufferedReader
111
8. String valueOf(all num type) int a=10; String s = String.valueOf(a); //s = “10”
String Methods
String Methods
114
SYNTAX OF FUNCTION EXAMPLE
boolean b; String s1 = “Computer”, s2 = “Comp”;
17. boolean startsWith(String s)
b = s1.startsWith(s2); sop(b); // b = true
boolean b; String s1 = “Computer”, s2 = “ter”;
18. boolean endsWith(String s)
b = s1.endsWith(s2); sop(b); // b = true
116
Q1 → WAP to input a string and find out its length and print all characters in vertical order and also print their ASCII values
of every character.
Q2 → WAP to input two strings and concatenate it in to third string without using function.
Q3 → WAP to input two strings and concatenate second string at the end of first string.
Q4 → WAP to input a string and reverse it in another string. Eg. s=“abc”; rev=“cba”;
Q5 → WAP to input a string and check whether it is palindrome string or not.
Q6 → WAP to input two strings and compare these two strings. If both strings are same then print strings are equals
otherwise print Strings are unequal.
Q7 → Write a program in Java to accept a string in lower case and change the first letter of every word to upper case.
Display the new string. (2018)
Sample input: we are in cyber world
Sample output: We Are In Cyber World
Q8 → Write a program to accept a sentence and print only the first letter of each word of the sentence in capital letters
separated by a full stop.
Example : INPUT SENTENCE : “This is a cat” OUTPUT : T.I.A.C.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→116
Ch 4 : String Handling Sub: Computer Application
JMD HGGM
ICSE Class 10th
Q8→ Write a program to accept a sentence and print only the first letter of each word of the sentence in capital
117 letters separated by a full stop. Example: INPUT SENTENCE : “This is a cat” OUTPUT : T.I.A.C.
import java.util.Scanner;
public class GetChars String Programs – based on chars
{
public static void main() Q9 → Special words are those words which starts and ends with
{ the same letter. Examples: EXISTENCE, COMIC, WINDOW
Scanner sc = new Scanner (System.in); Palindrome words are those words which read the same from left
String str; to right and vice-versa.
int i, len; Examples: MALAYALAM, MADAM, LEVEL, ROTATOR, CIVIC
char chr; All palindromes are special words, but all special words are not
System.out.println("Enter a String "); palindromes.
str = sc.nextLine(); Write a program to accept a word check and print whether the
len = str.length(); word is a palindrome or only special word.
str = “ ” + str;
for( i = 0; i < len; i++) Q10→ Write a program in java to accept a string and change the
{ case of each character of the string and display the new string.
chr = str.charAt(i); Sample input : WelComE TO School
if( chr == ‘ ’ ) Output : wELcOMe to sCHOOL
{
chr = str.charAt(i+1);
System.out.println(Character.toUpperCase(chr)+“.”);
}
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→117
Ch 4 : String Handling Sub: Computer Application
JMD HGGM
ICSE Class 10th
Q11→
118 a) Write a program to accept a String. Convert the string to Uppercase. Count and output the number of double letter
sequences that exist in the string.
Sample input : “SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE”
Sample Output : 4
b) Write a program to accept a String and convert its into its Piglatin form.To translate word into a Piglatin word, convert
the word into Uppercase and then place the first vowel of the original word as the start of the new word along with the
remaining alphabets. The alphabets present before the vowel being shifted towards the end followed by “AY”
Sample Input (1) : London, Sample output (1) : ONDONLAY
Sample Input (1) : Olympics, Sample output (1) : OLYMPICSAY
Q12→Write a program to assign a full path and file name as given below. Using library functions, extract and output the
file path, file name and file extension separately as shown.
Input: c:\users\admin\Pictures\flower.jpg
Output Path : c:\users\admin\Pictures\
File name : flower
Extension : jpg
Q13→Write a program to input a sentence from user and print every alternative characters (leaving space, vowel and
numbers) of it (starting from first character).
e.g; Sample Input : DISARI PUBLIC SCHOOL, HALDIA – 22 Sample output: DSRLCSHLI-
(Note: all alternate characters are underlined, output contains all of them except space, vowel and numbers).
Q12→ Write a program to assign a full path and file name as given below. Using library functions, extract and output the file
119
path, file name and file extension separately as shown. Input: c:\users\admin\Pictures\flower.jpg
Output: Path: c:\users\admin\Pictures\ File name: flower Extension: jpg
A12→ import java.util.Scanner;
public class GetChars
{ Hints:
public static void main() A11 a) A11 b)
{ for( i = 0; i < len; i++) str = str.toUpperCase();
Scanner sc = new Scanner (System.in); { chr1 = str.charAt(i); for( i = 0; i < len; i++)
String str, path = “”, fname=“”, ext=“”; chr2 = str.charAt(i+1); {
System.out.println("Enter a String "); if( chr1 == chr2 ) ch = str.charAt(i);
str = sc.nextLine(); { if(ch==‘A’||ch==‘E’||ch==‘I’||ch==‘O’||ch==‘U’)
ind = str.lastIndexOf(‘\’); cnt++; break;
path = str.substring(0, ind+1); i++; }
dot_ind = str.indexOf(‘.’); } str1 = str.substring(0, i);
fname = str.substring(ind+1, dot_ind+1); } str2 = str.substring(i);
ext = str.substring(dot_ind+1); nstr = str1 + str2 + “AY”;
System.out.println(“Path: “ + path); Sop(nstr);
System.out.println(“File name: “ + fname);
System.out.println(“Extension: “ + ext);
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→119
Ch 4 : String Handling Sub: Computer Application
JMD HGGM
ICSE Class 10th
Q14→ Write a program to arrange the letters of string in alphabetically order and print the new string. Any
120
character that is Not a part of the alphabet are added at the end of the new string.
E.g: if the input is “@Computer Application 2019”,
then the output is “aAcCeiilmnooppprttu@ 2019”. [Note that there is 2 spaces after @ in output string]
Q15→ Write a program to input any given string to calculate the total number of characters and vowels present in the
121
string and also reverse the string:-
Example : input a string : SNOWY
output
Total number of characters : 05
Number of Vowels : 01
Reverse string : YWONS
Q16→Write a program that asks the user to enter a sentence, and to print the sentence in reverse order, with the
case of each letter reversed. Eg:
Q17→WAP to input a string and find total number of capital, small alphabet, number or symbol.
import java.util.Scanner;
public class GetWords
{
public static void main()
{ for( i = 0; i < len; i++)
Scanner sc = new Scanner (System.in); {
String str, wrd = ""; chr = str.charAt(i);
int i, len; char chr; if(chr != ' ')
System.out.println("Enter a String "); { //hello java program
str = sc.nextLine(); wrd = wrd + chr;
str = str + " "; }
len = str.length(); else
{ /*This is the area
* where we can write the code
* according to given programs. */
System.out.println(wrd);
wrd = "";
}
} // End of for loop
} // End of main()
} // End of class()
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→122
Ch 4 : String Handling Sub: Computer Application
JMD HGGM
ICSE Class 10th
Q1→ WAP to input a sentence and print all words in vertical order.
123
Q2→ WAP to input a sentence and print all words in vertical order, serial no of words, total no. of character of words
and count the vowels of every word separately with following headings.
Sno. word word length Total vowels
---- ------ --------------- ----------------
Q3→ WAP to input a sentence and print all words in reverse order.
Q4→ WAP to input a sentence and print all palindrome words.
Input: MOM AND DAD ARE LEARNING MALAYALAM
Output: MOM DAD MALAYALAM
Q5→ WAP to input a sentence and print all special words from the sentence. Special words are those words which
starts and ends with the same letter. Eg: window, Existence, comic.
Q6→ Write a program to input a sentence and print the number of characters found in the longest word of the given
sentence.
For example is S = “India is my country” then the output should be 7.
Q7→ WAP to input a sentence and count the words ‘this’, ‘an’, ‘the’ separately.
Q8→ Write a program to enter a sentence from the keyboard and count the number of times a particular word occurs
in it. Display the frequency of the search word.
Eg: INPUT: Enter a sentence : the quick brown fox jumps over the lazy dog.
Enter a word to be searched : the
OUTPUT: Searched word occurs : 2 times.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→123
Ch 4 : String Handling Sub: Computer Application
JMD HGGM
ICSE Class 10th
126
Q7→ WAP to input a sentence and count the words ‘this’, ‘an’, ‘the’ separately.
127 Q9→WAP to input a sentence and print max and min word.
String Theory
String StringBuffer
Once a String object is created you cannot change the StringBuffer objects can be altered on the same instance
characters that comprise the string. after creation.
String objects are immutable. StringBuffer objects are mutable.
New object is required to alter the string. New object is not required.
Similarity: Both the classes are found in java.lang package & are used for string manipulation.
Library classes:
The java environment provides several built-in class libraries that contains many in-built methods for input-output, string
handling etc. This library is also known as Application Programming Interface (API). E.g: Math class, String class,
BufferedReader Class etc.
130
Contents
Methods / Functions
132
Methods/Functions are subprograms or small block of code which perform specific action. Or
A large program can be divided into smaller subprograms. These subprograms are called as function.
Advantages of function:-
➢ Complexity of program is reduced.
➢ Debugging (error checking) can be done easily.
➢ Memory is saved. As only a single copy of the function is
present in the memory but it can be called many times in a
program.
Functions/Methods which are defined by user is known Four Ways To Declare A Function
133
as User define function/method. 1. int sum ( int, int ); //with argument & with return type
2. void sum ( int, int ); //with argument & without return type
User defined function consists of three parts. 3. void sum ( ); //without argument & without return type
1. Function declaration/Prototype 4. int sum ( ); // without argument & with return type
2. Function calling/invoking
3. Function definition Function calling
Function Calling is used for its execution.
Function Declaration / Prototype Syntax: variable = Function_name(Argument value/variable);
It tells the compiler that a function is defined somewhere
in the program. DECLARATION PARTS CALLING PARTS
Function declaration is not required in java. int sum ( int, int ); s = sum(4, 7); or s = sum(a, b);
void sum ( int, int ); sum(4,7); or sum(a, b);
Syntax void sum ( ); sum( ); or sum();
Return-type function_name (datatype of arguments) int sum ( ); s = sum( ); or s = sum( );
Function Definition
134
It defines the purpose of function. Q1 → WAP to input 2 numbers and calculate their sum using function.
Syntax: Formal Parameters
Ans→ public class add
Return-type Function ( Argument var)
{
{
body of Function; static int sum ( int a, int b ) // function definition
} {
int s;
Example: s = a + b;
int sum (int a, int b) return s;
{
int s;
}
s = a + b; public static void main()
Actual Parameters
return s; {
} int a=10, b=20, s;
s = sum(a, b); // function calling
Note: → Return statement is used to return a System.out.println("addition =" + s);
value to the calling part. }
→ A function can return only one value. }
Q2 → WAP to input 3 numbers and calculate their average and product using function.
135
import java.util.Scanner;
Ans→ public class Pro_Avg
{
static int product ( int a, int b, int c ) public static void main()
{ {
int pro; int a, b, c, pro;
pro = a * b * c ; double av;
return pro; Scanner sc = new Scanner (System.in);
} System.out.println("Enter three numbers: ");
static double average ( int x, int y, int z ) a = sc.nextInt();
{ b = sc.nextInt();
double avg; c = sc.nextInt();
avg = (x + y + z)/3.0; pro = product(a, b, c);
return avg; av = average(a, b, c);
} System.out.println(“Product = " + pro);
System.out.println(“Average = " + av);
//another way to call function
System.out.println(“Product = ” + product(a, b, c));
}
}
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→135
Ch 5 : User-defined Methods Sub: Computer Application
JMD HGGM
ICSE Class 10th
136
Q3→ WAP to input three numbers and find greatest number using function. (HW)
Q4→ WAP to input a number and print its factors.
Q5→ WAP to input a number and find factorial using function.
Q6→ WAP to input a number and its power and calculate it. (HW)
Function & syntax of declaring a function Prototype of a function check which receives a
139
A function is a sub-program in a main program which processes data & character & an integer argument, returns true or
returns a value. Functions are set of instructions given to a computer to false.
perform some task. public boolean check (char c, int n);
General Syntax:
Function signature
Access-specifier modifier return-type method-name(formal parameters)
Function signature is the parameter list of the
{
function i.e number & type of parameters.
//function body
Eg. public void print( int a, int b);
}
Ans→ 1. return 2. static 3. null 4. new 5. package 6. break 7. continue 8. static 9. this 10. void 11. final 12. protected 13. import
14. boolean 15. Default 16. for 17. private 18. class 19. char 20. switch 21. try catch 22. extends 23. throws / throw
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→141
Ch 5 : User-defined Methods Sub: Computer Application
JMD HGGM
ICSE Class 10th
The value of actual parameters is copied in to formal The Reference of actual parameters is copied in to formal
parameters. parameters.
Any changes made to formal parameters do not affect Any changes made to formal parameters affects the
actual parameters. actual parameters.
Actual parameters passed are of primitive types. Actual parameters passed are of non-primitive type.
Eg. static void prod1(int a, int b) public void main() Eg. static void prod2(int c[ ]) public void main()
{ { { {
a = a*2; int a=10, b=20; c[0] = c[0] * 2; int c[ ] = {10, 20};
b = b*3; prod(a, b); c[1] = c[1] * 3; prod(c);
} Sop(“A=“+a); } Sop(“c[0]=“ + c[0]);
Sop(“B=“+b); Sop(“c[1]=“ + c[1]); }
}
Q.1: Q2:
145
a) Define: Function prototype line. a) Write the main function to invoke the following functions:
b) Debug the error and rewrite the following function prototype: i. Class Test {
(1) float product(a, int y); (2) float operator (int x, float = 3.4); public int mult(int x, int y)
c) If Car is a class, write a statement to create an object BMW. { return x*y; }
d) Give the output of the following code: }
void add(int a, int b) ii. Class Demo {
{ System.out.println( a + b ); } public void add(int x, int y)
void add(String a,String b) { System.out.println((x+y)); }
{ System.out.println( a + b ); } }
iii. Class Example{
If (i) add(“12”, “4”) is invoked. static int a=100, b=200;
(ii) add(4, 12 ) is invoked. public static void print()
e) { System.out.println(a+b);
(1) Name the function which does not change or modify the state of }
the arguments / variable that are received when called. }
(2) Name the statement/function that causes the control to transfer
back to method call. b) write a function prototype of the following:
f) What are the two ways of invoking functions? A function PosChar which takes a string argument and
g) What are the two types of functions? (pure, impure) a character argument and returns an integer value.
146
Contents
Oop In Java
Data Encapsulation
Wrapping up of data members and member methods together in a single unit which is known as Data Encapsulation.
Abstraction:
Abstraction is the act of representing essential features without getting in to complexity of the system.
Eg: We know how to drive a car. But we don’t know the mechanism that makes the car move.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→148
Ch 6 : Class as the Basis of all Computation (Classes & Objects) Sub: Computer Application
JMD HGGM
Components of OOP
CLASS
Class is a user defined data type in which data members and member functions/methods are combined together in a single
unit. It is also known as Data Encapsulation.
Class ➔ Data Members + Member Functions / Methods
Class helps to keep the data members in various visibility modes as private, public and protected. Usually, data members of
a class are kept in private or protected visibility modes and methods are kept in the public visibility mode. In java, Default
access specifier is public.
Private members are available to only own class and not accessible to function outside the class.
Private member data & function cannot be accessed outside the class. It is known as Data Hiding. They can be accessed
only through public members of the class.
Public members are the members which accessible from anywhere either inside or outside.
NEW: It is a keyword which is use to create an object and helps to allocate memory to an object.
Object can access the public member data & function of class using dot(.) operater.
How To Access : Example:
Syntax: S1.input();
ObjectName . publicMemberName; S1.x;
Q1→ Create a class named as Student which having public void calc()
151
Data members → name, rollno, marks of 3 subs, total, perc, {
Member functions → void input(), void calc(), void display(). tot = m1 + m2 + m3;
(Using BufferedReader class) perc = tot/3.0;
}
A1→ import java.io; void display()
public class Student {
{ System.out.println("rollno="+rollno);
private int rollno, m1, m2, m3, tot; System.out.println("name="+n);
private String n; System.out.println("marks="+m);
private double perc; }
public void input() public static void main() throws IOException
{ {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Student s1 =new Student(); //s1 is object.
System.out.println("Enter name, rollno, marks of 3 subs"); Student s2 =new Student(); //s2 is object.
n = br.readLine(); s1.input(); // calling of the function
rollno = Integer.parseInt(br.readLine()); s2.input();
m1 = Integer.parseInt(br.readLine()); s1.calc(); s2.calc();
m2 = Integer.parseInt(br.readLine()); s1.display(); s2.display();
m3 = Integer.parseInt(br.readLine()); }
} }
Q1→ Create a class named as Student which having public void calc()
152
Data member → name, rollno, marks of 3 subs, total, perc. {
Member function → void input(), void calc(), void display(). tot = m1 + m2 + m3;
(Using Scanner class) perc = tot/3.0;
}
A1→ import java.util.Scanner; void display()
public class Student {
{ System.out.println("rollno="+rollno);
private int rollno, m1, m2, m3, tot; System.out.println("name="+n);
private String n; System.out.println("marks="+m);
private double perc; }
public void input() public static void main()
{ {
Scanner sc = new Scanner( System.in ); Student s1 =new Student(); //s1 is object.
System.out.println("Enter name, rollno, marks of 3 subs"); Student s2 =new Student(); //s2 is object.
n = sc.nextLine(); s1.input(); //calling of the function
rollno = sc.nextInt(); s2.input();
m1 = sc.nextInt(); s1.calc(); s2.calc();
m2 = sc.nextInt(); s1.display(); s2.display();
m3 = sc.nextInt(); }
} }
Questions
Overloading of Function:
Function with same name but differ in their number of arguments or datatype of arguments is called as overloading
of function.
Eg: void input( );
void input( int );
void input( int, int );
void input( int, double );
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→153
Ch 6 : Class as the Basis of all Computation (Classes & Objects) Sub: Computer Application
JMD HGGM
Array of Object :
156
Q5→ Create a class named as Tel_dir to store
name, address, telephoneno.
Store and print data of 5 persons.
class tel_dir
{
String name, addr, tel;
void input() { }
void display() { }
public static void main( String arg[] )
{
tel_dir t [ ] = new tel_dir[5] ;
for ( int i = 0; i < = 4 ; i++ )
{
t[ i ] = new tel_dir();
t[ i ].input ( );
}
for ( i = 0 ; i < = 4 ; i++)
t[ i ].display ( );
}
}
void display() – To display all details of a customer such as name, coach, total amount and mobile number.
Write a main method to create an object of the class and call the above member methods.
Constructors
Constructor
159 It is a special member function that is used to initialize the object of the class.
➢ Constructor name should be same as class name.
➢ Constructor does not have any return type (not even void).
➢ Constructor is called automatically when the object is created.
➢ Constructor can be overloaded.( It means more than one constructor can be provided in the class.)
Constructor Programs
Q9: Q10:
161 Define a class named BookFair with the following description: Design a class name ShowRoom with the following description :
Instance variables/Data members : Instance variables/ Data members :
String Bname — stores the name of the book String name – To store the name of the customer
double price — stores the price of the book Member methods : long mobno – To store the mobile number of the customer
(i) BookFair() — Default constructor to initialize data members double cost – To store the cost of the items purchased
(ii) void Input() —To input and store the name and the price of the double dis – To store the discount amount
book. double amount – To store the amount to be paid after discount
Member methods: –
(iii) void calculate() — To calculate the price after discount.
ShowRoom() – default constructor to initialize data members
Discount is calculated based on the following criteria.
void input() – To input customer name, mobile number, cost
void calculate() – To calculate discount on the cost of purchased
Price Discount items, based on following criteria
Less than or equal to Rs. 1000 2% of price
Cost Discount
More than Rs. 1000 and less 10% of price
Less than or equal to Rs. 10000 5%
than or equal to Rs. 3000
More than Rs. 10000 and less than or equal to Rs. 20000 10%
More than % 3000 15% of price
More than Rs. 20000 and less than or equal to Rs. 35000 15%
(iv) void display() — To display the name and price of the book More than Rs. 35000 20%
after discount.
Write a main method to create an object of the class and call the void display() – To display customer name, mobile number, amount to
above member methods. be paid after discount
Write a main method to create an object of the class and call the
above member methods.
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→161
Ch 7 : Constructors (classes & Objects) Sub: Computer Application
JMD HGGM
Q11→ Add the d1 object and d2 object and store in d3 public static void main(String ar[ ])
163
object of distance class. {
distance d1 = new distance();
class distance distance d2 = new distance();
{ distance d3 = new distance();
private int feet, inch; sop(”Enter data in first object”);
public void input() d1.input();
{ sop(”Enter data in second object”);
do it yourself d2.input();
} d3.add(d1, d2);
sop(”After adding d1 & d2 object, newly object is“);
public void add(distance fd1, distance fd2) d3.display();
{ }
feet = fd1.feet + fd2.feet; }
inch = fd1.inch + fd2.inch;
}
public void display()
{ do it yourself }
Note: Data of the objects which are passed as an argument in function is used through the object name with dot(.) operator.
Eg: fd1.feet → Data of the object which is calling the function can be used directly.
Q12→ Add the d1 object and d2 object and store in d3 public static void main(String ar[ ])
164
object of distance class. {
A→ class distance distance d1 = new distance();
{ distance d2 = new distance();
private int feet, inch; distance d3 = new distance();
public void input() sop(”Enter data in first object”);
{ do it yourself } d1.input();
sop(”Enter data in second object”);
public distance add(distance fd2) d2.input();
{ d3 = d1.add(d2);
distance temp; sop(”After adding d1 & d2 object, newly object is“);
temp.feet = feet + fd2.feet; d3.display();
temp.inch = inch + fd2.inch; }
return temp; }
}
public void display()
{ do it yourself }
Q13→ Add two time objects without returning object.
Data member – hours, minutes, seconds
Member functions – void input(), void calc(), void display().
Q14→ Add two time object with returning object.
Q15→ Add two string object and store it in third string object
Inheritance
Advantages of Inheritance D1 D
➢ Reusability of code:
➢ Reusability of code saves money as well as time and Note: Java does not support
increases program reliability. D2 multiple inheritance
➢ Protection is never decreased while deriving the class.
Inheritance
5. Hybrid inheritance
168
S
D1 D2
D3
Access Specifiers
There are three types of access specifiers.
1) Private
2) Public
3) Protected
Inheritance program
Q18→ WAP To create a Single Inheritance. Super class is manager (data member - Mcode, Mname ),
169
Child class is employee (Ecode, Ename ), Functions are void input() and void display().
import java.util.*; class employee extends manager //derived class
class manager //base class {
{ private int ecode;
private int mcode; private String ename;
public void input() throws IOException
private String mname;
{
public void input() throws IOException
super.input();
{ // super.mcode=10; //if it is public
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Enter manager code and name"); System.out.println("Enter manager code and name");
mcode = sc.nextInt(); ecode = Integer.parseInt(br.readLine());
mname = sc.next(); ename = br.readLine();
} }
public void display() public void display()
{ {
System.out.println("manager code "+mcode); super.display();
System.out.println("manager name "+mname); System.out.println("employee code "+ecode);
System.out.println("employee name "+ename);
}
}
}
}
Inheritance PACKAGE
Exception Handling:
catch( )
This block is used to catch the exception error raised by try block.
Exception Handling:
throws:-
173 It is used when a method is throw an exception and there is no
exception handling in a body of function. Exception is catch in
that block where method is called.
Syntax Function_name( ) throws Exception_name
{
Statement;
}
Example3:
public class abc
{
void divide(int a, int b)
{
int c= a/b;
System.out.print(c);
}
public static void main(String[] args) throws Exception
{
abc ob = new abc();
ob.divide(10, 0);
} }
Class: A class is a blueprint or a prototype that defines characteristics & behaviour common to all objects of a certain kind.
It is the fundamental building block of Object Oriented Programming.
Eg: class - Student
characteristics: name, roll, std, marks.
Behaviour: calc_tot(), calc_per().
Object:
Object is an identifiable entity with some characteristics & behavior. It can be a place, a thing or a human.
Eg. Dog have state(name, colour, breed) & behaviour (barking, fetching, wagging the tail).
INHERITANCE
176
Inheritance is a process of creating new class from the existing class. The existing class is called as super class or base
class or parent class. The newly created class is called as derived class or sub class or child class. Inheritance is the most
powerful feature of Object Oriented Programming. The process of Inheritance does not affect the base class.
Base class & Derived class:
Base class is an existing class from which new classes are derived. It is also known as super class or Parent class.
Derived class is a new class which inherits properties from a base class. It is also known as sub class or child class.
Super class
Sub class
➢ Derived class inherits the features of base class.
➢ Derived class has its own features also.
Advantages of Inheritance
➢ Reusability of code:
➢ Reusability of code saves money as well as time and increases program reliability.
➢ Protection is never decreased while deriving the class.
Output Questions
Q1: Classify the following as primitive or non-primitive data Q6: In the program given below, state the name and the value of the (i) to (iv)
177 types: i) Method argument or argument variable
(i) char (ii) arrays (iii) int (iv) classes ii) Class variable
iii) Local variable
Q2: Name the following: iv) Instance variable
(i) Any one reference datatype v) What is object name of class myClass.
vi) Give the type of function used and its name.
Q3: List the variables from those given below that are vii) Name the variables for which each object of the class will have its
composite datatypes. own distinct copy.
(i) Static int x; (ii) boolean b; (iii) arr[i]=10 viii) Name the variables which are common to all objects of the class.
(iv) Private char chr (v) obj.display() (vi) String str
Class myClass
Q4: State the difference between constructor and Method.
{
static int x = 7;
Q5: What is call by value?
int y = 2;
How are the following passed?
public static void main(String args[])
(i) Primitive types
{
(ii) Reference types
myClass obj = new myClass();
System.out.println(x);
void sampleMethod(int n)
obj.sampleMethod(5);
{
int a=6; System.out.println(n);
System.out.println(a); System.out.println(n);
} }
Ans→ Q6 vii) y viii) x } //end of class
Practice Makes Perfect WWW.YPComputerClasses.in 7798161873 p→177
Ch 7 : Constructors (classes & Objects) Sub: Computer Application
JMD HGGM
178
179
1) Private
➢ Data members and methods declared as private are accessible only in the same class where they are declared.
➢ It is the most restrictive access specifier.
2) Protected
➢ Data members and methods declared as protected are accessible only in the same class where they are declared,
classes of the same package and in its derived classes.
➢ It is associated with inheritance.
3) package/default/friendly
➢ Data members and methods are accessible only in the same class where they are declared and in the classes which
are in the same package.
➢ It is the default access specifier.
4) public:
➢ Data members and methods declared as public are accessible everywhere, ie, same class, different class, same
package, different package as well.
➢ It is the least restrictive access specifier.
180
1) Instance variables
➢ Each object has its copy of instance variables.
➢ If any object changes its instance variable, the change is only reflected in that object.
➢ Accessible in all the functions of the class(non-static functions).
2) Static variables
➢ All objects share a common copy of the static variables.
➢ Changes made by any object in the static variables are reflected in all the objects.
➢ Accessible in all the functions of the class.
3) Local variables
➢ Variables declared within a block (not directly inside a class) are called local variables.
➢ They have their scope limited to the block in which they are declared.
4) Parameter variable
➢ The variables which are taken as formal parameters to any function are parameter variables.
➢ They have their scope limited to the function to which they are passed.
181
Year 2018
Q1) How are private members of a class different from public members?
Ans: The public members can be accessed by any class in any package. The private members allow only the methods of
the same class to access them.
Year 2016
Q2) Name any two types of access specifiers.
Ans: public and private
Year 2015
Q3) The access specifier which gives most accessibility is _____ and which gives least accessibility is_______.
Solution: public, private
Year 2014
Q4) Consider the following class:
public class myClass
{
public static int x=3,y=4;
public int a=2,b=3;
}
Year 2012
182
Q5) Differentiate between public and private modifiers for members of a class?
Q6) In the program given below, state the name and the value of the
i) method argument or argument variable. ii) class/variable.
iii) local Variable. iv) instance variable.
class myClass
{
static int x = 7;
int y = 2;
public static void main (String args[])
{
myClass obj = new myClass();
System.out.println(x);
obj.sampleMethod(5);
int a = 6;
System.out.println(a);
}
void sampleMethod(int n)
{
System.out.println(n);
System.out.println(y); } }
Year 2010
183
Q5) Differentiate between private and protected visibility modifiers.
Year 2009
Q6) Consider the following code and answer the questions that follow:
class academic
{
int x, y;
void access()
{
int a, b;
academic student = new academic
System.out.println(“Object created");
}
}
i) What is the object name of class academic?
ii) Name the class variables used in the program?
iii) Write the local variables used in the program.
iv) Give the type of function used and its name.
Year 2006
184
Q7) What is meant by private visibility of a method?
Ans: Data members and methods declared as private are accessible only in the same class where they are declared.
Private methods can be accessible or called in the same class where they are declared. It is the most restrictive
access specifier.
Access Level Access Modifier In same class In Same Package In Sub class Anywhere
Private private Yes No No No
default none Yes Yes No No
protected protected Yes Yes Yes No
Public Public Yes Yes Yes Yes
185
186