Module 2

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

Java’s Lineage

• The syntax of Java comes from C, a structured efficient


high level language that was designed to replace
assembly code for system programming.
• Syntax of Java are derived from „C‟.
• Many of Java‟s Object Oriented features were derived
from C++.
• Object Oriented Programming is intended to address the
problem of complexity through the use of inheritance,
encapsulation and polymorphism.

1
THE CREATION OF JAVA….
• Java was conceived by James Gosling, Patrick Naughton,
Chris Warth, Ed Frank and Mike Sheridan at Sun
Microsystems in 1991.
• It took 18 months to develop the first working version.
• Initially called as “Oak” and was renamed as “Java” in
1995.
• The primary motivation was the need for a platform –
independent (architectural neutral) language that could
be used to create software to be embedded in various
consumer electronic devices like microwave ovens,
remote controls….. 2
…….
• Many different types of CPUs are used as controllers and
the trouble with C & C++ is that they are designed to be
compiled for a specific target.
• To compile a C++ program with any CPU we require full
C++ compiler for that CPU.

3
JAVA Environment….
• Java Environment includes a large number of
development tools, hundred of classes and methods.
• The development tools are part of the system known as
Java Development Kit (JDK).
• The classes and methods are part of the Java Standard
Library (JSL) also called as Application Programming
Interface (API).
• The Java Development Kit comes with a collection of
tools that are used for developing and running Java
Programs.
4
5
….They Include
• appletviewer – enables us to run Java applets.
• java – Java interpreter which runs applets and applications
by reading and interpreting byte code files.
• javac – The Java compiler, translates Java source code to
byte code files that the interpreter can understand.
• javadoc – Creates HTML format documentation from Java
source code files.
• javah – Produces header files for use with native methods.
• javap – Java disassembler, which enables us to convert
bytecode files into a program description.
• jdb – Java debugger, helps us to find errors in programs.
6
Bytecode….
• A set of instructions designed to be executed by the java
runtime system.
• The Java Virtual Machine (JVM) is the execution engine
for Java byte code. The byte code is interpreted and
executed by the JVM.
• JVM must be implemented for each platform, byte code is
platform independent.
• When the JVM interprets the byte code it makes security
checks.

7
……
•The JVM can use a Just-in-time compiler to compile byte
code into native code on the fly. (eg HotSpot technology -
Sun)
• JIT compiler is a part of the JVM, selected portion of the
byte code are compiled into executable code in real time,
on a piece-by-piece, demand basis.
• JIT compiler compiles code as it is needed during
execution.

8
JVM (Java Virtual Machine)

9
Java Client/Server equation
• Applets - Client Side:
• special kind of Java program that is designed to be
transmitted over the Internet and automatically executed by a
Java-compatible web browser.

• An applet is downloaded on demand.

• 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.
10
Java Client/Server equation

• Servlets - Server Side:


• a small program that executes on the server.
• Servlets are used to create dynamically generated content
that is then served to the client.
• servlets are compiled into bytecode and executed by the
JVM, so they are highly portable.
• Eg: price update in online shopping portals, authenticating
online banking transactions etc.

11
Java Buzzwords……….
• Simple – Java syntax is similar to C, Java Object
Oriented concepts are taken from C++, no pointers, and
have Garbage collection.
• Secure – Java programs downloaded from the internet
will not be able to infect a computer with viruses.
• Portable – Java byte code is executable on any platform
that has the JVM ported to it.
•Object Oriented – Java is true O-O language,
everything is object, code and data reside within objects
and classes.
12
……
• Robust – compile time error checking and runtime error
checking help to eliminate errors before they make their
way into a program. Memory Management and Exception
handling.
• Multi-threaded – Java supports multi-threaded
programming at a low level. The Object class has several
facilities built in to support multi-threading.
•Architecture-neutral – Java is designed to be “write once
run anywhere”. This is accomplished because the
execution environment of the programs is the JVM.
13
……
•Interpreted and High-performance – Java source code
is compiled into byte code which is interpreted by the
JVM. Just in time compilers compile Java byte code into
native code for high performance.
• Distributed – Java programs handle TCP/IP protocols.
Java also supports distributed programming through
applets, servlets and Remote Method Invocation (RMI).
• Dynamic – Java performs many runtime checks on code
that it is loading. This makes it safe to load code
dynamically. Examples of this are applets.
14
Java 2 Platform–Java 2 Standard Edition J2SE

• The Software Developers Kit - SDK -contains everything


that you need to compile java programs.

• The Java Runtime Environment – JRE – contains all the


components necessary to run java programs including the
JVM.

• These components can be downloaded at:


http://java.sun.com 15
Module -2

Chapter -2

An Overview of JAVA

1
Object Oriented Programming…..
• There are two paradigms for a program construction:
Process Oriented Model
• Organizes program around its code(what‟s happening)
• This model can be thought of as code acting on data
• Procedural languages, such as C, characterize a series
of linear steps (that is, code).
Object- Oriented Programming
• Aims to manage increasing complexity.
• Organizes a program around its data (that is object)
and a set of well-defined interfaces to that data.
• This program can be characterized as data
controlling access to code.
2
Abstraction….
• The essential element of OOP is abstraction & humans
manage complexity through abstraction.

• It is the process of focusing on those features of


something that are essentials for the task at hand and
ignoring those that are not.

• For Eg. People do not think of a car as a set of tens of


thousands of individual parts. They think of it as a well
defined object with its own unique behavior.
3
……
• The powerful way to manage abstraction is through the
use of hierarchical classifications.
• This allows us to layer the semantic of complex systems,
breaking them into more manageable pieces.
• From the outside, the car is a single object. Once inside,
we see that car consists of several subsystems: steering,
clutch pedal, brakes, sound system, seat belts and so on.
• Each subsystem is made of more specialized units.
• The sound system consists of a radio, CD player, a tape
player.
4
……
• We have to manage the complexity of system through
the use of hierarchical abstractions.
• The data from a traditional process-oriented program can
be transformed into its component objects by abstraction .

• A sequence of process steps can become a collection of


messages between these objects.
• Each of these objects describes its own unique behavior.
• We can treat objects as concrete entities.

5
The Three Object Oriented Principles……

Encapsulation
Inheritance

Polymorphism

6
1. Encapsulation…..
• Encapsulation is the mechanism that binds together the
code and the data it manipulates and keeps both safe from
outside interference and misuse.

• Encapsulation acts as a protective wrapper that prevents


the code and data from being arbitrarily accessed by other
code defined outside the wrapper.

• Access to code and data inside the wrapper is tightly


controlled through a well-defined interface.
7
Encapsulation…..
• In java basis of encapsulation is the class.
•It contains: member variables and methods.
•Methods define how the member variables can be used.

•Private and public access.

8
9
2. Inheritance…...
• The process by which one object acquires the properties
of another object.

• By the use of inheritance, an object need only define


those qualities that make it unique within its class.

• It can inherit its general attributes from its parent.

10
11
12
3. Polymorphism……

• Polymorphism is a feature that allows one interface to be


used for a general class of actions.
• One might have a program that requires three types of
stacks. One stack is used for integer values, one for
floating-point values and one for character.
• The algorithm that implement each stack is the same,
even though the data being stored differs.
•One interface, multiple methods.

13
Simple program……
/* the first program.*/

class Example
{
public static void main(String args[])
{
System.out.println(“Hello, World!”);
}
}

14
Compiling the Example program……

• Compile the program using the java compiler. The


compiler will produce an output file Example.class

To compile the program:

C:\> javac Example.java

15
Running the Example program…..

• Run the example program by:


C:\> java Example

• This will run the Example program and generate

Hello, World!
as the output

16
A closer look at the Example program…….

• //  This is a single line comment.


• /* This is a multi-line comment. */

• Class Example {
This line states that the lines between the {} pair
defines a class named Example

17
……..
public static void main(String args[]) {
• This defines the main method.
• This method will be called by the JVM when the class
Example is specified on the command line.
• This is the starting point for the interpreter to begin the
execution of the program.
• A java application can have any number of classes but
only one of them must include a main method to initiate
the execution.
18
……
System.out.println(“Hello, World!”);
• This calls the println() method in the System class.
• It is used to output text on the console.
• We can use println() to output text and have a new line
appended or use print() to output text without the new
line.
• The println method is a member of the out object, which
is a static data member of System class.
• The statement ends with a semicolon.
19
………
Public :
• The keyword public is an access specifier that declares
the main method as unprotected and therefore making it
accessible to all other classes.

Static :
• The keyword static declares this method as one that
belongs to the entire class and not a part of any objects of
the class.
• The main must always be declared as static since the
interpreter uses this method before any objects are
created. 20
…..
Void :
• The type modifier void states that the main method does
not return any value (but simply prints some text to the
screen).

Main :
• main() is the method called when a java application
begins.
• main is different from Main.
• Java compiler also compiles the class that do not contain
main() method. 21
…..
String args[]
• Only one parameter in main(), but complicated one.
• String args[] declares a parameters named args, which is
an array of instances of the class String.
• args receive any command-line arguments information,
when the program is executed.

22
A second Short Example………
class Example2 {
public static void main(String args[]) {
int num; // This declares an integer variable
num = 100; // now initialize num to 100
System.out.println(“num = “ + num);
num = num * 2; // multiply num by 2
System.out.println(“Now num = “ + num);
}
} 23
Control Statements
If Statement………..

if (condition) statement;

Example:
if (num < 100)
System.out.println(“num is less than 100”);

24
A few relational operators………
< Less Than
> Greater Than
== (double equal signs) Is Equal to

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

int x = 10, y = 20; // declare and initialize x and y


if (x < y)
System.out.println("x is less than y");
if(x == 10)
System.out.println("x is equal to 10");
if ( y < x )
System.out.println(“y is less than x");
if(x == y)
System.out.println(“Both are equal values");
}
} 26
The for loop……
• Control construct that allows you to perform an action
repeatedly.

for (initialization ; condition ; iteration)


statement;

• The for loop has an initialization portion, a conditional


clause to control how many times the loop iterates and an
iteration clause that gets the loop ready for the next
iteration.(i.e loop control variable) 27
for example….

class ForDemo
{
public static void main(String args[])
{
int count;
for(count = 0; count < 5; count = count+1)
System.out.println("This is count: " + count);
System.out.println("Done!");
}
}
28
Using blocks of code…

•Code blocks are enclosed in { } curly braces.

if (w < h)
{
v = w * h;
w = 0;
}

29
Lexical Issues…

Whitespace
• Java is a free-form language. This means we do not need
to follow any special indentation rules.
• For ex. A program can be written in a single line.
• Whitespace characters are space, tab or newline.

30
Identifiers
• Identifiers are used for class names, method names and
variables.
• An identifier may be any descriptive sequence of
uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
• Identifiers cannot begin with a number.
• Identifiers are case sensitive, so VALUE is different from
Value.
• Valid identifiers : AvgTemp, count, a4, $test….
• Invalid identifiers : 2count, high-temp, Not/ok…
31
Literals…
• There are many different types of literals or constants.
• Integer – numbers like 45.
• Floating point – numbers like 98.6
• Character – character literals are represented with
opening and closing single quote characters. For
example: „a‟or „Z‟.
• String – String literals are represented with opening and
closing double quotes.
For example: “This is a String!”
32
Comments…
• // indicates a single line comment.
• /* begins a comment that must be terminated with */
• Documentation comments begin with /** and end with */
• Documentation comments are used to insert
documentation into code.
• These comments are then used to produce documentation
by javadoc .

33
Separators….
• ( ) – parenthesis, used to enclose parameters for
methods or to define precedence.
•{ } – braces, used to contain blocks of code such as
classes, methods and any group of statements that must
act a single unit.
• [ ] – brackets, declare and operate on arrays.
• ; - used to terminate statements.
• , - used to separate identifiers in a variable declaration.
•. – used to separate package
names, used to separate a variable or 34

method name from its class.


The Java Keywords…..

35
Java Class Libraries…
• Java has a wide array of standard classes that are
available for every programmer to use.
• We have already seen the use of the System class.
• The Java class libraries provide facilities for IO, string
handling, networking and graphics.
• The class Libraries save you from having to write base
functionality yourself.

36
Module-2

Chapter-3

Data Types, Variables and


Arrays
The simple Types…..
• Java defines eight simple types of data: byte, short, int,
long, char, float, double & Boolean. These can be put in
four groups……..
•Integers : This group includes byte(8), short(16), int(32)
& long(64), which are for whole valued signed numbers.
• Floating-point numbers : Includes float & double, which
represents numbers with fractional precision.
• Characters : Includes char, which represents symbols in a
character set, like letters and numbers.
• Boolean : Includes Boolean, which represents true/false.
GRNICA 2
Integer…..
• Java defines four integer types : byte, short, int & long.
• All of these are signed, positive & negative values.
• Java does not support unsigned, positive-only integers.

GRNICA 3
byte….
• The smallest integer type.
• Signed 8–bit type, ranging from -128 to 127.
• Variable of type byte are used when working with a
stream of data from a network or file.

Usage:
byte b, c;

GRNICA 4
short…..
• It is signed 16-bit type & probably the least-used java
type.
• Most applicable to 16-bit computer, ranging from -32,768
to 32,767.

Usage :
short s;
short t;

GRNICA 5
int…
• Most used type ranging from -2,147,483,648 to
2,147,483,647.
• It is the most versatile and efficient type.
• Usage of short or byte instead of int will never guarantee
that memory is saved. Coz type determines the behavior
and not size.

• But memory will be saved in array if byte or short is


used instead of int.

GRNICA 6
long….
• It is a signed 64-bit type and used where int type is not
large enough.
• It ranges from –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.

Usage :
long seconds;
long mm;

GRNICA 7
long type usage….
/* Compute the number of cubic inches in 1 cubic mile.*/
class Inches
{
public static void main(String args[])
{
long ci, im;
im = 5280 * 12;
ci = im * im * im;
System.out.println("There are " + ci +
" cubic inches in cubic mile.");
}
}

GRNICA 8
/*Use the Pythagorean theorem to find the length of the
hypotenuse given the lengths of the two opposing sides.*/

class Hypot
{
public static void main(String args[])
{
double x, y, z;
x = 3;
y = 4;
z = Math.sqrt(x*x + y*y);
System.out.println("Hypotenuse is " +z);
}
}

GRNICA 9
Floating-Point Types….
• Floating-point numbers (real numbers), used for
evaluating expressions that require fractional precision.

• There are two kinds of floating-point types, float and


double, which represent single- and double-precision
numbers, respectively.

• Type float is 32 bits wide and type double is 64 bits


wide.
GRNICA 10
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.
• Variables of float type are useful when we need a
fractional component, but don‟t require a large degree of
precision.
Usage :
float hightemp, dollar;

GRNICA 11
double….
• double having 64-bit width is actually faster than single
precision on some modern processors that have been
optimized for high-speed mathematical calculations.
• Transcendental math functions like sin(), cos(), and sqrt()
return double values.
Usage :
double gallons, liters;

GRNICA 12
/* This program converts gallons to liters. */

class GalToLit
{
public static void main(String args[])
{
double gallons; // holds the number of gallons
double liters; // holds conversion to liters
gallons = 10; // start with 10 gallons
liters = gallons * 3.7854; // convert to liters
System.out.println(gallons + " gallons is " +
liters + " liters.");
}
}

GRNICA 13
Characters…..
• The data type used to store characters.
• In Java, characters are not 8-bit quantities like they are
in most other computer languages. Instead, Java uses
Unicode.
• Unicode defines a character set that can represent all of
the characters found in all human languages.
• Thus, in Java, char is an unsigned 16-bit type having a
range of 0 to 65,536.
Usage :
char ch; GRNICA 14
15
class CharArithDemo
{
public static void main(String args[])
{
char ch;
ch = 'X';
System.out.println("ch contains " + ch);

ch++;
System.out.println("ch is now " + ch);

ch = 90;
System.out.println("ch is now " + ch);
}
}

GRNICA 16
The Boolean Type…..
• The boolean type represents true/false values.
• Java defines the values true and false using the reserved
words true and false.
• boolean is also the type required by the conditional
expressions that govern the control statements such as if
and for.
Usage :
boolean b;
b = true;
GRNICA 17
class BoolDemo
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println(“Will not execute.");
System.out.println("10 > 9 is " + (10 > 9));
}
} GRNICA 18
Literals….
• In Java, literals refer to fixed values that are represented
in their human-readable form.

• For example, the number 100 is a literal. Literals are also


commonly called constants.

• Java literals can be of any of the primitive data types.

• For example, 'a' and ' %' are both character constants.

GRNICA 19
Integer Literals….
• Integer constants are specified as numbers without
fractional components.
• For example, 1, 2, 42…are integer constants. These are
all decimal values, meaning they are describing a base 10
number.
• Octal - use a leading 0, for example: 0127.
• Hex - use a leading 0x, for example: 0xffff.
• Long – to specify a long literal append an l or L to the
literal, for example: 0xffffffffffL.
GRNICA 20
Floating Point Literals…
• Floating Point Literals represent decimal values with a
fractional component.
• Standard notation, for example: 123.456
• Scientific notation, for example: 6.022E23, 314159E-05
and 2e+100.

GRNICA 21
Boolean Literals…
• Boolean Literals can only be true or false.
• The values of true and false do not convert into any
numerical representation.
• Boolean true does not equal 1.
• Boolean false does not equal 0.

GRNICA 22
Character Literals – Escape Sequences….
•Octal character - \ddd
•Hexadecimal Unicode character - \uxxxx
•Single quote - \‟
•Double quote - \”
•Backslash - \\
•Carriage return - \r
•New Line or Line Feed - \n
•Form feed - \f
•Tab - \t
•Backspace - \b

GRNICA 23
String Literals…..
• Enclose string literals in double quotes–“Hello World!\n”
• Embedded escape sequences are allowed –
“this string will take up\ntwo lines\n”
• Embedded quotes for printing names –
System.out.println(“Error: \”” + filename + “\” is missing”);

GRNICA 24
Variables…..
• The variable is the basic unit of storage in a java
program.
• A variable is defined by the combination of an identifier,
a type, and an optional initializer.
• All variables have a scope, which defines their visibility
and lifetime.

GRNICA 25
Variable declarations….
• int intvar; // simple variable declaration
• int i = 0; // declaration with initialization
• int i = 0, j = 0, k = 23; // multiple declarations and
initializations on one line
• double PI = 3.14159; // double precision floating point
variable declaration with initialization.
• double sqrtOfTwo = Math.sqrt(2); // dynamic
initialization, initialization will be performed when the
program runs.
• char x = „x‟; // declare and init a character variable.
GRNICA 26
Dynamic Initialization…
• Java allows variables to be initialized dynamically.

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);
}
}

GRNICA 27
/* here is a short program that computes the volume of a
cylinder given the radius of its base and its height*/

class DynInit2
{
public static void main(String args[])
{
double radius = 4, height = 5;
// dynamically initialize volume
double volume = 3.1416 * radius * radius * height;
System.out.println("Volume is " + volume);
}
}

GRNICA 28
Scope of variables…..
• Java allows variables to be declared within any block.
• A code block within { } braces defines a scope. The scope
determines what parts of your program can see variables
declared in a scope.
• The scope of a variable also defines its lifetime.
• Variables declared inside a scope are not accessible by
code declared outside that scope.
• Objects and variables declared in a nested scope are not
accessible outside the scope, however objects and
variables declared in an outside scope are accessible in the
inner scope. GRNICA 29
Scope Example……
class Scope
{
public static void main(String args[])
{
int x = 10; // known to all code within main
if(x == 10)
{ // start new scope
int y = 20; // y known only in this block
System.out.println("x=“ + x + “y=“ + y); // x, y known
x = y * 2;
}
// y = 100; // Error! y not known here
System.out.println(“x=" + x); // x is still known here
}
} GRNICA 30
Variable Lifetime……

• Variables are created when their scope is entered and


destroyed when their scope is exited.
• Variables declared in a method will not maintain their
value from one method call to the next.
•If a variable declaration includes an initializer, then that
variable will be reinitialized each time the block in which
it is declared is entered.

GRNICA 31
// Demonstrate lifetime of a variable.
class VarInitDemo
{
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);
}
}
}

GRNICA 32
Type Conversion and Casting….
•Type casting allows us to assign variable of one type to
variable of another type.

• Automatic conversion is performed by java when the


types are compatible.

• Not all types are compatible, and thus, not all type
conversions are implicitly allowed.

GRNICA 33
Java’s Automatic conversion…..
• Automatic casting will occur when the two types are
compatible AND the destination type is larger than the
source type.

• This is called a widening conversion.

• Automatic conversions occur when storing a literals


integer constants into a byte, short or long.

GRNICA 34
Casting Incompatible Types…
• Although the automatic type conversions are helpful, they
will not fulfill all needs.
• It cannot assign an int value to a byte automatically
because a byte is smaller than an int.
• This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value
narrower so that it will fit into the target type.
• To create a conversion between two incompatible types,
we must use a cast, which is simply an explicit type
conversion.
GRNICA 35
…..
int a;
byte b;

b = (byte) a; // syntax: target_var = (targert_type) value;

If integer value is larger, then modulo of byte’s


range is done.
Truncation : during floating-point to integer
cast.
GRNICA 36
Automatic type promotion in expressions…

• Type promotion will occur when mixing variables of


different types in expressions.
• Java promotes each byte or short operand to int when
evaluating expressions.
byte a = 40;
byte b = 50;
byte c = 100;

int d = a * b / c ;
GRNICA 37
byte b = 50;
b = b*2; // error, cannot assign int to byte

b = (byte) (b*2);

GRNICA 38
…..
• If any operand is a long all operands are promoted to
long.
• If one operand is a float the entire expression is
promoted to a float.
• If one operand is a double the entire expression is
promoted to a double.

GRNICA 39
Arrays…..
• An array is a group of like - typed variable that are
referred to by a common name.
• Arrays of any type can be created and may have one or
more dimensions.
• A specific element in an array is accessed by its index.
• The principal advantage of an array is that it organizes
data in such a way that it can be easily manipulated.

GRNICA 40
One-Dimensional Arrays….
• A one-dimensional array is a list of related variables.
• Syntax to declare a one-dimensional array:
type var_name[ ]; OR type[ ] var-name;
array-var = new type[size]; new is a special
operator that
Ex : int a[ ];
allocates memory.
a = new int[10];
type array-name[ ] = new type[size];
Ex: int a[ ] = new int[10];
GRNICA 41
Example program1…
classArray{
public static void main(String args[]) {
int 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");
}
}
GRNICA 42
Example program2…..
class Arraytrials
{
public static void main(String args[])
{
int sample[] = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
System.out.println(“This is sample[” + i + “]:” +sample[i]);
}
}

GRNICA 43
…..
• Arrays can be initialized when they are declared.
• The process is much the same as that used to initialize the
simple types.
• An array initializer is a list of comma – separated
expressions surrounded by curly braces.
• The commas separate the values of the array elements.
• The array will automatically be created large enough to
hold the number of elements you specify in the array
initializer.
GRNICA 44
Example program1…..
class AutoArray
{
public static void main(String args[])
{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31,
30, 31, 30, 31 };
System.out.println(“April has “ + month_days[3] +
“days.”);
}
}
GRNICA 45
Example program2……

class Average
{
public static void main(String args[])
{
double nums[ ] = { 10.1, 11.2, 12.3, 23.4, 22.4};
double result = 0;
int i;
for(i = 0; i < 5; i++)
result = result +nums[i];
System.out.println(" Average is “ + result/5 );
}
}
GRNICA 46
Multi-dimensional Arrays….
•In Java multidimensional arrays are actually arrays
of array.
• These look and act like regular multidimensional arrays,
but there are a couple of subtle differences.
• To declare a multidimensional array variable, specify
each additional index using another set of square
brackets.
int twoD[ ][ ];
twoD = new int[4][5];

GRNICA 47
….
int twoD[ ][ ] = new int[4][5];
• This allocates an array with 4 rows and 5 columns.
• Internally this matrix is implemented as an array of
arrays of int.

[0][0] [0][1] [0][2] [0][3] [0][4]


[1][0] [1][1] [1][2] [1][3] [1][4]
int twoD[][] = new int[4][5];
[2][0] [2][1] [2][2] [2][3] [2][4]
[3][0] [3][1] [3][2] [3][2] [3][3]
GRNICA 48
Example program…
class TwoDArray
{
public static void main(String args[])
{
int twoD [ ] [ ] = new int [ 4] [ 5] ;
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++)
{
twoD[i] [j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ") ;
System.out.println( );
}
} GRNICA 49
}
Arrays of Three or More Dimensions…
• Java allows arrays with more than two dimensions.
• Here is the general form of a multidimensional array
declaration:

type name[ ][ ]...[ ] = new type[size1][size2]...[sizeN];

int multidim[][][] = new int[4][10][3];

GRNICA 50
Module – 2
chapter-4

OPERATORS
• Java provides a rich operator environment.
• Most of its operators can be divided into the following
four groups.
• Arithmetic
• Bitwise
• Relational
• Logical

GRNICA 2
Arithmetic Operators….
Operator Result
+ Addition
- Subtraction (also Unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
3
// Demonstrate several assignment operators.
class BasicMath
{
public static void main(String args[])
{
System.out.println("Integer Arithmetic");
int a = 1+1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println(" b = " + b);
System.out.println("c = " + c);
System.out.println(" d = " + d);
System.out.println(" e = "+ e);
GRNICA 4
System.out.println("\n Floating Point Arithmetic");
double da = 1+1;
double db = da * 3;
double dc = (db/4);
double dd = dc - da;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de =" + de);
}
}

GRNICA 5
// Demonstrate the % operator.

class Modulus
{
public static void main(String args[] )
{
int x = 42;
double y = 42.25;
System.out.println(“ x mod 10 = " + x % 10) ;
System.out.println(“ y mod 10 = " + y % 10) ;
}
}

GRNICA 6
Arithmetic Assignment Operators…..
• Java
provides special operators that can be used to
combine an arithmetic operation with an assignment.
Syntax Example
var = var op expn a=a%2, a=a+1, a = a >>4;
var op = expn a %=2, a+=1, a >>= 4;

GRNICA 7
// Demonstrate several assignment operators.
class OpEquals
{
public static void main(String args[])
{
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
} GRNICA 8
Increment and Decrement…
• The ++ and the – – are Java’s increment and decrement
operators.

• x = x + 1; is the same as x++;

• x = x - 1; is the same as x--;


• x = 10;
y = ++x; //pre-increment
In the above case, y is set to 11.
• x = 10;
y = x++; //post-increment
In the above case, y is set to 10.
• But in both the above cases x is still set to 11. 9
// Demonstrate ++.
class IncDec
{
public static void main(String args[])
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
} GRNICA 10

}
The Bitwise Operators..
•Java supports several bitwise operators which can be
applied to the integer types, long, int, short, char &
byte.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left 11

Operator Result
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

GRNICA 12
The Bitwise Logical Operators…
• The bitwise logical operators are &, |, ^ and ~

GRNICA 13
The bitwise NOT…
• Also called bitwise complement, ~, the unary NOT
inverts all of the bits of its operand.
• 00101010 (42) becomes 11010101 after NOT applied.
The bitwise AND
• &, the AND operator produces a 1 bit if both operands
are 1 and zero in all other cases.
• 00101010 (42)
&00001111 (15)
00001010 (10)
GRNICA 14
The bitwise OR
• |, OR operator combines bits such that if either of the bits
in the operand is a 1.
00101010 (42)
| 00001111 (15)
00101111 (47)
The bitwise XOR
• The XOR operator, ^, combines bits such that if exactly
one operand is 1, then the result is 1, else result is zero.
00101010 (42)
^ 00001111 (15)
00100101 (37) GRNICA 15
// Demonstrate the bitwise logical operators.
class BitLogic
{
public static void main(String args[])
{
String binary[] = { "0000", "0001", "0010",
"0011", "0100", "0101", "0110", "0111", "1000", "1001",
"1010", "1011", "1100", "1101", "1110", "1111” };
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;

GRNICA 16
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}

GRNICA 17
The Left Shift….

• <<, left shift operator shifts all of the bits in a value to the
left a specified number of times.

•for each left shift , the higher order bit is shifted out ( and lost), and
zero is brought in on the right.

syntax: Value << no_of_pos;

GRNICA 18
The Left Shift….

Syntax : value << num;


class Byteshift
{
public static void main(String args[])
{
byte a=64,b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: "+a);
System.out.println("i and b :"+i+" "+b);
}
}
GRNICA 19
The Right Shift….
• >>, shifts all of the bits in a value to the right a specified
number of times.

Syntax: value >> pos;


int a = 32;
a = a >> 2; // now a contains 8

int a = 35;
a = a >> 2; // a still contains 8, coz

00100011 >> 2 generates 00001000


(35) (8)
GRNICA 20
…..
• When we are shifting right, the top (leftmost) bits
exposed by the right shift are filled with the previous
contents of the top bit.
• This is called sign extension and serves to preserve the
sign of negative numbers which we shift them right.

11111000 (-8) in 2'complement


>>1
11111100 (-4)

GRNICA 21
The Unsigned Right Shift…..
• If we are shifting something that does not represent a
numeric value, we may not want sign extension to take
place.
• This is common when working with graphics.
• Here a zero is shifted to higher order bit no matter what
its initial value was.
• This is known as an unsigned shift.

>>> is the operator, called as right shift with zero fill.

GRNICA 22
….
int a = -1;
a = a >>> 24;

11111111 11111111 11111111 11111111 -1 in binary as


an int
>>>24

00000000 00000000 00000000 11111111 255 in binary


as an int

• The >>> operator is often not much useful , because it is only


meaningful for 32- and 64-bit values. 23
Relational Operators…
Operator Result

== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to

<= Less than or equal to

GRNICA 24
Boolean Logical Operators…
• Operate only on Boolean operands.
• Only two possible values: true or false.

GRNICA 25
GRNICA 26
Short circuit logical Operators…
• Short circuit-OR ||

• Short circuit-AND &&

GRNICA 27
The assignment Operator….
•var = expression – assigns the value of expression
to var.
• The type of Var must be compatible with the type of
expression.
• Assignment operations can be chained…

int x, y, z;
x = y = z = 100; // assign 100 to x, y, and z

GRNICA 28
The ?: Operator….
• Ternary operator that replace an if-then-else statement.
• Syntax :

expression1 ? expression2 : expression3;

GRNICA 29
GRNICA 30
GRNICA 31
Operator Precedence….

GRNICA 32
GRNICA 33
MODULE-2
Chapter-5

CONTROL STATEMENTS
Java’s Selection Statements
• Java supports two selection statements : if & switch.
• These statements allow you to control the flow of the
program’s execution based upon conditions known only
during run time.

if
• The if statement is Java’s conditional branch statement.
if ( condition ) Ex: int a,b;
statement1;
if(a<b) a=0;
else
else b=0;
statement2; GRNICA 2
…..
• It is possible to control the if using a single Boolean
variable.
boolean dataAvailable;
if (dataAvailable)
processdata();
else
waitformoredata();

int bytesAvailable;
if (bytesAvailable > 0){
processdata();
bytesAvailable -=n;
}else
GRNICA 3
waitformoredata();
Nested if…
• A nested if is an 'if' statement that is the target of another
if or else.

if(i == 10)
{
if (j < 20) a = b;
if(k > 100) c = d; // this if is
else // associated with this else
a = c;
}
else a = d; // this else refers to if (i = =10)
GRNICA 4
The if-else-if Ladder…..
• A common programming construct that is based upon a
sequence of nested ifs is the if-else-if ladder.

if(condition)
statement;
else if (condition )
statement;
else if(condition)
statement;
.
.
.
else
statement; GRNICA 5
Switch….
• The second of Java’s selection statements is the switch.
• The switch provides for a multiway branch. Thus, it
enables a program to select among several alternatives.
• Although a series of nested if statements can perform
multiway tests, for many situations the switch is a more
efficient approach.
• It works like this: the value of an expression is
successively tested against a list of constants.
• When a match is found, the statement sequence
associated with that match is executed.
GRNICA 6
The general syntax of switch…
switch(expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
...
default:
statement sequence
}
GRNICA 7
// Demonstrate the switch.
class SwitchDemo {
public static void main(String args[]) {
int i;
for(i=0; i<10; i++)
switch(i) {
case 0: System.out.println("i is zero");
break;
case 1: System.out.println("i is one");
break;
case 2: System.out.println("i is two");
break;
case 3: System.out.println("i is three");
break;
case 4: System.out.println("i is four");
break;
default: System.out.println("i is five or more");
}
}
} GRNICA 8
9
Nested switch Statements…..
• It is possible to have a switch as part of the statement
sequence of an outer switch.
• Thisis called a nested switch. Even if the case constants
of the inner and outer switch contain common values, no
conflicts will arise.
switch(ch1) {
case 'A': System.out.println("This A is part of outerswitch.");
switch(ch2) {
case 'A': System.out.println("This A is part of inner switch");
break;
case 'B': // ...
} // end of inner switch
break;
case 'B': // ...
GRNICA 10
Nested switch Statements…..
switch(ch1) {
case 'A': System.out.println("This A is part of outer switch.");

switch(ch2) {
case 'A': System.out.println("This A is part of inner switch");
break;
case 'B': // ...
} // end of inner switch
break;

case 'B': // ...

GRNICA 11
Iteration Statements….
• Java’s iteration statement are for, while & do-while.
• These statements create loops, a loop repeatedly executes
the same set of instructions until a termination condition
is met.
While
• While loop repeats a statement or block while its
controlling expression is true.
while(condition){
....// body of loop
}
GRNICA 12
GRNICA 13
do-while..
• Sometimes it is desirable to execute the body of a loop at
least once, even if the conditional expression is false to
begin with.
• The do-while loop always executes its body atleast once,
because its conditional expression is at the bottom of the
loop.
do{
// body of loop
}while(condition);

GRNICA 14
GRNICA 15
for…..
for(initialization;condition;iteration){
//body
}

Declaring loop control variables inside the for loop..


for(int i=10; i>0; i++)

Using the comma….


for(a=1, b=4; a<b; a++, b--)

GRNICA 16
GRNICA 17
18
GRNICA 19
GRNICA 20
The For-Each version of the for loop….
• The for-each version of the for is also refereed to as the
enhanced for loop.
• Syntax:
for(type itr-var : collection) statement-block
• type specifies the type.
• itr-var specifies the name of an iteration variable that will
receive the elements from a collection.
• The collection being cycled through is specified by
collection.
GRNICA 21
• There are various types of collections that can be used
with the for, ex. is array.
• 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.

int nums[ ]={1,2,3,4,5,6,7,8,9,10};


int sum=0;
for(int x: nums) sum=sum+x;
• As the iteration variable receives values from the
collection, type must be the same as the elements stored in
the collection. GRNICA 22
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)
{
System.out.println("Value is :"+x);
sum=sum+x;
}
System.out.println("Summation : "+sum);
}
}

GRNICA 23
GRNICA 24
class Search
{
public static void main(String args[])
{
int nums[]={6,8,3,7,5,6,1,4};
int val=5;
boolean found = false;
for(int x: nums)
{
if(x == val)
{
found = true;
break;
}
}
if(found)
System.out.println("Value found");
}
} 25
Jump Statements….
• Java supports three jump statements: break, continue &
return. These statements pass control to another part of
the program.

Using break….
• The java break statement has three uses.
1. Terminates a statement in a switch.
2. Used to exit a loop.
3. Used as a civilized form of goto.

GRNICA 26
Using break to Exit a loop…
• Using break, we can force immediate termination of loop
bypassing the conditional expression and any remaining
code in the body of the loop.
Class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i==10) break; //terminate loop if i is 10.
System.out.println(“ I : “ + i);
}
System.out.println("Loop complete.");
}
}
GRNICA 27
Using break as a Form of Goto….
• Java does not have a goto statement because it provides a
way to branch in an arbitrary and unstructured manner.
• There are few places where the goto is a valuable and
legitimate construct for flow control.
•The goto can be useful when we are exiting from a
deeply nested set of loops.
• Syntax :
break label;

GRNICA 28
class BreakLoop
{
public static void main(String args[])
{
outer: for(int i=0;i<3;i++)
{
System.out.print("Pass " + i + ": ");
for(int j=0;j<100;j++)
{
if(j==10) break outer; // exit both loops
System.out.println(j +" ");
}
System.out.println("This will not print.");
}
System.out.println("Loops complete.");
}
}
29
Using continue….
• If you want to continue running the loop but stop
processing the remainder of the code in its body for this
particular iteration, then will go for continue.
class Continue
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.print(i + " ");
if (i%2==0)
continue;
System.out.println(" ");
}
} 30

}
class ContinueLabel
{
public static viod main(String args[])
{
outer : for (int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if( j > i)
{
System.out.println();
continue outer;
}
System.out.println(" " + (i *j));
}
}
System.out.println();
} 31

}
return…
• The return statement is used to explicitly return from a
method.
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if (t)
return;
System.out.println("This won't execute.");
}
}
GRNICA 32

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy