Module 2class and Objects
Module 2class and Objects
Prepared By :
Dr. M S Patel
Associate Professor
Information Science and Engineering
RVITM, Bengaluru - 560076
Email: [email protected]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
class Employee
{
char name[30];
int age;
public:
void getdata(void);
void putdata(void);
};
void Employee:: getdata(void)
{
cout<<‖Enter Name and Age:‖;
cin>>name>>age;
}
void Employee:: putdata(void)
{
cout<<name<<‖\t‖<<age<<endl;
}
void main()
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
{
Employee e[5];
int i;
for(i=0; i<5; i++)
{
e[i].getdata();
}
for(i=0; i<5; i++)
{
e[i].putdata();
}
}
NAMESPACE:
Namespaces – enable C++ programmer to prevent pollution of global namespace
that lead to name clashes.
Global namespace refer to the entire source code. It includes all the directly and
indirectly included header files. By default, name of each class is visible in the
source code i.e. in the global space. This can lead to problems.
Namespace is used to define a scope where identifiers like variables, functions,
classes, etc are declared. The main purpose of using a namespace is to prevent
ambiguity that may occur when two identifiers have same name.
Consider
A1.h A2.h
class A
{
//body of A
}; class A
{
//body of A
};
Main_prog.cpp
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
/*A1.h*/
namespace A1
{
class A
{
};
} /*end of namespace A1.h*/ /*A2.h*/
namespace A2
{
class A
{
};
} /*end of namespace A2.h*/
The using directive enable us to make class definition inside A namespace visible
so that qualifying the name of referred Class by name of namespace is no longer
required. Code below tells how this is done.
#include ―A1.h‖ #include ―A2.h‖ void main()
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
{
using namespace A1;
A1::A Aobj1; //ok: Aobj1 is an object of class defined in A1.h
A2::A Aobj2; //ok: Aobj2 is an object of class defined in A1.h
}
Rules for namespace:
➢ Namespace declarations appear only at global scope.
➢ Namespace declarations can be nested within another namespace.
➢ Namespace declarations don‟t have access specifiers. (Public or private)
➢ No need to give semicolon after the closing brace of definition of
namespace.
CONSTRUCTORS:
A class constructor is a special member function of a class that is executed
whenever we create new objects of that class. Constructors can be very useful for
setting initial values for certain member variables.
Constructors are special class functions which performs initialization of every
object. The Compiler calls the Constructor whenever an object is created.
Characteristics of a constructor
➢ They should be declared in the public section.
➢ They are invoked directly when an object is created.
➢ They don‟t have return type, not even void and hence can‟t return any
values.
➢ They can‟t be inherited; through a derived class, can call the base class
constructor.
➢ Like other C++ functions, they can have default arguments.
➢ Constructors can‟t be virtual.
➢ Constructors can be inside the class definition or outside the class
definition.
➢ Constructor can‟t be friend function.
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
➢ They make implicit calls to the operators new and delete when memory
allocation is required.
➢ When a constructor is declared for a class, initialization of the class
objects becomes necessary after declaring the constructor.
Default Constructor:-
Default Constructor is also called as Empty Constructor which has no arguments
and It is Automatically called when we creates the object of class but Remember
name of Constructor is same as name of class and Constructor never declared
with the help of Return Type.
class Add
{
int x, y, z;
public:
Add(); // Default Constructor
void display(void);
};
Add::Add()
{
x=6;
y=5;
}
void Add :: display()
{
cout<< x+y;
}
void main()
{
Add a;
a.display();
}
Output:
11
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
Parameterized Constructor:-
This is Another type Constructor which has some Arguments and same name as
class name .We have to create object of Class by passing some Arguments at the
time of creating object with the name of class.
class Add
{
Int x, y, z;
public:
Add(int, int);
void display(void);
};
Add :: Add(int a, int b)
{
x=a;
y=b;
}
void Add :: display()
{
cout<<x+y;
}
void main()
{
Add a(5, 6);
a.display();
}
Output:
11
A parameterized constructor can be called:
(i) Implicitly: Add a(5, 6);
(ii) Explicitly : Add a=Add(5, 6);
Copy Constructor:-
This is also Another type of Constructor. In this Constructor we pass the object
of class into the Another Object of Same Class. As name Suggests you Copy,
means Copy the values of one Object into the another Object of Class .
When we are using or passing an Object to a Constructor then we must have to
use the & Ampersand or Address Operator.
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
class Add
{
int x, y, z;
public:
Add(int a, int b)
{
x=a;
y=b;
}
Add(Add &);
void display(void);
};
Add :: Add(Add &p)
{
x=p.x;
y=p.y;
cout<<‖Value of x and y for new object: ‖<<x<<‖ and
‖<<y<<endl;
}
void Add :: display()
{
cout<<x+y;
}
void main()
{
Add a(5, 6);
Add b(a);
b.display();
}
Output:
Value of x and y for new object are 5 and 6 11
DESTRUCTORS
➢ It is a special member function which is executed automatically when an
object is destroyed.
➢ Its name is same as class name but it should be preceded by the symbol ~.
➢ It cannot be overloaded as it takes no argument.
➢ It is used to delete the memory space occupied by an object.
➢ It has no return type.
➢ It should be declared in the public section of the class.
[Type here]
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
class A
{
A()
{
cout << "Constructor called";
}
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
NESTED CLASSES:
A class can be defined inside another class. Such a class is known as Nested Class.
The class that contains the nested class is known as enclosing class. Nested
classes can be defined in the private, protected, or public sections of the enclosing
class.
➢ A nested class is declared inside another class.
➢ The scope of inner class is restricted by the outer class.
➢ While declaring an object of inner class, the name of the inner class
must be preceded by the outer class name and scope resolution operator.
A nested class is created if it does not have any relevance outside its enclosing
class. By defining class as a nested class, name collision can be avoided. That is,
if there is class B defined as global class, its name will not clash with the nested
class B. The size of the object of an enclosing class is not affected by the presence
of nested classes.
8
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
void A :: B :: BTest()
{
//function body
}
#include <iostream.h>
class Nest
{ public:
class Display
{ private:
int s;
public:
9
RV Institute of Technology & Management®
10
RV Institute of Technology & Management®
INTRODUCTION TO JAVA
Java Byte Code:
11
RV Institute of Technology & Management®
Translating a Java program into bytecode makes it much easier to run a program
in a wide variety of environments because only the JVM needs to be
implemented for each platform. Once the run-time package exists for a given
system, any Java program can run on it.
Bytecode is the compiled format for Java programs. Once a Java program has
been converted to bytecode, it can be transferred across a network and executed
by Java Virtual Machine (JVM). Bytecode files generally have a .class
extension.
A method's bytecode stream is a sequence of instructions for the Java virtual
machine. Each instruction consists of a one-byte opcode followed by zero or
more operands. Rather than being interpreted one instruction at a time, Java
12
RV Institute of Technology & Management®
Java Development Kit contains two parts. One part contains the utilities like
javac, debugger, jar which helps in compiling the source code (.java files) into
byte code (.class files) and debug the programs. The other part is the JRE,
which contains the utilities like java which help in running/executing the byte
code. If we want to write programs and run them, then we need the JDK
installed.
Java Run-time Environment helps in running the programs. JRE contains the
JVM, the java classes/packages and the run-time libraries. If we do not want to
write programs, but only execute the programs written by others, then JRE
alone will be sufficient.
Java Virtual Machine is important part of the JRE, which actually runs the
programs (.class files), it uses the java class libraries and the run-time libraries
to execute those programs. Every operating system(OS) or platform will have
a different JVM.
13
RV Institute of Technology & Management®
JIT is a module inside the JVM which helps in compiling certain parts of byte
code into the machine code for higher performance. Note that only certain parts
of byte code will be compiled to the machine code, the other parts are usually
interpreted and executed.
Java is distributed in two packages - JDK and JRE. When JDK is installed it
also contains the JRE, JVM and JIT apart from the compiler, debugging tools.
When JRE is installed it contains the JVM and JIT and the class libraries. javac
helps in compiling the program and java helps in running the program. When the
words Java Compiler, Compiler or javac is used it refers to javac, when the
words JRE, Run-time Enviroment, JVM, Virtual Machine are used, it refers
to java.
Simple
Java was designed to be easy for the professional programmer to learn and use
effectively. If you already understand the basic concepts of object-oriented
programming like C++, learning Java will be even easier.
Object Oriented:
In Java, everything is an Object. The object model in Java is simple and easy to
extend, while primitive types, such as integers, are kept as high-performance non-
objects.
Platform Independent:
Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted
by the Virtual Machine (JVM) on whichever platform it is being run on.
15
RV Institute of Technology & Management®
To better understand how Java is robust, consider two of the main reasons for
program failure: memory management mistakes and mishandled exceptional
conditions. For example, in C/C++, the programmer must manually allocate and
free all dynamic memory. This sometimes leads to problems, because
programmers will either forget to free memory that has been previously allocated
or, worse, try to free some memory that another part of their code is still using.
Java virtually eliminates these problems by managing memory allocation and de-
allocation for you. Java helps in this area by providing object- oriented exception
handling.
Interpreted: Java byte code is translated on the fly to native machine instructions
and is not stored anywhere. The development process is more rapid and analytical
since the linking is an incremental and light-weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet. Java
also supports Remote Method Invocation (RMI). It handles TCP/IP protocols.
Dynamic: Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry extensive
amount of run-time information that can be used to verify and resolve accesses to
objects on run-time.
16
RV Institute of Technology & Management®
James Gosling initiated Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called ‗Oak‘ after an oak tree
that stood outside Gosling's office, also went by the name ‗Green‘ and ended up
later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised
Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
Three OO Concepts:
• Encapsulation
• Inheritance
• Polymorphism
Encapsulation
Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse. It acts as
a protective wrapper that prevents the code and data from being arbitrarily
accessed by other code defined outside the wrapper. Access to the code and data
inside the wrapper is tightly controlled through a well-defined interface.
17
RV Institute of Technology & Management®
When you create a class, you will specify the code and data that constitute that
class. Collectively, these elements are called members of the class. Specifically,
the data defined by the class are referred to as member variables or instance
variables. The code that operates on that data is referred to as member methods
or just methods.
Inheritance
Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical
classification.
The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
18
RV Institute of Technology & Management®
Since mammals are simply more precisely specified animals, they inherit all of
the attributes from animals. A deeply inherited subclass inherits all of the
attributes from each of its ancestors in the class hierarchy.
Polymorphism
19
RV Institute of Technology & Management®
Example: Consider a stack (which is a last-in, first-out list). You might have a
program that requires three types of stacks. One stack is used for integer values,
one for floating-point values, and one for characters. The algorithm that
implements each stack is the same, even though the data being stored differs.
Java Basics
• Object - Objects have states and behaviours. Example: A dog has states
- colour, name, breed as well as behaviour such as wagging their tail,
barking, eating. An object is an instance of a class.
21
RV Institute of Technology & Management®
This line outputs the string ―This is a simple Java program.‖ followed by a new
line on the
screen. In this case, println( )displays the string which is passed to it.
System is a predefined class that provides access to the system, and out is the
output stream that is connected to the console.
DATATYPES
Data Default
Range
Type size
Boolean False/ true 1 bit
char 0-65536 2 byte
byte –128 to 127 1 byte
short –32,768 to 32,767 2 byte
int –2,147,483,648 to 2,147,483,647 4 byte
–9,223,372,036,854,775,808 to
long 8 byte
9,223,372,036,854,775,807
float 1.4e–045 to 3.4e+038 4 byte
double 4.9e–324 to 1.8e+308 8 byte
22
RV Institute of Technology & Management®
Output would be
Value of char variable ch1 is :a
Value of char variable ch2 is :A
• Byte are useful when you‘re working with raw binary data that may not
be directly compatible with Java‘s other built-in types.
byte b1 = 100;
byte b2 = 20;
Output would be
Value of byte variable b1 is :100
Value of byte variable b1 is :20
23
RV Institute of Technology & Management®
boolean b1 = true;
boolean b2 = false;
boolean b3 = (10 > 2)? true:false;
import java.util.*;
23
RV Institute of Technology & Management®
Output would be
Value of double variable f is :1232.44
Java Literals
For example:
byte a = 68;
char a = 'A'
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using
these number systems for literals. For example:
String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes. Examples of
string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For
example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals
as well. They are:
24
RV Institute of Technology & Management®
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined
by the combination of an identifier, a type, and an optional initializer. Each
variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory;
Declaring a Variable
Local Variables
• Local variables are declared in methods, constructors, or blocks.
• Local variables are implemented at stack level internally.
25
RV Institute of Technology & Management®
Class/static Variables
• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless
of how many objects are created from it.
• Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
Dynamic Initialization
Here, three local variables—a, b, and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of the
hypotenuse
Java allows variables to be declared within any block. A block defines a scope.
Thus, each time you start a new block, you are creating a new scope. A scope
determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
26
RV Institute of Technology & Management®
As a general rule, variables declared inside a scope are not visible (that is,
accessible) to code that is defined outside that scope. Thus, when you declare a
variable within a scope, you are localizing that variable and protecting it from
unauthorized access and/or modification.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Output
x and y: 10 20
x is 22
• Widening Casting(Implicit)
27
RV Institute of Technology & Management®
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
The two types are compatible. The destination type is larger than the source type.
Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.
Ex:
long l;
int i;
l=i;
28
RV Institute of Technology & Management®
}
Output :
Double value 100.04
Long value 100
Int value 100
The result of the intermediate term a * b easily exceeds the range of either of its
byte operands. To handle this kind of problem, Java automatically promotes each
byte, short, or char operand to int when evaluating an expression. This means that
the sub expression a*b is performed using integers—not bytes. Thus, 2,000, the
result of the intermediate expression, 50 * 40, is legal even though a and b are
both specified as type byte.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
byte b = 50;
b = (byte)(b * 2); //which yields the correct value of 100.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
29
RV Institute of Technology & Management®
}
}
Output: will be of double data type
ARRAYS
One-Dimensional Arrays
A one-dimensional array is essentially, a list of like-typed variables. To create an
array, you first must create an array variable of the desired type. The general form
of a one-dimensional
array declaration is:
datatype identifier [ ];
Or
datatype[ ] identifier;
30
RV Institute of Technology & Management®
Arrays can be initialized when they are declared. There is no need to use new.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Output:
April has 30 days
Multidimensional Arrays
Ex:
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
31
RV Institute of Technology & Management®
Ex:
String[][] sampleData = { {"a", "b", "c", "d"}, {"e", "f", "g", "h"}, {"i", "j",
"k", "l"},
{"m", "n", "o", "p"} };
OPERATORS IN JAVA
Java provides a rich operator environment. Java provides a rich set of operators
to manipulate variables. We can divide all the Java operators into the following
groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Ternary Operator and
Assignment Operator.
32
RV Institute of Technology & Management®
Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instance of
Equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
Ternary ?:
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and
division—all behave as you would expect for all numeric types.
• The unary minus operator negates its single operand.
• The unary plus operator simply returns the value of its operand.
class OperatorExample{
public static void main(String args[]){ int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output
15
5
50
2
0
33
RV Institute of Technology & Management®
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
x mod 10 = 2
y mod 10 = 2.25
34
RV Institute of Technology & Management®
The relational operators determine the relationship that one operand has to the
other. The outcome of these operations is a boolean value. The relational
operators are most frequently used in the expressions that control the if statement
and the various loop statements.
operator Description
== Check if two operands are equal
!= Check if two operands are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
The Boolean logical operators shown here operate only on boolean operands and
relational expressions. All of the binary logical operators combine two boolean
values to form a resultant boolean value. The logical Boolean operators, &, |, and
^, operate on boolean values in the same way that they operate on the bits of an
integer.
Table 2:Logical Operators
For example, the following code fragment shows how you can take advantage
of short-circuit logical evaluation to be sure that a division operation will be
valid before evaluating it:
Since the short-circuit form of AND (&&) is used, there is no risk of causing a
run-time exception when denom is zero. If this line of code was written using
the single ―&‖ version of AND, both sides would have to be evaluated, causing
a run-time exception when denom is zero.
class ShortCircuitAnd
{
public static void main(String arg[])
{
int c = 0, d = 100, e = 50; // LINE A
if( c == 1 && e++ < 100 )
{
d = 150;
}
System.out.println("e = " + e );
}
}
OUTPUT
e = 50
36
RV Institute of Technology & Management®
operator description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
>>> Right Shift zero fill
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise X-OR assignment
>>>= Shift right zero fill assignment
>>= Shift right assignment
<<= Shift left assignment
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
37
RV Institute of Technology & Management®
Output:
false
10
false
11
The logical || operator doesn't check second condition if first condition is true. It
checks second condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is
true or false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c); //true || true = true
38
RV Institute of Technology & Management®
true
true
true
10
true
11
class OperatorExample
{
public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
}
>>> is also known as Unsigned Right Shift. For example, if you are shifting
something that does not represent a numeric value, you may not want sign
extension to take place. This situation is common when you are working with
pixel-based values and graphics. In these cases, you will generally want to shift a
zero into the high-order bit no matter what its initial value was. This is known as
an unsigned shift.
int x = 13 >>> 1;
Out put : 6
// 13 =
00000000000000000000000000001101
// 6 = 00000000000000000000000000000110
y = -8 >>> 2;
Output : 1073741822 // -8 =
11111111111111111111111111111000
39
RV Institute of Technology & Management®
The following code fragment demonstrates the >>>. Here, a is set to –1, which
sets all 32 bits to 1 in binary. This value is then shifted right 24 bits, filling the
top 24 bits with zeros, ignoring normal sign extension. This sets a to 255.
int a = -1;
a = a >>> 24;
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For nagative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Output
5
5
-5
1073741819
40
RV Institute of Technology & Management®
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Output
a=2
b=3
c=4
d=1
CONTROL STATEMENTS
41
RV Institute of Technology & Management®
If- else:
The if statement is Java‘s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if
statement:
if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed
in curly braces (that is, a block). The condition is any expression that returns a
boolean value. The else clause is optional.
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are
very common in programming. When you nest ifs, the main thing to remember is
that an else statement always refers to the nearest if statement that is within the
same block as the else and that is not already associated with an else.
Syntax :
if (condition)
{
if (condition){
//Do something
}
//Do something
}
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d;
42
RV Institute of Technology & Management®
Syntax: if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
public class ControlFlowDemo
{
public static void main(String[] args)
{
char ch = 'o';
Switch
The switch statement is Java‘s multiway branch statement. It provides an easy
way to dispatch execution to different parts of your code based on the value of an
expression. As such, it often provides a better alternative than a large series of if-
else-if statements. Here is the general form of a switch statement:
43
RV Institute of Technology & Management®
expression must be of type byte, short, int, char, or enumerated data type(
String).
class StringSwitch {
public static void main(String args[]) {
String str = "two";
switch(str)
{
case "one":
System.out.println("one");
break;
case "two":
System.out.println("two");
break;
case "three":
System.out.println("three");
break;
default:
System.out.println("no match");
break;
}}}
Output : two
44
RV Institute of Technology & Management®
Iteration Statements
Java‘s iteration statements are for, while, and do-while. These statements create
what we commonly call loops. As you probably know, a loop repeatedly executes
the same set of instructions until a termination condition is met. As you will see,
Java has a loop to fit any programming need.
while
The while loop is Java‘s most fundamental loop statement. It repeats a
statement or block
while its controlling expression is true. Here is its general form:
while(condition)
45
RV Institute of Technology & Management®
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long
as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop.
Example:
class WhileLoopExample{
public static void main(String[] args){
int num=0;
while(num<=5){
System.out.println(""+num);
num++;
}
}
}
do-while
The do-while loop always executes its body at least once, because its
conditional expression is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will
repeat. Otherwise, the loop terminates. As with all of Java‘s loops, condition must
be a Boolean expression.
The do-while loop is especially useful when you process a menu selection,
because you will
usually want the body of a menu loop to execute at least once.
class Menu {
public static void main(String args[])
{
char choice;
46
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
do
{
System.out.println("Help on: ");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" //...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
47
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
}
}
}
For:
There are two forms of the for loop.
The first is the traditional form that has been in use since the original version of
Java. The second is the newer ―for-each‖ form.
Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection(array), one at a
time, from beginning to end. The collection being cycled through is
specified by collection.
Ex : int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
48
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
49
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Jump Statements
Using break
In Java, the break statement has three uses. First, as you have seen, it
terminates a statement sequence in a switch statement. Second, it can be used to
exit a loop. Third, it can be used as a ―civilized‖ form of goto.
1) Using break to Exit a Loop
2) Using break as a Form of Goto:
Java does not have a goto statement because it provides a way to branch in
an arbitrary and unstructured manner. This usually makes goto-ridden code
hard to understand and hard to maintain.
public class BreakDemo
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // terminate loop if i is 5
}
System.out.print(i + " ");
}
System.out.println("Thank you.");
}
}
Output 1 2 3 4 Thank you
Using continue
In while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop. In a for loop, control
goes first to the iteration portion of the for statement and then to
50
RV Institute of Technology & Management®
MODULE 2 : CLASS AND OBJECTS (CONTD) OOC-18CS45
the conditional expression. For all three loops, any intermediate code is
bypassed.
Break Continue
The break statement results in the The continue statement stops the
termination of the loop, it will come current execution of the iteration and
out of the loop and stops further proceeds to the next iteration
iterations.
The break statement has two forms: The continue statement skips the
labelled and current iteration of a for, while , or do-
unlabelled. while loop. The unlabelled form skips
An unlabelled break statement to the end of the innermost loop's body
terminates the innermost switch, for, and evaluates the Boolean expression
while, or do-while statement, but a that controls the loop.
labelled break terminates an outer A labelled continue statement skips the
statement. current iteration of an outer loop
marked with the given label.
The general form of the labelled break The general form of the labelled
statement is shown here: continue statement is shown here:
break label; continue label;
class Break { class ContinueLabel {
public static void main(String args[]) { public static void main(String args[]) {
boolean t = true; outer: for (int i=0; i<4; i++)
first: { second: { {
third: { for(int j=0; j<4; j++)
System.out.println("Before the {
break."); if(j > i)
51
MODULE 1 : INTRODUCTION TO OBJECT ORIENTED CONCEPTS OOC-18CS45
if(t) {
break second; // break out of second System.out.println();
block continue outer;
System.out.println("This won't }
execute"); System.out.print(" " + (i * j));
} }
System.out.println("This won't }
execute"); System.out.println();
} }
System.out.println("This is after }
second block.");}}}
Output: 0
Before the break. 01
This is after second block. 024
0369
Return
The last control statement is return. The return statement is used to explicitly return
from a method. That is, it causes program control to transfer back to the caller of the
method. As such, it is categorized as a jump statement.
At any time in a method, the return statement can be used to cause execution
to branch back to the caller of the method. Thus, the return statement immediately
terminates the method in which it is executed.
class Return {
public static void main(String args[]) {
boolean t = true; System.out.println("Before
the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}