1. Java Handbook for
Class X
Computer Science
Programming is like playing a game. The coach can assist
the players by explaining the rules and regulations of the
game. But it is when the players practice on the field,
they get the expertise and nuances of the game. Same
way, the teacher explains the syntax and semantics of
the programming language in detail. It is when the
students explore and practice programs on the
computer; they get the grip of the language.
Programming is purely logical and application oriented.
Learning the basics of Java in X standard would be
helpful to revise the concepts learnt in IX standard.
Priya Kumaraswami
10/27/2013
2. Acknowledgement
I should thank my family members for adjusting with my time schedules and giving inputs and
comments wherever required.
Next, my thanks are due to my colleagues and friends who provided constant support.
My sincere thanks to all my students, their queries and curiosity have helped me compile the
book in a student friendly manner.
Special thanks to Gautham, Nishchay and Mohith for reviewing the book and providing valuable
comments.
Thanks to the Almighty for everything.
Priya Kumaraswami
CS WORKBOOK X
2
Priya Kumaraswami
3. Table Of Contents
Chapter – 1...........................................................................................................................4
Introduction to Programming...............................................................................................4
Chapter – 2...........................................................................................................................7
First Program in Java...........................................................................................................7
Chapter – 3.........................................................................................................................12
Java Variables and Constants.............................................................................................12
Chapter – 4.........................................................................................................................18
Java Datatypes...................................................................................................................18
Chapter – 5.........................................................................................................................26
Operators and Expressions.................................................................................................26
Chapter – 6.........................................................................................................................33
Input and Output................................................................................................................33
Chapter – 7.........................................................................................................................41
Conditions (if and switch)..................................................................................................41
Chapter – 8.........................................................................................................................63
Loops..................................................................................................................................63
Chapter – 9.........................................................................................................................89
Number Arrays...................................................................................................................89
Chapter – 10.....................................................................................................................103
Strings & Char Arrays.....................................................................................................103
Chapter – 11.....................................................................................................................115
Functions..........................................................................................................................115
Worksheet - 1..................................................................................................................131
Worksheet – 2 .................................................................................................................133
Worksheet – 3 .................................................................................................................135
Worksheet – 4 .................................................................................................................137
Worksheet – 5 .................................................................................................................139
CS WORKBOOK X
3
Priya Kumaraswami
4. Chapter – 1
Introduction to Programming
•
Program – Set of instructions / command given to the
computer to complete a task
•
Programming – The process of writing the
instructions / program using a computer language to
complete the given task.
Stages in Program Development
1. Analysis – Deciding the inputs required, features
offered and presentation of the outputs.
2. Design – Algorithm or Flowchart can be used to design
the program.
1. The given task / problem is broken down into
simple steps. These steps together make an
algorithm.
2. If the steps are represented diagrammatically
using special symbols, it is called Flowchart.
3. The steps to arrive at the specified output from
the given inputs are identified.
3. Coding – The simple steps are translated into high
level language instructions.
1. For this, the rules of the language should be
learnt (syntax and semantics).
4. Compilation – The high level language instructions are
converted to machine language instructions.
– At this point, the syntax & semantic errors in
the program can be removed.
– Syntax Error: error due to missing colon,
semicolon, parenthesis, etc.
– Semantic Error: it is a logical error. It is due
to wrong logical statements (statements that do
not give proper meaning).
CS WORKBOOK X
4
Priya Kumaraswami
5. 5. Running / Execution – The instructions written are
carried out in the CPU.
6. Debugging / Testing – The process of removing all the
logical errors in the program by checking all the
conditions that the program needs to satisfy.
Types / Categories of
Programming techniques
1. Procedural Programming
2. Object Oriented Programming (OOP)
Comparison
• In Procedural Programming, importance is given to the
sequence of things that needs to be done and in OOP,
importance is given to the data.
• In Procedural Programming, larger programs are divided
into functions / steps and in OOP, larger programs are
divided into objects.
• In Procedural Programming, data has no security,
anyone can modify it. In OOP, mostly the data is
private and only functions / steps inside the object
can modify the data.
Why should we learn a
programming language?
•
To write instructions / commands to the computer to
perform a task
All the programs and processes running inside the computer
are written in some programming language.
CS WORKBOOK X
5
Priya Kumaraswami
6. Components / Elements of a
programming language
1. Constants – Entities that do not change their values
during program execution. Example - 4 remains 4
throughout the program. “Hello” remains “Hello”
throughout the program
2. Variables – Entities that change their values during
program execution. These are actually memory locations
which can hold a value.
3. Operators
1. Arithmetic – Operations like +, -, *, /, ^
2. Relational – Compares two values (<, >, <=, >=, !
=, ==)
3. Logical – AND, OR, NOT, used in conditions
4. Expressions – Built with constants, variables and
operators.
5. Conditions – The statements that alter the flow of the
program based on their truth values (true / false).
6. Loops – A piece of code that repeats itself until a
condition is satisfied.
7. Arrays – Continuous memory locations which store same
type of data. Used to store bulk data. Single data is
stored in variables.
8. Functions – Portion of code within a
large program that performs a specific task and which
can be called as required
CS WORKBOOK X
6
Priya Kumaraswami
7. Chapter – 2
First Program in Java
// my first program in Java
public class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Explanation
// my first program in Java
•
This is a comment statement which is used for giving
remarks in between the program.
• Comments are not compiled / executed.
• This is a single line comment.
• For multi line comments, /* ……………… */ should be used.
• Example
/* This is a multi line comment
spanning three lines to demonstrate
the syntax of it */
public class HelloWorld
•
•
•
Since Java is a truly object oriented language, we
should have a class in our program.
The class name should be provided by the programmer.
It follows the rules for naming the variables.
public static void main (String args[])
•
•
•
•
Every program should have a main() function.
A function will start with { and end with }.
All the statements inside the function should end with
a semicolon.
The syntax of main function is given below.
CS WORKBOOK X
7
Priya Kumaraswami
8. •
•
public static void main (String args[])
{
…
…
}
Inside the main function, other statements can be
added.
We’ll learn how to declare, define and use other
functions in Chapter 11.
System.out.println("Hello World!");
•
•
•
•
•
•
•
System.out.println()is used for printing on the screen.
The syntax is System.out.println( “Message” );
We can combine many messages in one statement using +
as shown below.
System.out.println( “Message 1” + “Message 2”);
If the Message 2 has to be printed in next line,
use n.
‘n’ is called a newline character.
System.out.println( “Message 1” + “n Message 2”);
Saving the Java File
The above code has to be written in Notepad and should be
saved as HelloWorld.java.
File name should be same as classname. (Even the cases
should be the same because Java is Case Sensitive)
Compilation
•
•
•
•
•
•
•
After writing the code, the code has to be compiled.
Compilation is the process of converting high level
language instructions to machine language instructions.
To compile Java code, we need to use the 'javac' tool.
Open a command prompt (cmd)
Change to the folder where your java file is stored.
cd /d d:xclass
In the command prompt, type the following command to
compile:
javac HelloWorld.java
If the compilation is successful, javac will quietly
end and return to the command prompt.
CS WORKBOOK X
8
Priya Kumaraswami
9. •
•
•
•
•
If you look into the directory after compilation,
there will be a HelloWorld.class file.
This class file is nothing but the machine language
instructions of your code.
Once your program is in this form, it’s ready to run.
Check to see that a class file has been created. If
not, you would have received error messages on the
command prompt after compilation. Check for
typographical or syntax errors in your source code.
You're ready to run your first Java program.
Execution
•
•
•
Execution is the process of running the instructions
one by one in the CPU and getting the results.
To run the program, type the following command in the
command prompt:
java –classpath . HelloWorld
Output would be
Hello world!
•
Note: It is important to note that you use the full
name with extension when compiling (javac
HelloWorld.java) but only the class name when running
(java HelloWorld).
Integrated Development
Environment
•
•
•
An integrated development environment (IDE) is
a software application that provides
facilities for program development.
An IDE normally consists of:
o a source code editor where code can be written
o a compiler
o a provision to run the program
o a provision to debug the program
For java, BlueJ is a well known IDE. But, we use the
command line compilation and execution.
CS WORKBOOK X
9
Priya Kumaraswami
10. Exercise
1. Fill in the blanks
public _________________
public _________ void main _______
{
_______ (“ Hello”) ;
________
(“ How are you?” );
/* This program prints Hello in the first line
and How are you in the second line */
}
2. Write a program to print 3 lines of 10 stars.
3. Write a program to print your name, class, section and
age.
CS WORKBOOK X
10
Priya Kumaraswami
12. Chapter – 3
Java Variables and Constants
Before we learn Java variables and constants, we should
know these terms – integer, floating point, character and
string.
Integer represents any whole number, positive or negative.
The number should not contain decimal point or commas. They
can be used in arithmetic calculations.
Examples – 14, -19, 34, -504
Floating point represent any number (positive or negative)
containing decimal point. No commas. They can be used in
arithmetic calculations.
Examples – 14.025, -13.65, 506.505, -990.0, 0.65
Character represents any character that can be typed
through the keyboard. They cannot be used in arithmetic
calculations.
Examples – A, a, T, x, 9, 3, %, &, @, $
String (char array) represents a sequence of characters
that can be typed through the keyboard. They cannot be used
in arithmetic calculations.
Examples – Year2012, Gone with the wind, email@mailbox,
**(*)**
Constants
•
Constants are the entities that do not change their
values during program execution.
•
There are four types – string, character, floating
point and integer constants.
String Constants Examples
String or character array constants should be always
enclosed in double quotes.
CS WORKBOOK X
12
Priya Kumaraswami
13. •
•
•
•
“123”
“Abc”
“This is some text.”
“so many $”
(character
(character
(character
(character
array
array
array
array
)
)
)
)
char Constants Examples
Character constants should be always enclosed in single
quotes.
•
•
‘A’
‘z’
(character)
(character)
integer constants Examples
•
•
123
34
(integer)
(integer)
floating point constants Examples
•
•
34.78
5666.778
(floating point)
(floating point)
A sample program using constants
Variables
•
Variables are actually named memory locations which
can store any value.
•
It is the programmer who assigns the name for a memory
location.
CS WORKBOOK X
13
Priya Kumaraswami
14. •
Variables are the entities that can change their
values during program execution.
Example
A = 10;
A contains 10 now
A = A + 1;
A contains 11 now
A = 30;
A contains 30 now
•
There can be integer variables which can store integer
values, floating point variables to store floating
point values, character variables to store any
character or string variables to store a set of
characters.
The type (i.e., datatype) of a variable will be covered in
next chapter.
Rules for naming the variables
•
All variable names should begin with a letter and
further it can have digits or underscores or letters.
•
A variable name should not contain space or any other
special character.
•
Another rule that you have to consider when naming the
variables is that they cannot match any keyword of the
Java language. The standard reserved keywords in Java
are:
CS WORKBOOK X
14
Priya Kumaraswami
15. •
The Java language is a "case sensitive" language. It
means that a variable written in capital letters is
not equivalent to another one with the same name but
written in small letters. Thus, for example, the
RESULT variable is not the same as the result variable
or the Result variable. These are three different
variables.
•
Generally, it is considered a good practice to name
variables according to their purpose/functionality.
Exercise
1. Identify the type of constants
a. 123.45
b. 145.0
c. 1166
d. “1166”
e. “123.45”
f. ‘3’
g. “*”
2. Indicate whether the following variable names are
valid or not
a. fgh
b. Main
c. 5go
CS WORKBOOK X
15
Priya Kumaraswami
16. d. var name
e. var_name
f. var*name
3. Identify the errors
a. ‘abc’
b. 14.
c. .45
d. 50,000
CS WORKBOOK X
16
Priya Kumaraswami
18. Chapter – 4
Java Datatypes
•
Datatypes are available in a programming language to
represent different forms of data and to determine the
bytes used by each form of data.
•
Datatype technically indicates the amount of memory used
in the form of bytes.
•
•
•
•
•
So we need to understand bits and bytes.
A bit in memory can store either 1 or 0.
8 bits make a byte.
A byte can be used to store a sequence of 0’s and 1’s.
Example – 10110011 or 11110000
Decimal to Binary Conversion
Calculation of the range
•
With 1 bit, we can represent 2 numbers (21)
Bit Combination
Decimal Value
0
0
1
1
CS WORKBOOK X
18
Priya Kumaraswami
19. •
With 2 bits, we can represent 4 numbers (22)
Bit Combination
Decimal Value
00
0
01
1
10
2
11
3
•
With 3 bits, we can represent 8 numbers (23)
Bit Combination
Decimal Value
000
0
001
1
010
2
011
3
100
4
101
5
110
6
111
7
•
With 8 bits, we can represent 256 numbers (28). If it
has to cover both +ve and –ve numbers, that 256 has to
be split as -128 to + 127 including 0.
•
With 16 bits, we can represent 65536 numbers (216). If
it has to cover both +ve and –ve numbers, that 65536
has to be split as -32768 to + 32767 including 0.
Fundamental Datatypes
•
There are eight primitive data types supported by Java. –
byte, short, int, long, float, double, boolean, char
•
byte, short, int, long datatypes are used to represent
numbers.
• char datatype is used to represent a single character.
char is internally stored as a number as the system can
only understand numbers, that too binary numbers. So each
character present in the keyboard has a number equivalent,
called Unicode. The Unicode equivalent for the alphabet and
digits are given below.
Char
A to Z
a to z
0 to 9
CS WORKBOOK X
Unicode
65 to 90
97 to 122
48 to 57
19
Priya Kumaraswami
20. Please refer wikipedia for the complete Unicode table (for
all characters in the keyboard).
•
float and double datatype are used to represent a
floating point number.
•
void datatype is used in Java functions covered in
chapter 11. It means “nothing” stored.
•
boolean datatype is used to store the logical status –
true or false
•
String is a special datatype in java which represents a
set of characters.
•
The following table gives the size in bytes and the range
of numbers accommodated by each datatype.
Datatype Size in bytes
(Memory used)
Range
byte
short
int
1 byte
2 bytes
4 bytes
-128 to 127
-32768 to 32767
-2147483648 to
2147483647
long
8 bytes
-9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
99502384355245
float
double
char
4 bytes
8 bytes
2 bytes
Approx 7 digits
Approx 15 digits
12.43, 6789.566
56789.66666
‘a’, ‘A’, ‘$’, ‘1’,
‘0’, ‘%’
(Any single character
on the keyboard)
boolean
String
1 byte
According to
the number of
characters
(per char,
two bytes)
true / false
CS WORKBOOK X
20
Example data that can
be stored using the
given datatype
116, 12
12, 30000
12, 948900
Priya Kumaraswami
21. Variable Declaration
•
Any variable should be declared before we use it.
•
Associating a variable name with a datatype is called
declaration.
int a;
float mynumber;
These are two valid declarations of variables.
The first one declares a variable of type int with the
name a. Now a can be used to store any integer value.
It will occupy 4 bytes in memory.
The second one declares a variable of type float with
the name mynumber. Now mynumber can be used to store
any floating point value. It will occupy 4 bytes in
memory.
Similarly, we can declare char, long, double variables.
char ch;
long num;
double d;
•
(ch occupies 2 bytes)
(num occupies 8 bytes)
(d occupies 8 bytes)
If you are going to declare more than one variable of
the same type, you can declare all of them in a single
statement by separating their names with commas.
For example:
int a, b, c;
This declares three variables (a, b and c), all of
them of type int, and has exactly the same meaning as:
int a;
int b;
int c;
•
Multiple declaration of a variable is an error.
For example,
int a;
int a = 2;
//error as a is already declared in the
previous statement
CS WORKBOOK X
21
Priya Kumaraswami
22. Variable Initialization
•
Giving an appropriate value for a variable is known as
initialization
•
Examples
int a = 10;
float b = 12.5;
float c;
c = 26.0;
char ch1, ch2;
ch1 = ‘q’;
ch2 = ‘p’;
long t = 40000;
double d = 1189.345;
int x = 9, y = 10; (Multiple initializations)
A sample program using variables
public class test
{
public static void main (String args[])
{
int a, b;
int result;
a = 5;
b = 2;
a = a + 1;
// 1 is added to a value and stored in
// a again. a becomes 6 now.
result = a - b; // result contains 4 now
System.out.println(result); // 4 is printed on screen
}
}
Exercise
1. Write correct declarations for the following
a. A variable to store 13.5
b. A variable to store NCFE
c. A variable to store grade (A / B / C / D / E)
d. A variable to store 10000
CS WORKBOOK X
22
Priya Kumaraswami
23. 2. Convert the following decimal numbers to binary
a. 1024
b. 255
c. 1189
d. 52
3. Draw the table to show the bit combination and
decimal value for 4 bits binary.
4. Identify the errors in the following
a. int a = ‘a’;
b. float x; y; z;
c. short num = 45678;
d. char ch = “abc”;
e. char c = ‘abc’;
f. int m$ = 10;
g. long m = 90; n = 3400;
CS WORKBOOK X
23
Priya Kumaraswami
26. Chapter – 5
Operators and Expressions
Two Categories
•
•
Binary operators – operators which take 2 operands.
Examples +, - , > , <, =
Unary operators – operators which take 1 operand.
Examples ++, --, !
Operations and the Operators
Arithmetic Operators +, -, *, /, %
Arithmetic operators are used to perform addition (+),
subtraction (-), multiplication (*) and division (/).
% is a modulo operator which gives the remainder after
performing the division of 2 numbers.
10%3 will give 1.
14%2 will give 0.
27%7 will give 6.
Logical Operators &&, ||, !
Logical operators are used in conditions to combine
expressions.
a > 10 && a < 100
b == 10 || b == 20
!(b == 10)
Relational Operators >, <, >=, <=, !=, ==
Relational operators are used for comparisons.
10 > 2 will give true.
12 == 2 will give false.
6 <= 12 will give true.
7 != 7 will give false.
Assignment Operator =
Assignment operator is used to assign a value to a
variable
a = 10;
b = b + 20;
c = b;
There are shortcuts used in assignment.
CS WORKBOOK X
26
Priya Kumaraswami
27. A = A + B; can be written as A += B;
A = A * B; can be written as A *= B; (similarly for - , /
and % operators)
Increment Operator ++
Decrement Operator -•
•
These two operators increment or decrement the value
of a variable by 1.
There are 2 versions of them – post and pre
Pre increment – First the increment happens and then the
incremented value is used in the expression
Example a = 10, b = 20
C = (++a) + (++b) = 11 + 21 = 32
Post increment – First the current value is used in the
expression and then the values are incremented
Example a = 10, b = 20
C = (a++) + (b++) = 10 + 20 = 30 then a becomes 11 and b
becomes 21
Pre decrement – First the decrement happens and then the
decremented value is used in the expression
Example a = 10, b = 20
C = (--a) + (--b) = 9 + 19 = 28
Post decrement – First the current value is used in the
expression and then the values are decremented
Example a = 10, b = 20
C = (a--) + (b--) = 10 + 20 = 30 then a becomes 9 and b
becomes 19
Sample Problem
public class test2
{
public static void main(String args[])
{
int a = 20 , b = 40;
int c = a++ + ++b;
//20 + 41 = 61 (a becomes 21)
a = a + b++;
//21 + 41 = 62 (b becomes 42)
b = c - --a;
//61 – 61 = 0
System.out.println( a + “ “ + b + “ “ + c);
CS WORKBOOK X
27
Priya Kumaraswami
28. //61 0 61 will be printed
}
}
Expressions
Java Expressions are the result of combining constants,
variables and operators. Expressions can be arithmetic or
logical.
Arithmetic expressions use arithmetic operators and
int/float constants and variables.
Examples of arithmetic expression
(a, b, c are integer variables)
a = b + c;
a = a + 20;
b++;
c = c * 13 % 5;
Logical expressions use logical or relational
operators with constants and variables. The result of a
logical expression is always true or false.
Examples of logical expression
(a, b, c are integer variables)
a > 10 && a < 90
a != b
((c%6 == 1) || (c%6 == 2))
!(a < 100)
The evaluation of the expression generally follows order
of precedence (similar to BODMAS rule, but not same)
CS WORKBOOK X
28
Priya Kumaraswami
29. Expressions with char variable
When char is used in an expression, its Unicode
equivalent is taken.
Example
char ch = ‘a’;
ch += 5;
System.out.println(ch);//will print ‘f’ on the screen.
char c = ‘S’;
c -= 2;
System.out.println(c); //will print ‘N’ on the screen
Note:
ch = ch + 5;
c = c – 2;
will not work in java. Java does not allow to mix int and
char types.
Exercise
1. Evaluate the following expressions
a. System.out.println( 10 + 5 * 3 );
b. int a = 10;
a += 20;
System.out.println( a++);
c. System.out.println( 10 > 5 && 10 < 20);
d. boolean z = !(10 < 50);
System.out.println( z );
CS WORKBOOK X
29
Priya Kumaraswami
30. e. int f = 20 % 3 + 2;
System.out.println( f);
2. Write Java expressions for the following
a. C = A2 + B2
b. A is greater than 0 and less than 100
c. Grade is A or B
d. Increment the value of X by 20
3. Find the output for the following code snippets
a. int a = 39, b = 47;
a = a++ + 20;
b = ++b = 40;
int c = ++a + b++;
System.out.println( c );
b. int x = 23, y = 34;
x = x++ + ++x;
y = y + ++y;
System.out.println( x + “ “ + y);
c. int m = 44, n = 55;
int k = m + --n;
int j = n – m--;
int l = k / j;
System.out.println( l );
CS WORKBOOK X
30
Priya Kumaraswami
33. Chapter – 6
Input and Output
The output operation is already illustrated in Chapter 2
– “First Program in Java”. A recap of the same is given
below.
Output using
System.out.println() &
System.out.print()
System.out.println() is a function available in Java.
Since we are not getting into the oop concepts, further
explanation is not provided here about System class, out
variable and println() function.
System.out.println ( "Output sentence" );
// prints Output sentence on screen
System.out.println (120);
// prints number 120 on screen
System.out.println (x);
// prints the content of x on screen
Notice that the sentence in the first statement is
enclosed between double quotes (") because it is a
constant string of characters. Whenever we want to use
constant strings of characters we must enclose them
between double quotes (") so that they can be clearly
distinguished from variable names. For example, these two
sentences have very different results.
System.out.println ("Hello");
// prints Hello
System.out.println (Hello);
// prints the content of Hello variable
Multiple chunks to print can be combined using + operator
System.out.println ("Hello, " + "I am " + "a Java statement");
CS WORKBOOK X
33
Priya Kumaraswami
34. This last statement would print the message Hello, I am a
Java statement on the screen.
We can combine variables, constants and expressions in a
System.out.println() statement.
System.out.println ("Hello, I am " + age + " years old and my zipcode
is " + zipcode);
If we assume the age variable to contain the value 24 and
the zipcode variable to contain 90064 the output of the
previous statement would be:
Hello, I am 24 years old and my zipcode is 90064
It is important to notice that System.out.println() adds a
line break after its output automatically:
System.out.println ("This is a sentence.");
System.out.println ("This is another sentence.");
will be shown on the screen in two lines:
This is a sentence.
This is another sentence.
In order to continue writing in the same line, we must use
System.out.print().
System.out.print ("This is a sentence.");
System.out.print ("This is another sentence.");
will be shown on the screen in one line:
This is a sentence.This is another sentence.
In Java, a new-line character can be specified
as n (backslash, n):
System.out.println ("First sentence.n");
System.out.println ("Second sentence.nThird sentence.");
This produces the following output:
First sentence.
Second sentence.
CS WORKBOOK X
34
Priya Kumaraswami
35. Third sentence.
Input using args
While running the java program using java command, we can
combine the inputs required for the program.
For example, if a program expects 2 integers as input, then
when running the program, these 2 integers are passed as
shown below
java –cp . Demo 10 20
These two integers come as args[] in the program. The first
integer is args[0] and the second integer is args[1].
But these integers are in String format. So they should be
converted to int. For this, we use a function
Integer.parseInt(). See the example below.
input using args
We use this to
get input
public class Demo
{
public static void main(String args[])
{
int a = Integer.parseInt (args[0]);
int b = Integer.parseInt (args[1]);
String s = args[2];
float c = Float.parseFloat (args[3]);
double d = Double.parseDouble (args [4]);
char e = args[5].charAt(0);
long f = Long.parseLong(args[6]);
}
}
In the above program, we have taken 2 integers, 1 String, 1
float, 1 double and 1 char as inputs.
CS WORKBOOK X
35
Priya Kumaraswami
36. Note the functions Integer.parseInt() used for integers,
Float.parseFloat() used for float, Double.parseDouble()
used for double, Long.parseLong() for long.
char input uses charAt(0) function.
String input uses the args[] directly.
Sample Program showing input using args
public class Demo
{
public static void main(String args[])
{
int i;
System.out.println("Please enter an integer
value: ");
i = Integer.parseInt(args[0]);
System.out.println("The value you entered is " +
i);
System.out.println(" and its double is " + i*2);
}
}
In the above program, an int variable is declared and its
value is taken as input. Similarly, other type variables
(long, char, float, double) can be declared and their
values can be taken as inputs.
Input using readers
For using the readers, 2 java classes need to be imported
which are in java.io package – InputStreamReader and
BufferedReader.
import java.io.InputStreamReader;
import java.io.BufferedReader;
Then two objects need to be created as follows.
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Now br can be used to read a line of input. For this, we
use the function br.readLine(). But the input comes as a
String. So if an integer input is required, it should be
converted using Integer.parseInt() function.
CS WORKBOOK X
36
Priya Kumaraswami
37. int n = Integer.parseInt(br.readLine());
Additionally, throws Exception should be added to public
static void main(String args[]).
input using readers
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Demo
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int a = Integer.parseInt (br.readLine());
int b = Integer.parseInt (br.readLine());
String s = br.readLine();
float c = Float.parseFloat (br.readLine());
double d = Double.parseDouble (br.readLine());
char e = br.readLine().charAt(0);
long f = Long.parseLong(br.readLine());
}
}
Sample Program showing input using readers
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Demo
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr = new
InputStreamReader(System.in);
CS WORKBOOK X
37
Priya Kumaraswami
38. BufferedReader br = new BufferedReader(isr);
int a, b;
System.out.println("Please enter 2 integers: ");
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());
System.out.println("The sum is " + a + b);
}
}
Exercise
1. Write programs for the following taking necessary inputs
a. To find and display the area of circle, triangle and
rectangle
b. To calculate the average of 3 numbers
c. To find and display the simple interest
d. To convert the Fahrenheit to Celsius and vice versa
F = 9/5 * C + 32
C = 5/9 (F – 32)
e. To convert the height in feet to inches (1 foot = 12
inches)
CS WORKBOOK X
38
Priya Kumaraswami
41. Chapter – 7
Conditions (if and switch)
Null Statement
•
•
•
•
Statements are the instructions given to the computer
to perform any kind of action.
Statements form the smallest executable unit within a
program
Statements are terminated with a ;
The simplest is the null or empty statement ;
Compound Statement
•
•
•
It is a sequence of statements enclosed by a pair of
braces { }
A compound statement is also called a block.
A compound statement is treated as a single unit and
can appear anywhere in the program.
Control Statements
•
•
•
•
•
Generally a program executes its statements from the
beginning to the end of main().
But there can be programs where the statements have to
be executed based on a decision or statements that
need to be run repetitively.
There are tools to achieve these scenarios and those
statements which help us doing so are called control
statements
In a program, statements can be executed sequentially,
selectively (based on conditions) or iteratively
(repeatedly in loops).
The sequence construct means the statements are being
executed sequentially, from the first statement of the
main() to the last statement of the main(). This
represents the default flow of statements.
CS WORKBOOK X
41
Priya Kumaraswami
42. Operators used in conditions
•
>, <, >=, <=, ==, !=, &&, ||, !
•
Examples
grade == ‘A’
a > b
!x
x >=2 && x <=10
grade == ‘A’ || grade == ‘B’
•
Please note that == (double equal-to) is used for
comparisons and not = (single equal-to)
•
Single equal-to is used for assignment.
•
AND (&&) and OR(||) can be used to combine conditions
as shown below
a > 20 && a < 40
• Both the conditions a > 20 and a < 40 should be
satisfied to get a true.
•
•
•
•
•
if ( a == 0 || a < 0)
Either the condition a == 0 or the condition a < 0
should be satisfied to get a true.
Not operator (!) negates or inverses the truth value
of the expression
!true becomes false
!false becomes true
!(10 > 12) becomes true
Note:
a > 20 && < 40 is syntactically wrong.
a == 0 || < 0 is syntactically wrong.
Conditional structure: if
•
•
Also called conditional or decision statement
Syntax of if statement
if ( condition )
statement ;
CS WORKBOOK X
42
Priya Kumaraswami
43. •
•
•
•
Statement can be single or compound statement or null
statement
Condition must be enclosed in parenthesis
If the condition is true, statement is executed. If it
is false, statement is ignored (not executed) and the
program continues right after the conditional
structure.
Example
if (x == 100)
System.out.println("x is 100");
•
•
If x value is 100, “x is 100” will be printed.
If x value is 95 or 5 or 20 (anything other than 100),
nothing will be printed.
•
If we want more than a single statement to be executed
in case that the condition is true we can specify a
block using braces { }
if (x == 100)
{
System.out.print("x is ");
System.out.println(x);
}
Note:
if (x == 100)
{
System.out.print("x is ");
System.out.print(x);
}
•
•
If x value is 100, x is 100 will be printed.
If x value is 95 or 5 or 20 (anything other than 100),
nothing will be printed.
if (x == 100)
System.out.print ("x is ");
System.out.println(x);
•
•
If x value is 100, x is 100 will be printed.
If x value is 95 (anything other than 100), 95 will be
printed. This is because the if statement includes
only one statement in the absence of brackets. The
second statement is independent of if. Therefore, the
CS WORKBOOK X
43
Priya Kumaraswami
44. second statement gets executed irrespective of whether
the if condition becomes true or not.
Note:
Any non-zero value is true.
0 is false.
Conditional structure: if and else
We can additionally specify what we want to happen if the
condition is not fulfilled by using the keyword else. It is
used in conjunction with if.
if (condition)
statement1 ;
else
statement2 ;
// Note the tab space
// Note the tab space
Example:
if (x == 100)
System.out.println("x is 100");
else
System.out.println( "x is not 100");
prints on the screen x is 100 if x has a value of 100, but
if it is not 100, it prints out x is not 100.
Conditional structure: if … else if … else
If there are many conditions to be checked, we can use the
if … else if … else ladder as shown below in the example.
if (x > 0)
System.out.println("x is positive");
else if (x < 0)
System.out.println("x is negative");
else
System.out.println("x is 0");
The above syntax can be understood as… if condition1 is
satisfied, do something. Otherwise, check if condition 2 is
satisfied and if so, do something else. Otherwise (else),
do completely something else.
Remember that in case we want more than a single statement
CS WORKBOOK X
44
Priya Kumaraswami
45. to be executed for each condition, we must group them in a
block by enclosing them in braces { }.
if (x > 0)
{
System.out.print ("x is positive");
System.out.println( “ and its value is “ + x) ;
}
else if (x < 0)
{
System.out.print ("x is negative");
System.out.println( “ and its absolute value is “ + -x) ;
}
else
{
System.out.print ("x is 0");
System.out.println( “ and its value is “ + 0 );
}
Points to remember
•
•
•
If there is only one statement for ‘if’ and ‘else’, no
need to enclose them in curly braces { }
Example
if ( grade == ‘A’)
System.out.println( “Good grade”);
else
System.out.println( “Should improve”);
In an if statement, DO NOT put semicolon in the line
having test condition
if ( y > max) ; if the condition is true, only
null statement will be executed.
{
max = y;
}
Conditional structure: Nested if
•
In a nested if construct, you can have an if...else
if...else construct inside another if...else if
...else construct.
CS WORKBOOK X
45
Priya Kumaraswami
46. •
Syntax
if (condition 1)
statement 1;
else
{
if (condition 2)
statement 2;
else
statement 3;
}
if (condition 1)
{
if (condition 2)
statement 1;
else
statement 2;
}
else
statement 3;
if (expression 1)
{
if (condition 2)
statement 1;
else
statement 2;
else
{
if (condition 3)
statement 3;
else
statement 4;
}
Dangling else problem
if ( ch >= ‘A’)
if(ch <= ‘Z’)
upcase = upcase + 1;
else
others = others + 1;
•
•
Which if the else belongs to, in the above case?
The else goes with the immediate preceding if
CS WORKBOOK X
46
Priya Kumaraswami
47. •
The above code can be understood as shown below
if ( ch >= ‘A’)
{
if(ch <= ‘Z’)
upcase = upcase + 1;
else
others = others + 1;
}
•
If the else has to be matching with the outer if, then
use brackets { } as below
if ( ch >= ‘A’)
{
if(ch <= ‘Z’)
upcase = upcase + 1;
}
else
others = others + 1;
Difference between if…else if ladder and multiple
ifs
int a = 10;
if( a >= 0)
System.out.println(a);
else if ( a >= 5)
System.out.println(a + 5);
else if (a >= 10)
System.out.println(a + 10);
else
System.out.println(a + 100);
int a = 10;
if( a >= 0)
System.out.println(a);
if ( a >= 5)
System.out.println(a + 5);
if (a >= 10)
System.out.println(a + 10);
else
System.out.println(a + 100);
The output here is 10.
The first condition is
satisfied and therefore it
gets inside and prints 10.
The other conditions will
not be checked.
CS WORKBOOK X
The output here is 101520.
The code here has multiple
ifs which are independent.
The else belongs to the
last if.
47
Priya Kumaraswami
48. Conditional structure: switch
•
•
Switch is also similar to if.
But it tests the value of an expression against a list of
integer or character constants.
•
Syntax
switch (expression)
{
case constant1:
statements;
break;
case constant2:
statements;
break;
default:
statements;
}
•
switch evaluates expression and checks if it is equivalent
to constant1, if it is, it executes group of statements
under constant1 until it finds the break statement. When it
finds the break statement, the program jumps to the end of
the switch structure.
•
If expression was not equal to constant1 it will be checked
against constant2. If it is equal to this, it will
execute group of statements under constant2 until a break
keyword is found, and then will jump to the end of
the switch structure.
•
Finally, if the value of expression did not match any of
the specified constants (you can include as
many case labels as values you want to check), the program
will execute the statements included after
the default: label, if it exists (since it is optional).
•
If there is no break statement for a case, then it falls
through the next case statement until it encounters a break
statement.
•
A case statement cannot exist outside the switch.
CS WORKBOOK X
48
Priya Kumaraswami
49. Example of a switch construct with integer constant
int n = Integer.parseInt(args[0]);
switch(n)
{
case 1:
System.out.println(
break;
case 2:
System.out.println(
break;
case 5:
System.out.println(
break;
default:
System.out.println(
break;
}
“C++”);
“Java”);
“C#”);
“Algol”);
In the above program, if input is 1 for n, C++ will be printed.
If input is 2 for n, Java will be printed. If input is 5 for n,
C# will be printed. If any other number is given as input for n,
Algol will be printed.
Example of a switch construct with character constant
char ch = args[0].charAt(0);
switch(ch)
{
case ‘a’:
System.out.println(
break;
case ‘$’:
System.out.println(
break;
case ‘3’:
System.out.println(
break;
default:
System.out.println(
break;
}
“Apple”);
“Samsung”);
“LG”);
“Nokia”);
In the above program, if input is ‘a’ for ch, Apple will be
printed. If input is ‘$’ for ch, Samsung will be printed. If
CS WORKBOOK X
49
Priya Kumaraswami
50. input is ‘3’ for ch, LG will be printed. If any other character
is given as input for ch, Nokia will be printed.
Scope of a variable
•
A variable can be used only within the block it is declared.
•
Example1 - the scope of j is within that if block only,
starting brace of if to ending brace of if.
if( a == b)
{
int j = 10;
System.out.println(j);
valid as j is declared
inside the if block
}
System.out.println(j);
invalid as j is used
outside the block
•
Example2 - the scope of n is within the main(), starting
brace of main() to ending brace of main()
void main()
{
int n = Integer.parseInt(args[0]);
if ( n > 100)
{
System.out.println(n + “is invalid”);
}
System.out.println( “Enter the correct value for n”);
}
Sample Programs
7.1 Program to print pass or fail given the mark
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class status
{
public static void main(String args[])throws Exception
{
CS WORKBOOK X
50
Priya Kumaraswami
51. InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int x;
System.out.println( “Enter the mark”);
x = Integer.parseInt(br.readLine());
if (x >= 40)
{
System.out.println( “Pass J” );
}
else
{
System.out.println( “Fail L” );
}
}
}
7.2 Program to find the grade
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class grade
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int x;
System.out.println( “Enter the mark”);
x = Integer.parseInt(br.readLine());
char grade;
if (x >= 80 && x <= 100)
{
grade = ‘A’;
}
else if ( x >= 60 && x < 80)
{
grade = ‘B’;
}
else if ( x >= 45 && x < 60)
{
grade = ‘C’;
}
CS WORKBOOK X
51
Priya Kumaraswami
52. else if ( x >= 33 && x < 45)
{
grade = ‘D’;
}
else if ( x >= 0 && x < 33)
{
grade = ‘E’;
}
else
{
System.out.println(“Not a valid mark”);
grade = ‘N’;
}
System.out.println( “The grade for your mark is” +
grade);
}
}
7.3 Program to check whether a number is divisible by 5
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class div
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int x;
System.out.println( “Enter a number”);
x = Integer.parseInt(br.readLine());
if (x % 5 == 0)
{
System.out.println(“The number is divisible by
5”);
}
else
{
System.out.println(“The number is not divisible
by 5”);
}
}
}
CS WORKBOOK X
52
Priya Kumaraswami
53. 7.4 Program to check whether a number is positive or negative
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class number
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int i = Integer.parseInt(args[0]);
System.out.println( “Enter a number”);
if( i >= 0)
System.out.println( “positive integer”);
else
System.out.println( “negative integer”);
}
}
7.5 Program to calculate the area and circumference of a
circle using switch
This program takes r (radius) as input and also a choice n as
input.
Depending on the choice entered, it calculates area or
circumference.
It calculates area if the choice is 1. It calculates
circumference if choice is 2.
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class circleop
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int n , r;
System.out.println( “Enter choice:(1 for area, 2 for
circumference)” ) ;
n = Integer.parseInt(br.readLine()) ;
System.out.println( “Enter radius”);
r= Integer.parseInt(br.readLine());
CS WORKBOOK X
53
Priya Kumaraswami
54. float res;
switch(n)
{
case 1:
res = 3.14 * r * r;
System.out.println( “The area is “ + res);
break;
case 2:
res = 3.14 * 2 * r;
System.out.println(“The circumference is “ + res);
break;
default:
System.out.println( “Wrong choice”);
break;
}
}
7.6 Program to calculate the area and circumference of a
circle using switch fall through
This program takes r (radius) as input and also a choice n as
input.
Depending on the choice entered, it calculates area or (area
and circumference).
It calculates area if the choice is 1. It calculates area and
circumference if choice is 2.
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class circleop
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println( “Enter choice:(1 for area, 2 for
both)”) ;
int n , r;
n = Integer.parseInt(br.readLine()) ;
System.out.println( “Enter radius”);
r= Integer.parseInt(br.readLine());
float res;
switch(n)
{
case 2:
CS WORKBOOK X
54
Priya Kumaraswami
55. res = 3.14 * 2 * r;
System.out.println( “The circumference is “
+ res);
case 1:
res = 3.14 * r * r;
System.out.println( “The area is “+res);
break;
default:
System.out.println( “Wrong choice”);
break;
}
}
}
7.7 Program to write remarks based on grade
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class circleop
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println( “Enter the grade” );
char ch;
ch = br.readLine().charAt(0);
switch(ch)
{
case ‘A’:
System.out.println(“Excellent. Keep it up.
“);
break;
case ‘B’:
System.out.println(“Very Good. Try for A
Grade”);
break;
case ‘C’:
System.out.println( “Good. Put in more
efforts”);
break;
case ‘D’:
System.out.println( “Should work hard for
better results”);
break;
CS WORKBOOK X
55
Priya Kumaraswami
56. case ‘E’:
System.out.println(“Hard work and focus
required”);
break;
default:
System.out.println(“Wrong Grade entered.”);
break;
}
}
Exercise
1. Find the output for the following code snippets
a. int a , b;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
if( a % b == 0)
System.out.println(a / b);
System.out.println(a % b);
if a is 42 & b is 7 (1st time run)
if a is 45 & b is 7 (2nd time run)
b. int x, y = 4;
switch(x % y)
{
case 0:
System.out.println(x);
case 1:
System.out.println(x * 2);
break;
case 2:
System.out.println(x * 3);
case 3:
System.out.println(x * 4);
default:
System.out.println(0);
}
when x is given as 50, 51, 52, 53, 54, 55
c. char ch;
ch = args[0].charAt(0);
int val = 2;
switch (ch)
{
case ‘0’:
System.out.println(“converting from giga to
mega”;
CS WORKBOOK X
56
Priya Kumaraswami
57. System.out.println(val * 1024);
break;
case ‘1’:
System.out.println(“converting from giga to
kilo”);
System.out.println(val * 1024 * 1024);
break;
case ‘2’:
System.out.println( “converting from giga to
bytes”);
System.out.println(val * 1024 * 1024 * 1024);
break;
default:
System.out.println( “invalid option”);
break;
}
When ch is given as 1 2 3 a 0
d. int a, b;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
if( ! (a % b == 0))
if( a > 10)
a = a + b;
else
a = a + 1;
else
b = a + b;
System.out.println(a + “ “ + b);
when a = 10 and b = 5
when a = 9 and b = 3
when a = 8 and b = 6
2. Find the mistakes
int a, b;
if( a > b ) ;
System.out.print(a + “is greater than “);
System.out.println(b);
else if ( b > a)
System.out.print(b + “is greater than “) ;
System.out.println(a);
else ( a == b)
System.out.print(a + “is equal to “ );
System.out.println(b);
3. Convert the following if construct to switch construct
int m1, m2;
if( m1 >= 80)
{
if( m2 >= 80)
CS WORKBOOK X
57
Priya Kumaraswami
58. System.out.println( “Very Good”);
else if (m2 >= 40)
System.out.println( “Good”);
else
System.out.println( “improve”);
}
else if( m1 >= 40)
{
if( m2 >= 80)
System.out.println( “Good”);
else if (m2 >= 40)
System.out.println( “Fair”);
else
System.out.println( “improve”);
}
else
{
if( m2 >= 80)
System.out.println( “Good”);
else if (m2 >= 40)
System.out.println( “improve”);
else
System.out.println( “work hard”);
}
4. Write Programs
a. To accept the cost price and selling price and calculate
either the profit percent or loss percent.
b. To accept 3 angles of a triangle and check whether the
triangle is possible or not. If triangle is possible,
check whether it is acute angled or right angled or
obtuse angled.
c. To accept the age of a candidate and check whether he can
vote or not
d. To calculate the electricity bill according to the given
tariffs.
Units consumed
Charges
Upto 100 units
Rs 1.35 / unit
> 100 units and upto
Rs 1.50 / unit
200 units
> 200 units
Rs 1.80 / unit
e. To accept a number and check whether the number is
divisible by 2 and 5, divisible by 2 not 5, divisible by
5 not 2
f. To accept 3 numbers and check whether they are
Pythagorean triplets
CS WORKBOOK X
58
Priya Kumaraswami
59. g. To accept any value from 1 to 7 and display the weekdays
corresponding to the number entered. (use switch case)
h. To find the volume of a cube or a cuboid or a sphere
depending on the choice given by the user
Notes
CS WORKBOOK X
59
Priya Kumaraswami
63. Chapter – 8
Loops
A loop is a piece of code that repeats itself until a condition
is satisfied. A loop alters the flow of control of the program.
Each repetition of the code is called iteration.
Two Types
•
•
•
•
Entry Controlled - First the condition is checked. If the
condition evaluates to true, then the loop body is executed.
Example – for, while
Exit Controlled – First the loop body is executed, then the
condition is checked. If the condition evaluates to true,
then the loop body is executed another time.
Example – do while
Parts of a loop
•
•
•
•
Initialization expression – Control / counter / index
variable has to be initialized before entering inside the
loop. This expression is executed only once. (Initial Value
with which the loop will start)
Test expression – This is the condition for the loop to
run. Until this condition is true, the loop statements get
repeated. Once the condition becomes false, the loop stops
and the control goes to the next statement in the program
after the loop.
(Final Value with which the loop will end)
Update expression – This changes the value of the control /
counter / index variable. This is executed at the end of
the loop statements for each iteration
(Step Value to reach the final value from the initial value)
Body of the loop – Set of statements that needs to be
repeated.
for loop
•
Syntax
CS WORKBOOK X
63
Priya Kumaraswami
64. for (initialization expr ; test expr ; update expr)
statement;
The statement can be simple or compound.
•
Example 1
In this code, i is the index variable. Its initial value is
1. Till i value is less than or equal to 10, the statements
will be repeated. So, the code prints 1 to 10. After i=10
and printing it, the index variable becomes 11, but the
condition is not met. So the loop stops.
Note:
i=i+1 can also be written as i++.
i=i-1 can also be written as i--;
•
Example 2
for (int a= 10; a >= 0; a=a-3)
{
System.out.println(a);
}
This code prints 10 to 0 with a step of
So 10 7 4 1 get printed.
•
-3.
Example 3
for (int c= 10; c >= 1; c=c-2)
{
System.out.println( ‘*’);
}
This code loops 10 to 1 with a step of -2. But the c
variable is not printed. ‘*’ is printed 5 times.
CS WORKBOOK X
64
Priya Kumaraswami
65. •
Example 4
for (int i = 0; i < 5; i=i+1)
System.out.println(i * i);
This code prints 0 1 4 9 16. If there is only one statement
to be repeated, no need to enclose it in brackets.
•
Example 5
for (int c= 10; c >= 1; c=c-2)
System.out.println(c);
System.out.println(c);
This code loops 10 to 1 with a step of -2. So 10 8 6 4 2
get printed. Since the brackets are not there, the for loop
takes only one statement into consideration.
The above code can be interpreted as
for (int c= 10; c >= 1; c=c-2)
{
System.out.println(c);
}
System.out.println(c);
So outside the loop, one more time c gets printed. So 0
gets printed.
10 8 6 4 2 0 is the output from the above code.
Variations in for loop
Null statement in a loop
for (a= 10; a >= 0; a=a-3); Note the semicolon here
System.out.println(a);
This means the null statement gets executed repeatedly.
System.out.println(a); is independent.
Multiple initialization and update in a for loop
for (int a= 1, b = 5; a <= 5 && b >= 1; a++, b--)
System.out.println(a + “ “ + b );
The output of the above code will be
1 5
2 4
3 3
CS WORKBOOK X
65
Priya Kumaraswami
66. 4 2
5 1
Note:
for(int
for(int
for(int
for(int
c
c
c
c
=
=
=
=
0;
0;
0;
0;
c
c
c
c
<
<
<
<
5;
5;
5;
5;
c++) correct
c=c++) wrong
c=c+2) correct
c+2) wrong
The scope rules are applicable for loops as well.
A variable declared inside the body (block) of a for loop or a
while loop is not accessible outside the body (block).
while loop
• Syntax
Initial expression
while (test expression)
Loop body containing update expression
•
Example 1
In this code, a is the index variable. Its initial value is
0. Till a is less than or equal to 10, the statements will
be repeated. So, the code prints 0 to 10. After i=10 and
printing it, the index variable becomes 11, but the
condition is not met. So the loop stops.
•
Example 2
int a= 10;
while (a >= 0)
{
System.out.println(a);
a=a-3;
}
This code prints 10 to 0 with a step of -3.
So 10 7 4 1 get printed.
CS WORKBOOK X
66
Priya Kumaraswami
67. Variations in while loop
Infinite loop
•
Example 1
int a= 10;
while (a >= 0); Note the semicolon here
{
System.out.println(a);
a=a-3;
}
This means the null statement gets executed repeatedly. It
becomes infinite loop as the update does not happen within the
loop.
• Example 2
int a= 10;
while (a >= 0)
{
System.out.println(a);
}
There is no update statement here. So this also becomes infinite
loop as it does not reach the final value.
Multiple initialization and update in a while loop
int a= 1, b = 5;
while (a <= 5 && b >= 1)
{
System.out.println(a + “ “ + b );
a++;
b--;
}
The output of the above code will be
1 5
2 4
3 3
4 2
5 1
do while loop
CS WORKBOOK X
67
Priya Kumaraswami
68. • Syntax
Initial expression
do
{
Loop body containing update expression
}while (test expression);
•
Example 1
In this code, a is the index variable. Its initial value is
0. In the first iteration, 0 is printed. Then it becomes 1
and then the condition is checked. 1 is less than 10. So
one more iteration takes place. This loop continues
printing 1, 2, 3 …… 10. a becomes 11. The condition becomes
false and the loop stops.
•
Example 2
int a= 10;
do
{
System.out.println(a);
a=a-3;
}
while (a >= 0);
This code prints 10 to 0 with a step of -3.
So 10 7 4 1 get printed.
•
Example 3
int a= 0;
do
{
System.out.println(a);
a=a+3;
}
while (a < 0);
CS WORKBOOK X
68
Priya Kumaraswami
69. In the first iteration a is 0 and it gets printed. Then a
becomes 3. The condition is checked. If a is less than 0,
the loop will continue. But a is 3 now. So the loop stops.
This code prints 0.
Note:
do while loop executes at least once, even if the test condition
evaluates to false. Usually, we use it to run the loop as long
as the user wants.
The code below takes numbers from the user and sums them up.
int a;
char ch;
int sum = 0;
do
{
a = Integer.parseInt(br.readLine());
sum = sum + a;
System.out.println(“Do u want to enter more?”);
ch = br.readLine().charAt(0);
}
while (ch == ‘y’ || ch == ‘Y’);
This loop would continue as long as the user says ‘y’ or ‘Y’.
When he presses any other char, the loop would stop.
Quick Comparison of loops syntax
for loop syntax
while loop syntax
CS WORKBOOK X
69
Priya Kumaraswami
70. do while loop syntax
Nested Loops
•
•
A loop may contain one or more loops inside its body. It is
called Nested Loop.
Example 1
for(int i= 1; i<=3; i++)
{
for(int j= 2; j<=4; j++)
{
System.out.println(i * j);
}
}
Here, the i loop has j loop inside. For each i value, the j
value ranges from 2 to 4.
i value
CS WORKBOOK X
j value
output
70
Priya Kumaraswami
71. i = 1
i = 2
i = 3
•
j
j
j
j
j
j
j
j
j
=
=
=
=
=
=
=
=
=
2
3
4
2
3
4
2
3
4
Example 2
for(int i= 1; i<=2; i++)
{
for(int j= 3; j<=4; j++)
{
for(int k= 5; k<=6; k++)
{
System.out.println(i * j * k);
}
}
}
Here, the i loop has j loop inside which has k loop inside
it. For each i value, the j value ranges from 2 to 4. For
each value of j, k value ranges from 5 to 6.
i value
i = 1
j value
j = 3
j = 4
i = 2
j = 3
j = 4
•
1
3
4
4
6
8
6
9
12
k
k
k
k
k
k
k
k
k
value
= 5
= 6
= 5
= 6
= 5
= 6
= 5
= 6
output
15
18
20
24
30
36
40
48
Example 3
for(int i= 1; i<=2; i++)
{
for(int j= 3; j<=4; j++)
{
System.out.println(i * j);
}
for(int k= 5; k<=6; k++)
{
System.out.println(i * k);
}
CS WORKBOOK X
71
Priya Kumaraswami
72. }
Here, the i loop has j loop and k loop inside it. But j
loop is independent of k loop. For each i value, the j
value ranges from 2 to 4. For each value of i, k value
ranges from 5 to 6.
i value
i = 1
j value
j = 3
j = 4
k value
k = 5
k = 6
i = 2
j = 3
j = 4
k = 5
k = 6
•
•
•
output
3
4
5
6
6
8
10
12
In the syllabus, we learn to use nested loops for printing
Tables
Patterns
Series
Jump Statements
We will be learning 2 jump statements – break and return.
Basically, jump statements are used to transfer the control. The
control jumps from one place of the code to another place. We’ve
already seen break statement in switch. It breaks out of the
switch construct. break can be used inside a loop too to break
out of the loop if the condition is met.
Example
for(int c = 9; c < 30; c = c + 2)
{
if(c%7 == 0)
break;
}
System.out.println(c);
c starts from 9 and goes till 29 with a step of 2.
If in between any c value is divisible by 7, it breaks out of
the loop and prints that value.
The output will be 21.
CS WORKBOOK X
72
Priya Kumaraswami
73. return statement is used to return control from a function to
the calling code. If return statement is present in main
function, the control will be given to the OS (which is the
calling code) and the program will stop.
Example
public class test
{
public static void main(String args[])
{
for(int i=0; i<10;i++)
{
System.out.println(i);
if(i==4)
return;
}
}
}
The above program will print 0 1 2 3 4 and stop.
Sample Programs
8.1 Program to print multiplication tables from 1 to 10 upto x
20 using nested for loops.
public class test1
{
public static void main(String args[])
{
for (int i = 1 ; i <= 10; i=i+1)
{
System.out.println( i + “ table starts ”);
for (int j = 1 ; j <= 20; j=j+1) // this for loop
has only one statement to
repeat
System.out.println( i + “ x “+ j + “ = “+ i * j);
System.out.println( i + “ table ends”) ;
System.out.println( );
}
}
}
CS WORKBOOK X
73
Priya Kumaraswami
74. 8.2 Program to print multiplication tables from 1 to 10 upto x
20 using nested while loops.
public class test2
{
public static void main(String args[])
{
int i = 1;
while (i <= 10)
{
System.out.println( i + “ table starts ”);
int j = 1;
while (j <= 20)
{
System.out.println( i + “ x “+ j + “ = “+ i * j);
j = j + 1;
}
System.out.println( i + “ table ends”) ;
System.out.println( );
i = i + 1;
}
}
8.3 Program to print the pattern.
public class test3
{
public static void main(String args[])
{
for (int i = 1 ; i <= 5; i++)
{
for (int j = 1 ; j <= i; j++)
System.out.print( ‘*’);
*
**
***
****
*****
System.out.println( );
}
}
}
8.4 Program to print the pattern.
public class test4
{
public static void main(String args[])
{
CS WORKBOOK X
74
1
12
123
1234
12345
Priya Kumaraswami
75. for (int i = 1 ; i <= 5; i++)
{
for (int j = 1 ; j <= i; j++)
System.out.println(j);
System.out.println( );
}
}
}
8.5 Program to print the pattern.
public class test5
{
public static void main(String args[])
{
for (char i = ‘A’ ; i <= ‘E’; i++)
{
for (char j = ‘A’ ; j <= i; j++)
System.out.println(j);
A
AB
ABC
ABCD
ABCDE
System.out.println( );
}
}
8.6 Program to print the pattern.
CS WORKBOOK X
75
*
***
*****
*******
Priya Kumaraswami
76. 8.7 Program to print the pattern.
8.8 Program to print the pattern.
CS WORKBOOK X
76
*******
*****
***
*
*******
*
*
* *
*
Priya Kumaraswami
77. 8.9 Program to print the pattern.
1
121
12321
1234321
8.10 Program to print the pattern.
2
242
24642
2468642
CS WORKBOOK X
77
Priya Kumaraswami
78. 8.11 Program to print the pattern.
CS WORKBOOK X
78
2468642
24642
242
2
Priya Kumaraswami
79. 8.12 Program to print the pattern.
8.13 Program to print the pattern.
CS WORKBOOK X
79
$$$$$
$
$
$
$
$
$
$$$$$
$$$$$
$&&&$
$&&&$
$&&&$
$$$$$
Priya Kumaraswami
80. 8.14 Program to print the series.
1+
1
1
1
+ +
3! 5!
n!
8.15 Program to print the series.
CS WORKBOOK X
80
Priya Kumaraswami
81. 1+
x2 x4
xn
+ +
2!
4!
n!
8.16 Program to print the series.
x 3 x 5 x 7 x9
x n +1
−
+
− +
2! 4! 6! 8!
n!
CS WORKBOOK X
81
Priya Kumaraswami
82. 8.17 Program to find the sum of odd digits in a number (do-while)
8.18 Program to reverse the digits in a number (do-while)
CS WORKBOOK X
82
Priya Kumaraswami
83. Exercise
1. Find the outputs
a. int a = 33, b = 44;
for(int i = 1; i < 3; i++)
{
System.out.println( a + 2 + “ “ + b++ );
System.out.println( ++a + “ “ + b – 2);
}
b. long num = 64325;
int d, r = 0;
while(num != 0)
{
d = num % 10;
r = r * 10 + d;
num = num / 10;
}
System.out.println( r);
2. Convert the following nested for loops to nested while loops
and guess the output
for(int x = 10; x < 20; x=x+4)
CS WORKBOOK X
83
Priya Kumaraswami
84. {
for(int y = 5; y <= 50; y=y*5)
{
System.out.println( x );
}
System.out.println( y );
}
3. Write programs
a. To print the odd number series till 999
b. To print the sum of natural numbers from 1 to 100
c. To print the factorial of a given number
d. To generate prime numbers till 100
e. to generate the Fibonacci and Tribonacci series
f. To find the LCM and HCF of 2 numbers
g. To find the count of even digits in a number
h. To find the product of digits in a number that are
divisible by 3.
i. to accept 10 numbers and print the minimum out of them
j. to print the following patterns
1357531
55555 12345
1
1
%%%%%%%
13531
54321
1
4444
1234
21
131
%
%
131
4321
123
333
123
321
13531
%
%
1
321
12345
22
12
4321
1357531
%%%%%%%
21
1234567
1
1
54321
1
Notes
CS WORKBOOK X
84
Priya Kumaraswami
89. Chapter – 9
Number Arrays
•
•
•
An array represents continuous memory locations having a
name which can store data of a single data type.
An array is stored in contiguous memory locations. Lowest
address having the first element and highest address having
the last element.
Arrays can be single dimensional or multi dimensional.
Single Dimensional Array
Two Dimensional Array (Table format)
We learn only single dimensional arrays in class 10.
CS WORKBOOK X
89
Priya Kumaraswami
90. Declaration & Allocation of an array
•
•
•
•
•
•
•
•
•
datatype arrayname [ ] = new datatype[size];
Example
int a[] = new int[6];
The datatype indicates the datatype of the elements that
can be stored in an array.
We give the arrayname and it has to follow the rules of
naming the variables.
An array has size. The size denotes the number of elements
that can be stored in the array. Size should be positive
integer constant.
In the above example, a is an array that can store 6
integers.
Each array element is referenced by the index number.
The index number always starts from zero.
So, An array A [6] will have the following elements.
A [0], A [1], A [2], A [3], A [4]and A[5].
The index number ranges from 0 to 5
In this example, we have used an array of size 6.
int a[] = new int[6];
a[0] = 25;
a[1] = 36;
a[2] = 92;
a[3] = 45;
a[4] = 17;
a[5] = 63;
System.out.println(a[4]); will print 17 on the screen.
Calculation of bytes
The memory occupied by an array is calculated as
size of the element x number of elements
CS WORKBOOK X
90
Priya Kumaraswami
91. For example, int a[] = new int[15]; will take up 4 (size of an
int) x 15 (number of elements) = 60 bytes.
float arr[] = new float[20]; will take up 4 (size of a float) x
20 (number of elements) = 80 bytes
Loops for input, processing and
output
Usually, we use loops to take array elements as input, to
display array elements as output.
Example
int a[] = new int[6];
for(int i = 0; i < 6; i++)
// input loop
a[i] = Integer.parseInt(br.readLine());
for(i = 0; i < 6; i++)
a[i] = a[i] * 2;
// processing loop
for(i = 0; i < 6; i++)
System.out.println(a[i]);
// output loop
Combining the input and processing loops
int a[] =
for(int i
{
a[i]
a[i]
}
new int[6];
= 0; i < 6; i++)
// input & processing loop
= Integer.parseInt(br.readLine());
= a[i] * 2;
for(i = 0; i < 6; i++)
System.out.println(a[i]);
// output loop
Note:
Generally we avoid combining input and output of array elements
in a single loop because it mixes up the display on the screen.
Taking the size of the array from the user
int a[] = new int[50];
int size;
size = Integer.parseInt(br.readLine());
CS WORKBOOK X
91
Priya Kumaraswami
92. for(int i = 0; i < size; i++)
// input & processing loop
{
a[i] = Integer.parseInt(br.readLine());
a[i] = a[i] * 2;
}
for(i = 0; i < size; i++)
System.out.println(a[i]);
// output loop
Operations
The following operations are covered in class 10.
• Count of elements
• Sum of elements
• Minimum and Maximum in an array
• Replacing an element
• Reversing an array
• Swapping the first half with the second half
• Swapping the adjacent elements
• Searching for an element
Sample Programs
9.1 Program to count the odd elements.
CS WORKBOOK X
92
Priya Kumaraswami
93. 9.2 Program to sum up all the elements.
CS WORKBOOK X
93
Priya Kumaraswami
94. 9.3 Program to find the max and min in the given array.
9.4 Program to replace an element.
CS WORKBOOK X
94
Priya Kumaraswami
95. 9.5 Program to reverse the array.
CS WORKBOOK X
95
Priya Kumaraswami
96. 9.6 Program to swap the first half with the second half.
9.7 Program to swap the adjacent elements.
CS WORKBOOK X
96
Priya Kumaraswami
97. 9.8 Program to search for a given element using flag.
CS WORKBOOK X
97
Priya Kumaraswami
98. Exercise
1. Fill in the blanks
The following program searches for a given element using count.
Some portions of the program are missing. Complete them.
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class test8
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int a[] = new int[ 10];
for (
)
//input for array
;
int num;
System.out.println(“Enter the number to find”);
num = Integer.parseInt(br.readLine());
int count = 0;
for(__________________________)
{
if(____________)
count++;
}
if(count ______)
System.out.println(“found in the array”);
else
System.out.println(“not found in the array”);
}
2. Find
a.
b.
c.
the number of bytes required in memory to store
A double array of size 20.
A char array of size 30
A float array of size 50
CS WORKBOOK X
98
Priya Kumaraswami
99. 3. Write Programs
a. To count the number of elements divisible by 4 in the
given array of size 20
b. To sum up the even elements in the array of size 10
c. To combine elements from arrays A and B into array C
Notes
CS WORKBOOK X
99
Priya Kumaraswami
103. Chapter – 10
Strings & Char Arrays
Char arrays are similar to number arrays. The storage in memory
is similar to that of number arrays.
The difference comes when the char array is treated as a single
string. In that case, the input and output need not use a loop.
In the below diagram, though 8 bytes are allocated, we use only
6 bytes.
The above diagram shows a char array of size 8. But all the 8
bytes are not used since the array has to store only “classX”
which has length 6.
Declaration of char array
•
•
•
char arrayname[] = new char[size];
Example
char A []= new char[8];
We give the arrayname and it has to follow the rules of
naming the variables.
An array has size. The size denotes the number of elements
that can be stored in the array. Size should be positive
integer constant.
In the above example, A is an array that can store 8
characters.
CS WORKBOOK X
103
Priya Kumaraswami
104. •
•
Each array element is referenced by the index number.
The index number always starts from zero.
•
•
•
So, An array A [6] will have the following elements.
A [0], A [1], A [2], A [3], A [4] and A[5]
The index number ranges from 0 to 5
String to char array conversion
Input Operation
char str[] = new char[20];
String s = args[0];
// String input using args
Or
String s = br.readLine();
// String input using readers
str = s.toCharArray(); // conversion from String to char array
where toCharArray() is a function to convert a String input to
char array.
Output Operation
String s = new String(str);
System.out.println(s);
where the char array str is converted to String datatype and
printed.
Independent char array
Input Operation
char str[] = new char[20];
CS WORKBOOK X
104
Priya Kumaraswami
105. for(int i=0; i<20;i++)
str[i] = br.readLine().charAt(0);
Here we take each char in a loop. We do not consider the set
of chars as String.
Output Operation
for(int i=0; i<20;i++)
System.out.println(str[i]);
This will display all the 20 characters on screen.
Using length() function
We can use length() function to get the actual length of the
String input.
char str[] = new char[20];
String s = args[0];
// String input using args
Or
String s = br.readLine();
// String input using readers
str = s.toCharArray(); // conversion from String to char array
int len = s.length(); // calculating the length
char manipulation
All character manipulations take place inside the loop.
To check whether a char in a String is lowercase
char str[] = new char[20];
String s = args[0];
// String input using args
str = s.toCharArray(); // conversion from String to char array
int len = s.length(); // calculating the length
for(int i=0; i<len;i++)
{
if(c[i] >= ‘a’ && c[i] <= ‘z’) // check for lowercase
…
}
CS WORKBOOK X
105
Priya Kumaraswami
106. To check whether a char in a String is uppercase
char str[] = new char[20];
String s = br.readLine();
// String input using readers
str = s.toCharArray(); // conversion from String to char array
int len = s.length(); // calculating the length
for(int i=0; i<len;i++)
{
if(c[i] >= ‘A’ && c[i] <= ‘Z’) // check for uppercase
…
}
To check whether a char in a String is digit
char str[] = new char[20];
String s = br.readLine();
// String input using readers
str = s.toCharArray(); // conversion from String to char array
int len = s.length(); // calculating the length
for(int i=0; i<len;i++)
{
if(c[i] >= ‘0’ && c[i] <= ‘9’) // check for digit
…
}
To check whether a char in a String is a lowercase
vowel
char str[] = new char[20];
String s = br.readLine();
// String input using readers
str = s.toCharArray(); // conversion from String to char array
int len = s.length(); // calculating the length
for(int i=0; i<len;i++)
{
if(c[i] == ‘a’ || c[i] == ‘e’ || c[i] == ‘i’ || c[i] == ‘o’
|| c[i] == ‘u’) // check for lowercase vowel
…
}
Conversion of cases
We add 32 to convert from uppercase to lowercase and we
subtract 32 to convert from lowercase to uppercase. Since Java
is strict about the datatypes, typecasting is used to convert
the char to int and then add/subtract 32. Then it is converted
back to char as shown below.
CS WORKBOOK X
106
Priya Kumaraswami
107. for(int i = 0; i < len; i++)
{
if(c[i] >= ‘A’ && c[i] <= ‘Z’)
c[i] = (char)((int)c[i] + 32);
else if(c[i] >= ‘a’ && c[i] <= ‘z’)
c[i] = (char)((int)c[i] - 32);
}
Operations
The following operations are covered in class 10.
• Count of a char in an array
• Conversion of cases
• Replacing a char
• Reversing an array
• Checking for palindrome
• Searching for a char
Sample Programs
10.1 Program to take a string as input and change their cases.
For example, if “I am Good” is given as input, the program
should change it to “i AM gOOD”
CS WORKBOOK X
107
Priya Kumaraswami
108. 10.2 Program to take a string as input and count the number of
spaces, vowels and consonants
CS WORKBOOK X
108
Priya Kumaraswami
109. 10.3 Program to take a string as input and replace a given char
with another char
10.4 Program to take a string as input, reverse it and check if
it’s a palindrome
CS WORKBOOK X
109
Priya Kumaraswami
110. 10.5 Program to take a string as input and search for a char
CS WORKBOOK X
110
Priya Kumaraswami
111. Exercise
1. Find the output
a. char ch = ‘&’;
String s="BpEaCeFAvourEr";
char st[] = s.toCharArray();
int len = s.length();
for(int i=0;i<len;i++)
{
if(st[i]>='D' && st[i]<='J')
st[i]= (char)((int)st[i] + 32);
else if(st[i]=='A' || st[i]=='a'|| st[i]=='B' ||
st[i]=='b')
st[i]=ch;
else if(i%2!=0)
st[i]++;
else
st[i]=st[i-1];
}
String s1 = new String(st);
System.out.println(s1);
b. String s= “WELCOME”;
char msg[]= s.toCharArray();
int len = s.length();
for (int i = len - 1; i > 0; i--)
{
if (msg[i] >= ‘a’ && msg[i] <= ‘z’)
msg[i] = (char)((int)msg[i]-32);
CS WORKBOOK X
111
Priya Kumaraswami
112. else
if (msg[i] >= ‘A’ && msg[i] <= ‘Z’)
if( i % 2 != 0)
msg[i]=(char)((int)msg[i]+32);
else
msg[i]=msg[i-1];
}
String s1 = new String(msg);
System.out.println(s1);
2. Write Programs
a. To convert the vowels into upper case in a string
b. To replace all ‘a’s with ‘e’s (consider case)
c. To count the number of digits and alphabet in a string
d. To find the longest out of 3 strings
Notes
CS WORKBOOK X
112
Priya Kumaraswami
115. Chapter – 11
Functions
•
•
•
•
•
Large programs are difficult to manage and maintain.
A large program is broken down into smaller units called
functions.
A function is a named unit consisting of a set of
statements.
This unit can be invoked from other parts of the program.
Two types
• Built in – They are part of the libraries which come
along with the compiler.
• User defined – They are created by the programmer.
Parts of a function in a Program
•
•
Function Definition (below the main function)
Function Call (in the main function )
Example
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class test1
{
public static void main(String args[])throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int a, b, c, d, e, f;
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());
c = calculateresult (a, b);
Function call 1
d = Integer.parseInt(br.readLine());
e = Integer.parseInt(br.readLine());
f = calculateresult (d, e);
Function call 2
System.out.printline( f );
}
CS WORKBOOK X
115
Priya Kumaraswami
116. static int calculateresult (int p, int q)
{
int r;
r = p + q + (p * q);
Function Definition
return r;
}
}
Working of a function
Function call in the main() (or some other function) makes the
control go to the required function definition and do the work.
The argument values in the function call are copied to the
argument values in the function definition.
Function Definition is the code which does the actual work and
may return a result.
The control goes back to the main() and the result can be copied
to a variable or printed or used in an expression.
Function Definition Syntax
•
•
Function definition has a body
The function definition must have the return type, function
name and argument / parameter list (number and type).
static ReturnDatatype functionname ( datatype arg1, datatype
arg2, ……)
{
}
ReturnDatatype denotes the datatype of the return value from
the function, if any. If the function is not returning any
value, then void should be given. A function can return only
one value.
•
•
void data type specifies an empty value
It is used as the return type of functions which do not
return a value.
Functionname denotes the name of the function and it has to
follow the rules of naming the variables.
CS WORKBOOK X
116
Priya Kumaraswami
117. Within brackets (), the argument list is present. For each
argument, the datatype and name should be written. There can be
zero or more arguments. If there are more arguments, they should
be comma separated.
if the ReturnDatatype is not void
static ReturnDatatype functionname ( datatype arg1, datatype
arg2, ……)
{
return ____ ;
}
if the ReturnDatatype is void
static void functionname ( datatype arg1, datatype arg2, ……)
{
return;
// This is optional
}
CS WORKBOOK X
117
Priya Kumaraswami
118. Example
1. static float func ( int a, int b )
{
float k = 0.5 * a * b;
return k;
}
2. static int demo ( float x)
{
int n = x / 2;
return n;
}
3. static void test ( float m, int n, char p)
{
System.out.println( (m + n)* p );
}
4. static int example () throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int k;
k = Integer.parseInt(br.readLine());
k = k * 2;
return k;
}
Function call Syntax
if the ReturnDatatype is not void
ReturnDatatype variable = Functionname (arg1, arg2 …);
if the ReturnDatatype is void
Functionname (arg1, arg2 …);
Note that the arguments do not have their datatypes.
The returned value can be stored in a variable, printed or used
in an expression as shown below
•
•
int c = calculateresult (a, b );
returned value stored in a variable
System.out.println( calculateresult (a, b));
returned value printed directly
CS WORKBOOK X
118
Priya Kumaraswami
119. •
int d = calculateresult (a, b) + m * n;
returned value used in expression
Example
1.
2.
3.
4.
float ans = func (a, b );
int res = demo (x);
test (m, n, p);
int val = example ();
Possible Function Styles
1.
2.
3.
4.
Void function with no arguments
Void function with some arguments
Non void function with no arguments
Non void function with some arguments
Function Scope
•
Variables declared inside a function are available to that
function only
Example
CS WORKBOOK X
119
Priya Kumaraswami
120. Sample Programs
11.1 Program to calculate power ab using a function (returns a
value)
CS WORKBOOK X
120
Priya Kumaraswami
121. 11.2 Program to calculate factorial n! using a function (void)
CS WORKBOOK X
121
Priya Kumaraswami
122. 11.3 Program to calculate area of a triangle using a function
(area = ½ x b x h)
11.4 Program to calculate volume and surface area of a sphere
using 2 separate functions (volume = 4/3 pi r3 , surface area = 4
pi r2)
CS WORKBOOK X
122
Priya Kumaraswami
123. 11.5 Program to print the multiplication table of a given number
upto x 20 using a function
CS WORKBOOK X
123
Priya Kumaraswami
124. 11.6 Program to check whether a given number is prime using a
function
CS WORKBOOK X
124
Priya Kumaraswami
125. 11.7 Program to find the max in an int array of size 20 using a
function
Exercise
1. Find the output
a.
public static void main(String args[])
{
int m = 60, n = 44;
int p = calc (m, n);
m = m + p;
p = calc (n, m);
n = n + p;
System.out.println(m + “ “ + n + “ “ + p);
}
CS WORKBOOK X
125
Priya Kumaraswami
126. static int calc ( int x, int y)
{
x = x + 10;
y = y – 10;
int z = x % y;
return z;
}
b.
public static void main(String args[])
{
int arr[6] = { 12, 15, 3, 9, 20, 18 };
calc (arr, 6);
}
static int calc ( int x[6], int y)
{
for(int i=0; i<6; i=i+2)
{
switch(i)
{
case 0:
case 1:
System.out.println(x[i] * (i+1));
break;
case 2:
case 3:
System.out.println(x[i] * 3);
case 4:
case 5:
System.out.println(x[i] * 5);
break;
}
}
}
2. Rewrite the following program after correcting syntactical
errors
public static void main(String args[])
{
float p, q;
int r = demo(p , q);
System.out.println(r);
CS WORKBOOK X
126
Priya Kumaraswami
127. }
static void demo ( int a ; int b);
{
p = p + 10;
q = q – 10;
r = p + q;
return r;
}
3. Write Programs using functions
a. To find a3 + b3 given a and b
b. To convert the height of a person given in inches to feet
c. To print the sum of odd numbers in a given int array
d. To convert the cases of a char array
Notes
CS WORKBOOK X
127
Priya Kumaraswami
131. Worksheet - 1
(Java Datatypes, Constants, Variables, Operators, Input and Output)
1. Match the following
a. An integer constant
b. A floating point
constant
c. A char constant
d. A string (char array)
constant
e. A variable declaration
f. A variable
initialization
int a;
“java”
C = 20;
9.5
‘n’
100
2. Give examples of your own for
a. An integer constant
b. A floating point constant
c. A char constant
3.
4.
5.
6.
7.
d. A string (char array)
constant
e. A variable declaration
f. A variable initialization
List the basic data types in Java and explain their ranges.
Identify constants, variables and data types in the following statements.
a. int a = 10;
d. float f = 3.45;
b. char c = ‘d’;
e. double d = m;
c. System.out.println( c +
“alphabet” );
Find the mistakes in the following Java statements and write correct
statements.
a. int a = 10,000;
e. System.out.println( a(b+c)
b. char c = “f”;
);
c. char ch = ‘go’;
f. float f$ = 5.49;
d. System.out.println( the
g. int k = 40,129;
result is + “k” );
Identify the valid and invalid variables from the following giving reasons
for invalid ones
a. int My num;
e. int num1;
b. int my_num;
f. int main;
c. int my-num;
g. int Main;
d. int 1num;
Write Java expressions (applying BODMAS)
a. a2b
a 2 + 2ab
f. k =
b. 2ab
n −b
c. pnr/100
2
2
1
d. a + 2ab + b
g. z = ab +
(x – y)2
e. sum =
8. Write
a.
b.
c.
d.
e.
f.
9. Write
n( n +1)
2
3
Java statements for the following
Initialize a variable c with value 10
Print a floating point variable f
Print a string constant “Programming is
Print a string constant “Result” and an
Print a string constant “Result” and an
Print 10 stars in 2 line
Java code to take a number as input and
CS WORKBOOK X
131
fun”
integer constant 10
integer variable x
print the same using
Priya Kumaraswami
132. a. Args
b. Readers
10.
Write Java programs for the following with proper messages wherever
necessary
a. Print the area and perimeter of a square whose side is 50 units
b. Print the sum, difference, product and quotient of any 2 numbers
c. Calculate the average and total marks of any five subjects
d. Interchange the values of 2 variables using a third variable
e. To accept temperature in degree Celsius and convert it to degree
Fahrenheit
(F = 9/5 * C + 32)
11.
Evaluate the following if a = 88, b = 101, c = 34
a. b = (b++) + c;
a = a – (--b);
c = (++c) + (a--);
b. a * b / c + 10
c. a / 2 + b * b + 3 * c
d. a * b – a / b + c * 2
e. a = b + 20;
c = (a++) + 10;
b = b – (--a)
12.
Find the output of the following
public static void main(String args[])
{
int x = 9, y = 99, z = 199;
System.out.println (x+7);
x = x + y;
System.out.print(“random”+(y+ z));
System.out.println( z % 8);
}
13.
public static void main(String args[])
{
int p = 20;
int q = p;
q = q + 3;
p = p + q;
System.out.println(p + “ “ + q);
}
Find the mistakes in the following code sample
public static void main(String args[])
{
int k;
k = k + 10;
p = p + 20;
System.out.println( “k + p”);
System.out.println( ncfe);
}
14.
15.
16.
17.
List the types of operators.
Give examples of unary and binary operators.
Write dos commands to
a. Change directory to e:myjava
b. Compile a java program first.java
c. Run a java program first.java
Why do we use the following?
a. Integer.parseInt()
b. br.readLine()
c. import java.io.InputStreamReader; import java.io.BufferedReader;
CS WORKBOOK X
132
Priya Kumaraswami
133. Worksheet – 2
(if..else)
1. Write ‘if’ statements for the following
a. To check whether the value of int variable a is equal to 100
b. To check whether the value of int variable k is between 40 and 50
(including 40 and 50)
c. To check whether the value of int variable k is between 40 and 50
excluding 40 and 50)
d. To check whether the value of int variable s is not equal to 50
e. To check whether the value of a char variable ch is equal to
‘lowercase a’ or ‘uppercase a’
2. Find the output of the following
a.
int i = j = 10;
if ( a < 100)
if( b > 50)
i = i + 1;
else
j = j + 1;
System.out.println(i + “ “ + j );
Value supplied for a and b a = 30, b = 30
Value supplied for a and b a = 60, b = 70
b.
int i = j = 10;
if ( a < 100)
{
if( b > 50)
i = i + 1;
}
else
j = j + 1;
System.out.println(i + “ “ + j );
Value supplied for a and b a = 30, b = 30
Value supplied for a and b a = 60, b = 70
c.
if (!true)
{
System.out.println(“Tricky”);
}
System.out.println(“Yes”);
d.
if ( true )
System.out.println(“Tricky again”);
else
System.out.println(“Am I right?”);
System.out.println(“No??”);
e.
if ( false )
System.out.println(“Third Time Tricky”);
System.out.println(“Am I right?”);
CS WORKBOOK X
133
Priya Kumaraswami
134. f.
int a = 3;
if ( !(a == 4 ))
System.out.println(“Fourth Time Tricky”);
System.out.println(“No??”);
g.
if ( false )
System.out.println(“Not again”);
else
System.out.println(“Last time”);
System.out.println(“Thank God”);
3. Find the mistakes and correct them.
a)
int b;
if (b = 10);
System.out.println( “Number of bats = 10” );
System.out.println( “10 bats for 11 players… Not sufficient!”);
else if ( b = 15)
System.out.println( “Number of bats = 15”);
System.out.println( “Cool… Bats provided for the substitutes too..” );
else (b = 20)
System.out.println( “Number of bats = 20” );
System.out.println( “Hurray…We can provide bats to the opponents also” );
4. Write complete Java programs using if construct
a. To find the largest and smallest of the given 3 numbers A, B, C
b. To find whether the number is odd or even, if its even number
check whether it is divisible by 6.
c. To convert the Fahrenheit to Celsius or vice-versa depending on
the user’s choice
d. To find whether a year given as input is leap or not
e. To create a four function calculator ( +, -, /, *)
f. To calculate the commission rate for the salesman. The commission
is calculated according to the following rates
Sales
Commission Rate
30001 onwards
15%
22001 – 30000
10%
12001 – 22000
7%
5001 – 12000
3%
0 – 5000
0%
5. Illustrate Nested If with examples
CS WORKBOOK X
134
Priya Kumaraswami
135. Worksheet – 3
(switch)
1. Convert the following ‘if’ construct to ‘switch’ construct
char ch;
ch = br.readLine().charAt(0);
if( ch == ‘A’)
System.out.println(“Excellent. Keep it up.”);
else if (ch == ‘B’)
System.out.println( “Good job. Try to get A grade next time”);
else if (ch == ‘C’)
System.out.println( “Fair. Should work hard to get good grades”);
else if (ch == ‘D’)
System.out.println( “Preparation not enough. Should work very hard”);
else
System.out.println( “Invalid grade”);
2. Find the output of the following
int ua = 0, ub = 0, uc = 0, fail = 0, c;
c = Integer.parseInt(args[0]);
switch(c)
{
case 1:
case 2: ua = ua + 1;
case 3:
case 4: ub = ub + ua;
case 5: uc = uc + ub;
default: fail = fail + uc;
}
System.out.println( ua + “-“ + ub + “-“ + uc + “-“ + fail );
The above code is executed 6 times and in each execution, the value of
c is supplied as 0, 1, 2, 3, 4 and 5.
3. Find the mistakes and correct them.
int b = Integer.parseInt(br.readLine());
switch (b)
{
case ‘10’;
System.out.println( “Number of bats = 10” );
break;
case ‘10’:
System.out.println( “Number of bats = 15” );
case ‘20’
System.out.println( “Number of bats = 20” );
}
4. Write complete Java programs using switch construct
a. To display the day depending upon the number (example, if 1 is
given, “Sunday” should be printed, if 7 is given, “Saturday”
should be printed.
b. To calculate the area of a circle, a rectangle or a triangle
depending upon user’s choice
c. To display the digit in words for digits 0 to 9
CS WORKBOOK X
135
Priya Kumaraswami
136. 5. Convert the following ‘if’ construct to ‘switch’ construct
int a;
char b;
a = Integer.parseInt(br.readLine());
b = br.readLine().charAt(0);
if( a == 1)
{
System.out.println(“Engineering”);
if(b == ‘a’)
System.out.println(“Mechanical”);
else if ( b == ‘b’)
System.out.println(“Computer Science”);
else if ( b == ‘c’)
System.out.println(“Civil”);
}
else if (a == 2)
{
System.out.println(“Medicine”;
if(b == ‘a’)
System.out.println(“Pathology”);
else if ( b == ‘b’)
System.out.println(“Cardiology”);
else if ( b == ‘c’)
System.out.println(“Neurology”);
}
else if (a == 2)
{
System.out.println(“Business”;
if(b == ‘a’)
System.out.println(“Finance”);
else if ( b == ‘b’)
System.out.println(“Human Resources”);
else if ( b == ‘c’)
System.out.println(“Marketing”);
}
6. Find the output of the following if a gets values 0, 1 and 2 in three
consecutive runs.
int a;
a = Integer.parseInt(br.readLine());
switch (a)
{
default:
System.out.println('d');
case 0:
System.out.println(0);
case 1:
System.out.println(1);
}
7. Switch works with _______ and ________ constants.
8. What is the difference between if and switch?
CS WORKBOOK X
136
Priya Kumaraswami
137. Worksheet – 4
(Loops)
Looping Programs
1. WAP to find the sum of alternate digits in a given 6-digit number.
(For example, if the given number is 194572. It should print 1+4+7 = 12 and
9+5+2=16)
2. WAP to find the LCM of 2 numbers
3. WAP to find the GCD of 2 numbers
4. WAP to print tables of 3,6,9,….n upto x15
5. Write Programs to print the following patterns using nested loops
1
23
456
78910
2
242
24642
2468642
(*****)
(***)
(*)
1
13
135
1357
13579
1
31
531
7531
97531
6. WAP to compute the following expressions a) X +
b) 1 −
97531
7531
531
31
1
&
&$&
&$$$&
&$$$$$&
&$$$$$$$&
X2
X3
Xn
+
+
3!
5!
( 2 n −1)!
X2
X4
X6
Xn
+
−
+
3!
5!
7!
(n +1)!
Find & Explain the output of the following code snippets
7. int i=6;
while(i != 0)
System.out.println(i--);
System.out.println( " n thank you") ;
8.
int m = -3, n = 1;
while( m > -7 )
{
m = m - 1;
n = n * m;
S.o.p( n );
}
9. What is wrong with the following while loops
:
a. int counter = 1;
b.
int counter = 1;
while ( counter < 100)
while ( counter < 100)
{
System.out.println(counter);
System.out.println(counter);
counter ++;
counter --;
}
10.
Convert the following nested for loops to nested while loops and
find the output
for(int i=0; i<5;i++)
{
for(int j=1;j<3;j++)
{
if( i != j)
CS WORKBOOK X
137
Priya Kumaraswami
138. }
}
11.
System.out.println( i * j);
Explain the steps and find the output.
int a = 5, b = 15;
int num = 12345;
int d;
int s = 0;
while (num != 0)
{
d = num % 10;
S.o.p( d );
s = s + d;
num = num / 10;
}
S.o.p( s);
if ( (a + b) % 2 == 0)
{
b = b % 10;
a = a + b;
S.o.p( a + “ “ + b );
}
if ( a % 10 == 0)
{
switch(a)
{
case 10:
S.o.p( “AA”);
case 20:
S.o.p( “BB”);
}
}
12.
What will be the output?
a. for (int c = 0; c <= 10; c++);
S.o.p( c);
S.o.p( c);
b. for (int c = 0; c <= 10; c++)
S.o.p( c);
S.o.p( c);
c. for (int c = 0; c <= 10; c++)
{
S.o.p( c);
S.o.p( c);
}
d. for (int c = 0; c <= 10; c++)
{
S.o.p( c);
}
S.o.p( c);
13.
Which out of the following will execute 5 times?
a.
b.
c.
d.
e.
for ( int j = 0; j <= 5; j++)
for ( int j = 1; j < 5; j++)
for ( int j = 1; j < 6; j++)
for ( int j = 0; j < 6; j++)
for ( int j = 0; j < 5; j++)
14.
Differentiate between entry controlled and exit controlled loops.
15.
What statement should be given to abruptly end the loop
iteration? Explain with an example.
Note – S.o.p should be expanded as System.out.println
CS WORKBOOK X
138
Priya Kumaraswami
139. Worksheet – 5
Function related Programs
1. Write a Java program with a function to find the area of a triangle.
The function has the following signature:- static float area (int base,
int height);
2. Write a Java program with a function to find the simple interest. The
function has the following signature:- static void calcinterest (int p,
int q, float r);
Find & Explain the output of the following code snippets
3. public static void main(String args[])
{
int Number=20;
Direct(Number);
Indirect(10);
System.out.println( “ Number=” + Number ) ;
}
static void Indirect(int Temp)
{
for (int I=10; I<=Temp; I = I+5)
System.out.println(I);
}
static void Direct (int Num)
{
Num = Num + 10;
Indirect(Num);
}
4. static void print(int y, int i)
{
y = y * i;
System.out.println( y );
}
public static void main(String args[])
{
int x[ ] = {11, 21, 31, 41};
for (int i = 0; i < 4; i++)
{
print(x[i], i);
}
}
5. void arm(int n)
{
int number, sum=0,dg,dgg,digit;
number=n;
while(n>0)
{
dg=n/10;
dgg=dg*10;
digit=n-dgg;
S.o.p(digit+digit);
sum=sum+digit*digit*digit;
n=n/10;
}
S.o.p(digit+sum);
CS WORKBOOK X
139
Priya Kumaraswami