Chapter2 ControlstructureIntroducingclasses
Chapter2 ControlstructureIntroducingclasses
(JAVA)
2009
RIZVI
COLLEGE
CP-II ( java)
CP-II ( java)
1. 2. 3. 4. 5. 6.
The if statement Multiple statements The if-else statement The if-else statement as Block Nested if statement Nested if-else statement
1)
The if statement
The if statement is used to specify conditional execution of a program statement The general format of if statement is:
/* program to demonstarte if statement*/ class IfDemo1 { public static void main(String args[]) { int no; no=5; if(no<100)
3
CP-II ( java)
System.out.println("The number is less than 100!!!"); }} 2) Multiple statements : The if statement is used to specify conditional execution of a program statement, or a group of statements enclosed in braces. The general format of if statement is: if (expression) { statement-block; } program statement; Fig : Format of IF block statement When an if statement is encountered, expression is evaluated and if its value is true, then statement-block is executed, and after the execution of the block, the statement following the if statement (program statement) is executed. If the value of the expression is false, the statement- block is not executed and the execution continues from the statement immediately after the if statement (program statement).
/*Program to demonstrate Multiple statements within if*/ class IfDemo2 { public static void main(String args[]) { int marks; marks = 35; if(marks<40) { int lessmarks=40-marks; System.out.println("\nSorry!!!!!you are failed"); System.out.println("\nYou should have got "+lessmarks+" more marks"); } } } 4
CP-II ( java)
/* program to check whether number is even or odd */ class EvenOdd { public static void main(String args[]) { int no , temp ; no = 35; temp = no % 2 ; if (temp == 0) System.out.println("The number "+no+" is Even"); else System.out.println("The number "+no+" is Odd"); } }
CP-II ( java)
4). The "if ... else Statements as a BLOCK The purpose of if-else statement is to carry out logical tests and then, take one of the two possible The general Syntax of if-else block : if (condition) { block of one; or more C++ statements; } else { block of one; or more C++ statements; }
5. Nested if statement :
Syntax:
if (condition 1) if (condition 2) if (condition 3) statements 1;
/* Program to tests whether the given number is divisible by 3 and 5, both*/ class Divby3_5 { public static void main(String args[]) { int no ; no = 15; if (no%3 == 0) if (no%5 == 0) System.out.println("The number "+no+" is divisible by 3 and 5"); } }
6
CP-II ( java)
6.
/*program to determine grade for given marks*/ class Grade { public static void main(String args[]) { int marks = 83; String grade; if(marks > 79) grade="Honours"; else if(marks>59) grade="First division"; else if(marks > 49) 7
CP-II ( java)
grade="Second division"; else if(marks > 39) grade="Third division"; else grade="Fail"; System.out.println("Marks : "+marks+"\t Grade : "+grade); } }
/* Program to determine which season a particular month is in */ class Season { public static void main(String args[]) { int month = 3; // March String season; if(month==12||month==1||month==2) season="Winter"; else if(month==3||month==4||month==5) season="Spring"; else if(month==6||month==7||month==8) season="Summer"; else if(month==9||month==10||month==11) season="Autumn"; else season= "False Month"; System.out.println(" The March is in the "+season+"."); } }
CP-II ( java)
CP-II ( java)
class SwitchDemo { public static void main(String args[]) { int x , y ; char choice; x = 10; y = 2; System.out.println("\t\tMenu\n"); System.out.println("\t1. Addition System.out.println("\t2. Subtraction System.out.println("\t3. Division \n"); \n"); \n");
System.out.println("\t4. Multiplication \n"); try { System.out.println("Enter your choice :"); choice= (char)System.in.read(); switch (choice) {
10
CP-II ( java)
case 'A' : System.out.println("Addition of "+x+" and "+y+" : "+(x+y)); break ; case 'S' : System.out.println("Subtraction of "+x+" and "+y+" : "+(x-y)); break ; case 'D' : System.out.println("Division of "+x+" and "+y+" : "+((float)x/(float)y)); break ; case 'M' : System.out.println("Multiplication of "+x+" and "+y+" : "+(x*y)); break ; default :System.out.println("Wrong choice !!"); } } catch(Exception e) { System.out.println("I/O Error"); } } } *************** Output *********** Enter any two numbers : 3 5 Menu 1. Addition 2. Subtraction
11
CP-II ( java)
3. Division 4. Multiplication 5. Modulus Enter your choice : M Multiplication of 3 and 5 : 15 /* Program 5 : The switch statement */ #include <iostream.h> #include<conio.h> void main() {char c ; clrscr(); cout<<"Enter any one character from the word 'worry': "; cin>>c; switch (c) {case 'W': case 'w':cout<<"I am in case w\n"; break ; case 'O': case 'o':cout<<"I am in case o\n"; break ; case 'R': case 'r':cout<<"I am in case r\n"; break ;
12
CP-II ( java)
case 'Y': case 'y':cout<<"I am in case y\n"; break ; default:cout<<"U entered the wrong letter !!\n"; }getch();} ******************* OUTPUT**************** Enter any one character from the word 'worry': o I am in case o
Loop Statements
(for, while & do-while statements)
1. The while loop 2. The do -while loop 3. The for loop
CP-II ( java)
{ public static void main(String args[]) { int i = 1 , sum = 0 ; while (i<11) { sum = sum + i ; i++ ; } System.out.println("The sum of first ten numbers is : "+sum); } }
14
CP-II ( java)
} }
15
CP-II ( java)
The sequence of control flow or the evaluation of these three expressions is: 1. The initialization (expr1 is evaluated) is done only once at the beginning. 2. Then the condition (expr2) is tested. If satisfied (evaluates to nonzero) the body of the loop is executed, otherwise the loop is terminated. 3. When the expr2 evaluates to non-zero the body of the loop is executed. Upon reaching the closing braces of for, control is sent back to for statement, where the increment (expr3) is performed. 4. Again the condition is tested and will follow the path based on the results of the test condition. /* Program to compute sum of first 20 numbers using for loop */ class ForDemo1 {
for (i=1 ; i<21 ; i++) sum = sum + i ; System.out.println("The sum of first twenty numbers is "+sum); } }
public static void main(String args[]) { int i = 0 ; System.out.println("Table of 15 -\n"); for (i=1 ; i<=10 ; i++) System.out.println("15 * "+i+" : "+(15*i));
/* Program to display squares and cubes of first ten numbers */ class ForDemo3 {
public static void main(String args[]) { int num , square , cube ; System.out.println("\nThe squares and cubes of first
System.out.println("============================ =====================\n\n");
16
CP-II ( java)
System.out.println("Number\tSquare\tCube\n"); for (num=1 ; num<11 ; num++) { square = num * num ; cube = num * square ; System.out.println(num+"\t"+square+"\t"+cube); } }
/* program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7 */ class ForDemo4 { public static void main(String args[]) { int no,count=0,sum=0; for(no=101;no>100&&no<200;no++) if(no%7==0) { System.out.println(" "+no+" is divisible by 7"); sum=sum+no; count=count+1; } System.out.println("\n Total no. of integer between 100 to 200 that are divisible by 7 : "+count); System.out.println(" Sum of all integer between 100 to 200 that are divisible by 7 : "+sum); } } /* Program to display a particular pattern of stars using nested for loops.*/ class NestedForDemo { public static void main(String args[]) { int i , j , num ; num = 6 ; //value of num is between 1 to 10 for (i=1 ; i<=num ; i++) { for (j=1 ; j<=i ; j++) System.out.print("*\t"); System.out.println(" "); } } }
17
CP-II ( java)
break statement:
The break statement is used to terminate loops or to exit from a switch. It can be used within a for, a while, a do-while or a switch statement. The break statement is written simply as : break; without any embedded expressions or statements. /* using break to exit a for loop*/ class BreakDemo1 { public static void main(String args[]) { for(int i =0;i<100;i++) { if(i==10) break; //terminate loop if i is 10 System.out.println("i ="+i); } System.out.println("End of Loop"); } }
(a)continue statement:
The continue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather, the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop. The continue statement can be included within a for, a while or a do-while statement. The continue statement is written simply as : continue;
18
CP-II ( java)
without any embedded expressions or statements. The continue is a keyword in the C++ program and the semicolon must be inserted after the continue statement. for (i = 0; i < n; i++) { if (arr[i] < 0) continue; sum += a[i]; } The above code fragment calculates the sum of only the positive elements in the array arr; negative values are skipped.
/* Program to demonstrate continue statment */ class ContinueDemo1 { public static void main(String args[]) { for(int i =0;i<10;i++) { System.out.print(i+" "); if(i%2==0) continue; System.out.println(""); } } }
The exit function The standard library function, exit ( ), is used to terminate execution of the program. The difference between break statement and exit function is, break just terminates the execution of loop in which it appears, whereas exit ( ) terminat
19
CP-II ( java)
INTRODUCING CLASSES
20
Introducing classes:
Objects and Classes When you write a program in an object-oriented language, you don't define actual objects. You define classes of objects, where a class is a template for multiple objects with similar features. A class is a generic template for a set of objects with similar features. An object that belongs to a class is said to be an instance of that class. 1 Defining Classes Defining classes is easy. To define a class, use the class keyword and the name of the class: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.
CP-II ( java)
2 Simple Class Let.s begin our study of the class with a simple example. Here is a class called Box that defines three instance variables: width, height, and depth. class Box { double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; rmybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } } Every Box object will contain its own copies of the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. When you compile this program, you will find that two .class files have been created, one for Box and one for BoxDemo. To run this program, you must execute BoxDemo.class. When you do, you will see the following output:
22
CP-II ( java)
Volume is 3000.0 3 Declaring Objects Obtaining objects of a class is a two-step process. First, you must declare a variable of the class type. This variable is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator dynamically allocates memory for an object and returns a reference to it. In the preceding sample programs, a line similar to the following is used to declare an object of type Box: Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object The first line declares mybox as a reference to an object of type Box. After this line executes, mybox contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use mybox at this point will result in a compile-time error. The next line allocates an actual object and assigns a reference to it to mybox. After the second line executes, you can use mybox as if it were a Box object. 4 Creating methods Method is a block of code written to perform a specific task which may or may not return a value. The general form of a method: Type method name(parameter-list) { // body of method }
23
CP-II ( java)
Method definitions have four basic parts: The name of the method The type of object or primitive type the method returns A list of parameters The body of the method Example:class Box { double width; double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume();
24
CP-II ( java)
// display volume of second box mybox2.volume(); } } This program generates the following output Volume is 3000.0 Volume is 162.0 5 Adding a Method That Takes Parameters Parameterized method can operate on a variety of data and or be used in a number of slightly different situations. Here is a method that returns the square of the number 10: int square() { return 10 * 10; } While this method does, indeed, return the value of 10 squared, its use is very limited. However, if you modify the method so that it takes a parameter, as shown next, then you can make square( ) much more useful. int square(int i) { return i * i; } Now, square( ) will return the square of whatever value it is called with. Example: int x, y; x = square(5); // x equals 25 x = square(9); // x equals 81 y = 2; x = square(y); Example of parameterized methods:class Box {
25
CP-II ( java)
double width; double height; double depth; // sets dimensions of box void setDim(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); // get volume of box vol = mybox1.volume(); System.out.println("Volume is " + vol); } }
6 Constructors
A constructor is a public method (a method that can be accessed anywhere in a program) with the same name as the class and it enables an object to initialize itself when it's created. There are two types of constructor:1. Default constructor:- Default constructor fires automatically and initializes all instance variable to the default values. It will fire in the
26
CP-II ( java)
absence of even if a single parameterized constructor. 2. Parameterized constructor:- If the method defines parameters inside the method in parenthesis, it is called parameterized constructor A constructor initializes an object immediately upon creation. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. Constructors have no return type, not even void. This is because the implicit return type of a class. constructor is the class type itself. Example:class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo7 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box
27
CP-II ( java)
vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } The output from this program is shown here: Volume is 3000.0 Volume is 162.0
7 Overloading Methods
Method overloading is the phenomenon using the same method name more than once in the same class and making it perform different functions. o Different number of parameter passed o Different order of passing parameter o Different data types of the parameter When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Method overloading is used when objects are required to perform similar tasks but using different input parameters. Method overloading is one of the ways that Java implements polymorphism. Example:// Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter.
28
CP-II ( java)
void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { 156 J a v a . 2 : T h e C o m p l e t e R e f e r e n c e System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625
29