Lecture Notes: Module-2: Subject: Object Oriented Concepts Course Code: 18CS45 Semester: 4
Lecture Notes: Module-2: Subject: Object Oriented Concepts Course Code: 18CS45 Semester: 4
Prepared by:
Mr Nithin Kumar Heraje
Asst Professor
Dept of CSE.
Object Oriented Concepts MODULE 2 18CS45
Class and Objects (contd): Objects and arrays, Namespaces, Nested classes, Constructors, Destructors.
Introduction to Java: Java’s magic: the Byte code; Java Development Kit (JDK); the Java Buzzwords, Object-
oriented programming; Simple Java programs. Data types, variables and arrays, Operators, Control
Statements.
The class definition is self-explanatory. However, the comments indicate that it is better to
throw exceptions rather than terminate the function.
1.9 Namespaces
Namespaces enable the C++ programmer to prevent pollution of the global namespace that
leads to name clashes.
The term ‗global namespace‘ refers to the entire source code. It also includes all the directly
and indirectly included header files. By default, the name of each class is visible in the entire
source code, that is, in the global namespace.
Suppose a class with the same name is defined in two header files.
Now, let us include both these header ¿ les in a program and see what happens if we declare
an object of the class.
The global visibility of the definition of class A makes the inclusion of the two header ¿ les
mutually exclusive. Consequently, this also makes use of the two definitions of class A
mutually exclusive. How can this problem be overcome? How can we ensure that an
application is able to use both definitions of class A simultaneously? Enclosing the two
definitions of the class in separate namespaces overcomes this problem.
Now, the two definitions of the class are enveloped in two different namespaces. The
corresponding namespace, followed by the scope resolution operator, must be prefixed to the
name of the class while referring to it anywhere in the source code. Thus, the ambiguity
encountered in the above listing can be overcome.
1.11 Constructors
The constructor gets called automatically for each object that has just got created. It appears
as member function of each class, whether it is de¿ ned or not. It has the same name as that of
the class. It may or may not take parameters. It does not return anything (not even void). The
prototype of a constructor is
<class name> (<parameter list>);
Domain constraints on the values of data members can also be implemented via constructors.
For example, we want the value of data member inches of each object of the class Distance to
be between 0.0 and 12.0 at all times within the lifetime of the object. But this condition may
get violated in case an object has just got created. However, introducing a suitable constructor
to the class Distance can enforce this condition.
The compiler embeds a call to the constructor for each object when it is created. Suppose a
class A has been declared as follows:
Zero-argument Constructor
We can and should de¿ ne our own constructors if the need arises. If we do so, the compiler
does not de¿ ne the constructor. However, it still embeds implicit calls to the constructor as
before. The constructor is a non-static member function. It is called for an object. It,
therefore, takes the this pointer as a leading formal argument just like other non-static
member functions. Correspondingly, the address of the invoking object is passed as a leading
parameter to the constructor call. This means that the members of the invoking object can be
accessed from within the definition of the constructor.
Parameterized Constructors
Constructors take arguments and can, therefore, be overloaded. Suppose, for the class
Distance, the library programmer decides that while creating an object, the application
programmer should be able to pass some initial values for the data members contained in the
object. For this, he/she can create a parameterized constructor
Explicit Constructors
Constructors are declared explicit by prefixing their declarations with the explicit keyword.
Let us first look at the syntax for declaring an explicit constructor
Copy Constructor
The copy constructor is a special type of parameterized constructor. As its name implies, it
copies one object to another. It is called when an object is created and equated to an existing
object at the same time. The copy constructor is called for the object being created. The
preexisting object is passed as a parameter to it. The copy constructor member-wise copies
the object passed as a parameter to it into the object for which it is called.
The prototype and the definition of the default copy constructor defined by the compiler are
as follows
1.12 Destructors
The destructor gets called for each object that is about to go out of scope. It appears as a
member function of each class whether we de¿ ne it or not. It has the same name as that of
the class but prefixed with a tilde sign. It does not take parameters. It does not return anything
(not even void). The prototype of a destructor is
~<class name> ();
There is a need for a function that guarantees deinitialization of member data of a class and
frees up the resources acquired by the object during its lifetime, Destructors fulfil this need.
A user-defined destructor
Java’s Lineage
Java is related to C++, which is a direct descendant of C. Much of the character of
Java is inherited from these two languages. From C, Java derives its syntax. Many of Java‘s
object-oriented features were influenced by C++.
threshold at which a program becomes unmanageable. C++ added features that enabled this
threshold to be broken, allowing programmers to comprehend and manage larger programs.
,theprimarymotivationwastheneedforaplatform-independent(thatis,architecture-neutral)
languagethatcouldbeusedtocreatesoftwaretobeembeddedinvariousconsumerelectronic
devices,suchasmicrowaveovensandremotecontrols.
This second force was, of course, the World Wide Web. Had the Web not taken shape at
about the same time that Java was being implemented, Java might have remained a useful but
obscure language for programming consumer electronics. However, with the emergence of
the World Wide Web, Java was propelled to the forefront of computer language design,
because the Web, too, demanded portable programs.
The C# Connection
Perhaps the most important example of Java‘s influence is C#. Created by Microsoft to
support the .NET Framework, C# is closely related to Java. For example, both share the same
general syntax, support distributed programming, and utilize the same object model. There
are, of course, differences between Java and C#, but the overall ―look and feel‖ of these
languages is very similar. This ―cross-pollination‖ from Java to C# is the strongest
testimonialtodatethatJavaredefinedthewaywethinkaboutanduseacomputerlanguage.
Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the
Internet and automatically executed by a Java-compatible web browser. Furthermore, an
applet is downloaded on demand, without further interaction with the user. If the user clicks a
link that contains an applet, the applet will be automatically downloaded and run in the
browser. Applets are intended to be small programs. They are typically used to display data
provided by the server, handle user input, or provide simple functions, such as a loan
calculator, that execute locally, rather than on the server. In essence, the applet allows some
functionality to be moved from the server to the client.
Security
In order for Java to enable applets to be downloaded and executed on the client computer
safely, it was necessary to prevent an applet from launching such an attack.
JavaachievedthisprotectionbyconfininganapplettotheJavaexecutionenvironment and not
allowing it access to other parts of the computer. The ability to download applets with
confidence that no harm will be done and that no security will be breached is considered by
many to be the single most innovative aspect of Java.
Portability
If a Java program were to be run on virtually any computer connected to the Internet, there
needed to be some way to enable that program to execute on different systems.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use
effectively.
As Java inherits the C/C++ syntax and many of the object-oriented features of C++,
its easy to learn.
Object-Oriented
The object model in Java is simple and easy to extend, while primitive types, such as
integers, are kept as high-performance non objects.
Robust
the program must execute reliably in a variety of systems. To gain reliability, Java
restricts us to find mistakes early in program development.
As Java is a strictly typed language, it checks code at compile time. also checks code
at run time.
Java programmes behave in a predictable way under diverse conditions is a key
feature of Java.
Programs fail in 2 conditions, memory management mistakes and mishandled
exceptional conditions
Java virtually eliminates memory management problems by managing memory
allocation and deallocation automatically.
Exceptional conditions(run time errors) in Java is handled well by providing object
oriented exception handling
Multithreaded
Java programs can do many things simultaneously.
The Java run-time system supports multi process synchronization that enables to
construct smoothly running interactive systems.
Java‘s easy-to-use approach to multithreading allows to work on specific behavior of
the program, not the multitasking subsystem.
Architecture-Neutral
A central issue for the Java design was that of code longevity and portability.
As Operating system upgrades, processor upgrades, and changes in core system
resources can all combine to make a program malfunction. (same program will not
execute in different platforms)
Java Virtual Machine in an attempt to alter this situation. The goal is ―write once; run
anywhere, any time, forever.‖
Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. This code can be executed on any
system that implements the Java Virtual Machine.
the Java bytecode was carefully designed so that it would be easy to translate directly
into native machine code for very high performance by using a just-in-time compiler.
Distributed
Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.
Java supports Remote Method Invocation (RMI). This feature enables a program to
invoke methods across a network.
Dynamic
Java programs carry run-time type information that is used to verify and resolve
accesses to objects at run time.
This makes it possible to dynamically link code in a safe manner.
This is crucial to the robustness of the Java environment, in which small fragments of
bytecode may be dynamically updated on a running system.
Java SE 6
ThenewestreleaseofJavaiscalledJavaSE6. Java SE 6 builds on the base of J2SE 5, adding
incremental improvements. Java SE 6 adds no major features to the Java language proper, but
it does enhance the API libraries, add several new packages, and offer improvements to the
run time.
Object-Oriented Programming
Object-orientedprogramming(OOP)isatthecoreofJava.Infact,allJavaprogramsaretoat least
some extent object-oriented. OOPis so integral to Java that it is best to understand its
basicprinciplesbeforeyoubeginwritingevensimpleJavaprograms.
Two Paradigms
All computer programs consist of two elements: code and data. Furthermore, a program can
be conceptually organized around its code or around its data.
The first way is called the process-oriented model. This approach characterizes a program as
a series of linear steps (that is, code). The process-oriented model can be thought of as code
acting on data. Procedural languages such as C employ this model to considerable success.
Tomanageincreasingcomplexity,thesecondapproach,called object-orientedprogramming, was
conceived. Object-oriented programming organizes a program around its data (that is,
objects) and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code.
Abstraction
An essential element of object-oriented programming is
abstraction.Apowerfulwaytomanageabstractionisthroughtheuseofhierarchicalclassifications.
This allows you to layer the semantics of complex systems, breaking them into more
manageable pieces.
2. Inheritance
Inheritance is the process by which one object acquires the properties of another
object.Adeeplyinheritedsubclassinheritsalloftheattributesfromeachofitsancestors in the class
hierarchy.Ifyouwantedtodescribeamorespecificclassofanimals,suchasmammals,theywould
have more specific attributes, such as type of teeth, and mammary glands. This is known as a
subclass of animals, where animals are referred to as mammals‘ superclass.
3. Polymorphism
Polymorphism (from Greek, meaning ―many forms‖) is a feature that allows one interface to
be used for a general class of actions.More generally, the concept of polymorphism is often
expressed by the phrase ―one interface, multiple methods.‖ This means that it is possible to
design a generic interface to a group of related activities. This helps reduce complexity by
allowing the same interface to be used to specify a general class of action. It is the compiler‘s
job to select the specific action (that is, method) as it applies to each situation.
A First Simple Program
/*
This line begins the main( ) method. This is the line at which the program will begin
executing. All Java applications begin execution by calling main( ).
The public keyword is an access specifier, which allows the programmer to control
the visibility of class members.
When a class member is preceded by public, then that member may be accessed by
code outside the class in which it is declared.
main( ) must be declared as public, since it must be called by code outside of its class
when the program is started.
The keyword static allows main( ) to be called without having to instantiate a
particular instance of the class. This is necessary since main( ) is called by the Java
Virtual Machine before any objects are made.
The keyword void tells the compiler that main( ) does not return a value.
String args[ ] declares a parameter named args, which is an array of instances of the
class String.
args receives any command-line arguments present when the program is executed.
System.out.println("This is a simple Java program.");
Output is actually accomplished by the built-in println( ) method, 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.
any place that a single statement can. For example, a block can be a target for Java‘s if
and for statements.
if(x < y)
{ // begin a block
x = y;
y = 0;
} // end
Lexical Issues
Javaprogramsareacollectionofwhitespace,identifiers,literals, comments, operators,
separators, and keywords.
Whitespace
Java isafree-formlanguage.Thismeansthatyoudonotneedtofollowanyspecialindentation
rules.In Java, whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. They must not begin with a number, lest they be confused with a
numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value.
Literals
A constant value in Java is created by using a literal representation of it.For example,
100, 98.6, 'X', "This is a test"
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is
acharacterconstant,andthelastisastring.Aliteralcanbeusedanywhereavalueofitstype is allowed.
Comments
As mentioned ,there are three types of comments defined by Java. We have already seen two:
single-lineandmultiline.Thethirdtypeiscalledadocumentationcomment.Thistypeofcomment
isusedtoproduceanHTMLfilethatdocumentsyourprogram.Thedocumentationcomment begins
with a /**and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon. As you have seen, it is used to terminate statements. The
separators are shown in the following table:
Integers This group includes byte, short, int, and long, which are for whole-valued
signed numbers
Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
Characters This group includes char, which represents symbols in a character set, like
letters and numbers
Boolean This group includes boolean, which is a special type for representing
true/false values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions
thatrequirefractionalprecision. There are two kindsoffloating-pointtypes,
floatanddouble,whichrepresentsingle-anddouble-precision numbers, respectively. Their width
and ranges are shown here:
Characters
InJava,thedatatypeusedtostorecharactersis char. Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent all of the characters
found in all human languages.For this purpose, it requires 16 bits. Thus, in Java char is a 16-
bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127 as always, andthe extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255.
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, as in the
case of a < b. boolean is also the type required by the conditional expressions that govern the
control statements such as if and for.
Integer Literals
Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values,
meaning they are describing a base 10 number. There are two other bases which can be used
inintegerliterals,octal(baseeight)andhexadecimal(base16).OctalvaluesaredenotedinJava
byaleadingzero.Normaldecimalnumberscannothavealeadingzero.You signify a hexadecimal
constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A
through F (or a through f ) are substituted for 10 through 15. Integer literals create an int
value, which in Java is a 32-bit integer value.
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They can be
expressedineitherstandardorscientificnotation.Standardnotationconsistsofawholenumber
componentfollowedbyadecimalpointfollowedbyafractionalcomponent.Forexample,2.0,
3.14159,and0.6667representvalidstandard-notationfloating-pointnumbers.Scientificnotation
uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by
which the number is to be multiplied. The exponent is indicated by an E or e followed by a
decimalnumber,whichcanbepositiveornegative.Examplesinclude6.022E23,314159E–05, and
2e+100. Floating-point literals in Java default to double precision. To specify a float literal,
you must append an F or f to the constant.
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have,
trueandfalse.Thevaluesoftrueandfalsedonotconvertintoanynumericalrepresentation.
ThetrueliteralinJavadoesnotequal1,nordoesthefalseliteralequal0.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values.
Aliteralcharacter isrepresentedinsideapairofsinglequotes.
String Literals
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.
Variables
The variable is the basic unit of storage in a Java program. Avariable is defined by the
combinationofanidentifier,atype,andanoptionalinitializer.Inaddition,allvariableshave a scope,
which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java‘s atomic types, or the name of a class or interface. The identifier is
the name of the
variable.Todeclaremorethanonevariableofthespecifiedtype,useacommaseparated list.
Dynamic Initialization
Here is a short program that computes the length of the hypotenuse of a right triangle given
the lengths of its two opposing sides:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
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.
Sofar,allofthevariablesusedhavebeendeclaredatthestartofthemain()method.However, Java
allows variables to be declared within any block.block is begun with an opening curly brace
and ended by a closing curly brace. Ablock defines a
scope.Thus,eachtimeyoustartanewblock,youarecreatinganewscope.Ascopedetermines what
objects are visible to other parts of your program. It also determines the lifetime of those
objects.
In Java, the two major scopes are those defined by a class and those defined by a method.
Adifferent type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. As you know, integers do not have fractional components. Thus, when a
floating-point value is assigned to an integer type, the fractional component is lost. For
example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The
0.23 will have been truncated.
In an expression, the precision required of an intermediate value will sometimes exceed the
range of either operand. For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a*beasily exceeds the range of either of its byte operands.
To handle this kind of problem, Java automatically promotes each byte, short,
orcharoperandtointwhenevaluatinganexpression. Thismeansthatthesubexpressiona*b
isperformedusingintegers—notbytes. Thus,2,000,theresultoftheintermediateexpression, 50
*40,islegaleventhoughaandbarebothspecifiedastypebyte.
Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of
anytypecanbecreatedandmayhaveoneormoredimensions.Aspecificelementinanarray is
accessed by its index. Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
Aone-dimensionalarrayis,essentially,alistoflike-typedvariables.Tocreateanarray,youfirst must
create an array variable of the desired type. The general form of a one-dimensional array
declaration is
type var-name[ ];
Here,typedeclaresthebasetypeofthearray.Thebasetypedeterminesthedatatypeofeach element
that comprises the array. Thus, the base type for the array determines what type of data the
array will hold.
Ex: int month_days[];
Thisexampleallocates a 12-element array of integers and links them to month_days.
month_days = new int[12];
Putting together all the pieces, here is a program that creates an array of the number of days
in each month.
// Demonstrate a one-dimensional array.
class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Multidimensional Arrays
InJava,multidimensionalarraysareactuallyarraysofarrays.. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For
example, the following declares a twodimensional array variable called twoD.
inttwoD[][] = new int[4][5];
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
intal[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
The String type is used to declare string variables. You can also declare arrays of strings.
Aquoted string constant can be assigned to a String variable. Avariable of type String canbe
assigned to another variable of type String. You can use an object of type String as an
argument to println( ). For example, consider the following fragment:
String str = "this is a test";
System.out.println(str);
Here, str is an object of type String. It is assigned the string ―this is a test‖. This string is
displayed by the println( ) statement.
Operators
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical.
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The outcome of these operations is a
boolean value.
The relational operators are shown here:
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that
they operate on the bits of an integer. The logical ! operator inverts the Boolean state:
!true==falseand!false==true.Thefollowingtableshowstheeffectofeachlogicaloperation:
The ? Operator
Javaincludesaspecialternary(three-way)operatorthatcanreplacecertaintypesofif-then-else
statements. This operator is the ?.The ? has this general form:
expression1 ? expression2 : expression3
Operator Precedence
The following table shows the order of precedence for Java operators, from highest to lowest
Using Parentheses
Parenthesesraisetheprecedenceoftheoperationsthatareinsidethem.
Considerthefollowingexpression:
a >> b + 3
Thisexpressionfirstadds3tobandthenshiftsarightbythatresult.Thatis,thisexpression
canberewrittenusingredundantparentheseslikethis:
a >> (b + 3)
Control Statements
Aprogramming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program. Java‘s program control statements can
be put into the following categories: selection, iteration, and jump. Selection statements allow
your program to choose different paths of execution based upon the outcome of an expression
or the state of a variable. Iteration statements enable program execution to repeat one or more
statements (that is, iteration statements form loops). Jump statements allow your program to
execute in a nonlinear fashion.
Nested ifs
Anestedifisanifstatementthatisthetargetofanother iforelse.Nestedifsareverycommon 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.
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; // this else refers to if(i == 10)
...
else statement;
Theifstatementsareexecutedfromthetopdown.Assoonasoneoftheconditionscontrolling the if is
true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will be executed. The final else
acts as a default condition;
Switch
TheswitchstatementisJava‘smultiwaybranchstatement.Itprovidesaneasywaytodispatch
executiontodifferentpartsofyourcodebasedonthevalueofanexpression.
Hereisthegeneralform ofaswitchstatement:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
default:
// default statement sequence
}
Iteration Statements
Java‘s iteration statements are for, while, and do-while. These statements create what we
commonly call loops.
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)
{
// 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. The curly braces are unnecessary if only a
single statement is being repeated.
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);
Eachiterationofthedo-whileloopfirstexecutesthebodyoftheloopandthenevaluates
theconditionalexpression.Ifthisexpressionistrue,theloopwillrepeat.Otherwise,theloop
terminates.
For
Thefirstisthetraditionalform
thathasbeeninusesincetheoriginalversionofJava.Thesecondisthenew―for-each‖form.
Bothtypesofforloopsarediscussedhere,beginningwiththetraditionalform. Here is the general
form of the traditional for statement:
for(initialization; condition; iteration)
{
// body
}
Jump Statements
Javasupportsthreejumpstatements: break,continue,andreturn.Thesestatementstransfer
controltoanotherpartofyourprogram.
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.
Using continue
Sometimesitisusefultoforceanearlyiterationofaloop.Thatis,youmightwanttocontinue
runningtheloopbutstopprocessingtheremainderofthecodeinitsbodyforthisparticular
iteration..The continue statement performs such an action.
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(inti=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0)
continue;
System.out.println("");
}
}
}
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.
QUESTION BANK