Sie sind auf Seite 1von 23

Chapter 1:

Foundation Concepts of Class and Objects

1.0 Introduction

In our everyday life we interact with so many real-life objects like


books, friends, chairs, tables, computers, teachers, cars, etc. etc. Interactions with many
such physical objects become necessary to get our daily work done. For example, you can
tell your friend Pradip or Pritima to take out a computer book from a rack and place it on
your reading table so that you can go through that book. Your intention is converted into a
voice message, which you pass on to a particular friend of yours. He /She then takes
necessary actions by pulling out the book from the rack and placing it on the specified
table. In this simple task, quite a few real objects are involved, such as -- Pradip or
Pratima (a member of your friend set), computer-book (a member of the set book); table/
rack (a member of the set furniture), etc.
Pradip or Pratima , as an individual, has name, address, father’s name, school
where he/she goes, class in which he/she reads, etc. Moreover he/she can read/write/speak
English, can operate computer, can swim, can sing, etc. Therefore, you can describe any
one of your friends with a number of attributes like name, age, address, ...., etc. and by a
group of activities he/she is capable of doing like writeEnglish(), operateComputer(),
giveAddress, tellName, ....., etc.

Following the Object Oriented concept, we can say that Pratima or Pradip is
an object belonging to the Class Friend. As you can have many friends, all of them can
be described by a common description blueprint (or template) called Friend. In the same
way a particular book can be described by a description blueprint called Book which
should have attributes like book_name, author_name, publisher, price, ..., etc.

Thus the blueprint with the help of which many similar objects can be described
and manipulated in an Object Oriented Program (OOP) has been given the name Class.
Like any OOP language, Java takes help of class definitions to create required number of
software objects to solve problems by a computer. A class or the objects’ blueprint should
have a unique name by calling which a collection of attributes and methods (Fig-1.1)
can be manipulated as a software unit.

Class Name

Attribute1
Attribute2
State | Fig:1.1 A Class blueprint
|
attributeM

Behaviour Method1
Method2
|
|
MethodN
As shown in Fig 1.1, a Class can be regarded also as a special data type which
encapsulates a bundle of attributes (which describes the State an Object) and a collection
of methods (exhibiting all common behaviour of objects). In a Java program, many
similar objects can be created from a Class definition.
Java being an Object Oriented Programming language, a java program
consists of one or more Class definitions out of which Objects are created and
manipulated by allowing messages (Fig-1.2) to pass in between them.

Class-A Class-B

Obj-i.methodx(p)
Obj-i Obj-k
Message

Fig-1.2 Message passing between two objects

As shown in Fig-1.2, Obj-k intends to get a work done by calling the method
methodx(p) which obj-i is capable of performing. A message is normally passed in the
form of --
Obj-i.methodx(p)

-- where p stands for the parameter(s) to be passed with the method while
calling, if any. Method invocation without any parameter passing is quite possible and
often done.

1.1 Java Programming and Interactions between Objects

Let us start by writing a very simple java program.

/** Example 1.1 Sum of Two Integers


* class FirstJava
* @author (A.M.ghosh)
* @version (3.05)
*/

class FirstJava
{ public static void main() {
int x, y;
int result;

x = 10;
y = 20;
result = x+y;

System.out.println(" Value of x + y =" + result);


}
}

Picture 1.1 Java Source Codes of Example 1.1

If you run this program, the value of (x + y) will be displayed. The class
FirstJava has a method main() which starts program execution. To display the output
result, a method -- println() ( available within java library class System.out) has been
utilized.
Picture 1.2 (Top) Executed by clicking void main() menu (bottom) Terminal Window
showing the output result
No one, of course, will use java programs to solve such simple problems. To write
programs for solving complex problems, we have to identify the objects, classes, and the
interactions that can take place between objects specific to the particular problem
domain.

In real-life physical objects interact, whereas in a program, software objects


interact by passing messages in the form as shown in Fig-1.2. An example can help you in
understanding the importance of interactions by passing messages.

Suppose, a customer – Amit wants to withdraw a sum of Rs. 500/- from his
savings account (“xyz..”) from a bank (“abc..”). He will hand over the cheque to a clerk.
The clerk will first verify the signature – if found OK; then the balance available with the
account will be checked. Again, if (balance > withdraw_amount ) then the payment
order will be issued, the balance will be updated, cash will be handed over and finally
the transaction will be closed by stamping “paid”. We see that there are several actions
that are to be carried out by maintaining a proper sequence so that no error creeps in the
process of transaction.

Taking help of a computer program one may carry out such transactions. The real-
life objects involved in such bank transactions can be identified as –

Class Bank: a bank (having bank_name, branch,....etc) where Amit has an account;

Class Customer: Amit, a customer object, should be identified by attributes like


name, address, profession, age, account_no, signature, ..etc.; + common
Methods like – getAccno(), putSignature(), ....... can be encapsulated.

Class SBAccount: Specific Account_no (xyz..) having attributes like Present-


Balance, last-transaction_date, etc [ every transaction changes the State of the
specific account as some attribute values get altered]; + common
Functions or methods involved with such SBAccounts will be like –
checkBalance(account-no); updateBalance(withdraw_amount); depositAcc(
accountNo, amount); displayBalance(accNo); etc.

Class Cheque: A particular cheque with attributes like chequeNo, account_no,


amount, signature, date, payTo, etc. + methods like verifyAcc, verifySignature, etc

One Java program can help a bank-clerk in taking routine actions. That
program can make use of software objects created out of the defined Classes like --
Customer, SBAccount, Cheque, etc. Besides instance variables to accept attribute values,
appropriate functions or methods are to be encapsulated with each Class type, such as --
with Customer : checkCustomerName(name);
verifyAccNo(accNo); ... ... ...etc

with SBAccount : checkBalance(accNo);


updateBalance(accNo);
displayBalance(accNo); ... ... ...etc

with Cheque : verifyDate(chNo);


verifyAccNo(chNo);
verifyCustomerEntry(accNo); ... ... ...etc

A diagram as shown in Fig-1.3 can describe bank transactions scenario.

Cheque Customer Record SBAccount Record

gives checkBalance
verify
signature
Amit AccNo ... updateBalance

Hand over
cash Bank Clerk allowWithdraw

Fig –1.3 Actors and Activities involved in a Bank Transaction

From Fig-1.3 we find that real-life actors (like Amit, Bank-Clerk, ...) are interacting
with either paper records or software objects ( like customer-records, SBAccount records,
etc.) to achieve the desired goal of error-free cash withdrawal. So a system can be
divided into actors or users and software objects.
To have computer support in bank transactions, a program can be written in Java
to process cheque verification, searching customer records, verifying and updating
SBAccounts, etc. The question is how to develop a general program by using which cash
withdrawal for any customer will be possible. Customers are many, SBAccounts are many,
cheques are many – but each individual case can be handled by creating objects of
respective Classes. The customer Amit can be regarded as an object of the Class –
BankCustomer; Amit’s SBAccount can be taken as an object of another Class -
SBAccount; Amit’s cheque can belong to the Cheque Class of the Bank, etc.
Therefore, the bank transaction project should have defined classes like
Customer, SBAccounts, ... etc. A typical BankCustomer class definition blueprint is shown
below: --

class BankCustomer { // identifying attributes


String name; // instance-variable1
String address; // instance-variable2
int age; //instance-variable3
String accNo; //instance-variable4
|
| // different methods
<ret> getName() {body of getName};
<ret> setAccNo() {body of setAccNo};
<ret> verifyAge() {body of verifyAge};
|
|
}
String, int, etc are the data types of the attributes used in the class and <ret> stands for the
data type of the value returned by the methods or functions like getName(), setAccNo(),
etc.

1.2 Software Objects Created from A Class

Let us now expand our concept about software objects. From a class definition
many objects with similar attributes and functions or methods can be created in a computer
memory. For example, from a defined Class – School-- details of many schools can be
collected and stored by a java program. Attribute values or an object’s state (like name,
address, etc.) will be different for different schools. Those values can be set by a method
(say) – setDetails() – and checked by calling the displayDetails() method coded within
the Class definition.

The class School can be defined in a general format as shown below:–

class School { // attributes or data members


<data type> name;
<data type> address;
<data type> year_of_affiliation;
<data type> contactPerson;
|
|
// methods or member functions
<return type> displayDetails(parameter-list){ display codes} ;
<return type> getName(parameter-list){ getName codes };
<return type> setName(parameter-list){ setName codes };
<return type> changeCP(parameter-list) { changeCP codes };
|
|
}

/** Example 1.2 Creating Objects from class School


* Write a description of class School here.
* @author (A.M.Ghosh)
* @version (22.3.2005) */
public class School
{
// instance variables

String name = "Modern High School";


String address = " 25B Park Avenue, Kolkata-700016.";

/**
* Two methods defined -
*/
public void displayName() // no need of any parameter to pass
{
System.out.println(" School Name is :" + name);
}
public void displayAddress( ) // no need of any parameter
{
System.out.println(" School Address is :" + address);
}
}

Please note that the class School has not included any main() method but has made use of
methods like displayName() and displayAddress().

Use BlueJ editor to enter the java program shown in example-1.2. By clicking the
School box on new School() menu, create an instance of School – school_1 and see what
happens when you call the methods – void displayName() or void displayAddress()
associated with that object.

From a defined Class, one can create as many objects as required with different
values of instance variables.

As methods, included in a class, are functions -- so each one of them must return a
value of some data type. In general description, the data type of the return value has been
shown as <return type> or <rets>. When no value is returned by a function but some
action is only taken, the return type is set as void. That is why void as <return type> is used
with displayName() or displayAddress() method.

Of course, some function may require one or more input parameter(s) to pass while
calling a method. Data type of each such parameter, when needed should also be mentioned
explicitly while defining that method.

1.2.1 The new operator

By pre-defining a class, a special user defined data type is kept ready for
subsequent use in a Java program (which is nothing but a collection of one or many such
class definitions out of which one must contain a main() method). To create objects out of a
defined class – you have to make use of the new operator.

manySchool school1 = new manySchool();


manySchool school2 = new manySchool();
|
|
manySchool schoolN = new manySchool();

Thus N-numbers of school objects can be created out of the class defined as
manySchool.

• Run Example-1.3 in BlueJ environment and verify that as many objects can be
created from the manySchool class as you wish.

The general form of the java statement with new operator looks like: -

<class-name> object-name = new class-name();

Thus a new instance of a software object gets created according to the definition
found in the class <class-name>. The class-name is used as a user defined data type. The
new operator reserves a chunk of memory space that will be required to store that object
during execution time.

A class defines a user defined data type (with a number of instance variables
and methods) that can be used as a template for creating many objects.

Suppose the ICSE board wants to print out the details of all the schools sending
students for the final examinations. A Java program using the Class manySchool -- can
create school objects giving names as school_1, school_2, ..... school_N and by calling the
method as school_1.displayDetails(), ...., school_N.displayDetails() details of all N-
schools can be found out. This is the beauty of an OOP language like Java.
Java has another advantage, which other OOP languages are not having. It is
platform independent – that means you can run the same Java program on any computer
platform irrespective of the hardware, operating system and network protocol differences.
Discussion about this aspect has already been made in chapter-0.

Example 1.3 Creating many Objects from a Class

/* User Defined Data Type or class manySchool


* @author (A.M.ghosh)
* @version (24.3.05)
*/
public class manySchool
{
// Instance variable
String name;

/**
* Constructor for objects of the class manySchool
*/
public manySchool()
{
// Initialize instance variable
name = "null";
}

/**
* methods used in the class
*/
public void setName(String actualName )
{

name = actualName;
}
public void displayName()
{
System.out.println( " School name is : " + name);
}
}

Please note that void is a return type. The setName() method has one String type input
parameter and displayName() has no parameter to pass.

Using BlueJ run this program to create as many school objects you like by clicking
repeatedly new manySchool(), set the school names, one by one, by calling setName()
method. Check the name of a particular school-object by calling the displayName()
method. (See Picture 1.3)
Picture 1.3 Creating many school objects from manySchool class

1.2.2 Constructors

How can you initialize the variables in a class each time an instance gets created?
Java allows objects to initialize themselves when they are created. Using one or more
constructor(s) [see Example 1.3] initialization is performed. A programmer can either
define constructor(s) according to his/her requirements of initialization or can depend on the
default constructor. For the time being we will depend on the default constructor and the
detailed discussions on user defined constructors will be made in chapter-3.

You have seen that the new operator can create an object school_1 from the class
School ---

School school_1 = new School ();

What actually happens is that the constructor – School () creates the school_1
object. The School () constructor may be a default one if it is not defined explicitly. The
default constructor initializes all instance variables (like name, address, etc. .....) with null
or zero values. For a simple class, the default constructor may be sufficient; but for more
complex and sophisticated applications, a programmer is forced to define one or more
constructors for the class being defined.

Details about constructors will be discussed elaborately in chapter- 3.


1.3 Importance of Library Classes for Software Development

A java program is a collection of one or more Classes out of which one class
must contain the main() method. Program execution starts with that class where the main()
method is present. Therefore a single class java program must contain the main() method
besides any other method(s) required to be included.

In a program one can easily include any predefined class or classes lying stored in the Java
Library. Such reuse of Class(es) helps a programmer in minimizing program
development time and taking burden of extra coding.
For example, you have already taken help of a System Class from java library. To
display any result or text message, on the VDU-screen or terminal window, you use the
statement

System.out.println (.........................);

Where println (......) is a method of the object referenced by System.out created


from a class already available in the Java language package. Users can make use of
many such classes available in the java library of the JDK 1.3.

1.3.1 Java.lang Classes

A library package is a collection of many commonly used Classes, which are often
required by java programmers. The most essential support package, java.lang, is got to be
included with any java program. It includes classes like System, Compiler, String, Runtime,
etc. That is why the java.lang package gets automatically included with any java program.

Being a member of the java.lang package, Math classes [which contain functions like – sin(),
cos(), tan(), exp(), log(), sqrt(), etc.] are implicitly included with any java program you load
for execution.
There are quite a few other useful packages, like java.util containing utility classes,
java.io containing input/output classes, etc., which are although present within the Java
Development Kit, but are not automatically included with java programs. Except java.lang
package all other packages are to be imported explicitly by adding import statements like ---

import java.io.*;
import java.util.*;
...... ......

Example 1.4 <An example Showing use of Math Library >

/* Finding Sin of an angle


using Math Library
available within the java.lang.* package
*/
public class Sin
{
//member variables
double deg;

/**
* Constructor for objects of class Sin
*/
public Sin(double ang)
{
// initialise instance variables
deg = ang;
}

/**
* An example of a method using Math Library
*/
public void sinMethod()
{
double rad = deg*22/(7*180);
double result = Math.sin(rad);
System.out.println (" sin of the angle =" + result);
}
}

Execute this program to find out the sine values of different angles fed as a
constructor parameter.

Points To Ponder

Class stands as a common replicable structure for many Objects to be


created with different attribute values but having same behaviour.

*An object can be taken as an instance of a Class. [A particular student is an instance


a Class – Student.]

* Different attribute values (like name, address, age, etc.) [used as instance
variables] differentiate one object from another. Attributes are also called state
members.
*Member Functions or Methods of a Class give descriptions of the behaviour of
any object belonging to that Class.

• An object of one class can interact with the objects of other classes by passing
messages.

• A message is passed in the form of ObjectName.methodName(parameters) .

• A class with a main () method can start execution without creation of any object
out of it first.

• A class not having a main () method cannot start functioning unless an object
instance of it is created first.

Important Questions

• How to specify the attribute(s) of a Class/object? Give examples.

• How can one define a method or member function in a Class? How is main ()
method defined?

Note: In a class data type of every attribute and the return type of every function or
method must be specified explicitly. When do you specify void as a return type?

1.4 Attribute Values and Data Types

In our day to day activities we make use of numeric values to specify numbers or
quantities. Similarly, to write names, addresses, etc. we use alphabetic symbols and any
alphanumeric combinations.
Again, numeric values may be of Integer type (like 34,95, 8, .....) or float type ( like
3.14, 229.65372, ......). Similarly, alphabetic symbols use characters (like ‘y,’ ‘n’, ‘t’, ‘f’,
‘x’, ‘y’, ‘z’........); and the String type uses character combinations (like “Amit”, “
Modern School” , “ 37/1-B Park Street”, ........etc).

Java language allows the following primitive data types --

Integers : whole valued signed numbers specified in the units of


byte (8 bits), [range: -128 to 127]
short ( 16 bits), [range : -32768 to 32767 ]
int ( 32 bits) , [range : -2147483648 to 2147483647 ] and
long ( 64 bits). [range : -9223372036854775808 to
9223372036854775807 ]

Examples – declaration of integer variables....


byte a,d;
short x,y;
int age;
long distance;

Floating-point number: numbers with fractional precision represented in the form of


either float or double.

Examples -- float height;


double pi;

Characters: represent symbols of a character set, like alphabets, digits, +, *, etc.


[ as found on a keyboard ].

Examples – char ch1, ch2;


ch1 = ‘T’;
ch2 = ‘a’;

Boolean: To specify binary variables like true or false; yes or no.

Examples – boolean b;
b = true;

All values, shown above, are the examples of simple or primitive data types. Java
can handle any data also as objects belonging to some wrapper classes like Integer, Float,
Boolean, Long, Double, etc. Java provides classes for each of the simple data types. For
example, Float objects can be constructed with values of simple data type float or double.

Note the convention – all wrapper class names start with the Capital letters.

1.4.1 class String

Every string in Java is an object created out of the class String (which remains
defined in the java.lang package). String constants are actually String objects.

String mystring = “ This is a book on BlueJ.”;

---- is a Java statement which creates a string constant [ mystring] using character values
[ placed within “ ........”]. Remember, once a string object is created in a java program its
contents cannot be altered. Moreover, once a string object gets defined it can be used at any
place where a string is allowed. For example

System.out.println (mystring); --- // is a valid Java statement.


The class String has a method of adding small strings into a bigger string. Suppose you
wish to add consecutive words “ Amit” “has” “an” “account” “in” “UTI” “bank.” to form a
sentence. You can do that by writing a Java statement as –

String mysentence = “Amit” + “has” + “an” + “account” + “in” + “UTI” +


“bank.”;

You are familiar with the + operator used to add two numeric values. String Class is
capable of adding sub-strings into a longer string (technically known as concatenation) as
shown above. String Class also contains methods like equals (....), length (...), charAt(....),
etc. We will discuss about them in some later chapter.

1.4.2 Operators and Expressions

Java allows arithmetic operations like + (addition), - (subtraction),


*(multiplication), / (division), % (modulus), ++ (increment); += (Addition
assignment), -= (Subtraction assignment), *= (Multiplication assignment), /=
(Division assignment), %= (Modulus assignment), -- (Decrement).

The operands of the arithmetic operators should be of numeric data types


like integer, float, double, etc. Boolean or character data types cannot be used with
any arithmetic operations.

Example 1.5 Program involving Arithmetic & Trigonometric Operations

public class NewCalDemo


{

// operands
double x;
double y;
// Constructor

public NewCalDemo( double a, double b)


{x = a;
y = b;
}

/** creating objects from the defined


* classes Add, Sub, etc....
*/
public void compute(){
Add plus = new Add(x,y);
Sub minus = new Sub(x,y);
Mult product = new Mult(x,y);
Div divide = new Div(x,y);
Power topow = new Power(x,y);
Sin angsin = new Sin(x);
Log logval =new Log(y);
Inv invert = new Inv(x);
Cos angcos = new Cos(x);

/**
* examples of different operations
*/

double presult = plus.addMethod();


System.out.println(" value of x+y= " + presult);
double mresult = minus.subMethod();
System.out.println(" value of x-y= " + mresult);
double into = product.multMethod();
System.out.println(" value of x * y = " + into);
double dresult = divide.divMethod();
System.out.println( "value of x/y = " + dresult);
angsin.sinMethod();
angcos.cosMethod();
logval.logMethod();
double invres = invert.invMethod();
System.out.println(" Inverse of x is = " + invres);

}
}

If you run this program with x = 12.0 and y = 3.0 the output that you will see is shown
below:

value of x+y= 15.0

value of x-y= 9.0

value of x * y = 36.0

value of x/y = 4.0

sin of the angle =0.2079941472217805

cos of the angle =0.9781300704515142

log of invalue =1.0986122886681096

Inverse of x is = 0.08333333333333333
Besides arithmetic operators, Java allows Bitwise Operators [NOT, AND, OR,
XOR, shift Right, etc. ], Relational Operators [ (= =)equal to, ( !=) not equal to, (>) greater
than, (<) less than, etc.], Boolean Operators [ AND,OR, XOR, etc. ], the Assignment
operator [ variable = expression], etc. We will discuss about them in details afterwards.

1.4.3 Introducing Methods or member Functions

We know that a Class is a combination of two things – attributes and methods. We


have also seen how attributes are to be specified with appropriate data types. Now we have to
see how a method can be defined.

A method is written in the form of ---


<return type> method_name ( parameters) {
method body
}
Methods are nothing but functions each one of which must return a value when
invoked or called. The return type (like int, float, double, etc.) is specified first followed
by the method name (with a list of parameters to pass). As a method body you can pack java
codes as per requirements.
It may so happen that a method is not returning any value but taking all specified
action(s) within its internal boundary --- then the return value is got to be specified as void.
For better understanding, two classes (see Example-1.6) will be defined now – one
with a method [cover () ] which returns a numeric value when called and another with a
method main() which does not return any value but takes all actions specified within its
body.

Example 1.6 To find the area covered by a rectangle.

/**
* Write a description of the class Area here.
*
* @author (A.M.ghosh)
* @version (7.3.2005)
*/
public class Area
{
int length, width; // attributes

public int cover() // a Method which returns int value


{
return (length*width);
}
}
public class AreaDemo
{
public static void main() // observe this line carefully
{ // which does not return any value

// Two objects created out of predefined class Area


Area area1 = new Area();
Area area2 = new Area();
int c1, c2;
// assign values to area instance 1
area1.length =12;
area1.width =9;
// assign values to area instance 2
area2.length =20;
area2.width = 16;
// message passed to compute covered area
c1 = area1.cover();
System.out.println(" Covered area of 1 = " + c1);
c2 = area2.cover();
System.out.println(" Covered area of 2 + " + c2);
}
}

The class Area knows how to calculate the area of a rectangle when its length and
width are specified. The AreaDemo class utilizes the Area’s cover () method to find out the
covered area of a rectangle. The static main () method of AreaDemo class controls all
activities concerned with the area calculation project making it self-start.

Enter and run example -1.6 and check the output values.

1.4.4 The main () Method

If a Java project needs many classes for interactions, there must have one class to
control all interacting objects. That computation controlling class must contain the static
main (.. ) method which has a constructional look like –

public static void main(String args[]) { .... }

and program execution gets started from that class.

The meaning of each key word of the main (...) line will not be explained here
because that would demand a detailed understanding of Java’s approach. Just be satisfied
with the remarks given here.

The keyword public indicates that this particular member (method here) may be
accessed by any external class codes.
The keyword static allows java’s interpreter to call the main () method without
creating any particular object instance of that class.

The key word void tells the java’s compiler that this main () method does not return
any value as output. Of course, main (..) method is quite capable of returning values, if
situation demands.

Note: If you work with BlueJ environment, simple main () can be used instead of main
(String args []). For text based command interactions, main (String args []) construct is got
to be used always.

Java is case sensitive – so always write main and never Main.

One class may be defined within another class for use.

1.5 Computation as Message Passing between Objects

Carefully study the example-1.6. In that program two classes, namely Area and
AreaDemo, have been defined. Identify the message passing statements used there.
Objects can interact between themselves by passing messages. Such message
interactions invoke functions, which ultimately do the computational work.
The class containing the main () method generates all objects and controls the
messages required to perform the computational activities – like assignment of values to the
variables, invoking appropriate methods and printing results as per job requirements.

Learn by Doing: --

(1) Study carefully the example-1.6 and try to detect the presence of messages there.

(2) Create a project with more than one classes defined within it. Control your
program by the class which contains the main ( ) method.

1.5 .1 A Method that takes Parameters

Many methods need parameters. What is a parameter? A parameter is a variable,


which is to be specified for a method (parameters) to function.

The main(...) is a method which is capable of accepting command line parameters

public static void main ( String args[ ]) {


// method body }
String args[ ] declares a parameter named args ( of type String ) which can
accept any command-line arguments when the program is called to execute.
[For example – javac Test.java – where javac is the first argument and Test.java is
the second argument.]

User defined methods may have zero, one or more parameters to pass according to
the activities taking place within the method body.
Parameters can help a method to operate on a variety of data. For example --

double square( double i) {


return i*i ; }

Here by passing any value of i, one can get its square value. Now square can act as
a general-purpose method.

Try to understand the difference between a parameter and an argument. “A


parameter is a variable defined by a method that receives a value when the method
is called” [Java2 Reference Book]. In the method Square( ..) -- i is a parameter.

An argument is a value that is passed to a method when it is invoked. For


example, square (10.54) passes 10.54 as an argument.

1.6 Conditionals and non-nested loops

Java statements are like English sentences. A statement forms a unit of execution.
The statements like assignment (a = 12.5:), decrement (b--; ), method call
[ System.out.println ( “ The value of a is “ + a); ] , declaration ( int x = 25;) are
called expression statements. In a java program, such statements are executed in a
sequential order.

A control flow statement can regulate the order of execution sequence in a


program. Java’s control statements can be of selection type [if-else, if-else-if, case-
switch, etc.], iteration or loop type [while-do, do-while, for, etc.] and jump [break,
continue, return ] type. One inner loop inside an outer loop is called nesting. Java
allows nesting.

Program execution can be diverted from one sequence path to another (Fig-
1.4) looking at some condition. If the condition gets satisfied then the path1
statement(s) will be executed, else path2 statement(s) will be executed.

The condition helps a program to take decision on the execution-path to be followed. An


example can make the concept clear.

if ( a < b) max = b; // to determine which number is greater


else max = a;
if

condition
else
Fig-1.4 If-else then
Construct
Path1 Path2

In a generic form if-else statement can be written as ---

if (condition) statement1;
else statement2;

Java allows a sequence of nested ifs [if-else-if ladder] whose construct has the look like
this :--

if (condition1) statement_group1;
else if (condition2) statement_group2;
else if (condition3) statement_group3;
|
|
else
statement_group_default;

Such if statements are executed from the top down. As soon as one of the conditions
gets satisfied, the associated statement_group is executed and the rest of the ladder is
bypassed. The final else acts as a default statements.

The switch statement is Java’s multi-way branch statement. It provides a better


alternative to if-else-if ladder. The details will be discussed in the Decision-Making chapter.

Iteration means repeating a procedure again and again. That means, for a group of
statements, execution will start from the top and reaching the bottom-most statement the
control will loop back again to the top. Such looping can continue for a fixed number of
times or will go on continuing until a pre-defined condition gets satisfied.
1.6.1 Known and Unknown Number of Iterations

Iteration or looping is fundamental to computation. Suppose you have to


add 10 numbers, but a computer can add only two numbers at a time. Therefore, a
computer can add 10 numbers, by maintaining the following sequence ---

Result =0; // clear location where Result will be stored


Result +n1 = Result; // 1st number entered
Result +n2 = Result; // 2nd number added
Result +n3 = Result; // 3 numbers added
|
|
Result +n10 = Result;
// 10 numbers added by repeating the addition process 10 times

print Result;

Such repetition can be carried out easily using a for statement: --

result = 0;
for (int i=0; i <10; i++) {
result = result + number[i];
}
System.out.println ( “ Sum of 10 numbers = “ + result);

The general form of the for statement looks like:-

for ( initialization; condition; iteration) {


// body of the loop
}

If only one statement is repeated, there is no need to use curly braces. For a fixed number of
iterations, for-loop is most suitable.

The while loop is most popular in Java. It has the general form of:-

while( condition) {
body of the loop
}

The body of the loop will be executed as long as the condition expression remains true. This
while-do construct is used when the condition is checked first before the loop body gets
executed. If condition is found false, the body will remain unexecuted. If you want to ensure
the execution of the loop body at least once, then you have to make use of the do-while
construct:--

do {
body of the loop
} while (condition);

Further discussions with applications of such control statements will be made in chapter-7.

1.7 Conclusions

This chapter has tried to give an “Elementary concept of Objects and Classes “ that
forms the foundation of OOP. The concept of physical objects, and the attributes by which
they can be differentiated has been explained first. Software objects in Object Oriented
Programming are created as replica of physical objects so that object interaction can imitate
the real-life activities. Since physical objects are capable of doing some work, so software
objects are also made to behave similarly with the added methods or functions. Thus a
special composite data type – called class, which encapsulates both attributes and methods –
is framed to use for OOP languages.

Java supports simple data types like int, float, etc.; complex data types like objects
belonging to the wrapper classes of the types Integer, Float, etc. and User Defined Data
Types like class/objects. The importance of String class is also described briefly.

The importance of library classes in a java program has been explained. The
special role that the main () method of a class is supposed to play has been shown with
appropriate examples.

Creation of objects out of defined classes and interactions allowed between them
by passing messages fulfil the goal of computation. This concept has been demonstrated by
considering a real-life bank transaction example.

The chapter ends with a note on conditionals and non-nested loops.

Review Questions & Assignments

< To be added here >

Das könnte Ihnen auch gefallen