Module 1 Java
Module 1 Java
(BCS306A)
MODULE 1
An Overview of Java:
Introduction to JAVA:
1. Java was originally designed for interactive television.
2. Java was developed by James Gosling
3. Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.
5. In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
6. Java is just a name, not an acronym.
Java has become a popular and useful programming language because of its excellent features,
which play a very important role in contributing to the popularity of this language. The Java
features are called “Java BuzzWords”.
Simple:
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Micro Systems, Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object Oriented:
Java strongly supports the concepts of Object-Oriented Programming due to which it is
called a pure object-oriented language.
Java supports major Object-Oriented programming features like Encapsulation,
Abstraction, and Inheritance.
Almost everything in Java is an object. All programs and data live within objects and
classes. ‘Objects’ model Java rather than the ‘processes’. Java comes with an extensible
set of classes organized in packages.
Platform Independent:
The most significant feature of Java is that it provides platform independence which
leads to a facility of portability, which ultimately becomes its biggest strength.
Being platform-independent means a program compiled on one machine can be
executed on any machine in the world without any change.
Java achieves platform independence by using the concept of the BYTE CODE.
The Java compiler never converts the source code to machine code like that of the C/C++
compiler.
Instead, it converts the source code into an intermediate code called the byte code and
this byte code is further translated to machine-dependent form by another layer of
software called JVM (Java Virtual Machine).
Intrepreted:
Usually, a computer language can be either compiled or interpreted. Java integrates
the power of Compiled Languages with the flexibility of Interpreted Languages.
Java compiler (javac) compiles the java source code into the bytecode.
Java Virtual Machine (JVM) then executes this bytecode which is executable on many
operating systems and is portable. The diagram below shows the above process
Secured:
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox-A separate environment
that allows users to execute their applications without affecting the underlying
system.
It has a bytecode verifier that checks the code fragments for any illegal code
that violates the access right.
Portable:
Java is portable because it facilitates the programmer to carry the Java bytecode to any
platform.
In Java, the size of the primitive data types is machine-independent, which were
dependent in the case of C/C++. So, these provisions make Java programs portable
among different platforms such as Windows, Unix, Solaris, and Mac.
Moreover, any changes and updates made in Operating Systems, Processors and System
resources will not enforce any changes in Java programs.
Architecture Neutral:
This buzzword means that the program written on one platform or OS
is independent of other platforms or environments and can run on any other Operating
System without recompiling them.
In other words, it is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-
run-everywhere’ (WORE) approach.
Byte-code is not dependent on any machine architecture and Java Virtual Machine
(JVM) can easily translate bytecode into a machine-specific code.
Robust:
Robust simply means strong.
Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Dynamic:
Java is dynamic and extensible means with the help of OOPs, we can add classes and
add new methods to classes, creating new classes through subclasses. This makes it
easier for us to expand our own classes and even modify them.
Java gives the facility of dynamically linking new class libraries, methods, and objects.
It is highly dynamic as it can adapt to its evolving environment.
Java even supports functions written in other languages such as C and C++ to be written
in Java programs. These functions are called “native methods”. These methods are
dynamically linked at runtime.
High Performance:
The performance of Java is impressive for an interpreted language because of its
intermediate bytecode.
Java provides high performance with the use of “JIT – Just In Time compiler”, in which
the compiler compiles the code on-demand basis, that is, it compiles only that method
which is being called. This saves time and makes it more efficient.
Java architecture is also designed in such a way that it reduces overheads during
runtime. The inclusion of multithreading enhances the overall execution speed of Java
programs.
Bytecodes generated by the Java compiler are highly optimized, so Java Virtual
Machine can execute them much faster.
Multi-Threaded:
A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Distributed:
Java is distributed because it encourages users to create distributed applications.
In Java, we can split a program into many parts and store these parts on different
computers.
A Java programmer sitting on a machine can access another program running on the
other machine. This feature in Java gives the advantage of distributed programming,
which is very helpful when we develop large projects.
Java helps us to achieve this by providing the concept of RMI (Remote Method
Invocation) and EJB (Enterprise JavaBeans).
Java comes with an extensive library of classes for interacting, using TCP/IP protocols
such as HTTP and FTP, which makes creating network connections much easier than
in C/C++
It also enables multiple programmers at many locations to work together on a single
project.
Two Paradigms:
Object Oriented:
Object oriented programs are written based on ―Who is being affected‖ around,
Baswanthrao Patil, Assistant Professor, CSE (AIML) 6
OOP With Java BCS306A
Inheritance:
Inheritance is the process by which one object acquires the properties of another
object. This is important as it supports the concept of hierarchical classification.
By the use of inheritance, a class has to define only those qualities that make it
unique. The general qualities can be derived from the parent class or base class.
Ex: A child inheriting properties from parents.
Polymorphism
Polymorphism (meaning many forms) is a feature that allows one interface to be used
for a general class of actions. The specific action determined by the exact nature of
the situation. This concept is often expressed as ― one interface, multiple methods‖.
Ex: ―+‖ can be used for addition of 2 numbers and also concatenation of 2 strings.
System.out.println(2+4); // outputs 6 as answer
System.out.println(―Hello‖ + ―Gautham‖); // outputs Hello Gautham as answer
Object:
An object can be any real world entity.
Ex: an animal, bank, human, box, fan etc
An object is a software bundle of related state and behavior.
An object is an instance of class.
Class:
A class is a blueprint or prototype from which objects are created.
Its just a template for an object, which describes an object.
Ex: a class describes how an animal looks like.
A class is a user defined data type.
Abstraction:
Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed information in
program without presenting the details.
Ex: a database system hides certain details of how data is stored and created and
maintained.
class Example
{
public static void main(String args[])
{
System.out.println(―Welcome to Programming in Java‖);
}
}
2. Save the above program with .java extension, here file name and class name
should be same,
ex: Example.java
3. Open the command prompt and Compile the above program
javac Example.java
From the above compilation the java compiler produces a bytecode(.class file)
4. Finally run the program through the
interpreter java Example.java
Output of th e program:
Welcome to Programming in Java
Note:
In Java all code must reside inside a class and name of that class should match the
name of the file that holds the program.
Java is case-sensitive
Description:
(1) Class declaration: ―class Example‖ declares a class, which is an object- oriented
construct. Sample one is a Java identifier that specifies the name of the class to
be defined.
(2) Opening braces: Every class definition of Java starts with opening braces and ends with
matching one.
(3) The main line: the line ― public static void main(String args[]) ― defines a method
name main. Java application program must include this main. This is the starting point
of the interpreter from where it starts executing. A Java program can have any number
of classes but only one class will have the main method.
(4) Public: This key word is an access specifier that declares the main method as
unprotected and therefore making it accessible to the all other classes.
(5) Static: Static keyword defines the method as one that belongs to the entire class and not
for a particular object of the class. The main must always be declared as static.
(6) Void: the type modifier void specifies that the method main does not return any value.
(7) The println: It is a method of the object out of system class. It is similar to the printf
or cout of c or c++. This always appends a newline character to the end of the string
i.e, any subsequent output will start on a new line.
The statement System.out.println(― the value of n is ―+n), the sign ―+‖ causes the value of
―n‖ to be appended to the string that preceeds it, and the resulting string is output.( Actually n is
first converted from an integer into its string equivalent and the concatenated with the string
that preceeds it)
The System.out.print( ) method is just like println( ) except that it does not output a newline
character after each call.
if statement
The if- statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluatesto
true.
Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
System.out.println(―a is positive number‖);
System.out.println(― End of program‖);
}
}
In the above program since a is greater than o it prints the output as a is
positive number
End of program
2
3
4
End of Program
Java supports code blocks - which means that two or more statements are grouped
into blocks of code.
Opening and closing braces is used to achieve this.
Each block is treated as logical unit.
Whenever two or more statements has to be linked blocks can be used.
Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
{ // begin of block
System.out.println(―a is positive number‖);
System.out.println(― inside block‖);
}// end of block
}
}
Lexical issues:
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace:
Java is a free from language- means no need to follow any indentation rules.
Whitespace is a space, tab, or newline.
Key Words:
Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statement contains an
expression that contains the action carried out on data. The compiler recognizes the tokens
for building up the expression and statements. Smallest individual units of programs are
known as tokens. Java language includes five types of tokens. They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
Reserved keyword:
Java language has 50 words as reserved keywords. They implement specific feature of the
language. The keywords combined with operators and separators according to syntax build
the Java language.
Identifiers:
Identifiers are programmer-designed token used for naming classes methods variable,
objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.
Literals:
Literals in Java are sequence of characters that represents constant values to be stored in
variables. Java language specifies five major types of Literals. They are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce an
result.
Separators:
Separators are the symbols that indicates where group of code are divided and arranged.Some
of the operators are:
Comments:
Java supports 3 styles of comments
Multiline comment: this type of comment begins with /* and ends with */
Ex: /* Welcome to
Java Programming */
Single line comments: this type of comment begins with // and ends at the end of
current line
Ex: // Welcome to java Programming
Documentation Comment: this type of comment is used to produce an HTML file that
documents your program. The documentation comment begins with /** andends
with */
Data types
The various data types supported in java is as follows
Data types
class
boolean interfaces
Integer Floating type
character string etc
byte float
short double
int
t
long i
v
e
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. As shown in above figure.
The primitive types represent single values—not complex objects. Although Java is
otherwise completely object-oriented, the primitive types are not.
They are analogous to the simple types found in most other non–object-oriented
languages.
The reason for this is efficiency. Making the primitive types into objects would have
degraded performance too much. The primitive types are defined to have an explicit
range and mathematical behavior.
Because of Java‗s portability requirement, all data types have a strictly defined range.
For example, an int is always 32 bits, regardless of the particular platform.
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.
Many other computer languages support both signed and unsigned integers.
However, Java‗s designers felt that unsigned integers were unnecessary. Specifically,
they felt that the concept of unsigned was used mostly to specify the behavior of
the high-order bit, which defines the sign of an integer value.
byte
The smallest integer type is byte.
This is a signed 8-bit type that has a range from –128 to127.
Variables of type byte are especially useful when you‗re working with a stream of
data from a network or file.
Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c: byte b, c;
short
short is a signed 16-bit type.
It has a range from –32,768 to 32,767.
It is probably the least-used Java type.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
For example, calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
There are two kinds of floating-point types, float and double, which represent
single- and double-precision numbers, respectively.
float
The type float specifies a single-precision value that uses 32 bits of storage.
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors
that have been optimized for high-speed mathematical calculations.
Characters
In Java, the data type used to store characters is char.
However, C/C++ programmers beware: char in Java is not the same as char in C or
C++.
In C/C++, char is 8 bits wide. This is not the case in Java. Instead, 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.
It is a unification of dozens of character sets, such as Latin, Greek
Arabic, Cyrillic,Hebrew, Katakana, Hangul, and many more. 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
Booleans:
Java has a simple type called boolean for logical values. It can have only one of two possible
values. They are true or false.
Literals:
A constant value in Java is created by using a literal representation of it. There are 5 types of
literals.
Integer Literals.
Floating-point Literals.
Character Literals.
String Literals.
Boolean Literals.
Integer literals:
Any whole number value is an integer literal.
These are all decimal values describing a base 10 number.
There are two other bases which can be used in integer literal, octal( base 8) where 0
is prefixed with the value, hexadecimal (base 16) where 0X or 0x is prefixed with the
integer value.
Example:
int decimal = 100; int
octal = 0144; int
hexa = 0x64;
Example:
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal7D
Double-precision floating-point literal
.01f Floating-point literal
Character literals:
char data type is a single 16-bit Unicode character.
We can specify a character literal as a single printable character in a pair of single
quote characters such as 'a', '#', and '3'.
You must know about the ASCII character set. The ASCII character set includes 128
characters including letters, numerals, punctuation etc.
Below table shows a set of these special characters.
Boolean Literals:
The values true and false are treated as literals in Java programming.
When we assign a value to a Boolean variable, we can only use these two values.
Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent
to false in Java.
We have to use the values true and false to represent a Boolean value.
Example
boolean chosen = true;
String Literal
The set of characters in represented as String literals in Java.
Always use "double quotes" for String literals.
There are few methods provided in Java to combine strings, modify strings and to
know whether to strings have the same values.
Example:
―hello world‖
―Java‖
Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may have different value in the different phase of the program. To declare one
identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
Dynamic initialization:
Java allows variables to be initialized dynamically, using expression valid at the time
variable is declared.
Example:
class Example
{
public static void main(String args[])
{
double a=10, b=2.6;
double c=a/b;
System.out.println(―value of c is‖+c);
}
}
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);
}
}
Note:
There should not be two variables with the same name in different scope.
The variable at outer scope can be accessed in inner scope but vice versa is not
possible.
1. Widening Casting(Implicit)
Example :
}
Output :
}
Output :
Double value 100.04
Long value 100
Int value 100
the operands were automatically promoted to int when the expression was evaluated, theresult
has also been promoted to int. Thus, the result of the expression is now of type int,which
cannot be assigned to a byte without the use of a cast.
byte b = 50;
b = (byte)(b * 2); which yields the correct value of 100.
Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described.
Then, if one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float.
If any of the operands is double, the result is double.
Arrays in Java
Arraywhich stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type.
Example:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
Example:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of
the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays: class
TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and create an arrayof
arrays (and those arrays can contain arrays, and so on, for however many dimensions you
need), and access them as you would C-style multidimensional arrays:
int coords[] [] = new int[12] [12];
Programs:
// Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance; // approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here seconds =
days * 24 * 60 * 60; // convert to secondsdistance =
lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
This program generates the following output:
Scope of variable
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:y is:
-1
y is now: 100y is:
-1
y is now: 100
y is: -1
y is now: 100
Type conversion
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142; System.out.println("\nConversion
of int to byte.");b = (byte) i;
System.out.println("i and b " + i + " " + b);
Additional:
Applications of Java
Some of the applications of Java is that internet users can use Java to create applet
programs and run them using a web-browser.
The first application program written in Java was HotJava, a web browser to run applet
on internet.(An applet is a special kind of Java program that is designed to be
transmitted over the internet and automatically executed by a Jva compatible web
browser)
Further internet users can also set up their websites containing java applets,that could
be used by other remote users of the internet. Hence Java is popularly called as ―
Language of Internet‖.
Before the invention of Java, world wide web was limited to displaying text and still
images. However, the incorporation of Java into web pages has made web capable of
supporting animations, graphics, games and wide range of special effects.
Stand alone Java application: Stand alone Java application are programs
written in Java to carry out certain tasks on a certain stand alone system. Executing
a stand-alone Java program contains two phases:
(a) Compiling source coded into bytecode using javac compiler.
(b) Executing the bytecodede program using Java interpreter.
Java applet: Applets are small Java program developed for Internet
application. An applet located on a distant computer can be downloaded via
Internet and execute on local computer.
Java Environment:
Java environment includes a large number of development tools and hundred of
classes and methods.
The development tools are part of the system known as Java Development Kit(JDK)
The classes and methods area apart of the Java Standard Library (JSL) also known
as Application Program Interface (API)
JRE(java runtime environment) consists of tools required to execute the java code,
contianing JVM, runtime class libraries, user interface toolkits.
Java is iterpreted:
Java as a language initially gained popularity mainly due to its platform independentarchitecture
or portaibility feature. The reason for Java to be portable is that it is interpreted.Firstly Java
compiler translates source code into bytecode(an intermediate representation). This byte code
is given as an input to the Java interpreter that generates the machine code that can be
executed by the native system. So we call java as an interpreter language.
The Bytecode:
This concept allows java to solve both security and portability problems. When the source
program is given as an input to the Java compiler, it will never generate the machine level
language executable code, rather it generates ―bytecode‖.
Bytecodes are highly optimized set if instructions designed to be executed by the java runtime
system called JVM. Translating a java program into bytecode makes it much easier to run a
program in a wide variety of environment because only the JVM needs to be implemented
for each platform.
Control Statements
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.
The if statement
The if statement executes a block of code only if the specified expression is true.
If the value is false, then the if block is skipped and execution continues with the rest
of the program.
You can either have a single statement or a block of code within an if statement.
Note that the conditional expression must be a Boolean expression.
Syntax:
if (<conditional expression>) {
<statements>
}
Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
Syntax:
if (condition)
statement1;
else statement2;
Nested ifs
A nested if is an if statement that is the target of another if or else.
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.
Here is an
example:
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)
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
Example:
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block.
If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in cases
where there are no matches.
We can have a nested switch within a case block of an outer switch.
Syntax:
switch (<non-long integral expression>) {
case label1: <statement1> ; break;
case label2: <statement2> ; break;
…
case labeln: <statementn> ; break;
default: <statement>
}
Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
The break statement is optional. If you omit the break, execution will continue on
into the next case.
It is sometimes desirable to have multiple cases without break statements between
them.
For example, consider the following program:
// In a switch, break statements are optional.class
MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++) switch(i)
{
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
In summary, there are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match
between the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.
Baswanthrao Patil, Assistant Professor, CSE(AIML)
OOP With Java BCS306A
Iteration Statements
Syntax:
while (<loop condition>) {
<statements>
}
Example:
public class Example {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}
}
Example:
Syntax:
for (<initialization>; <loop condition>; <increment expression>) {
<loop body>
}
Example:
public class Example {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
Here is another interesting for loop variation. Either the initialization or the iteration
expression or both may be absent, as in this next program:
// Parts of the for loop can be empty. class
ForVar {
public static void main(String args[]) {
int i;
boolean done = false;i =
0;
for( ; !done; ) {
System.out.println("i is " + i);if(i
== 10) done = true;
i++;
}
}
}
Here, the initialization and iteration expressions have been moved out of the for. Thus, partsof
the for are empty
Here is one more for loop variation. You can intentionally create an infinite loop (a
loop that never terminates) if you leave all three parts of the for empty.
For example:
for( ; ; ) {
// ...
}
This loop will run forever because there is no condition under which it will terminate.
Here, type specifies the type and itr-var specifies the name of an iteration variable
that will receive the elements from a collection, one at a time, from beginning to end.
The collection being cycled through is specified by collection.
There are various types of collections that can be used with the for, but the only type
used in this chapter is the array.
Working:
With each iteration of the loop, the next element in the collection is retrieved and
stored in itr-var.
The loop repeats until all elements in the collection have been obtained.
Because the iteration variable receives values from the collection, type must be the
same as (or compatible with) the elements stored in the collection.
Thus, when iterating over arrays, type must be compatible with the base type of the
array.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0; for(int x :
nums) {
sum += x;
}
For example, this program sums only the first five elements of nums:
class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums) {
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}
nums[i][j] = (i+1)*(j+1);
// use for-each for to display and sum the values
for(int x[] : nums) {
for(int y : x) {
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
In the program, pay special attention to this line:
for(int x[] : nums) {
Notice how x is declared. It is a reference to a one-dimensional array of integers.
This is necessary because each iteration of the for obtains the next array in nums,
beginning with the array specified by nums[0].
The inner for loop then cycles through each of these arrays, displaying the values of
each element.
}
}
Nested Loops
Like all other programming languages, Java allows loops to be nested.
That is, one loop may be inside another. For example, here is a program that nests for
loops:
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.
Syntax:
break; // the unlabeled form
break <label>; // the labeled form
Syntax:
continue; // the unlabeled form
continue <label>; // the labeled form
Syntax:
The return statement has two forms:
One that returns a value
return val;
One that doesn't returns a value
return;
Example:
public class Example {
public static void main(String[] args) {
int res = sum(10, 20);
System.out.println(res);
}
private static int sum(int a, int b) {
return (a + b);
}
}
OOP With Java BCS306A