java publish

165
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

Upload: priya-kumaraswami

Post on 10-May-2015

1.568 views

Category:

Technology


2 download

DESCRIPTION

Java Basics - Study Material for X standard

TRANSCRIPT

Page 1: Java publish

Java Handbook for Class XComputer 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 Kumaraswami10/27/2013

Page 2: Java publish

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 X1

Priya Kumaraswami

Page 3: Java publish

Table Of Contents

Chapter – 1...........................................................................................................................3Introduction to Programming..............................................................................................3Chapter – 2...........................................................................................................................6First Program in Java...........................................................................................................6Chapter – 3.........................................................................................................................11Java Variables and Constants............................................................................................11Chapter – 4.........................................................................................................................17Java Datatypes...................................................................................................................17Chapter – 5.........................................................................................................................25Operators and Expressions................................................................................................25Chapter – 6.........................................................................................................................32Input and Output................................................................................................................32Chapter – 7.........................................................................................................................40Conditions (if and switch).................................................................................................40Chapter – 8.........................................................................................................................62Loops.................................................................................................................................62Chapter – 9.........................................................................................................................88Number Arrays..................................................................................................................88Chapter – 10.....................................................................................................................102Strings & Char Arrays.....................................................................................................102Chapter – 11.....................................................................................................................114Functions..........................................................................................................................114Worksheet - 1..................................................................................................................130Worksheet – 2..................................................................................................................132Worksheet – 3..................................................................................................................134Worksheet – 4..................................................................................................................136Worksheet – 5..................................................................................................................138

CS WORKBOOK X2

Priya Kumaraswami

Page 4: Java publish

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.

CS WORKBOOK X3

Priya Kumaraswami

Page 5: Java publish

– Semantic Error: it is a logical error. It is due to wrong logical statements (statements that do not give proper meaning).

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 Programming2. 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 X4

Priya Kumaraswami

Page 6: Java publish

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 X5

Priya Kumaraswami

Page 7: Java publish

Chapter – 2

First Program in Java

// my first program in Javapublic 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 commentspanning three lines to demonstratethe 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 X6

Priya Kumaraswami

Page 8: Java publish

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 FileThe 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

CS WORKBOOK X7

Priya Kumaraswami

Page 9: Java publish

• 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.

• 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:

CS WORKBOOK X8

Priya Kumaraswami

Page 10: Java publish

o a source code editor where code can be writteno a compiler  o a provision to run the programo a provision to debug the program

• For java, BlueJ is a well known IDE. But, we use the command line compilation and execution.

Exercise1. 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 X9

Priya Kumaraswami

Page 11: Java publish

Notes

CS WORKBOOK X10

Priya Kumaraswami

Page 12: Java publish

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

CS WORKBOOK X11

Priya Kumaraswami

Page 13: Java publish

String or character array constants should be always enclosed in double quotes.

• “123” (character array )• “Abc” (character array )• “This is some text.” (character array )• “so many $” (character array )

char Constants Examples

Character constants should be always enclosed in single quotes.

• ‘A’ (character)• ‘z’ (character)

integer constants Examples

• 123 (integer)• 34 (integer)

floating point constants Examples

• 34.78 (floating point)• 5666.778 (floating point)

A sample program using constants

Variables

CS WORKBOOK X12

Priya Kumaraswami

Page 14: Java publish

• Variables are actually named memory locations which can store any value.

• It is the programmer who assigns the name for a memory location.

• Variables are the entities that can change their values during program execution.ExampleA = 10; A contains 10 nowA = A + 1; A contains 11 nowA = 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.

CS WORKBOOK X13

Priya Kumaraswami

Page 15: Java publish

• 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:

• 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 constantsa. 123.45b. 145.0c. 1166d. “1166”e. “123.45”f. ‘3’

CS WORKBOOK X14

Priya Kumaraswami

Page 16: Java publish

g. “*”

2. Indicate whether the following variable names are valid or not

a. fghb. Mainc. 5god. var namee. var_namef. var*name

3. Identify the errorsa. ‘abc’b. 14.c. .45d. 50,000

CS WORKBOOK X15

Priya Kumaraswami

Page 17: Java publish

Notes

CS WORKBOOK X16

Priya Kumaraswami

Page 18: Java publish

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

CS WORKBOOK X17

Priya Kumaraswami

Page 19: Java publish

• With 1 bit, we can represent 2 numbers (21)Bit Combination Decimal Value0 01 1

• With 2 bits, we can represent 4 numbers (22)Bit Combination Decimal Value00 001 110 211 3

• With 3 bits, we can represent 8 numbers (23)Bit Combination Decimal Value000 0001 1010 2011 3100 4101 5110 6111 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.

CS WORKBOOK X18

Priya Kumaraswami

Page 20: Java publish

Char UnicodeA to Z 65 to 90a to z 97 to 1220 to 9 48 to 57

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 Example data that can be stored using the given datatype

byte 1 byte -128 to 127 116, 12short 2 bytes -32768 to 32767 12, 30000int 4 bytes -2147483648 to

214748364712, 948900

long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

99502384355245

float 4 bytes Approx 7 digits 12.43, 6789.566double 8 bytes Approx 15 digits 56789.66666char 2 bytes ‘a’, ‘A’, ‘$’, ‘1’,

‘0’, ‘%’(Any single character on the keyboard)

boolean 1 byte true / falseString According to

the number of characters (per char, two bytes)

CS WORKBOOK X19

Priya Kumaraswami

Page 21: Java publish

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; (ch occupies 2 bytes)long num; (num occupies 8 bytes)double d; (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;

CS WORKBOOK X20

Priya Kumaraswami

Page 22: Java publish

int a = 2; //error as a is already declared in the previous statement

Variable Initialization

• Giving an appropriate value for a variable is known as initialization

• Examplesint 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

CS WORKBOOK X21

Priya Kumaraswami

Page 23: Java publish

1. Write correct declarations for the followinga. A variable to store 13.5b. A variable to store NCFEc. A variable to store grade (A / B / C / D / E)d. A variable to store 10000

2. Convert the following decimal numbers to binarya. 1024b. 255c. 1189d. 52

3. Draw the table to show the bit combination and decimal value for 4 bits binary.

4. Identify the errors in the followinga. 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 X22

Priya Kumaraswami

Page 24: Java publish

Notes

CS WORKBOOK X23

Priya Kumaraswami

Page 25: Java publish

CS WORKBOOK X24

Priya Kumaraswami

Page 26: Java publish

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 OperatorsArithmetic 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 < 100b == 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 variablea = 10;b = b + 20;c = b;

CS WORKBOOK X25

Priya Kumaraswami

Page 27: Java publish

There are shortcuts used in assignment.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 expressionExample a = 10, b = 20C = (++a) + (++b) = 11 + 21 = 32

Post increment – First the current value is used in the expression and then the values are incrementedExample a = 10, b = 20C = (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 expressionExample a = 10, b = 20C = (--a) + (--b) = 9 + 19 = 28

Post decrement – First the current value is used in the expression and then the values are decrementedExample a = 10, b = 20C = (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

CS WORKBOOK X26

Priya Kumaraswami

Page 28: Java publish

System.out.println( a + “ “ + b + “ “ + c);//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 < 90a != 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 X27

Priya Kumaraswami

Page 29: Java publish

Expressions with char variableWhen char is used in an expression, its Unicode equivalent is taken.Examplechar 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 expressionsa. 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);

CS WORKBOOK X28

Priya Kumaraswami

Page 30: Java publish

System.out.println( z );e. int f = 20 % 3 + 2;

System.out.println( f);

2. Write Java expressions for the followinga. C = A2 + B2

b. A is greater than 0 and less than 100c. Grade is A or Bd. Increment the value of X by 20

3. Find the output for the following code snippetsa. 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 X29

Priya Kumaraswami

Page 31: Java publish

Notes

CS WORKBOOK X30

Priya Kumaraswami

Page 32: Java publish

CS WORKBOOK X31

Priya Kumaraswami

Page 33: Java publish

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 screenSystem.out.println (120); // prints number 120 on screenSystem.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 HelloSystem.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 X32

Priya Kumaraswami

Page 34: Java publish

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 X33

Priya Kumaraswami

Page 35: Java publish

Third sentence.

Input using argsWhile 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

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 X34

Priya Kumaraswami

We use this to get input

Page 36: Java publish

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.

CS WORKBOOK X35

Priya Kumaraswami

Page 37: Java publish

So if an integer input is required, it should be converted using Integer.parseInt() function.

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

{

CS WORKBOOK X36

Priya Kumaraswami

Page 38: Java publish

InputStreamReader isr = new InputStreamReader(System.in);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 inputsa. To find and display the area of circle, triangle and

rectangle b. To calculate the average of 3 numbersc. 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 X37

Priya Kumaraswami

Page 39: Java publish

Notes

CS WORKBOOK X38

Priya Kumaraswami

Page 40: Java publish

CS WORKBOOK X39

Priya Kumaraswami

Page 41: Java publish

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).

CS WORKBOOK X40

Priya Kumaraswami

Page 42: Java publish

• 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.

Operators used in conditions• >, <, >=, <=, ==, !=, &&, ||, !

• Examplesgrade == ‘A’a > b!xx >=2 && x <=10grade == ‘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

CS WORKBOOK X41

Priya Kumaraswami

Page 43: Java publish

• Also called conditional or decision statement• Syntax of if statement

if ( condition )statement ;

• 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);

CS WORKBOOK X42

Priya Kumaraswami

Page 44: Java publish

• 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 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 ; // Note the tab space

else statement2 ; // 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

CS WORKBOOK X43

Priya Kumaraswami

Page 45: Java publish

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 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 { }

• Exampleif ( 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 conditionif ( 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 X44

Priya Kumaraswami

Page 46: Java publish

• Syntax

Dangling else problem

if (condition 1){

if (condition 2) statement 1;else statement 2;

}else

statement 3;

if (condition 1)statement 1;

else{

if (condition 2) 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;

}

CS WORKBOOK X45

Priya Kumaraswami

if ( ch >= ‘A’)if(ch <= ‘Z’) upcase = upcase + 1;

elseothers = others + 1;

Page 47: Java publish

• Which if the else belongs to, in the above case?• The else goes with the immediate preceding if

• The above code can be understood as shown below

• If the else has to be matching with the outer if, then use brackets { } as below

Difference between if…else if ladder and multiple ifs

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.

The output here is 101520. The code here has multiple ifs which are independent. The else belongs to the last if.

CS WORKBOOK X46

Priya Kumaraswami

if ( ch >= ‘A’) {

if(ch <= ‘Z’) upcase = upcase + 1;

}else

others = others + 1;

if ( ch >= ‘A’){

if(ch <= ‘Z’) upcase = upcase + 1;

else others = others + 1;

}

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);

Page 48: Java publish

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 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).

switch (expression){ case constant1:

statements;break;

case constant2:statements;break;

default:statements;

}

Page 49: Java publish

• 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.

Example of a switch construct with integer constant

int n = Integer.parseInt(args[0]);switch(n){

case 1:System.out.println( “C++”);break;

case 2:System.out.println( “Java”);break;

case 5:System.out.println( “C#”);break;

default:System.out.println( “Algol”);break;

}

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( “Apple”);break;

case ‘$’:System.out.println( “Samsung”);break;

case ‘3’:System.out.println( “LG”);break;

default:

Page 50: Java publish

System.out.println( “Nokia”);break;

}

In the above program, if input is ‘a’ for ch, Apple will be printed. If input is ‘$’ for ch, Samsung will be printed. If 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

Page 51: Java publish

import java.io.InputStreamReader;import java.io.BufferedReader;

public class status{

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());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){

Page 52: Java publish

grade = ‘B’;}

else if ( x >= 45 && x < 60){ grade = ‘C’;} 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 5import 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{

Page 53: Java publish

System.out.println(“The number is not divisible by 5”);

}}

}

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);

Page 54: Java publish

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());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)”) ;

Page 55: Java publish

int n , r;n = Integer.parseInt(br.readLine()) ;System.out.println( “Enter radius”);r= Integer.parseInt(br.readLine());float res;switch(n){

case 2: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;

Page 56: Java publish

case ‘C’:System.out.println( “Good. Put in more efforts”); break;

case ‘D’:System.out.println( “Should work hard for better results”); break;

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 snippetsa. 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);

Page 57: Java publish

}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”;

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 = 5when a = 9 and b = 3when a = 8 and b = 6

2. Find the mistakesint a, b;if( a > b ) ;System.out.print(a + “is greater than “);System.out.println(b);else if ( b > a)

Page 58: Java publish

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 constructint m1, m2;if( m1 >= 80){

if( m2 >= 80)System.out.println( “Very Good”);

else if (m2 >= 40)System.out.println( “Good”);

elseSystem.out.println( “improve”);

}else if( m1 >= 40){

if( m2 >= 80)System.out.println( “Good”);

else if (m2 >= 40)System.out.println( “Fair”);

elseSystem.out.println( “improve”);

}else{

if( m2 >= 80)System.out.println( “Good”);

else if (m2 >= 40)System.out.println( “improve”);

elseSystem.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 ChargesUpto 100 units Rs 1.35 / unit> 100 units and upto Rs 1.50 / unit

Page 59: Java publish

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

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

Page 60: Java publish
Page 61: Java publish
Page 62: Java publish
Page 63: Java publish

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.

Page 64: Java publish

for loop• Syntax

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 -3.So 10 7 4 1 get printed.

• Example 3

for (int c= 10; c >= 1; c=c-2){

System.out.println( ‘*’);}

Page 65: Java publish

This code loops 10 to 1 with a step of -2. But the c variable is not printed. ‘*’ is printed 5 times.

• 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 loopNull statement in a loopfor (a= 10; a >= 0; a=a-3); Note the semicolon hereSystem.out.println(a);

This means the null statement gets executed repeatedly. System.out.println(a); is independent.

Multiple initialization and update in a for loopfor (int a= 1, b = 5; a <= 5 && b >= 1; a++, b--)System.out.println(a + “ “ + b );

Page 66: Java publish

The output of the above code will be1 52 43 34 25 1

Note:for(int c = 0; c < 5; c++) correctfor(int c = 0; c < 5; c=c++) wrongfor(int c = 0; c < 5; c=c+2) correctfor(int c = 0; c < 5; 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

• SyntaxInitial expressionwhile (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 2int a= 10;while (a >= 0){

System.out.println(a); a=a-3;

}

Page 67: Java publish

This code prints 10 to 0 with a step of -3.So 10 7 4 1 get printed.

Variations in while loopInfinite 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 2int 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 loopint a= 1, b = 5; while (a <= 5 && b >= 1){

System.out.println(a + “ “ + b ); a++;b--;

}

The output of the above code will be1 52 43 34 25 1

Page 68: Java publish

do while loop• SyntaxInitial expressiondo{

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 2int 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 3int a= 0;do{

System.out.println(a); a=a+3;

}

Page 69: Java publish

while (a < 0);

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

Page 70: Java publish

while loop syntax

do while loop syntax

Nested Loops

• A loop may contain one or more loops inside its body. It is called Nested Loop.

• Example 1for(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.

Page 71: Java publish

i value j value outputi = 1 j = 2 1

j = 3 3j = 4 4

i = 2 j = 2 4j = 3 6j = 4 8

i = 3 j = 2 6j = 3 9j = 4 12

• Example 2for(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 j value k value outputi = 1 j = 3 k = 5 15

k = 6 18j = 4 k = 5 20

k = 6 24i = 2 j = 3 k = 5 30

k = 6 36j = 4 k = 5 40

k = 6 48

• Example 3for(int i= 1; i<=2; i++){

for(int j= 3; j<=4; j++){

System.out.println(i * j);

Page 72: Java publish

}for(int k= 5; k<=6; k++){

System.out.println(i * k);}

}

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 j value k value outputi = 1 j = 3 3

j = 4 4k = 5 5k = 6 6

i = 2 j = 3 6j = 4 8

k = 5 10k = 6 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.

Examplefor(int c = 9; c < 30; c = c + 2){

if(c%7 == 0)break;

}

Page 73: Java publish

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.

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.

Examplepublic 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);

Page 74: Java publish

System.out.println( i + “ table ends”) ;System.out.println( );}

}}

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( );}

} }

***************

112123123412345

Page 75: Java publish

8.4 Program to print the pattern.

public class test4{

public static void main(String args[]){

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);

System.out.println( );}

}

8.6 Program to print the pattern.

AABABCABCDABCDE

* *** ************

Page 76: Java publish

8.7 Program to print the pattern.

8.8 Program to print the pattern.

******* ***** *** *

******* * * * * *

Page 77: Java publish

8.9 Program to print the pattern.

8.10 Program to print the pattern.

1 121 123211234321

2 242 246422468642

Page 78: Java publish

8.11 Program to print the pattern.

2468642 24642 242 2

Page 79: Java publish

8.12 Program to print the pattern.

8.13 Program to print the pattern.

$$$$$$ $$ $$ $$$$$$

$$$$$$&&&$$&&&$$&&&$$$$$$

Page 80: Java publish

8.14 Program to print the series.

Page 81: Java publish

8.15 Program to print the series.

8.16 Program to print the series.

Page 82: Java publish

8.17 Program to find the sum of odd digits in a number (do-while)

Page 83: Java publish

8.18 Program to reverse the digits in a number (do-while)

Exercise

1. Find the outputsa. 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){

Page 84: Java publish

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 outputfor(int x = 10; x < 20; x=x+4){

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 999b. To print the sum of natural numbers from 1 to 100c. To print the factorial of a given numberd. To generate prime numbers till 100e. to generate the Fibonacci and Tribonacci seriesf. To find the LCM and HCF of 2 numbersg. To find the count of even digits in a numberh. 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 themj. to print the following patterns

Notes

123451234123121

543214321321211

555554444333221

121321432154321

1 131 135311357531

1357531 13531 131 1

%%%%%%%% %% %%%%%%%%

1123123451234567

Page 85: Java publish
Page 86: Java publish
Page 87: Java publish
Page 88: Java publish
Page 89: Java publish

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.

Page 90: Java publish

Declaration & Allocation of an arraydatatype arrayname [ ] = new datatype[size];Exampleint 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 bytesThe memory occupied by an array is calculated as size of the element x number of elements

Page 91: Java publish

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 outputUsually, 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++) // processing loopa[i] = a[i] * 2;

for(i = 0; i < 6; i++) // output loopSystem.out.println(a[i]);

Combining the input and processing loopsint a[] = new int[6];for(int i = 0; i < 6; i++) // input & processing loop{

a[i] = Integer.parseInt(br.readLine());a[i] = a[i] * 2;

}

for(i = 0; i < 6; i++) // output loopSystem.out.println(a[i]);

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());

Page 92: Java publish

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++) // output loopSystem.out.println(a[i]);

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.

Page 93: Java publish

9.2 Program to sum up all the elements.

Page 94: Java publish

9.3 Program to find the max and min in the given array.

9.4 Program to replace an element.

Page 95: Java publish

9.5 Program to reverse the array.

Page 96: Java publish

9.6 Program to swap the first half with the second half.

9.7 Program to swap the adjacent elements.

Page 97: Java publish

9.8 Program to search for a given element using flag.

Page 98: Java publish

Exercise

1. Fill in the blanksThe 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”);

elseSystem.out.println(“not found in the array”);

}

2. Find the number of bytes required in memory to store a. A double array of size 20.b. A char array of size 30

Page 99: Java publish

c. A float array of size 50

3. Write Programsa. To count the number of elements divisible by 4 in the

given array of size 20b. To sum up the even elements in the array of size 10c. To combine elements from arrays A and B into array C

Notes

Page 100: Java publish
Page 101: Java publish
Page 102: Java publish
Page 103: Java publish

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];Examplechar 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.

Page 104: Java publish

• In the above example, A is an array that can store 8 characters.

• 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 conversionInput Operation

char str[] = new char[20];String s = args[0]; // String input using argsOrString s = br.readLine(); // String input using readersstr = 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

Page 105: Java publish

Input Operation

char str[] = new char[20];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 argsOrString s = br.readLine(); // String input using readersstr = s.toCharArray(); // conversion from String to char arrayint 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 argsstr = s.toCharArray(); // conversion from String to char arrayint len = s.length(); // calculating the lengthfor(int i=0; i<len;i++){

Page 106: Java publish

if(c[i] >= ‘a’ && c[i] <= ‘z’) // check for lowercase…

}

To check whether a char in a String is uppercase

char str[] = new char[20];String s = br.readLine(); // String input using readersstr = s.toCharArray(); // conversion from String to char arrayint len = s.length(); // calculating the lengthfor(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 readersstr = s.toCharArray(); // conversion from String to char arrayint len = s.length(); // calculating the lengthfor(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 vowelchar str[] = new char[20];String s = br.readLine(); // String input using readersstr = s.toCharArray(); // conversion from String to char arrayint len = s.length(); // calculating the lengthfor(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

Page 107: Java publish

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.

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”

Page 108: Java publish

10.2 Program to take a string as input and count the number of spaces, vowels and consonants

Page 109: Java publish

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

Page 110: Java publish

10.5 Program to take a string as input and search for a char

Page 111: Java publish

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);

Page 112: Java publish

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);

elseif (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 Programsa. To convert the vowels into upper case in a stringb. To replace all ‘a’s with ‘e’s (consider case)c. To count the number of digits and alphabet in a stringd. To find the longest out of 3 strings

Notes

Page 113: Java publish
Page 114: Java publish
Page 115: Java publish

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 1d = Integer.parseInt(br.readLine());e = Integer.parseInt(br.readLine());f = calculateresult (d, e); Function call 2System.out.printline( f );

Page 116: Java publish

}

static int calculateresult (int p, int q){

int r;r = p + q + (p * q); Function Definitionreturn 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.

Page 117: Java publish

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}

Page 118: Java publish

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;

Page 119: Java publish

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

• int d = calculateresult (a, b) + m * n; returned value used in expression

Example

1. float ans = func (a, b );2. int res = demo (x);3. test (m, n, p);4. int val = example ();

Possible Function Styles

1. Void function with no arguments2. Void function with some arguments3. Non void function with no arguments4. Non void function with some arguments

Function Scope• Variables declared inside a function are available to that

function only

Page 120: Java publish

Example

Sample Programs

11.1 Program to calculate power ab using a function (returns a value)

Page 121: Java publish

11.2 Program to calculate factorial n! using a function (void)

Page 122: Java publish

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)

Page 123: Java publish

11.5 Program to print the multiplication table of a given number upto x 20 using a function

Page 124: Java publish

11.6 Program to check whether a given number is prime using a function

Page 125: Java publish

11.7 Program to find the max in an int array of size 20 using a function

Exercise1. 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);

}

Page 126: Java publish

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);

Page 127: Java publish

}

static void demo ( int a ; int b);{

p = p + 10;q = q – 10;r = p + q;return r;

}

3. Write Programs using functionsa. To find a3 + b3 given a and bb. To convert the height of a person given in inches to feetc. To print the sum of odd numbers in a given int arrayd. To convert the cases of a char array

Notes

Page 128: Java publish
Page 129: Java publish
Page 130: Java publish
Page 131: Java publish

Worksheet - 1(Java Datatypes, Constants, Variables, Operators, Input and Output)

1. Match the followinga. An integer constant int a;b. A floating point

constant“java”

c. A char constant C = 20;d. A string (char array)

constant9.5

e. A variable declaration ‘n’f. A variable

initialization100

2. Give examples of your own fora. An integer constantb. A floating point constantc. A char constant

d. A string (char array) constant

e. A variable declarationf. A variable initialization

3. List the basic data types in Java and explain their ranges.4. Identify constants, variables and data types in the following statements.

a. int a = 10;b. char c = ‘d’;c. System.out.println( c +

“alphabet” );

d. float f = 3.45;e. double d = m;

5. Find the mistakes in the following Java statements and write correct statements.

a. int a = 10,000;b. char c = “f”;c. char ch = ‘go’;d. System.out.println( the

result is + “k” );

e. System.out.println( a(b+c));

f. float f$ = 5.49;g. int k = 40,129;

6. Identify the valid and invalid variables from the following giving reasons for invalid ones

a. int My num;b. int my_num;c. int my-num;d. int 1num;

e. int num1;f. int main;g. int Main;

7. Write Java expressions (applying BODMAS)a. a2bb. 2abc. pnr/100d. a2 + 2ab + b2

e. sum =

f. k =

g. z = ab + (x – y)2

8. Write Java statements for the followinga. Initialize a variable c with value 10b. Print a floating point variable fc. Print a string constant “Programming is fun”d. Print a string constant “Result” and an integer constant 10e. Print a string constant “Result” and an integer variable xf. Print 10 stars in 2 line

Page 132: Java publish

9. Write Java code to take a number as input and print the same usinga. Argsb. 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 unitsb. Print the sum, difference, product and quotient of any 2 numbersc. Calculate the average and total marks of any five subjectsd. Interchange the values of 2 variables using a third variablee. 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 = 34a. b = (b++) + c;

a = a – (--b);c = (++c) + (a--);

b. a * b / c + 10c. a / 2 + b * b + 3 * cd. a * b – a / b + c * 2e. a = b + 20;

c = (a++) + 10;b = b – (--a)

12. Find the output of the following

13. Find the mistakes in the following code sample

14. List the types of operators.15. Give examples of unary and binary operators.16. Write dos commands to

a. Change directory to e:\myjavab. Compile a java program first.javac. Run a java program first.java

17. Why do we use the following?a. Integer.parseInt()b. br.readLine()c. import java.io.InputStreamReader; import java.io.BufferedReader;

public static void main(String args[]){

int k;k = k + 10;p = p + 20;System.out.println( “k + p”);System.out.println( ncfe);

}

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);

}

public static void main(String args[]){

int p = 20;int q = p;q = q + 3;p = p + q;System.out.println(p + “ “ + q);

}

Page 133: Java publish

Worksheet – 2 (if..else)

1. Write ‘if’ statements for the followinga. To check whether the value of int variable a is equal to 100b. 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 50e. 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;

elsej = j + 1;

System.out.println(i + “ “ + j );Value supplied for a and b a = 30, b = 30Value 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 = 30Value 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?”);

Page 134: Java publish

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.

4. Write complete Java programs using if constructa. To find the largest and smallest of the given 3 numbers A, B, Cb. 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 choiced. To find whether a year given as input is leap or note. 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 Rate30001 onwards 15%22001 – 30000 10%12001 – 22000 7%5001 – 12000 3%0 – 5000 0%

5. Illustrate Nested If with examples

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” );

a)

Page 135: Java publish

Worksheet – 3 (switch)

1. Convert the following ‘if’ construct to ‘switch’ constructchar 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”);elseSystem.out.println( “Invalid grade”);

2. Find the output of the followingint 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.

4. Write complete Java programs using switch constructa. 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

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” );

}

Page 136: Java publish

5. Convert the following ‘if’ construct to ‘switch’ constructint 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?

Page 137: Java publish

Worksheet – 4 (Loops)

Looping Programs1. 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 numbers3. WAP to find the GCD of 2 numbers4. WAP to print tables of 3,6,9,….n upto x155. Write Programs to print the following patterns using nested loops

6. WAP to compute the following expressions a)

b)

Find & Explain the output of the following code snippets7. 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 outputfor(int i=0; i<5;i++){

for(int j=1;j<3;j++){

if( i != j)

( * * * * * ) ( * * * ) ( * )

2 242 246422468642

12345678910

131531753197531

113135135713579

& &$& &$$$& &$$$$$&&$$$$$$$&

975317531531311

Page 138: Java publish

System.out.println( i * j);}

}11. Explain the steps and find the output.

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. for ( int j = 0; j <= 5; j++)b. for ( int j = 1; j < 5; j++)c. for ( int j = 1; j < 6; j++)d. for ( int j = 0; j < 6; j++)e. 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

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);

int a = 5, b = 15;

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”);

}}

Page 139: Java publish

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 snippets3. 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);

Page 140: Java publish

}void main( ){

int num =191;arm(num);

} Char Array Programs

6. Write a program to convert the string given as input as specified belowa. All capital letters should be replaced with the next letter (for

example – A should be changed as B, B should be changed as C …. Z remains Z etc)

b. All small letters should be replaced with the previous letter (for example – a remains a, b should be changed as a, c should be changed as b etc)

c. Example Input Computer Example Output DnlotsdqInteger / Float Array Program

7. Write a user defined function which intakes single dimensional array and size of array as argument and find sum of elements which are positive.

If 1D array is 10 , 2 , −3 , −4 , 5 , −16 , −17 , 23 Then positive numbers in above array is 10, 2, 5, 23 Sum = 10 + 2 + 5 + 23 = 40 Output is 40

8. Write a program to combine the contents of two equi-sized arrays A and B by computing their corresponding elements with the formula 2 *A[i]+3*B[i], where value I varies from 0 to N-1 and transfer the resultant content in the third same sized array.

9. Write a program which accepts an integer array and its size and replaces elements having even values with its half and elements having odd values with twice its value.eg: if the array contains 3, 4, 5, 16, 9then the array should be rearranged as 6, 2,10,8, 18

Find & Explain the output of the following code snippets10. int AY[]={2,4,8,16,32};

int cnt = 5;for(int m = cnt-1; m >= 0 ; m--){

switch (m){ case 0:

case 4: System.out.println(AY[m]* cnt);case 2: case 1: System.out.println(AY[m]);

}}

11. String str = "Computers@NCFE@2011";int len = str.length(); char a[]=str.toCharArray();for(int i=0;i<len;i++){

if(a[i]>=97 && a[i]<=122)a[i]--;

else if(a[i]>='0' && a[i]<='9')a[i]=a[i-1];

else if(a[i]>='A' && a[i]<='Z')a[i]+=32;

elsea[i]='#';

}

Page 141: Java publish

String s = new String(a); System.out.println(a);