Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Notes Module 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

MODULE-1: Introduction to Object oriented programming

and JAVA

Introduction to Object oriented programming and JAVA:

Introduction to Object Oriented Programming, Difference between procedure and object-


oriented programming, Features of Object-Oriented Programming Introduction to Java and Java
applications, Java Buzzwords, Object-oriented programming; The Primitive Types, Operators,
Control Statements: Java’s Selection Statements, Iteration Statements, Jump Statements

Introduction:
Object-oriented programming was developed because limitations were discovered in
earlier approaches to programming Object oriented programming is an approach to
program organization and development that attempts to eliminate some of the pitfalls of
conventional programming methods by incorporating the best structured programming
features with several powerful new concepts. It is a new way of organizing and developing
programs.

Procedure Oriented Programming:


C, Pascal, FORTRAN, and similar languages are procedural languages. In procedure-
oriented approach, the problem is viewed as sequence of things to be done such as reading,
calculating, and printing. A number of functions are written to accomplish these tasks. The
primary focus is on function.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


We normally use a flowchart to organize these actions and represent the flow of control
from one actions to another. While we concentrate on the development of functions, very
little attention is given to the data that are being used by various functions. The following
are the disadvantages of POP:

 Unrestricted Access to global data :In a multi-function program, many important


data items are placed as global so that they may be accessed by all the functions.
Many functions can modify a given block of data. So data can corrupted or
something goes wrong with data it becomes very difficult pinpoint which function
misbehave to create the bug. Figures shows the relationship of data and functions in
a procedure-oriented program.

 Real-World Modeling: Problem with the procedural paradigm is that its


arrangement of separate data and functions does a poor job of modeling things in
the real world.
 Large number of connections: Larger number of potential connections between
functions and data causes problems in several ways.

Introduction to object-oriented programming


it is necessary to understand some of the concepts used extensively in object-oriented
programming. These include: Objects, Classes, Data abstraction and encapsulation,
Inheritance, Polymorphism, Dynamic binding, Message Passing.

1. Classes:

Class is a user-defined data type and is a way to bind the data and its associated functions
together. Classes behave like the built-in types of a programming language. The syntax used
to create an object is no different than the syntax used to create an integer object in C. If

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


fruit has been defined as a class, then the statement fruit mango; will create an object
mango belonging to the class fruit which is similar to the declaration of built-in data type
variable int x;

A class serves as a plan, or blueprint.

It specifies what data and what functions will be included in objects of that class. Defining
the class doesn’t create any objects, just as the mere existence of data type int doesn’t
create any variables.

2. Objects:

An object means anything from real world.

Objects are the basic run-time entities in an object-oriented system. They may represent a
person, or a student, a place, a bank account, a table of data or any item that the program
has to handle. They may also represent user-defined data such as vectors, time and lists.
Thinking in terms of objects, rather than functions using which easily programs can be
designed Programming problem is analyzed in terms of objects and the nature of
communication between them. Program object should be chosen such that they match
closely with the real-world objects.

Object is a variable of the type class or instance of the class. Objects are variables of the
type class. Once a class has been defined, we can create any number of objects belonging to
that class. Each object is associated with the data of type class with which they are created.
The fundamental idea behind object-oriented languages is to combine into a single unit
both data and the functions that operate on that data. Such a unit is called an object. An
object’s functions, called member functions or methods in Java typically provide the only
way to access its data. If you want to read a data item in an object, you call a member
function in the object. It will access the data and return the value to you. You can’t access
the data directly. The data is hidden, so it is safe from accidental alteration.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


3. Data Encapsulation and Abstraction

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.

The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between
the objects data and the program.

This insulation of the data from direct access by the program is called data hiding of
information hiding.

Abstraction refers to the act of representing essential features without including the
background details or explanations.

Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost, and functions to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created.

The attributes sometimes called data members because they hold information. The
functions that operate on these data are sometimes called methods or member
functions. Since the classes use the concept of data abstraction, they are known as
Abstract Data Types(ADT).

4. Inheritance:

Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
It supports the concept of hierarchical classification. For example, the bird ‘robin’ is
a part of the class ‘flying bird’ which is again a part of the class ‘bird’.
In OOP, the concept of inheritance provides the ideas of reusability. A programmer
can take an existing class and, without modifying it, add additional features and
capabilities to it. This is done by deriving a new class from the existing one. The new
class will inherit the capabilities of the old one, but is free to add new features of its
own. In Java the original class is called the super class; other classes can be defined
that share its characteristics, but add their own as well. These are called sub classes.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


5. Polymorphism

Polymorphism is another important OOP concept. Polymorphism is derived from 2


Greek words: poly and morphs. The word "poly" means many and "morphs" means
forms. Polymorphism, means the ability to take more than one form. An operation
may exhibit different behaviors in different instances.

The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a
sum. If the operands are strings, then the operation would produce a third string by

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


concatenation.
Figure illustrates that a single function name can be used to handle different
number and different types of arguments. This is something similar to a particular
word having several different meanings depending on the context.
Using a single function name to perform different types of tasks is known as
function overloading. Polymorphism plays an important role in allowing objects
having different internal structures to share the same external interface.

Polymorphism in Java

Polymorphism in Java can be performed by two different methods:

Method Overloading
Method Overriding

Method overloading is defined as a process that can create multiple methods of the same
name in the same class, and all the methods work in different ways. Method overloading
occurs when there is more than one method of the same name in the class. In this process,
the call to the method is resolved at compile-time hence known as Static Polymorphism
or Compile-Time polymorphism

Method Overriding:

Method overriding is defined as a process when the subclass or a child class has the same
method as declared in the parent class. In this case calling of method is resolved at run time
hence known as Dynamic Binding or Run-time Polymorphism.

6. Dynamic Binding:
Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding (also known as late binding) means that the
code associated with a given procedure call is not known until the time of the call at
run-time. It is associated with polymorphism and inheritance.

A function call associated with a polymorphic reference depends on the dynamic


type of that reference.

Features of Object-oriented programming


Object-oriented programming (OOP) is a programming language model organized around
objects rather than "actions" and data rather than logic. The major motivating factor in the
invention of object-oriented approach is to remove some of the flaws encountered in
procedural approach. Some of the features of object-oriented programming are:

Emphasis is on data rather than procedure.


OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system.
It ties data more closely to the functions that operate on it, and protects from
accidental modification from outside functions.
Data is hidden and cannot be accessed by external functions.

Programs are divided into what are known as objects.


OOP allows decomposition of a problem into a number of entities called objects and
then builds data and functions around these objects.
The data of an object can be accessed only by the function associated with that
object.
Objects may communicate with each other through functions.

New data and functions can be easily added whenever necessary.


However, functions of one object can access the functions of other objects.

Other advantages of OOP is as follows:

The technology of data hiding facilitates the programmer to design and develop safe
programs that do not disturb code in other parts of the program.

Save development time (and cost) by reusing code – once an object class is created it
can be used in other applications. All object oriented programming languages allows
creating extended and reusable parts of programs. Object oriented programming
changes the way of thinking of a programmer. This results in rapid development of
new software in a short time.

Using inheritance, we can eliminate redundant program code and continue the use
of previously defined classes.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


The encapsulation feature provided by OOP languages allows programmer to define
the class with many functions and characteristics and only few functions are
exposed to the user.

Easier debugging – classes can be tested independently – reused objects have


already been tested.

Object oriented programs can be comfortably upgraded. Objects communicate with


each other and pass messages.

Operator overloading(which is available in C++ but not in Java) gives an extra


ability to an operator to act on a User-defined operand (Objects). An operator will
act differently depending on the operands provided. Operator overloading makes
code much more readable.

Comparison between procedural programming paradigm and object- oriented


programming paradigm

Procedure Oriented Object Oriented Programming


Programming

Divided Into Program is divided into small Program is divided into parts called
parts called functions objects.

Importance Importance is not given to data Importance is given to the data rather
but to functions as well as than procedures or functions because
sequence of actions to be done. it works as a real world.

Access POP does not have any access OOP has access specifiers named
Specifiers specifier. Public, Private, Protected, etc.

Data In POP, Data can move freely In OOP, objects can move and
Moving from function to function in the communicate with each other
system. through member functions.

Data Access Most function uses Global data Data cannot move easily from
for sharing that can be accessed function to function, it can be kept
freely from function to function in public or private so we can control
the system. the access of data.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


Data Hiding POP does not have any proper OOP provides Data Hiding so
way for hiding data so it is less provides more security.
secure.

Overloading In POP, Overloading is not In OOP, overloading is possible in the


possible. form of Function Overloading and
Operator Overloading.

Expansion To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.

Examples C, Fortran, Pascal, etc C++, Java, C#

Introduction to Java
The history of java starts from Green Team. Java team members (also known as Green
Team), initiated a revolutionary task to develop a language for digital devices such as set-
top boxes, televisions etc Later, Java technology as incorporated by Netscape. Currently,
Java is used in internet programming, mobile devices, games, e-business solutions etc.

The major points that describe the history of java are as follows:

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like settop
boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Java is an island in Indonesia where the first coffee was produced (called Java coffee).
It is a kind of espresso bean. Java name was chosen by James Gosling while having a
cup of coffee nearby his office.
6) In 1995, Time magazine called Java one of the Ten Best Products of 1995. JDK 1.0 was
released on January 23, 1996.
7) Java Version History There are many java versions that has been released. Current
stable release of Java is Java SE 17.

Java Buzzwords (Features of Java)

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


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.There
are many features of java. They are also known as java buzzwords. The Java Features are as follows:

1. Simple : Java is very easy to learn, and its syntax is simple, clean and easy to understand. Java
programming language is very simple and easy to learn, understand, and code. Most of the syntaxes
in java follow basic programming language C and object-oriented programming concepts are
similar to C++. In a java programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed.

2. 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.

3. Portable: n C/C++, the source code may run slightly differently on different hardware platforms,
but Java simplifies it. You can run Java bytecode on any hardware that has a compliant JVM which
can convert the bytecode according to that particular machine.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


4. Platform independent and Architecture neutral: 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.

5. Secured :Java is a more secure language as compared to C/C++, as it does not allow a
programmer to explicitly create pointers. Java supports access modifiers to check memory access
and also ensures that no viruses enter an applet.

6. Robust: Java is robust as it is capable of handling run-time errors, supports automatic garbage
collection and exception handling,

7. Dynamic and extensible: 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.

8. Interpreted :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.

9. 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.

10. Multithreaded: 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. The inclusion of multithreading
enhances the overall execution speed of Java programs.

11.Distributed: A Java programmer sitting on a machine can access another program running on
the other machine using internet. This feature in Java is very helpful when we develop large
projects

Java Program execution:


For building and running a java application we need JDK(Java Development Kit)

With the help of JDK the user compiles and runs his java program. The following steps are used in
executing a Java Program.

Step 1:

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


To compile: javac Simple.java

When we compile Java program using javac tool, the Java compiler converts the source code
into an intermediate code called byte codeand a .class file is created.(in this example Simple.class is
created). This intermediate byte code is platform independent (you can take this bytecode from a
machine running windows and use it in any other machine running Linux or MacOS etc) andalso
only understandable by the JVM and not the user or even the hardware /OS layer.

Step 2:

To execute: java Simple

Now the JVM comes into play, which is made to read and execute this bytecode. The JVM is
linked with operating system and runs the bytecode to execute the code depending upon operating
system. Therefore, a user can take this class file(Bytecode file) formed to any operating system
which is having a JVM installed and can run his program easily without even touching the syntax of
a program and without actually having the source code. The .class file which consists of bytecode is
not user-understandable and can be interpreted by JVM only to build it into the machine code.

First Java Program


class Prg1
{
public static void main(String args[ ])

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


{
System.out.println(“Hello World!!!”);
}

Save this program as Prg1.java. A java program source code is a text file containing one or more
class definitions is called as compilation unit and the extension of this file name should be .java.
To compile above program, use the following statement in the command prompt –

javac Prg1.java

Now, the javac compiler creates a file Prg1.class containing bytecode version of the program,
which can be understandable by JVM. To run the program, we have to use Java application
launcher called java. That is, use the command –

java Prg1
The output of the program will now be displayed as –
Hello World!!!
Let us have closer look at the terminologies used in the above program now –

class is the keyword to declare a class.


Prg1 is the name of the class. You can use any valid identifier for a class name.
main() is name of the method from which the program execution starts.
public is a keyword indicating the access specifier of the method. The public members
can be accessed from outside the class in which they have been declared. The
main() function must be declared as public as it needs to be called from outside
the class.
static The keyword static allows main() to be called without the creation of of the class.
This is necessary since main() is called by the Java Virtual Machine before any
objects are made.
void indicates that main() method is not returning anything.
String args[ ] The main() method takes an array of String objects as a command-line argument.

System is a predefined class (present in java.lang package) , contains pre-defined


methods and fields, which provides facilities like standard input, output, etc.

out is a static final (means not inheritable) field (ie, variable)in System class which is of
type PrintStream (a built-in class, contains methods to print the different data
values). Static fields and methods must be accessed by using the class name, so
we need to use System.out.
println is a public method in PrintStream class to print the data values. After printing the
data, the cursor will be pushed to the next line

Data Types in Java


Java is a strongly-typed programming language in which each type of data (such as integer,
character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


language and all constants or variables defined for a given program must be described with one
of the data types. Certain operations may be allowable only with certain data types.

Data types in Java are classified as Primitive and Non primitive data types. Examples of non-
primitive data type are classes, strings, arrays etc.

The Primitive Types

Java defines eight primitive (or simple) data types viz.

 Integer data types -byte, short, int, long : belonging to Integers group involving whole-
valued signed numbers.
 byte: Byte variables are declared by use of the byte keyword. For example,
byte b, c;
 short :Here are some examples of short variable declarations: short s;short t;
 int: The most commonly used integer type is int. ex: int x=10;
 long: It is useful for those occasions where an int type is not large enough to hold the
desired value.The range of a long is quite large. This makes it useful when big, whole
numbers are needed.
Width
Name Range
(inbits)
long 64 -263 to+263–1

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


int 32 -231 to+231–1

short 16 -215to+215–1 (-32768to+32767)

byte 8 -27 to+27–1(-128to+127)

 Floating point data types


Floating-point (or real) numbers are used when evaluating expressions that require
fractional precision. Java implements the standard (IEEE–754) set of floating-point types
and operators. There are two kinds of floating-point types, float and double, which
represent single- and double-precision numbers, respectively. Their width and ranges are
shown here:

Width(inbi
Name Range
ts)
double 64 4.9e–324to1.8e+308

float 32 1.4e–045to3.4e+038

 float: The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision,
but will become imprecise when the values are either very large or verysmall.
Ex: float x=11.345f;
We have to append f at the end of floating point literal. This is because any floating point
literal is considered as double by default and causes type casting error.
 double : Double precision is actually faster than single precision on some modern
processors that have been optimized for high-speed mathematical calculations. All
transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
double d1 = 12.3 ;

 Character data type


In Java, char This is used for representing symbols in character set like alphabets, digits,
special characters etc. In C or C++, char is of 8 bits, whereas in Java it requires 16 bits. Java
uses Unicode to represent characters. Unicode is a computing industry standard for the
consistent encoding, representation and handling of text expressed in many languages of
the world. Unicode has a collection of more than 109,000 characters covering 93 different
languages like Latin, Greek, Arabic, Hebrew etc. That is why, it requires 16 bits. The range
of a char is 0 to 65,536. The standard set of characters known as ASCII still ranges from 0
to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
Since Java is designed to allow programs to be written for worldwide use, it makes sense
that it would use Unicode to represent characters. Though it seems to be wastage of
memory as the languages like English, German etc. can accommodate their character set in
8 bits, for a global usage point of view, 16-bits are necessary.
Ex: char letterA = 'A' ;

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


 boolean : The Boolean data type is used to store only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.The Boolean data type
specifies one bit of information, but its "size" can't be defined precisely.

Example: boolean flag = false;

All these are signed numbers and Java does not support unsigned numbers.

Operators in Java

The table above lists the precedence of operators in Java; higher it appears in the table, the higher
its precedence.Operator precedence is a rule that decides which operator will be executed first in

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


an expression. Operators with higher precedence are evaluated before operators with lower
precedence.

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. The operands of the arithmetic operators
must be of a numeric type. You cannot use them on boolean types, but you can use them on char types,
since the char type in Java is a subset of int.

 Basic arithmetic operators like +, -, * and / behave as expected for numeric data.
 The – symbol can be used as unary operator to negate a variable.
 If / is operated on two integer operands, then we will get only integral part of the result by
truncating the fractional part.
 The % operator returns the remainder after division. It can be applied on integer and floating-
point types. in C/C++, the % operator cannot be used on float or double and should be used only
on integer variable.
For example, int x=57; double y= 32.8;
System.out.println(“on integer “ + x%10); //prints 7
System.out.println(“on double “ + y%10); //prints 2.8
 Compound assignment operators like += will perform arithmetic operation with assignment.
That is, a+=2; a=a+2;
 Increment/decrement operators (++ and -- ) will increase/decrease the operand by 1. That is,
a++; a=a+1; b--; b=b-1;
 The ++ and -- operators can be used either as pre-increment/decrement or
postincrement/decrement operator. For example, x= 5; y=x++; //post increment Now, value of x
(that is 5) is assigned to y first, and x is then incremented to become 6.
x= 5;
y=++x; //pre-increment Now, x is incremented to 6 and then 6 is assigned to y.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


Bitwise Operators :Java defines several bitwise operators that can be applied to long, int, short, char,
and byte. These operators act upon the individual bits of their operands. They are summarized in the
following table:

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


Bitwise XOR:

int x=5, y=6,z; z= x ^ y;

Now, this operation is carried out as

class ShiftDemo

{ public static void main(String args[])

int a = 64,i,j

i = a << 2;

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


j=i>>2;

System.out.println("Original value of a: " + a);

System.out.println("Original value of i: " + i);

System.out.println("Original value of j: " + j);

} } The result would be

Original value of a: 64

Original value of i:256

Original value of j:16

Relational Operators The relational operators determine the relationship between two operands.
Specifically, they determine equality and ordering among operands. Following table lists the relational
operators supported by Java.

Logical Operators The Boolean logical operators shown here operate only on boolean operands. All of
the binary logical operators combine two boolean values to form a resultant boolean value.

classMain {
publicstaticvoidmain(String[] args) {

// && operator
System.out.println((5>3) && (8>5)); // true
System.out.println((5>3) && (8<5)); // false

// || operator
System.out.println((5<3) || (8>5)); // true
System.out.println((5>3) || (8<5)); // true
System.out.println((5<3) || (8<5)); // false

// ! operator

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


System.out.println(!(5 == 3)); // true
System.out.println(!(5>3)); // false
}
}

The ?: Operator(Ternary or Conditional operator): Java supports ternary operator which sometimes
can be used as an alternative for if-then-else statement. The general form is – var = expression1 ?
expression2 : expression3; Here, expression1 is evaluated first and it must return Boolean type. If it
results true, then value of expression2 is assigned to var, otherwise value of expression3 is assigned to
var. For example, int a, b, c ; ………. c= (a>b)?a:b; //c will be assigned with biggest among a and b

Assignment operators: Assignment operators are used to transfer the value of one operand (on RHS) to other(on
LHS). There are two kinds of assignment operations: simple assignment, in which the value of the second operand
is stored in the object specified by the first operand, and compound assignment, in which an arithmetic, shift, or
bitwise operation is performed prior to storing the result. All assignment operators in the following table except
the = operator are compound assignment operators.

Operator Meaning

= Store the value of the second operand in the object specified by the first operand (simple
assignment).

*= Multiply the value of the first operand by the value of the second operand; store the result in
the object specified by the first operand.

/= Divide the value of the first operand by the value of the second operand; store the result in
the object specified by the first operand.

%= Take modulus of the first operand specified by the value of the second operand; store the
result in the object specified by the first operand.

+= Add the value of the second operand to the value of the first operand; store the result in the
object specified by the first operand.

–= Subtract the value of the second operand from the value of the first operand; store the result
in the object specified by the first operand.

<<= Shift the value of the first operand left the number of bits specified by the value of the

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


second operand; store the result in the object specified by the first operand.

>>= Shift the value of the first operand right the number of bits specified by the value of the
second operand; store the result in the object specified by the first operand.

&= Obtain the bitwise AND of the first and second operands; store the result in the object
specified by the first operand.

^= Obtain the bitwise exclusive OR of the first and second operands; store the result in the
object specified by the first operand.

|= Obtain the bitwise inclusive OR of the first and second operands; store the result in the object
specified by the first operand.

Control Statements (Selection statements)


A programming 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: conditional statement, iteration statement, and jump statement. Conditional
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 set of
statements for one or more times.(that is, iteration statements form loops). Jump statements allow your
program to execute in a nonlinear fashion. All of Java’s control statements are examined here.

Java’s Conditional Statements Java supports two conditional statements: if and switch.

These statements allow you to control the flow of your program’s execution based upon conditions
known only during run time.

If statement:

If(condition) {

statements;

If the condition is true, then the statements written within true block will be executed. The condition
should result into Boolean type.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


if -else Statement The general form is –

if (condition)

{ //true block }

else

{ //false block }

If the condition is true, then the statements written within true block will be executed, otherwise false
block will be executed.

For example

,int a, b, m;

------

if(a>b) max=a;

else

max=b;

Nested-if Statement A nested if is an if statement that is the target of another if or else.

For example, if(condition 1)

if(condition 2)

{ statements;

} // statements will be executed only when both condition 1 and 2 tested true.

The if-else ladder:

The general form is –

if(condition1)

block1;

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


else if(condition2)

block2;

…………..

…………..

else

Blockn;

The if statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the block associated with that if is executed, and the rest of the ladder is bypassed. The final else
acts as a default condition; that is, if all other conditional tests fail, then the last else statement is
performed.

switch Statement
The switch statement is Java’s multi-way 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:

switch (expression)

{ case value1: // statement sequence

break;

case value2: // statement sequence break; ………….... case valueN: // statement sequence break; default:
// default statement sequence } The expression must be of type byte, short, int, or char; each of the
values specified in the case statements must be of a type compatible with the expression. The switch
statement works like this: The value of the expression is compared with each of the literal values in the
case statements. If a match is found, the code sequence following that case statement is executed. If
none of the constants matches the value of the expression, then the default statement is executed.
However, the default statement is optional. If no case matches and no default is present, then no
further action is taken. The break statement is used inside the switch to terminate a statement
sequence. When a break statement is encountered, execution branches to the first line of code that
follows the entire switch statement. This has the effect of “jumping out” of the switch. The break
statement is optional. If you omit the break, execution will continue on into the next case.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


switch(expression)

case const1: statements;

break;

case const2: statements;

break;

case constn: statements;

break;

default: statements;

example

int a=1;

switch(a)

case 0: System.out.println(”zero”);

break;

case 1: System.out.println(”one”);;

break;

case 2: System.out.println(”two”);

break

default: System.out.println(”invalid”);

 switch statement, the value of the expression followed by switch is evaluated the value, which is
returned by expression is compared with the constant values followed by the case. The
statements under the case are executed if the match occurs.
 The value of the expression should be short,byte, int or a char
Example: float x=8.9fExample:switch( Grade )

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


{
case 'A' System.out.println"Excellent" ;
case 'B' : System.out.println< "Good" ;
case 'C' System.out.println< "OK" ;

} Here, if the Grade is 'A' then the output will be

Excellent Good OK
//corrected
switch( Grade )
{
case 'A' : System.out.println("Excellent") ; break;
case 'B' : System.out.println("Good") ; break;
case 'C' System.out.println("OK") ;
}
 Default statements are optional in switch statement and are executed if the cases are not met. If
the default statement is omitted, and no case match is found, none of the statements in the switch
body are executed. The default statement need not come at the end; it can appear anywhere in the
body of the switch statement. Irrespective its placement default statements will be executed at the end
if no match is found. Example see notes
;
switch(x)
{
Case 4.5System.out.printlnoption 1”; break;
Case 8.9: System.out.println<”option 2”; break;
} //illegal as x and case constants cannot be float.
 case should be followed by constant values. It cannot have expression or variables or string
constants.
Example case a+b:
case “hello”: are invalid.(see notes for ex)
 Each compound statement of a switch case should contain break statement to exit from
case.break prevents the program from executing the code in all the other case statements.
 If a common set of statements to be executed under multiple cases, statements should be placed in
front of the last case statement.

char ch=’b’;

Switch(ch)

case 'a' :

case 'b' :

case 'c' :

case 'd' :
case 'e' :
case 'f' : count++;
} //legal

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


char ch=’b’;

Switch(ch)

case 'a',case 'b',case 'c' ,case 'd' ,case 'e' ,case 'f' : count++;

}//illegal

 Notice that switch can only be used to compare an expression against constants. Therefore we
cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):)
because they are not valid constants.

Looping Statements:

Basically, the types of looping statements depends on the condition checking mode. Condition checking
can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping
statements.

 Entry controlled loop example for and while loop


 Exit controlled loop example do-while loop

for loop:

 for loop is used when the number of iterations are fixed and known to the programmer.

syntax: for(exp1;exp2;exp3)

statements;

Where

 exp1: initialization expression which is used to initialize loop variable. There can be multiple
initializations. initialization_expression is executed only once before starting the loop.
 Exp2: conditional/testing expression which results in either true or false. For each iteration of
the loop the condition is tested, statements inside the loop are executed if the tested condition
is true. This can have multiple testing expressions followed by logical AND /OR.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


 Exp3: arithmetic expression, updates the loop variable. Usually consists of increment
/decrement expression. This expression is executed at the end of each iteration. This can have
multiple increment/decrement expressions separated by comma operator.

Example : int i;

for(i=0;i<10;i++)

System.out.println(”hi hello welcome to Java”);

for(j=0,k=4;j<n;j++,k--) //multiple variable initialization

b[j]=c[k];

 All 3 expressions are optional , ie for loop can be written by omitting any or all 3 expressions.
Example
int k=0;
for(;k<5;k++)

System.out.println (“hello”);

for(; ;) //unconditional for loop must have break statement inside it else runs in infinite loop

 loop variable used inside the for expression should not be float
Example: for(float i=1.0;i<10.0;i++) System.out.println (”float”); //illegal
 In such type of loop, the test condition is checked first before the loop is executed. Hence it is
called as entry controlled loop or pre condition testing loop.

While loop:

 While loop is used when exact numbers of iterations are not known. The syntax is as follows:

example:

while(condition ) while(n!=100)

{ {

Statements; System.out.println (”hello”);

} n++;

 The condition in while loop is tested at the beginning of each iteration and statements inside the
while loop are executed as long as the condition tested is true. When the condition evaluates
false the loop is terminated and statement next to while loop is executed.

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


 In such type of loop, the test condition is checked first before the loop is executed. Hence it is
called as entry controlled loop or pre condition testing loop.

Do-while loop:

 This loop is used when the statements inside the loop are to be executed at least once.

 Syntax:
{
Statements;
} while(condition);

 The statements inside the loop are executed at least once even if the condition is false.
 In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed. Hence it is called as exit controlled loop or post condition testing loop.

Jump Statements
break statement:

 break statement is used in switch to exit from case. break prevents the program from
executing the code in all the other case statements.
 break is used inside the loop statements(for,while or do-while) to stop further iterations of the
loop and exit from the loop.
 Syntax : loop statement
{
break;
}
 Inside the loop break statement usually follows a condition to exit the loop.
 It can be used to end an infinite loop, or to force it to end before its natural end.
Example see notes.

Continue statement:
 This is used inside the loop to skip the current iteration and continue to next iteration.
 When continue is executed, the statements after the continue will be skipped and control is
transferred to next iteration.
 This is used to skip some intermediate iteration.
 Syntax : loop statement
{
continue;
statements; //these statements will be skipped
}

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


References and links:
https://www.tutorialspoint.com/java/index.htm
https://www.programiz.com/java-programming/hello-world
https://www.geeksforgeeks.org/java/

https://nptel.ac.in/courses/106/105/106105191/

Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming


Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming

You might also like