100% found this document useful (1 vote)
115 views129 pages

1 To 5 Chap

The document provides an overview of event driven programming in Java. It discusses key Java concepts like packages and interfaces, exception handling, multithreaded programming, input/output, applets, event handling, AWT, Swings, databases, and servlets. It also covers object-oriented programming principles in Java like encapsulation, polymorphism, inheritance. It describes how Java uses bytecode, the Java virtual machine, and how Java is both compiled and interpreted.

Uploaded by

Rakesh Garg
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
115 views129 pages

1 To 5 Chap

The document provides an overview of event driven programming in Java. It discusses key Java concepts like packages and interfaces, exception handling, multithreaded programming, input/output, applets, event handling, AWT, Swings, databases, and servlets. It also covers object-oriented programming principles in Java like encapsulation, polymorphism, inheritance. It describes how Java uses bytecode, the Java virtual machine, and how Java is both compiled and interpreted.

Uploaded by

Rakesh Garg
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 129

Event Driven Programming With JAVA

Contents
Overview Of Java Packages and interfaces Exception Handling Multithreaded Programming Input/Output Applets EventHandling AWT Swings DataBases Servlets JavaBeans

Overview Of JAVA
OOP ByteCode Concept Java Technology & type of JavaPrograms Simple Java Program/Application DataTypes,Variables and Arrays Operators Control Statements Classes and Methods Inheritance

OOP

Two Paradigms
All computer programs have two elements namely code and data. Conceptual organization of the program containing code and data can be of two ways. Process oriented:Organized around what is happening(function oriented)(code acting on data or sequence of processing steps) Example:Pascal,C etc

Two Paradigms
Object oriented: Organized around what is being affected. organized around data and a set of well defined interfaces to this data data controlling access to code This was essential due to increase in complexity. Example: C++,Java,C#.................

Abstraction
The essential element of OOP is 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 a personal system, we are interested only in people objects and only the ones that are employed by the company. The skiers, golfers, and cyclists are not included.

The powerful way to manage abstraction is through the use of hierarchical


classifications This allows us to layer 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, heading,, and so on. Each subsystem is made of more specialized units. The sound system consists of a radio, CD player, a tape player

Hierarchical Abstractions
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 by abstraction into its component objects.

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 threat objects as concrete entites that respond to
messages telling them to do something This is the essence of object-oriented programming.

OOP principles
Encapsulation Polymorphism Inheritance
A programming language is said to support OO design if it supports these three concepts in its syntax

Encapsulation
Perhaps the most important of the object-oriented concepts is that of encapsulation.

Encapsulation refers to the concept of making an object a


"black box."
In other words;

Encapsulation is the process of hiding all the details of an


object that do not contribute to it's characteristics. In other words;

Encapsulation is the concept that an object should totally


separate its interface from its implementation.
All the data and implementation code for an object should be entirely
hidden behind its interface.

As summary;

Encapsulation (cont)

When we use an object, we should not know its internal workings.

We don't need to understand how an object


works.

An object should expose only the absolute


necessary information needed to interface with it.

It should give us a friendly interface to those


limited set of methods, and properties that the designer thought might be useful for other users.

Encapsulation (cont)
This means:
An object should completely contain any data it requires,
and It should also contain all the code required to manipulate that data. Programs should interact with our object through an interface,

using properties and methods. Client code should never work directly with the data owned by
the object. .

Encapsulation (cont)
In terms of object-oriented concept:
Programs interact with objects by sending messages to the
object

The messages:

are generated by other objects, or by external sources such as the user, and indicate which method or property would be invoked.

The way the object reacts to these messages is through


methods or properties

Encapsulation (cont)
In Java the basis of encapsulation is class Objects are sometimes referred to as instance of a class
Thus: A class is a logical construct An object has physical reality

The class defines the structure and behavior (data and


code) that will be shared by a set of objects

When we create a class, we will specify the code


and data that constitute that class. These elements are called members of the class The data defined by the class are referred to member variables or just methods (C/C++ programmer calls this as a function)

Methods and Properties


Some of the information in the object may actually be
directly accessible

Other information may require us to use a method to


access it . Because:

The information stored internally may be unnecessary


for the user

and

Only certain things can be written into the information


space, and the object needs to check whether the program is outside the limits.

Methods and Properties (cont)


The directly accessible bits of information in the object
are its properties.

The difference between data accessed via properties


and data accessed via methods is that:

with properties
you see exactly what you're doing to the object; with methods, unless you created the object yourself, you just see the effects of what you're doing.

A Class

Private instance variables

Private methods

Public methods Public instanve variables (not recommended)

Encapsulation: public methods can be used to protect private data

The Purpose of a Class


Since the purpose of a class is to encapsulate complexity,
there are mechanisms for hiding the complexity of implementation inside the class.

Each method or variable in a class may be marked as


private and public.
The public interface of a class represents everything that external users of the class need to know The private methods and data can only be accessed by code that is a member of the class. Any other code that is not a member of the class cannot access a private method or variable.

Polymorphism
It refers to one interface to be used for a general class of actions.The specific action depends on exact nature of situation A program using three stacks for different type of data(int,float,char) may use basically the same behavior of stack but different data as content based on situation. In other languages you may create 3 stacks with independent routines to solve the above requirement

Contd..
Principle of One interface many methods is used here in polymorphism It is possible to define a generic interface to a group of related activities and leave the job of distinguishing the lower detail to the compiler based on situation. Define a genral stack interface containing one set of push pop and make it behave in different ways as per requirement based on type of data to be stored in stack. This helps reducing programmer burdon and complexity of s/w.

Inheritance
Is the process by which one object acquires the properties of the other. Supports hierarchical classification concept Every thing has some general attributes which make it similar to other and some unique attributes which makes itself a different entity. In such situations we use the concept of inheritance. A general class may define the common attributes and the specific class below it can define additional behaviors that make it unique and so on

Contd..
Example To describe Animal: Size,intelligence,type of skeletal system and behaviorwise eat,breath,sleep. To describe Mammal: mammary glands,teeths.In addition to above Since Mammal has all characteristics of animal and additional, animal is the super class and mammal is the subclass

Contd..
It interacts with encapsulation and gives following advantages Program complexity grows linearly Code reuse is another advantage of inheritance

Byte code Concept


Java is both compiled and interpreted.But output of java compiler is not executable code, and is called bytecode Bytecode is an optimized set of instructions executable by JVM(Java irtual Machine)or JavaRunTimeSystem(JRS). JVM is an interpreter. It is called virtual because no physical machine exists with instruction set executable by JVM

Contd
Advantages It helps to run java program under different environments.Because only different JVM is needed for different environments.Input for all JVM is bytecode If compiler converting to native code was used then different combinations of interpretes would be required for different CPUs connected to Internet.

Contd
Security is another advantage of using JVM as program execution is under full control by JVM and Java itself has several security measures as part of language.

Java Technology
Java technology is both a programming
language and a platform The Java programming language is a high-level language that can be characterized as follows:
Simple, Distributed, Multithreaded, Object Oriented, High Performance, Robust, Dynamic, Portable, Interpreted, Secure

Simple
Primary characteristics of the Java programming
language include a simple language that can be programmed without extensive programmer training.

The fundamental concepts of Java technology


are grasped quickly; programmers can be productive from the very beginning

Object Oriented
Java technology provides a clean and efficient object-based
development platform. Java programming language is designed to be object oriented from the ground up.

Distributed, client-server based systems coincide with the


encapsulated, message-passing paradigms of objectbased software. Programmers can access existing libraries of tested objects Providing functionality from basic data types through I/O and network interfaces to graphical user interface toolkits. These libraries can also be extended to provide new behavior.

Portable & Distributed


Java technology is designed to support applications that will
be deployed into heterogeneous network environments. Applications must be capable of executing on a variety of hardware architectures The Java Compiler generates bytecodes (an architecture neutral) to supply the diversity of operating environments Intermediate format designed to transport code efficiently to multiple hardware and software platforms. The interpreted nature of Java technology solves both the binary distribution problem and the version problem The same Java programming language byte codes will run on any platform.

Architecture Neutrality
Just one part of a truly portable system The programs are the same on every platform There are no data type incompatibilities across
hardware and software architectures.

The architecture-neutral and portable language platform of


Java technology is known as the Java virtual machine. Java programming language compilers generate code to specifiy an abstract machine. Then; Specific implementations of the Java virtual machine provide the concrete realization of the virtual machine for specific hardware and software platforms. The Java virtual machine is based primarily on the POSIX interface specification (an industry) Standard definition of a portable system interface.

High Performance
Performance is always a consideration. The interpreter can run at full speed without needing to
check the run-time environment. The Java platform achieves superior performance by adopting a scheme The automatic garbage collector runs as a low-priority background thread Ensuring a high probability that memory is available when required, Leading to better performance. Applications requiring large amounts of compute power can be designed such that Compute-intensive sections can be rewritten in native machine code as required and interfaced with the Java platform. In general, interactive applications respond quickly even though they're interpreted.

Interpreted & Threaded


The Java interpreter can execute Java bytecodes directly on
any machine to which the interpreter and run-time system have been ported. Modern network-based applications, such as the HotJava Browser for the WWW, can do several things at the same time A user working with HotJava Browser can run several animations concurrently while downloading an image and scrolling the page. Java technology's multithreading capability provides to build applications with many concurrent threads of activity. Thus, multithreading results in a high degree of interactivity for the end user. The Java platform supports multithreading at the language level with the addition of sophisticated synchronization primitives: The language library provides the Thread class, The run-time system provides monitor and condition lock primitives.

Dynamic
Java Language and run-time system are dynamic in
their linking stages; but The Java Compiler is strict in its compile-time static checking Classes are linked only as needed. New code modules can be linked in on demand from a variety of sources, even from sources across a network. In the case of the HotJava Browser and similar applications, interactive executable code can be loaded from anywhere, enabling transparent updating of applications. On-line services constantly evolve; they can remain innovative and fresh, draw more customers, and encourage the growth of electronic commerce on the Internet.

Type of Java Programs


Application Programs written to be executed in the same environment or at the same place [main method for such program is must] Applet Special type of java program written usually with the aim of transmitting over network and executing in different environments at client machines as part of webpage by java enabled webbrowser

A first Simple Program Example1.1


/* This is a Simple Java Program printing HelloWorld */ class Example{ public static void main(String args[]) { System.out.println(Hello World); } }

Explanation
/* This is a Simple Java Program printing HelloWorld */ Is the Comment and non executable part which is usually used to explain program steps. Other notation is used by java like C++ to indicate comments and is //. // is used for single line comments // This is simple java program Another is /** */

Main Part of Example.java


class Example{ Describes that Example is a name of class being defined. class is the keyword of java. The contents of the class are embeded in {} public static void main(String args[]) This is the main method and every java program execution starts here.

Contd..
public keyword is access modifier used to control visibility main always must be public since it is called by outside program usually at start up. static is to indicate that main can be called before any object instanciation void indicates return type String is name of built in class. The String args[ ] is the parameter to main used to store commandLine parameters as array of strings. Java is case sensitive hence the cases should be followed correctly

Contd
System.out.println(HelloWorld); The above line outputs string embedded in , followed by newline. Note:Always main method should have the above mentioned prototype including case of the letters If u make any mistake say Main the compiler do not inform u that it is an error,instead treats it as another method.And while running u enter into problems due to unmatch of main.

The Requirements to Write Any Java Program I


We need two items to write a Java program for the Java 2 Platform, Standard Edition

The Java2 Platform, Standard Edition


http://java.sun.com/j2se/1.4.2/download.html Or other version

A text editor. We can use the simple editor


NotePad included with the Windows

Creating the First Java Application


Create a source file.
A source file contains text, written in the Java programming language. We can use any text editor to create and edit source files.

Compile the source file into a bytecode file


The compiler, javac, takes the source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. In other words: The compiler converts these instructions into a bytecode file.

Run the program contained in the bytecode file.


The Java interpreter installed on the computer implements the Java VM. This interpreter takes the bytecode file and carries out the instructions by translating them into instructions that the computer can understand

Entering contd..
Use java compiler as follows C:\student\yourroll> javac Example.java Observe the example.class file in the same directory which is the bytecode file Execution : C:\student\yourroll> java Example Observe the output as: HelloWorld Program description : The Java uses /* and */ to embed the comments in a program. In Example.java first line

Write Once and Run Everywhere


This important and famous property of the Java programming language means that:

When we compile our program, we don't generate instructions for one specific platform. we generate Java bytecodes, which are instructions for the Java Virtual Machine (Java VM).

Whether our platform is Windows, UNIX, MacOS, or an


Internet browser, it has the Java VM it can understand those bytecodes.

Additional Topics
History of Java Design goals Java and C++ comparison Why is java important to internet? JIT Compiler [Refer chapter 1 of Text book for these topics]

Java Design goals


Support secure, high-performance, robust applications running as-is on multiple platforms and over networks Architecture-neutral, portable, allow dynamic updates and adapt to new environments Look enough like C++ for programmer comfort Support object-oriented programming Support concurrency (multithreading) Simplicity

Lexical issues
Java source programs can contain whitespace,identifiers,keywords,comments ,separators,literals,built-in classs Ex: Example.java Keywords are: main,static,void,public,class etc Literals: HelloWorld Identifiers: Example Separators: {},()

What are these?


Comments: Described earlier Whitespaces: These are blank,\n,\t characters. There can be any number of whitespaces in source program provided you dont include it as part of keyword or any identifier name. Example.java could be written in a single line too. Separators: The charactes used to separate two lexical units. Ex: ;(statement separator),(),[ ], { }. Identifiers: These are names chosen by programmer for classes,variables and methods.

Contd..
Rule of chosing/forming a name in java are as follows 1.First letter must not be a number. 2.They can contain letters (uppercase or lowercase),_,$,numbers. 3.Names cannot be keywords Example for valid names: A,a1,$test,_fj etc Example for invalid names: 1a,high-temp,not/ok,%f etc

Contd
Note:Remember variable name Value is not same as Value,or VALUE or any other with case change in any one letters. Literals are nothing but constants Example: 2, 3.5 ddd, d Keywords: Java reserved words indicating a particular construct of the language. Refer: Table2-1 of TextBook

JavaClassLibraries
Java provides a large Library of built in classes collectively called APIs, designed using hirearchical package structure. Ex: The print,println methods are defined in System class of java class library package which is automatically included in java program.

Data Types and Variables

Java is a Strongly Typed Language


All variables must first be declared before they can be used. This involves stating the variable's type and name Every expression has a type and every type is strictly defined. All the assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. No automatic coercions or conversions of conflicting types as in some languages Java compiler checks all expressions and parameters to ensure that the types are compatible

Primitive Data Types


Eight primitive data types supported by the Java programming language can be put into 4 groups: Integers-byte, short, int, long Floating-point numbers- float, double Characters- char Boolean- boolean

Primitive Data Types (contd)


They have an explicit range and math behavior All data types have a strictly defined range unlike in C/C++ which allow size of an integer to vary based on the exn environment

Integers
Four integer types: byte, short, int, long Are signed, positive and negative values

Name long int short byte

Width 64 32 16 8

byte
-is an 8-bit signed two's complement integer. -has a minimum value of -128 and a maximum value of 127 (inclusive). -useful for saving memory in large arrays, -can also be used in place of int where their limits help to clarify your code -useful when working with raw binary data Example: byte num, diff;

short
is a 16-bit signed two's complement integer has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). Least-used Example:
short s; short t;

int
is a 32-bit signed two's complement integer. has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice Commonly employed to control loops and index arrays Expression involving byte, shorts, ints and literal numbers, entire expression is promoted to int before calculation.

long
is a 64-bit signed two's complement integer Useful for situations where an int type is not large enough to hold the desired value

Integers
long: 64 bits, +/- 9.223 X 1018 int: 32 bits, +/- 2.147 X 109 short: 16 bits, -32,768 to 32,767 byte: 8 bits, -128 to 127

Floating point

double, 64 bits, 1.7e-308 to 1.7e+308 float, 32 bits, 3.4e-38 to 3.4e38

float
is a single-precision 32-bit IEEE 754 floating point. use a float (instead of double) if you need to save memory in large arrays of floating point numbers. Variable of type float are useful when you need a fractional component, but dont require large degree of precision Example: float hightemp, lowtemp;

double

is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice. Math functions such as sin(), cos() and sqrt() return double values Example:

Characters
char 16 bits, 0 to 65,536, but displayed as char Unicode http://www.unicode.org/charts/ supports double byte characters

Booleans
boolean displayed as true or false

Declaration
Data type identifiername[,idname2,..]; Ex: int k,j;

Data type identifiername=value[,idname2=value,.]; Ex: float x=3.5f,t=2.0f;

Dynamic Initialization
Variables can be initilized dynamically
Example: int k=Math.sqrt(64); Or int k=obj.sum(1,2); int p=k;

EXAMPLE1.2
Another small example //Program to add 2 numbers and display sum class Add{ public static void main(String args[]) { int a,b,sum; a=20; b=100; sum=a+b; System.out.println(Sum is+sum); }} Description The second example declares three integers and assigns values to them through these lines int a,b,sum; a=20; b=100; sum=a+b;

DataType Conversion
Size Direction of Data Type
Widening Type Conversion (Casting down)
Smaller Data Type Larger Data Type

Narrowing Type Conversion (Casting up)


Larger Data Type Smaller Data Type

Who will convert the type?


Implicit type conversion
Carried out by compiler automatically

Explicit type conversion


Carried out by programmer using casting

Type Conversion
Widening Type Converstion
Implicit conversion by compiler automatically
Examples :
byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double

[WideningTypeConversion.java]

Type Conversion
Narrowing Type Conversion
Programmer should describe the conversion explicitly Examples :
byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long doule -> byte, short, char, int, long, float

syntax
L.H.S=(lhs data type)Expression/variable Ex: byte a=50; byte b=40; byte c=(byte)a*2;//Error if not casted

Behavior of byte=(byte)int
If the value of integer variable assigned to byte is <=127(Highest +ve value for byte) then result after type cast is same as number. Ex: int a=127; byte b=(byte)a; System.out.println(b);// b=127

Contd..
If value of the integer variable is >=128 and <256 then the result=value-256. Ex: int i=255;byte b=(byte)i; //b=-1 If value>256 the result is value%256. Ex: int i=516;byte b=(byte)i;// b=4 The same behaviour can be seen with other data type on R.H.S. For float,double above behaviour is applied after removing fraction

For other data types


When u use short on L.H.S. the behaviour is same like byte but ranges used are different as per short data type. [-32768 to +32767 and 65536] The same for int too.

TypePromotion in Expressions
byte,short Converted to int. If one operand is long whole exp is promoted to long. If one operation is float,entire exp is promoted to float If any one operand is double then result of such an expression is double

Examples
class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result);}}

Type Conversion
Implicit Type Conversion
Converted by compiler automatically
char c='A'; short s=1; int i=2; long l=3; float f=2.1f; double d=3.2; (1) i = (c + s); (int T) (char T) (short T) (short T) (int T) [LowerToUpperConversion.java] // i = ??

Type Conversion
Explicit type conversion
Converted by programmer using cast operator char c='A';
short s=1; int i=2; long l=3; float f=2.1f; double d=3.2; (1) s = (short) (c + i); (short T) (char T) (int T) (int T) (short T) // s = ??

Type Conversion
Type Conversion Prohibit
boolean type
Only Can covert into same type

Type conversion

The same rules apply during method call and parameter matching too.

literals
A literal is the source code representation of a fixed value literals are represented directly in your code without requiring computation. It is possible to assign a literal to a variable of a primitive type:
boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000;

Numeric Primitive Data


The difference between the various numeric primitive types is their size, and therefore the values they can store:
Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 Max Value 127 32,767 2,147,483,647 > 9 x 1018

+/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits

Integer literals
The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimal number systems. The prefix 0 indicates octal, whereas 0x indicates hexadecimal. To specify a long literal, append the l or L to the literal. Example:
int decVal = 26; // The number 26, in decimal int octVal = 032; // The number 26, in octal int hexVal = 0x1a; // The number 26, in hexadecimal long num = 725L;// long number

When a integer literal is assigned to a byte or short variable, no error is generated if the literal value is within the range of the target type.

Floating-point literals
Floating point literals in Java default to double precision. The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal). Example:
double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f;

Boolean literals
Simple Has only 2 logical values-true and false The values do not convert into any numerical representation The true literal in Java does not equal to 1 and vice versa.

Character literals
Represented inside a pair of single quotes Escape sequences are used for characters which cannot be represented using single quotes EXAMPLE: A, $, \n, \

String literals
Represented by enclosing a sequence of characters between a pair of double quotes. Java strings must begin and end on the same line. Strings in Java are actually of object types

Escape Sequences
What if we wanted to print a double quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you.");

Escape Sequences
Some Java escape sequences:
Escape Sequence
\b \t \n \r \" \' \\

Meaning
backspace tab newline carriage return double quote single quote backslash

Reserved Words
The Java reserved words:
abstract boolean break byte byvalue case cast catch char class const continue default do double else extends false final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient true try var void volatile while

Arrays
Single dimensional int ar[]=new int [10]; Initialization: int ar[]={1,2,3}; MultiDimensional int ar[][]=new int [2][3]; Initialization int ar[][]={{1,2},{3,4},{4,5}};

Arrays
Accessing: ar[0] or ar[1]SingleDimension ar[0][0] or ar[1][2].MultiDimension Alternate Syntax: On L.H.S. you can change position of []. Ex: int []ar=new int[10];

Additional
When you declare an array ,you can use arrayname.length variable as size in your programs. Ex: int ar[]=new int[5]; System.out.println(ar.length); // will print 5. For 2D : int a[][]=new int[2][3]; a.length will be 2, a[0].length will be 3; You cannot change length value: a.length=9; //WRONG

Common Errors
int a[]; a[0]=9; //Uninitialized error int a[]; a=new int[3]; a[0]=9; Multicolumn size 2D array; int a[][]=new int [2][]; a[0]=new int[3]; //first row size=3 a[1]=new int[4]; //second row size=4

Chapter 4 OPERATORS

Kinds of Operator
Arithmetic Op. : + * / %

Relational Op. : > >= < <= == !=


Logical Op. : && || ! Inc/Dec Op. : ++ --

Operators of Java

Bit Op. : & | ^ ~ << >> >>>


Conditional Op. : ?: Assign Op. : = += -= *= /= %= &= ^= |= >>= <<= >>>= Casting Op. : (Data Type) Array Op. : [] Method Op. : () .

instanceof Op. : instanceof

Arithmetic Operator
Operator for arithmetic operation
Single term operator : +, Binary term operator : +, -, *, /, % Ex: int k=42; float f=42.8f; int z=(int)(f%k); double d=f%k; //Answer will be 0 and 0.8

Arithmetic Operator
Real type operation
Floating point discription and operation: IEEE754 Standard underflow, overflow

Infinitive arithmetic
java.lang.Float, java.lang.Double,
POSITIVE_INFINITY, NEGATIVE_INFINITY constant

NaN(Not a Number)

Relational Operator
Compare two value Result : true or false Expression include relational operator
for, while, ...

Operator
, , , , ,
precedence

a > b + c ===> a > (b + c) b == x < y ===> b == (x < y)

Conditional Operator
Conditional Logical Relationship of two operands Operator
! , && , ||,|,&

a < b && b < c


1 3 2

Increment & Decrement Operator


Operator
++, - Prefix operator
n = 1; x = ++n; // x=2, n=2

Postfix operator
n = 1; x = n++; // x=1, n=2

(a +at b)++ // error Cannot use at expression, only variable Cannot apply at real type

Bitwise Operator
Operator
&, |, <<, >>, >>>, ^, ~ Operand should be integer type Precedence
Operator ~ << >> >>> & ^ | Precedence
(H)

(L)

Bitwise Operator
Bitwise AND
10012 & 00112 = 00012 To extract the special area in variable by masking that area

Bit OR
10012 | 00112 = 10112

Exclusive AND
10012 ^ 00112 = 10102

1s Complement
~ 000010102 = 111101012

Bitwise Operator
Bitwise Shift Operator
Shift lefe(<<)
x << y = x * 2y

Shift right(>>)y
x >> y = x / 2

Unsigned shift right(>>>)


Give this operator because Java does not support unsigned integer. [ShiftOperators.java]

The Conditional Operator


Operator
Expr1 ? Expr2 : Expr3 (3 Terms Operator)
max = x > y ? x : y ;
if (x > y) max = x; else max = y;

m = a > b ? (c > a ? c : a) : (c > b ? c : b) ;

Assignment Operators
Expr 1 = Expr 1 op Expr2 Expr1 op= Expr 2

Operator
Arithmetic operator : + - * / % Bitwise operator : & | ^ << >> >>>
sum = sum + i ; sum += i ;

x = x * y + 1;

x *= y + 1;

x = x * (y+1)

Cast Operator
Data Type Casting Operator
(Data Type)

Cast operator : ( , )
(int) 3.75 (float) 3 (float) (1 / 2) (float)1/2 ===> ===> ===> ===> 3 3.0 0.0 0.5

ShortCircuitOperator
&& and || Checks result of first operand then decides if the second operation is to be executed or not. Ex: if (d!=0 && n/d>10) is OK even if d=0 BUT if(d!=0 & n/d>10) is NOTOK generates exception because both expressions are evaluated.

Operator Precedence
Operator
() [] . ! ~ ++ -- + - (Data Type) * / % + << >> >>> < <= > >= instance == != & ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= >>>=

Association Precedence
Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. Left Assoc. (High)

(Low)

Scope And LifeTime


Block scope; Variable declared will be visible under the defined block and inner blocks (nested) A block is sequence of statements embedded in { and }.

In java u can declare variable anywhere, in any block. Ex: for(int i=9;i<60;i+=2) { // i is valid here inside for block only} i is not valid here

Scope And LifeTime


EX: { int k; { int t; //k and t can be used here } //t is invalid here }

Method Parameters Scope


int f(int k,int l) { //k and l are visible here //if you declare any other variable with same name it will be redeclaration }

Chapter 5 CONTROL STATEMENTS

ControlStatements
If, if-else,if-else-if,switchcase[BRANCHING] While, do-while,for [loops] Return,break,continue [ Syntax exactly similar to C++] Changes to be noted are as follows

Evaluation of Condition
Boolean results for condition to be given While(1) //Error While(true)// correct int flag=1; if(flag)// Error if(flag==1) //correct

Break&Continue
Usual behaviour of these is found like C++ Ex: for(i=1;i<10;i++) for(j=1;j<12;j++) if(j==3) { break;} //Comes out of inner loop each time j reaches 3.

Break and Continue


Ex: for( i=1;i<5;i++) for (j=1;j<4;j++) { if(j==3) continue; System.out.println(j);} //Skips printing j when j=3

Labelled Break
Break out of a nested set of control structures (e.g. while, for, switch) to the named label.
C++-style break only breaks out one level

BreakLabelTest.java
: public class BreakLabelTest { public static void main (String args[]) { : stop: { // labeled compound statement for ( int row = 1; row <= 10; row++ ){ for (int col = 1; col <= 5; col++) { if (row == 5) break stop; Hardly ever // jump to end of stop block needed. : } } } // end of stop block :

Labelled Break
Stop2: for(k=1;k<5;k++){ Stop1: for (i=1;i<4;i++){ for(j=1;j<4;j++){ if(j==2) break Stop1;} //Comes out of the corresponding for

Labelled Continue
A labelled continue inside a loop control structure (e.g. for, while) causes execution to jump out of the nested loops to the next loop prefixed with the label.

ContinueLabelTest.java
: public class ContinueLabelTest { public static void main(String args[]) { : nextRow: // targetted for-loop for ( int row = 1; row <= 5; row++ ) { for (int col = 1; col <= 5; col++) { if (col > row) AVOID continue nextRow; using this. // jump to next iteration : } } :

Switch-Case
switch(expression) { case <literal1>: break; case <literal2>: .. break; default: . } //expression should result in byte,short,int,char data type.

There are lots of Java resources at the following sites: http://java.sun.com/docs/books/tutorial/ http://www.developer.com/java/ http://www.javaprepare.com/index.html http://java.sun.com/docs/books/jls/second_edition/html/jTOC. doc.html Textbooks: Java 2: The Complete Reference - Third Edition, Patrick Naughton & Herbert Schildt, McGraw-Hill , 1999. Java Tutorial, Second Edition, Object-Oriented Programming for the Internet, Mary Campione & Kathy Walrath, Addison Wesley, 1998 Learning Java Patrick Niemeyer& Jonathan Knudsen OReilly, 2000. Object-Oriented programming with Java,Barry J.Holmes & Daniel T. Joyce, Jones and Bartlett Pub. 2001.

You might also like