You are on page 1of 131

MODULE 1

1
2

Javas History
Developed by James Gosling and team at
Sun Microsystems
The java language project initiated in june 1991.
Originally designed for small, embedded systems in
electronic appliances like set-top boxes.
Originally called Oak
Renamed as java in 1995
Sun microsystems was acquired by Oracle Corporation
in 27-jan-2010
3

Java Applications and Applets

Java can be used to create two types of programs

An application is a program that runs on your


computer, under the operating system of that
computer.

An applet is an application designed to be


transmitted over the Internet and executed by a
Java-compatible Web browser.
An applet is actually a tiny Java program
An applet is a program that can react to user input and
dynamically change
Provides security and portability
4

Java Programming Language Platforms

A Java platform is a particular environment in


which Java programming language applications
run.
All Java platforms consist of a Java Compiler , Java
Virtual Machine (JVM) and an application
programming interface (API).

An API is a collection of software components that


you can use to create other software components
or applications.
The API is a library of available java classes,
packages and interfaces.
5

Java Programming Language Platfo


Java Platform, Standard Edition (J2SE)
Current version of the language is 1.8
Java SE's API provides the core functionality of the Java
programming language.
J2SE can be used to develop standalone applications or
applets.
Java Platform, Enterprise Edition (J2EE)
The Java EE platform provides an API and runtime
environment for developing and running large-scale
applications.
Java platform Micro Edition (J2ME)
J2ME can be used to develop applications for mobile
devices such as cell phones.
JavaFX
JavaFX is a platform for creating desktop as well as rich
6

Java Versions

JDK Alpha and Beta (1995)


JDK 1.0 (1996)
JDK 1.1 (1997)
J2SE 1.2 (1998)
J2SE 1.3 (2000)
J2SE 1.4 (2002)
J2SE 1.5 (2004)
Java SE 6 (2006)
Java SE 7 (2011)
Java SE 8 (2014)
7

The Compilation Process for Non-


Java Programs

source code
(programming
language Programmers write
instructions) this.

Compilers
compile source
code into object
code.
object code
(binary Computers run this.
instructions)
8

The Compilation Process for Java


Programs

Java source
code
Java compilers
compile source code
into bytecode.
bytecode
When a Java program
is run, the JVM
translates bytecode to
object code.
object code
9

Java Virtual Machine


How can bytecode be run on any type of
computer?
As a Java programs bytecode runs, the bytecode is
translated into object code by the computer's
bytecode interpreter program. The bytecode
interpreter program is known as the Java Virtual
Machine, or JVM for short.

Bytecode is a highly optimized set of instructions


designed to be executed by the Java run-time
system, which is called the Java Virtual Machine
(JVM).
10
Characteristics of Java
Java was designed to be easy for
Java Is Simple
the programmer
Java Is Object- For Object-oriented programmers,
Oriented learning Java will be even easier.
Java Is Distributed Confusing concepts from C++ are
left out of Java or implemented in a
Java Is Interpreted
cleaner manner.
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
11
Characteristics of Java
Java Is Simple Java is inherently object-
Java Is Object- oriented.
Although many object-oriented
Oriented languages began strictly as
Java Is Distributed procedural languages, Java was
Java Is Interpreted designed from the start to be
object-oriented
Java Is Robust The object model (properties of
Java Is Secure objects in general) in Java is
simple and easy to extend
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
12
Characteristics of Java
Java Is Simple
Distributed computing involves
Java Is Object- several computers working
Oriented together on a network.
Java handles TCP/IP protocols
Java Is Distributed
Networking capability is
Java Is Interpreted inherently integrated into Java,
Java Is Robust writing network programs is
like sending and receiving data
Java Is Secure to and from a file.
Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
13
Characteristics of Java
Java Is Simple You need an interpreter to run
Java programs.
Java Is Object- The programs are compiled
Oriented into the Java Virtual Machine
Java Is Distributed code called bytecode.
The bytecode is machine-
Java Is Interpreted independent and can run on
Java Is Robust any machine that has a Java
interpreter
Java Is Secure Bytecode is easy to translate
Java Is Architecture- into machine code for very
Neutral high performance using JIT
compiler
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
14
Characteristics of Java
Java Is Simple
Java Is Object- Java compilers can detect
Oriented many problems that would first
show up at execution time in
Java Is Distributed other languages.
Java Is Interpreted Java has eliminated certain
types of error-prone
Java Is Robust programming constructs found
Java Is Secure in other languages.
Java manages memory
Java Is Architecture- allocation and deallocation for
Neutral you
Java Is Portable Java has a runtime exception-
handling feature to provide
Java's Performance programming support for
Java Is Multithreaded robustness.
Java Is Dynamic
15
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted Java implements several security
mechanisms to protect your
Java Is Robust system against harm caused by
Java Is Secure stray programs.

Java Is Architecture-
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
16
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure Write once, run anywhere
Java Is Architecture-
With a Java Virtual Machine
Neutral (JVM), you can write one
Java Is Portable program that will run on any
Java's Performance platform.

Java Is Multithreaded
Java Is Dynamic
17
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture- Because Java is architecture
Neutral neutral, Java programs are
Java Is Portable portable. They can be run on any
platform without being
Java's Performance recompiled.
Java Is Multithreaded
Java Is Dynamic
18
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture- The execution speed of Java
Neutral programs improved
Java Is Portable significantly due to the
introduction ofJust-In Time
Java's Performance Compilation(JIT)
Java Is Multithreaded They can be run on any
platform without being
Java Is Dynamic recompiled.
19
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral Allows you to write programs that
do many things simultaneously.
Java Is Portable Multithread programming is
Java's Performance smoothly integrated in Java,
whereas in other languages you
Java Is Multithreaded
have to call procedures specific to
Java Is Dynamic the operating system to enable
multithreading.
20
Characteristics of Java
Java Is Simple
Java Is Object-
Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-
Neutral
Java Is Portable Java programs carry with them
substantial amount of run time
Java's Performance information
Java Is Multithreaded Java resolves accesses to object at
runtime
Java Is Dynamic
21

What is OOP?
Conventional programming(process-oriented
model)
This approach characterizes
A program as a series of linear steps (that is,
code).
The process-oriented model can be thought of as
code acting on data.

Object-oriented programming organizes a program


Around its data (that is, objects) and a set of well-
defined interfaces to that data.
An object-oriented program can be characterized
as data controlling access to code.
22

Classes and Objects

Writing object-oriented programs involves creating


classes, creating objects from those classes, and
creating applications, which are stand-alone
executable programs that use those objects.

A class is a template, blueprint, or contract that


defines what an objects data fields and methods
will be.
An object is an instance of a class. You can create
many instances of a class.
Additionally, a class provides methods of a special
type, known as constructors, which are invoked to
create a new object.
23

Attributes and Methods


Objects are made up of attributes and methods.
Attributes are the characteristics that define an
object; the values contained in attributes
differentiate objects of the same class from one
another.
Methods are used to define actions
To understand this better lets take example of
Mobile as object. Mobile has characteristics like
model, manufacturer, cost, operating system etc. So
if we create Samsung mobile object and IPhone
mobile object we can distinguish them from
characteristics.
The values of the attributes of an object are also
referred to as the objects state.
24

Abstraction
Abstraction is a powerful methodology to manage
complex systems.
Abstraction is managed by well-defined objects and
their hierarchical classification.
Abstraction in Java or Object orientedprogramming
is a way to seperate implementationfrom interface
For example a car in itself is a well-defined object,
which is composed of several other smaller objects
like a gearing system, steering mechanism, engine,
which are again have their own subsystems. But for
humans car is a one single object, which can be
managed by the help of its subsystems, even if
their inner details are unknown.
25

Encapsulation
Encapsulation means putting together all the
variables and the methods into a single unit
called Class " T h e D o u g h n u t D ia g r a m "
S h o w in g t h a t a n o b je c t h a s
The data (state) of p r iv a t e s t a t e a n d
b e h a v io u r . S t a t e
p u b l ic
c a n o n ly b e

an object is private
c h a n g e d b y in v o k in g s o m e
b e h a v io u r

it cannot be P r iv a t e D a t a
accessed directly.
The state can only
be changed P u b li c I n t e r f a c e

through its
behaviour,
otherwise known as
its public interface
26

Encapsulation
Looking at the example of a power steering
mechanism of a car.
Power steering of a car is a complex system,
which internally have lots of components tightly
coupled together, they work synchronously to
turn the car in the desired direction. It even
controls the power delivered by the engine to the
steering wheel. But to the external world there is
only one interface is available and rest of the
complexity is hidden. Moreover, the steering unit
in itself is complete and independent. It does not
affect the functioning of any other mechanism.
Inheritance
Inheritance is the ability to define a new class in
terms of an existing class
The existing class is the parent, base or superclass
The new class is the child, derived or subclass
The child class inherits all of the attributes and
behaviour of its parent class
It can then add new attributes or behaviour
Or even alter the implementation of existing behaviour
Inheritance is therefore another form of code
reuse
28

For example: Car is a classification of Four


Wheeler. Here Car acquires the properties of a
four-wheeler.

Other classifications could be a jeep, tempo, van


etc.

Four Wheeler defines a class of vehicles that


have four wheels, and specific range of engine
power, load carrying capacity etc. Car (termed as
a sub-class) acquires these properties from Four
Wheeler (termed as a super-class), and has some
specific properties, which are different from other
Polymorphism
Ability to take many forms

Ability to create functions or variables that


behave differently in different programming
context.

Polymorphism allows objects to be treated as if


theyre identical

E.g. both a Plane and a Car could respond to a


turnLeft message,
however the means of responding to that message
(turning wheels, or banking wings) is very different for
A Simple Java Program
30

Hello.java
/*
Hello World, first application, only output.
*/

import java.io.*;

class Hello{
public static void main (String args []) {
System.out.println(Hello World\n);
} //end main
}//end class
31

How to get it running


Text in Hello.java file
Why?

To compile:
javac Hello.java

To run:
java Hello
Note : - Set Environment variables To run java programs anywhere
Set path to JDK bin directory
set path=C:\Program Files\Java\jdk1.8.0_31\bin
Set classpath to include the current directory
Add a new system variable Classpath . set classpath=.;
32

Notice:
Java is CASE SENSITIVE!!
File name has to be the same as class name in
file.
Need to import necessary class definitions
All statements in Java end with a semicolon.
Whitespace is ignored by compiler
In Java, all code must reside inside a class.
33

A closer look
1. Multi line
/* comment
Hello World, first application, only output.
*/

import java.io.*;

class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
2. Single line
}//end class comment
3. Documentation
comment
34

/*
Hello World, first application, only output.
*/ Similar to
#include<stdio.h>
Access to all the classes
import java.io.*;
defined in java.io
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
}//end class
35

/*
Hello World, first application, only output.
*/ Keyword class to
declare a new
import java.io.*; class
Name of the class
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
}//end class
36

/*
Hello World, first application, only output.
*/

import java.io.*; Enter main method

Execute statement
class Hello{
public static void main (String args []) {
System.out.println(Hello World);
} //end main
}//end class
37
public static void main (String args
[])

All Java applications begin execution by calling


main( ). (This is just like C/C++.) Access Modifier

main( ) must be declared as public, since it must


be called by code outside of its class when the
program is started.
The keyword static allows main( ) to be called
without having to instantiate a particular instance
of the class. This is necessary since main( ) is
called by the Java interpreter before any objects
are made.
The keyword void simply tells the compiler that
main( ) does not return a value.
38

String args[ ]
String args[ ] declares a parameter named
args, which is an array of instances of the class
String.

Objects of type String store character strings.


In this case, args receives any command-line
arguments present when the program is
executed.
39

System.out.println(Hello
World);

This line outputs the string Hello World followed


by a new line on the screen.

Output is actually accomplished by the built-in


println( ) method.
In this case, println( ) displays the string which is
passed to it.
System is a predefined class that provides access
to the system, and out is the output stream that is
connected to the console.
40

class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called
num
num = 100; // this assigns num the value 100

System.out.println("This is num: " + num);


num = num * 2;

System.out.print("The value of num * 2 is ");


System.out.println(num);
}
Java Reserved Words
or Keywords
abstract default if private this
boolean do implementsprotected throw
break double import public
throws
byte else instanceof return tran
case extends int short try
catch final interface static void
char finally long strictfp vola

class float native super whil


const for new switch
continue goto package synchronized
Keyword and identifiers
An identifier is a word used by a programmer to
name a variable, method, class, or label.
Keywords and reserved words may not be used as
identifiers.

An identifier must begin with a letter, a dollar


sign ($), or an underscore (_); subsequent
characters may be letter, dollar signs, underscores,
or digits.
43
Data Types - 4 Simple Types
The simple types represent single values
Integers This group includes byte, short, int, and
long, which are for whole valued signed numbers.

Floating-point numbers This group includes float


and double, which represent numbers with
fractional precision.

Characters This group includes char, which


represents symbols in a character set, like letters
and numbers.

Boolean This group includes boolean, which is a


special type for representing true/false values.
44
45

Integers

Byte
Variables of type byte are especially useful when
youre working with a stream of data from a
network or file.
For raw binary data that may not be directly
compatible with Javas other built-in types.

Short
It is probably the least-used Java type
This type is mostly applicable to 16-bit computers,
which are becoming increasingly scarce.
46

Int
The most commonly used integer type is int.
Commonly employed to control loops and to index
arrays.

Long
Occasions where an int type is not
Large enough to hold the desired value.
47

Floating-Point
Java implements the standard (IEEE754) set of
floating-point types and operators.
Float
Variables of type float are useful when you need a
fractional component, but dont require a large
degree of precision.
Double
All math functions, such as sin( ), cos( ), and sqrt(
), return double values.
When you need to maintain accuracy over many
iterative calculations, or are manipulating large-
valued numbers, double is the best choice.
48

Characters
In C/C++, char is 8 bits wide.
Java uses Unicode to represent characters. It
requires 16 bits.
Unicode defines a fully international character set
that can represent all of the characters found in
all human languages
The ASCII character set occupies the first 127
values in the Unicode character set.

Note : - Even though chars are not integers, in


many cases you can operate on them as if they
were integers. This allows you to add two
characters together, or to increment the value of
49

Booleans
Java has a simple type, called boolean, for
logical values.
It can have only one of two possible values, true
or false.

This is the type returned by all relational


operators, such as a < b. boolean is also the
type required by the conditional expressions that
govern the control statements such as if and for.
50

Demonstrate double
variables
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;

r = 10.8; // radius of circle


pi = 3.1416; // pi, approximately

a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
51

Demonstrate boolean
variables.
class BoolTest {
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.");


}
}
52

Demonstrate char variables

class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';

System.out.print("ch1 and ch2: ");


System.out.println(ch1 + " " + ch2);
}
}
Literals - Integer
Literals
Integral literals may be expressed in decimal,
octal, or hexadecimal.

To indicate octal, prefix the literal with 0 (zero)


To indicate hexadecimal, prefix the literal with 0x
or 0X;
54

Floating-Point Literals
They can be expressed in either standard or
scientific notation.

Standard notation consists of a whole number


component followed by a decimal point followed
by a fractional component.
Eg:- 2.0, 3.14159, and 0.6667
Scientific notation uses a standard-notation,
floating-point number plus a suffix that specifies a
power of 10 by which the number is to be
multiplied.
Eg:- 6.022E23, 314159E5, and 2e+100.
Floating-point literals in Java default to double
55

Boolean Literals
Boolean : In Java, they can only be assigned to
variables declared as boolean, or used in
expressions with Boolean operators.

Either takes the value true or false


56

Character Literal

A char literal can be expressed by enclosing the


desired character in single quotes,

For example:

char c = ' w ';


57

String Literals
String literals in Java are specified like they are in
most other languages
By enclosing a sequence of characters between a
pair of double quotes.
Eg:- Hello World
58

Variables
The variable is the basic unit of storage in a Java
program.

Declaring a Variable
type identifier [ = value][, identifier [=
value] ...] ;
The type is one of Javas atomic types, or the
name of a class or interface.
The identifier is the name of the variable.
59

Dynamic Initialization

class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;

// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
60

Scope and Lifetime of


Variables
Java allows variables to be declared within any
block.
A block is begun with an opening curly brace and
ended by a closing curly brace. A block defines a
scope.

The scope of a variable defines the section of the


code in which the variable is visible.
In Java, the two major scopes are those defined by
a class and those defined by a method.

The lifetime of a variable refers to how long the


variable exists before it is destroyed.
Demonstrate block scope. 61

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 : -Nested blocks can have access to its outermos
62

Demonstrate lifetime of a
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);
}
}
}
63

Difference from C,C++


// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error bar already
defined!
}
}
}
Note: -Although blocks can be nested, you cannot declare
a variable to have the same name as one in an outer
scope. In this regard, Java differs from C and C++.
64

Type Conversion
Widening conversion - Java automatic type conversion
will take place iff
a. Two type are compactable
b. The destination type > source type
Eg:- int byte
Numeric types are compactable but not compactable with
char,bool etc..
Narrowing conversion
A cast is simply an explicit type conversion
(target-type) value
Eg:- byte int
Eg 1:- b = (byte) i;
Eg 2:- i = (int) d;
65

Automatic Type Promotion in


Expressions
Java automatically promotes each byte or short
operand to int when evaluating an expression.
byte b=50;
b=b*2 // Compiler error
byte is promoted to int during evaluation but
promoted result must be stored in int.

In cases where you understand the


consequences of overflow, you should use an
explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
66

Type Promotion Rules

All byte and short values are promoted to int


If one operand is long then the whole expression
is promoted to long
If one operand is float then the whole expression
is promoted to float
If one operand is double then the whole
expression is promoted to double
Arrays
Collection of homogenous elements stored in
adjacent locations

Arrays can be of any type and dimensions

Array elements can be accessed using an index


1 D array
Declaring an array
Syntax: type var-name[];
Eg: int month_days[];
This will declare the array. But no allocation is
done

Allocating an array
Syntax 1 : var-name=new type[size];
Eg : month_days=new int[12];

Declaring and allocating


Eg: int month_days[] = new int[12];
These elements will be automatically initialized to Zero
Accessing an array
class Arrays
{
public static void main(String args[])
{
int i=0;
int month_days[];
month_days=new int[12];
month_days[0]=1;
month_days[1]=2;
month_days[2]=3;
month_days[3]=4;
month_days[4]=5;
for(i=0;i<5;i++)
System.out.println(month_days[i]);
}
}
Array Intialization
class Arrays
{
public static void main(String args[])
{
int i=0;
int month_days[]={1,2,3,4}; //There is no need to use
new.
for(i=0;i<4;i++)
System.out.println(month_days[i]);
}
}
Java runtime strictly checks you dont try to
store/refer any location out of bounds. This run
time check is not provided by c/c++(robust???)
#include<stdio.h>
class Arrays #include<conio.h>
{ void main()
public static void main(String args[]) {
{ int a[5]={1,2,3,4,5};
int i=0; int i;
int month_days[]={1,2,3,4}; clrscr();
for(i=0;i<6;i++) for(i=5;i<=10;i++)
System.out.println(month_days[i]); a[i]=1;
} for(i=0;i<=10;i++)
} printf("%d",a[i]);
getch();
}
Write a java program to declare a double array
num
a) initialize with the following values
10.1, 11.2, 12.3, 13.4, 14.5
b) Find the average
class Average
{
public static void mian(String args[])
{
double
num[]={10.1,11.2,12.3,13.4,14.5};
int i;
double result=0;

for(i=0;i<5;i++)
result=result+num[i];
System.out.println(result/5);

}
}
Multi Dimensional Arrays

Array of arrays
Syntax : type array-name[][]=new type[row][col]
Eg : int towD[][]=new int[4][5];

Right index determines column

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

Left index [1][0] [1][1] [1][2] [1][3] [1][4]


determine
s row
[2][0] [2][1] [2][2] [2][3] [2][4]

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


class TwoD
{
public static void main(String args[])
{
int two[][]=new int[4][5];
int i , j , k=0;
for(i=0;i<4;i++)
for(j=0;j<5;j++)
{
two[i][j]=k; k++;
}
System.out.print("\n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
System.out.print(two[i][j] + " ");
}
System.out.print("\n");
}
}
}
Manual Memory Allocation
Specify the rows. Columns can be allocated
manually later.
int num[][]=new int[4][];
num[0]=new int[1];
num[1]=new int[2];
num[2]=new int[3];
num[3]=new int[4];

[0][0]

[1][0] [1][1]

[2][0] [2][1] [2][2]

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


class Arr
{
public static void main(String arags[])
{
int num[][]=new int[4][];
num[0]=new int[1];
num[1]=new int[2];
num[2]=new int[3];
num[3]=new int[4];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<i+1;j++)
{
num[i][j]=k;
k++;
}
for(i=0;i<4;i++)
{
for(j=0;j<i+1;j++)
{
System.out.print(num[i][j]+ " ");
}
System.out.print("\n");
}
}
}
Initializing Multi Dimensional
Array
double m[][]={
{1.1,2.1,3.1,4.1},
{2.1,2.2,2.3,.2.4}
};
Alternate Array Declaration

Syntax: type[] var-name;


int[] a1=new int[12];
char[][] w=new char[4][5];
1. Arithmetic Operators
Operator Result
+ Addition
- Subtraction(Also Unary Minus)
* Multiplications
/ Division
% Modulus
++ Increment
+= Addition Assignment
-= Subtraction
*= Multiplication ,,
/= Division ,,
%= Modulus ,,
-- Decrement
Modulus Operator
Returns the remainder of the division
It can be applied to floating point as well as
integers(in c/c++ only applicable to integers)
Increment and decrement
Op++/ ++Op
Op--/--Op

x=42;
y=++x; // y will be ??

x=42;
y=x++; // y will be ??

Note: -In both cases x will be set to 43


2. Bitwise Operators
Operator Result
~ Bitwise Unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
>> Shift Right
>>> Shift Right Zero Fill
<< Shift Left
&= Bitwise AND Assignment
|= Bitwise OR ,,
^= Bitwise Excusive OR ,,
>>= Shift right ,,
>>>= Shift right zero fill ,,
Binary Representation in Java
byte b=42;

2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0

0 0 1 0 1 0 1 0

2^1+2^3+2^5
2+8+32=42

left most bit 0 means positive, left most bit 1 means


negative
Representing Negative
numbers
Java uses 2s complement encoding
Negative numbers are represented by
a. inverting 1 to 0 and vice versa
b. add 1 to the result

Eg: -
byte b=-42;
42 is represented as 00101010
a. Inver 1s and zeros =11010101
b. Add 1 to the result 11010101+
1
Result= 11010110
To decode

a. Invert all 1s and 0s


b. Add 1 to the result
eg:-
-42= 11010110
a. Inver all 1s and zeros= 00101001 +
b. Add 1 1
Result=00101010
Bitwise logical operators

A B A|B A&B A^B ~A


0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
The Left Shift
Syntax: value<<num;
Shifts all the bits in a value to the left a specified
number of times
For each shift a high order bit is shifted out and a
zero is brought in on the right
The right shift
Syntax: value>>num;
Shifts all the bits in a value to the right a
specified number of times
For each shift a low order bit is shifted out and a
zero is brought in on the left
But the signed bit will not be changed to keep the
sign
Unsigned right Shift >>>
Sometimes it is not required to keep the sign
Eg: pixel values
In >>> the bit position will not be preserved as in
>>
Bitwise operator Assignment
Combines the assignment and bit wise operators
a>>=4 ie a=a>>4
a|=b ie a=a|b
4. Relational Operator
To determine relationship that one operand has to
the other
== , !=, >, <, >=, <=
Can be used with int,float,char and boolean
Result is a boolean
5. Boolean Logical Operators

Operator Result
& Logical AND
| Logical OR
^ Logical XOR
|| Short circuit OR
&& Short Circuit AND
! Logical Unary NOT
&= AND assignment
|= OR Assignment
^= XOR Assignment
== Equal to
!= Not Equal to
?: Ternary if then else
A B A|B A&B A^B !A

FALS FALS
E E
TRUE FALS
E
FASL TRUE
E
TRUE TRUE
Short circuit Logical
Operators
The && and || operators "short-circuit",
meaning they don't evaluate the right hand side
if it isn't necessary.
The & and | operators, when used as logical
operators, always evaluate both sides.

There is only one case of short-circuiting for each


operator, and they are:
false && ... - it is not necessary to know what the right hand
side is, the result must be false
true || ... - it is not necessary to know what the right hand
side is, the result must be true
Assignment Operator
variable=expression;
Variable must be compactable with expression
= can be used to create chain of assignments

int x,y,z;
x=y=z=100;
Ternary(Three way) operator

expression1? Expression2 : expression3;

If expression1 is true then expression2 is


evaluated else expression3 will be evaluated

Write a java program to greatest of two variables


using ternary operator?
DOT
Operator Precedence OPERATOR

Precedence

1 () [] .
2 ++ -- ~ !
3 * / %
4 + -
5 >> >>> <<
6 > >= < <=
7 == !=
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 = OP=
Control Statements
Cause the flow of execution

3 categories
Selection
Iteration
Jump
Selection Control Statement
Allows to choose different paths of execution
based on o/p of an expression or state of a
variable according to run time conditions

if
switch
if
if(condition)
statement1;
else
statement2;
Each statement may be single or compound
enclosed in curly brackets
Condition is an expression that returns a boolean
value
Else clause is optional
Eg:- int a,b,c;
if(a>b)
c=a;
else
If using a boolean value
boolean flag;
if(flag)
..
else
..
Nested if
if(i==10)
{
if(j<20)
a=b;
if(k>100)
c=d;
else
a=c;
}
else
a=d;
If-else-if ladder
if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;

Executed from the top down


As soon as one if is found true the statement(s)
will be executed and the rest is bypassed
If none is true statement(s) in else will be
Switch Statement
Multi way branch statement based on value of an expression
switch(expression)
{
case value1:
//statement sequence
break;
case value 2:
// statement sequence
break;
.
.
case value n:
// statement sequence
break;
default:
//statement sequence
Expression must be type byte,short,int or char
Case statement must be type compactable with
the expression
Case value must be unique literal(only constant
not a variable)
Duplicate case values are not allowed
Working
Value of expression is compared with case literals.

If a match found the sequence of statements are


executed in that case
If no match found the default statements are executed
If there is no default then no action will take place
If a break is encountered then it will come out of switch
statement block

Break is optional. If break is omitted then execution will


continue to next case
10
8

Write a java program to print integers 1,2,3,4 and


5 in words using switch ?
class Testcase1
{
public static void main(String args[])
{
int i;
for(i=1;i<6;i++)
switch(i)
{
case 1: System.out.println("One");
break;
case 2: System.out.println("Two");
break;
case 3: System.out.println("Three");
break;
case 4: System.out.println("Four");
break;
default: System.out.println("Five");
}
}
}
class Testcase2
{
public static void main(String args[])
{
int i;
for(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: System.out.println("i is less than
10");
break;
default: System.out.println("i is 10 or
more");
}
Nested Switch
switch(count)
{
case 1:
switch(target)
{
case 0: System.out.println(target=0);
break;
case 1: // No conflict with the case 1 of the outer
switch
System.out.println(target=1);
break;
}
break;
case 2:
//
Comparison with if

Switch can only test for equality whereas if can


evaluate any type of boolean expression
No two case statements can be identical in a switch
block
Switch statement is more efficient than set of nested
ifs

Switch is faster because it can perform equality of


case constants and expression and both are of same
type
When compiled java compiler inspects each case values in switch
and creates a JUMP TABLE. This table is used to decide the path
of execution
Iteration Statements
Loops repeatedly executes the same set of
instructions until a termination condition is met

while and do- while


for
while
The most fundamental loop Entry controlled loop
while(condition)
{
//body of loop
}
Condition can be any boolean expression
Body of the loops is executed as long as the
condition is true

Write a java program to initialize an integer array with


any ten numbers and print the elements using a
while loop
class LoopTest
{
public static void main(String args[])
{
int a[]={1,2,3,4,5,6,7,8,9,10};
int i=0;

while(i<10)
{
System.out.println(a[i]);
i++;
}
}
}
do while

Exit control loop


do
{

// body of loop

} while(condition);

Used for menu driven programs


Loop will display the menu once then user gives the
choice
For loop
Count control loop
for(initialization;condition;iteration)
{

// body of loop

}
Declaring loop control
variables inside the for loop
Possible to declare the variable inside the
initialization portion of for
Eg:- for(int i=0; i<10;i++)
{

}
Scope of this variable is limited to the for block
Using comma
It is possible to include more than one statement in
initialization and iteration part of for loop
class Comma {
public static void main(String args[])
{
int first, second ;
for ( first = 0, second = 10 ; first < second ; first++,
second-- )
{
System.out.println( first + " " + second ) ;
}
}

}
Some loop variations

Condition can be any boolean expression

boolean done=false;
int i=0;
for(;!done;)
{
System.out.println(i);
if(i==10)
done=true;
i++;
}
Infinite loop
for(; ;)
{
//body of the loop
}
Nested loops

for(i=0;i<m;i++)
for(j=i;j<n;j++)
{
//body of the inner loop
}
Jump Statements
Break, continue and return
Break

break statement has three uses

1.It terminates a statement sequence in switch


2.It can be used to exit a loop
3.It can be used as goto
Break to exit a loop
When break is encountered inside a loop
loop is terminated
control of execution goes to next statement following the loop;
class Test_break
{

public static void main (String args[])


{
int i;
for(i=0;i<20;i++)
{

if(i==10)
break;
System.out.println(i);
}
}
Note : -In case of nested loops break only terminates the inne
}
Break as a form of goto
Java does not have goto statement
Instead break can be used to tell where the
execution exactly should resume

Labeled break
Syntax :- break label;
Label is a java identifier with a column
12
7

Note:-
When this form of break executes, control is
transferred out of the named block of code.

The labeled block of code must enclose the break


statement, but it does not need to be the
immediately enclosing block.
class Testbreak
{
public static void main(String args[])
{
boolean t=true;
first:{
second:{
third:{
System.out.println("Before the Break");
if(t)
break second;
System.out.println("This wont execute");
}
}
System.out.println("This is after second!");
}
}
}
Note: - The break statement causes execution to jump forward, past the end
the block labeled second, skipping the two println( ) statements.
Continue
Continue the loop but by pass the remaining code
in the body of loop for the current iteration
class TestContinue
{
public static void main(String
args[])
{
for(int i=0;i<10;i++)
{
if(i%2!=0)
continue;
System.out.println(i);
} Note:-This code uses the % operator to check if i is eve
} is, the loop continues without printing a newline.
Continue using label
class Testcontinue
{
public static void 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.print(" "+ i*j +
");
} Note:- The continue statement in this
} example terminates the loop counting j and
} continues with the next iteration of the loop
} counting i
Return
Explicitly return from a method/function to the
caller function
class testreturn
{
public static void main(String args[])
{
boolean t=true;
System.out.println("Before return");
if(t)
return;
System.out.println("This wont
execute!");
}
}

Here control is transferred to Java run time


system since main is called by Java Run time

You might also like