0% found this document useful (0 votes)
117 views29 pages

Chapter2 ControlstructureIntroducingclasses

This document contains notes on control structures in Java programming. It discusses conditional statements like if, if-else, switch statements. It also covers loop statements like for, while and do-while loops. Examples are provided to demonstrate if/else statements, nested if statements, switch statements with multiple cases. Looping constructs are explained with examples to add first ten numbers using while loop.

Uploaded by

Srinath Aiyangar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
117 views29 pages

Chapter2 ControlstructureIntroducingclasses

This document contains notes on control structures in Java programming. It discusses conditional statements like if, if-else, switch statements. It also covers loop statements like for, while and do-while loops. Examples are provided to demonstrate if/else statements, nested if statements, switch statements with multiple cases. Looping constructs are explained with examples to add first ten numbers using while loop.

Uploaded by

Srinath Aiyangar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

( java) Notes by Deepak Gaikar CCP-II OMPUTER PROGRAMMING-II.

(JAVA)

Control Structure Introducing Classes.. .CHAPTER-1

Mumbai UniversitySem-II Contents:

2009

Primitive Data Types in Java


Java Operators, Literals, Identifiers. key words in Java Addition of Integers in Java, Multiplication and division in Java The Remainder or Modulus Operator in Java Operator Precedence in Java, Mixing Data Types Converting Strings to Numbers, The char data type in Java The if, else, else-if statement in Java The While loop, The for loop, The do whil e loop in Java Booleans, Relational Operators, relational Operator Precedence Break, Continue, The switch statement in Java The? : operator in Java , Logical Operators in Java

Object Oriented Programming


Constructing objects with new, Methods, Invoking Method Implied this , Member Variables vs. Local Variables Passing Arguments to Methods, Returning Multiple Values From Methods, constructors

Access Protection, The four Levels of Access Protection

RIZVI

COLLEGE

CP-II ( java)

Notes by Deepak Gaikar

Introduction Control Statements in java


The order in which the statements are written in a program is extremely important. Normally, the statements are executed sequentially as written in the program. In other words, when all the operations specified in a particular statement are executed, the statement appearing on the next line of the program is taken up for execution. This is known as the normal flow of control. If one were restricted to this normal flow of control it would not be possible to perform alternate actions based on the result of testing a condition. For example, a realistic java program may require that a logical test be carried out at some particular point within the program. One of several possible actions will then be carried out, depending on the outcome of the logical test. This is known as branching. There is also a special kind of branching, called selection, in which one group of statements is selected from several available groups. In addition, the program may require that a group of instructions be executed repeatedly, until some logical condition has been satisfied. This is known as looping. Sometimes the required number of repetitions is known in advance; and sometimes the computation continues indefiritely until the logical condition becomes true. All of these operations ran be carried out by using the various control statements included in java. Control statements alter the flow of execution of the programs. Control statements can be broadly divided into three categories : (1) Decision-making or Conditional Statements (Branching and Selection) (a) if statement (b) if-else statement (c) switch statement (a) (b) (c) (a) (b) (c) for statement while statement do-while statement break statement continue statement goto statement

(2) Loop statements:

(3) Breaking control statements :

CP-II ( java)

Notes by Deepak Gaikar

1) Decision-making or Conditional Statements (Branching and Selection) :


The major decision making constructs of C ++ language are:

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:

if (condition) statement; Fig 3.1: Format of IF statement

/* program to demonstarte if statement*/ class IfDemo1 { public static void main(String args[]) { int no; no=5; if(no<100)
3

CP-II ( java)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

3 ) The if-else statement :


The purpose of if-else statement is to carry out logical tests and then, take one of the two possible actions The general syntax of if-else statement is: if (expression) true -s tatement; else false-statement; Fig : Format of if..else statement If the expression is true, then the true-statement, which immediately follows the if is executed otherwise, the false-statement is executed.

/* 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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

6.

Nested if-else statement :


if (condition) { if (condition) { statement; } else { statement; } } else { if (condition) { statement; } else { statement; }

/*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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

Case control structure: The switch statement 1) The simple switch :


The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values , and branches accordingly. Syntax of switch: switch (integer expression) { case value1: statement-block1; break; case value2: statement-block2: break; default: default-block; } Fig : Format of simple switch statement If your program must select from one of many different actions, the "switch" structure will be more efficient than an "if ..else..." struct

CP-II ( java)

Notes by Deepak Gaikar

/* Program 4:The switch statement */


/*Program to performed arithmetic operations using switch case*/

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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

1. The while loop :


initialization; while (condition) statements;

2.The while loop as a block :


initialization; while (condition) { statements; // code } /* Program of adding first ten numbers using the while loop */ class AddWhile
13

CP-II ( java)

Notes by Deepak Gaikar

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

2) The do...while loop


The general format of a dowhile loop is: initialization; do { statement-block; } while (expression); Fig 3.11: Format of do...while loop
/* Program to reverse the digits of any integer number*/ class ReverseDigits { public static void main(String args[]) { int num , temp ; num = 1234; System.out.println(" The Number is : "+num); System.out.print(" The Reverse Number is : "); do { temp = num % 10 ; System.out.print(temp); num = num / 10 ; } while (num != 0) ;

14

CP-II ( java)

Notes by Deepak Gaikar

} }

(3) for statement :


The for statement or for loop is useful while executing a statement a number of times. The for loop is the most commonly used statement in C + + . This loop consists of three expressions : The first expression is used to initialize the index value. The second expression is used to check whether or not the loop is to be continued again, and The third expression is used to change the index value/or further iteration. The geneta\ toiirv of for statement is for (expression I; expression 2; expression 3) statement; In other words : for (initial conditionj teat condition; incrementer or decrementer) { statement 1 statement 2 ....... } This is equivalent to expr1; while (expr2) { statement-block; expr3; } where : * expression 1 is the initialization of the expression or the condition called an| index expression 2 is the condition checked. As long as the given expression is true| the loop statements will be repeated, and expression 3 is the incrementer or decrementer to change the index value ofl the for loop variable.

15

CP-II ( java)

Notes by Deepak Gaikar

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 {

public static void main(String args[]) { int i , sum = 0 ;

for (i=1 ; i<21 ; i++) sum = sum + i ; System.out.println("The sum of first twenty numbers is "+sum); } }

/* Program to display table of 15 */ class ForDemo2 {

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

ten numbers :\n");

System.out.println("============================ =====================\n\n");
16

CP-II ( java)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

Breaking Control Statements


(break, continue & goto statements) (a)

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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)

Notes by Deepak Gaikar

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

You might also like