1 To 5 Chap
1 To 5 Chap
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.
Hierarchical Abstractions
We have to manage the complexity of system through the
use of hierarchical abstractions.
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.
As summary;
Encapsulation (cont)
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.
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
and
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 methods
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
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.
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.
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.
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.
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.
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 /** */
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.
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
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).
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]
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: {},()
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.
Integers
Four integer types: byte, short, int, long Are signed, positive and negative values
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
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;
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
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
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;
+/- 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. : + * / %
Operators of Java
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
Conditional Operator
Conditional Logical Relationship of two operands Operator
! , && , ||,|,&
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
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)
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
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.
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.