Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 246

Programming in Java

Prof K.Khadar Nawas


Design Goals
• Java technology must enable the development
of
– secure,
– high performance,
– and highly robust applications on multiple
platforms in heterogeneous, distributed networks.
• must be architecture neutral, portable, and
dynamically adaptable.
■Simple
■ Secure
■ Portable
■ Object-oriented
■ Robust
■ Multithreaded
■ Architecture-neutral
■ Interpreted
■ High performance
■ Distributed
Program Structure

• The source code for an Java program consists of one or


more compilation units. Each compilation unit can
contain only the following
– a package statement
– import statements
– class declarations
– interface declarations
• When Java source code is compiled, the result is Java
bytecode.
• Java bytecode consists of machine-independent
instructions that can be interpreted efficiently by the
Java runtime system.
JVM

• The JVM is an abstract computing machine,


having an instruction set that uses memory.
Virtual machines are often used to implement
a programming language. The JVM is the
cornerstone of the Java programming
language. It is responsible for Java's cross-
platform portability and the small size of its
compiled code.
• The Solaris JVM is used to execute Java
applications. The Java compiler, javac, outputs
bytecodes and puts them into a .class file. The
JVM then interprets these bytecodes, which
can then be executed by any JVM
implementation, thus providing Java's cross-
platform portability. The next two figures
illustrate the traditional compile-time
environment and the new portable Java
compile-time environment
Lexical Issues

• Comments
• Identifiers
• Keywords
• Literals

– Integer Literals
– Floating Point Literals
– Boolean Literals
– Character Literals
– String Literals

• Operators and Miscellaneous Separators


• The Java language has three styles of comments:
• // text :- All characters from // to the end of the line
are ignored.

• /* text */ :-All characters from /* to */ are ignored.

• /** text */ :- These comments are treated specially


when they occur immediately before any declaration.

• They are illegal in any other place in the code.


• These comments indicate that the enclosed text
should be included in automatically generated
documentation as a description of the declared item.
Identifiers

• Identifiers must start with a letter, underscore


("_"), or dollar sign ("$");
• subsequent characters can also contain digits
(0-9)
• legal
– The characters "A" through "Z"
– The characters "a" through "z"
– All Unicode characters with a character number
above hex 00C0
Keywords
Literals
Literals are the basic representation of any integer, floating point, boolean, character, or string
value.

• Integer Literals
– Integers can be expressed in decimal (base 10),
hexadecimal (base 16), or octal (base 8) format
– A leading 0 (zero) on an integer literal means it is
in octal; a leading 0x (or 0X) means hexadecimal.
– A literal can be forced to be long by appending an
L or l to its value.
The following are all legal integer literals:
2, 2L , 0777 ,0xDeadBeef
Floating Point Literals

• A floating point literal can have the following


parts: a decimal integer, a decimal point ("."),
a fraction (another decimal number), an
exponent, and a type suffix. The exponent
part is an e or E followed by an integer, which
can be signed
• 3.1415, 3.1E12 , .1e12, 2E12
• 2.0d or 2.0D :- double
• 2.0f or 2.0F or 2.0 :-float
• Boolean Literals
– Has true and false value
• Character Literals
– A character literal is a character (or group of characters
representing a single character) enclosed in single quotes.
• String Literals
• A string literal is zero or more characters
enclosed in double quotes.
• Each string literal is implemented as a String
object (not as an array of characters)
"" ( the empty string )
"\""
"This is a string"
"This is a \ two-line string"
Java
Constants, Variables, and Datatypes
• Java Constants  final keyword
 eg final pi=3.14
• Integer  100,12345
• Floating point  1.1,0.222,0.00002
• Character ’a’ ‘*’
• Boolean  true/false
• String  “welcome”
• Variables have the attribute
– Name,Value,Address,Size,Datatype,Range
Java Primitive Datatypes
• int (integer)-short ,long
• float
• double(floating point)
• char (Character)
• boolean (logical)
Variable initialization in declaration:
int timeInSeconds = 245;
char a = 'K', b = '$';
boolean flag = true;
double maxVal = 35.875;
String object
• A string in Java is not a primitive data type.
• Examples of string constants:
"watermelon", "fig", "$%&*^%!!", "354", " "
(space), "" (null string)

The string declaration


String item = "apple";
String item1=new String(“apple”);
Java Operators
• Types Of Operators:
– Arithmetic Operators.
– Relational Operators.
– Bitwise Operators.
– Logical Operators.
– Assignment Operators.
– new operator
Rules of Operator Precedence
Simple.java
class Simple
{  
    public static void main(String args[])
{  
     System.out.println("Hello World");  
    }  
}  
Java Keywords
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float

for goto if implements import

instanceof int interface long native


new package private protected public
return short static strictfp super

switch synchronized this throw throws

transient try void volatile while


Java Constructor
• Constructor creates a instance for the class
• Constructor initiates (initialize) something
related to the class's methods
• special member functions , member function
name is the same as the class name
class Demo
{
public Demo()
{
System.out.println("This is a default constructor");
}
}
• There are two types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
class Demo
{
public Demo(int num, String str)
{
System.out.println("This is a parameterized constructor");
}
}
Scanner Class
• used to read user input from console
• provide methods to read data in String, int,
byte, short, Long, Float and Double

• Constructor:
Scanner obj=new Scanner(System.in);
Important Methods

Method Description

public String nextLine() For reading whole line

public int nextInt() Function is used to read the int value


For reading the long value using
public long nextLong() Scanner class
public float nextFloat() For reading the float value
Used to read value into double
 public double nextDouble() variable
public char nextChar() Read a char

public boolean nextBoolean() For reading boolean value


Use this method to read byte value
public byte nextByte() from the stream
If you have to read the short value
public short nextShort() then use this method
Program-1
• Write an application that inputs from the user
the radius of a circle as an integer and prints
the circle’s diameter, circumference and area
using the floating-point value 3.14159 for π.
Program-2
• Create a BMI calculator application that reads
the user’s weight in pounds and height in
inches (or, if you prefer, the user’s weight in
kilograms and height in meters), then
calculates and displays the user’s body mass
index.
• Also, the application should display the
following information from the Department of
Health so the user can evaluate his/her BMI:
Operators and Miscellaneous
Separators
Data Types
• Numeric Types
– Integer Types
– Floating Point Types
– Character Types
• Boolean Types
• Arrays
Flow of execution
if statement

if (logical expression)
statement
if...else statement
If else ladder
Nested if
Conditional Operator (? :)
• expression1 ? expression2 : expression3
Switch statement
While loop
do...while
For loop
• Integers are similar to those in C and C++
Arithmetic Operators and
Expressions
• If an arithmetic operator is combined with int operands,
then the resulting type is int
• If an arithmetic operator is combined with one or two
double operands, then the resulting type is double
• If different types are combined in an expression, then the
resulting type is the right-most type on the following list that
is found within the expression
byteshortintlongfloatdouble
Type Casting
• A type cast takes a value of one type and produces a value of
another type with an "equivalent" value
– If n and m are integers to be divided, and the fractional portion of the
result must be preserved, at least one of the two must be type cast to
a floating-point type before the division operation is performed
double ans = n / (double)m;
– Note that the desired type is placed inside parentheses immediately in
front of the variable to be cast
– Note also that the type and value of the variable to be cast does not
change

1-49
More Details About Type Casting
• When type casting from a floating-point to an integer type,
the number is truncated, not rounded
– (int)2.9 evaluates to 2, not 3
• When the value of an integer type is assigned to a variable of
a floating-point type, Java performs an automatic type cast
called a type coercion
double d = 5;
• In contrast, it is illegal to place a double value into an int
variable without an explicit type cast
int i = 5.5; // Illegal
int i = (int)5.5 // Correct

1-50
Type Conversion and Casting
• an automatic type conversion will take place if
the following two conditions are met:
■ The two types are compatible.
■ The destination type is larger than the source
type.
For example,
– the int type is always large enough to hold all valid
byte values, so no explicit cast statement is
required.
• The numeric types, including integer and
floating-point types, are compatible with
each other.
• The numeric types are not compatible with
char or boolean.
• char and boolean are not compatible with
each other.
Casting Incompatible Types
• want to assign an int value to a byte variable?
• a byte is smaller than an int
• called a narrowing conversion
• Form : (target-type) value

int a;
byte b;
// ...
b = (byte) a;
// Demonstrate casts.
Class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Why the output is?

• When the value 257 is cast into a byte variable,


the result is the remainder of the division of 257
by 256
• value is reduced modulo 256, which in this case is
67.
Type Promotion

• Java automatically promotes each byte or short operand to


int when evaluating an expression.

• This means that the sub expression a * b is performed using


integers—not bytes
Promotion example
Class Scanner
• java.lang
• Scanner sc = new Scanner(System.in);
• nextLine()  string
• nextInt() Integer
• nextFloat()float
• nextDouble() double
Java BufferedReader Class
InputStreamReader r=new InputStreamReader(System.in);  
BufferedReader br=new BufferedReader(r); 

Or

BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));

• int read() single char


• String readLine() String
Arrays

• Arrays in the language are first class objects.


They replace pointer arithmetic.
• All objects (including arrays) are referred to
by pointers that cannot be damaged by being
manipulated as numbers.
• Arrays are created using the new operator:
char s[] = new char[30];
Demo
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
// An improved version of the previous program.
class AutoArray
{
public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };

System.out.println("April has " + month_days[3] + " days.");


}
}
Multidimensional Arrays
• int twoD[][] = new int[4][5];
Manually fixing other dimension
Want o/p like below

• Program?
Control and Looping
• While
• Do-while
• For
• Java 5.0 introduced a new “enhanced” form of the for
loop
– that is designed to be convenient for processing data
structures
– for example, a list is a data structure that consists simply
of a sequence of items.
– The enhanced for loop can be used to perform the same
processing on each of the enum constants that are the
possible values of an enumerated type.
• To give a concrete example, suppose that the following
enumerated type has been defined to represent the days of
the week:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY, SUNDAY }
for ( Day d : Day.values() )
{
System.out.print( d );
System.out.print(" is day number ");
System.out.println( d.ordinal() );
}
o/p
• MONDAY is day number 0
• TUESDAY is day number 1
• WEDNESDAY is day number 2
• THURSDAY is day number 3
• FRIDAY is day number 4
• SATURDAY is day number 5
• SUNDAY is day number 6
if Statement
switch
playing cards

• How to print a random card name such


as ”Queen of Clubs”
Using random function in java

•Math. random() is used to return a pseudorandom double type number


greater than or equal to 0.0 and less than 1.0.
•The default random number always generated between 0 and 1.
• If you want to specific range of values, you have to multiply the returned
value with the magnitude of the range.
Using random function in java

•Math. random() is used to return a pseudorandom double type number


greater than or equal to 0.0 and less than 1.0.
•The default random number always generated between 0 and 1.
• If you want to specific range of values, you have to multiply the returned
value with the magnitude of the range.

How to create a  deck of 52 playing cards?


Creating deck of playing cards
Creating deck of playing cards

How to shuffle these cards in a deck?


Shuffling the deck
Strings
• string: An object storing a sequence of text
characters.
• Indexes:
• Characters of a string are numbered with 0-
based indexes:
• String name = "Ultimate";
String methods

• These methods are called using the dot notation:

• String starz = "Yeezy & Hova ";


• System.out.println(starz.length()); // 12
String method examples

• Methods like substring and toLowerCase build


and return a new string, rather than modifying
the current string.
Suggests a baby name based on
parents' names.
Suggests a baby name based on
parents' names and gender.
Example Output:
Parent 1 first name? Danielle
Parent 2 first name? John
Child Gender? f
Suggested baby name: JODANI
Parent 1 first name? Danielle
Parent 2 first name? John
Child Gender? Male
Suggested baby name: DANIJO
Comparing strings
• Relational operators such as < and == fail on
objects
• The equals() method :
• Technically this is a method that returns a
value of type boolean ,the type used in logical
tests.
String test methods

String name = console.next();


if(name.endsWith("Kweli"))
{
System.out.println("Pay attention.");
}
else if(name.equalsIgnoreCase("NaS"))
{
System.out.println(" never.");
}
Type char
• A primitive type representing single characters
• Each character inside a String is stored as a
char value
• Literal char values are surrounded with
apostrophe (single-quote) marks, such as 'a'
or '4' or '\n' or '\'‘
• It is legal to have variables, parameters,
returns of type char
• char values can be concatenated with strings.
The charAt method
• The chars in a String can be accessed using the
charAt method.
String food = "cookie";

char firstLetter = food.charAt(0); // 'c‘

System.out.println(firstLetter + " is for " + food);

• You can use a for loop to print or examine


each character.
String major = "CSE";
for (int i = 0; i < major.length(); i++) {
char c = major.charAt(i);
System.out.println(c);
}
char vs. String
• "h" is a String 'h' is a char
• String is an object; it contains methods
• char is primitive; you can't call methods on it
char vs. int
• All char values are assigned numbers internally by the
computer, called ASCII values.
Examples:
'A' is 65, 'B' is 66, ' ' is 32
'a' is 97, 'b' is 98, '*' is 42
• Mixing char and int causes automatic conversion to int.
– 'a' + 10 is 107 , 'A' + 'A' is 130
• To convert an int into the equivalent char, type-cast it.
– (char) ('a' + 2) is 'c'
Comparing char values
• You can compare char values with relational
operators:
• 'a' < 'b' and 'X' == 'X' and 'Q' != 'q'
• An example that prints the alphabet:
Comparing char values
• You can compare char values with relational
operators:
• 'a' < 'b' and 'X' == 'X' and 'Q' != 'q'
• An example that prints the alphabet:

Write a program to test the given string if plural or


singular
StringBuffer class
• java StringBuffer class is used to create mutable
(modifiable) string.

• The StringBuffer class in java is same as String class


except it is mutable i.e. it can be changed.
• Constructor:
– StringBuffer()
– StringBuffer(String str)
– StringBuffer(int capacity)

– Eg: StringBuffer sb=new StringBuffer("Hello ");
– StringBuffer sb=new StringBuffer();
methods
• append() eg: sb.append("Java");

• insert() eg:sb.insert(index,"Java")

• replace() eg:sb.replace(beginindex,endindex,string)

• reverse()

• delete() eg:sb.delete(beginindex,endindex)
StringBuilder class
• Java StringBuilder class is used to create
mutable (modifiable) string.
• The Java StringBuilder class is same as
StringBuffer class except that it is non-
synchronized
• Constructor:
– StringBuilder()
– StringBuilder(String str)
eg:eg:StringBuilder sb=new StringBuilder("Hello ");
– StringBuilder(int length)
•StringBuffer is synchronized and therefore thread-safe.
StringBuilder is compatible with StringBuffer API but with no
guarantee of synchronization.

•Because it's not a thread-safe implementation, it is faster and it is


recommended to use it in places where there's no need for thread
safety.
StreamTokenizer class
• This class allows you to break a string into
tokens. It is simple way to break string
• Constructor:
– StringTokenizer(String str)
– StringTokenizer(String str, String delim)
– StringTokenizer(String str, String delim, boolean
returnValue)
methods
• hasMoreTokens()
• nextToken()
• nextToken(String delim)
• hasMoreElements()
import java.util.StringTokenizer;  
public class Simple
{  
 public static void main(String args[])
{  
   StringTokenizer st = new StringTokenizer("my,name,is,nawas“ ,“,");  
     while (st.hasMoreTokens()) {  
         System.out.println(st.nextToken());  
     }  
   }  
}  
Class Definition

A class contains a name, several variable declarations


(instance variables) and several method declarations. All are
called members of the class.
General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}

L 4.7
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }

L 4.8
Methods

• General form of a method definition:


type name(parameter-list) {
… return value;

}
• Components:
1) type - type of values returned by the method. If a method
does not return any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.

L 5.4
Example: Method

• Classes declare methods to hide their internal data


structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
L 5.5
Parameterized Method

• Parameters increase generality and applicability of a


method:
• 1) method without parameters
int square() { return 10*10; }
• 2) method with parameters
int square(int i) { return i*i; }
• Parameter: a variable receiving value at the time the
method is invoked.
• Argument: a value passed to the method when it is
invoked.
L 5.6
Static Methods
• Place a keyword “static” before the return
type in the method’s declaration
• can call any static method by specifying the
name of the class in which the method is
declared, followed by a dot (.) and the method
name
Example :Math Class
• Class Math provides a collection of methods
that enable you to perform common
mathematical calculations.
• For example, you can calculate the square
root of 900.0 with the static method call
Constructor

• A constructor initializes the instance variables of an object.


• It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return
type of a class
• constructor is the same class
• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.

L 5.1
Example: Constructor

class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}

L 5.2
Parameterized Constructor

class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
L 5.3
Method Overloading
• It is legal for a class to have two or more methods
with the same name.

• However, Java has to be able to uniquely associate


the invocation of a method with its definition
relying on the number and types of arguments.

• Therefore the same-named methods must be


distinguished:

1) by the number of arguments, or


2) by the types of arguments

• Overloading and inheritance are two ways to


implement polymorphism.
L 7.1
Example: Overloading
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}

void test(int a)
{
System.out.println("a: " + a);
}

void test(int a, int b)


{
System.out.println("a and b: " + a + " " + b);
}

double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
}
L 7.2
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): "
}
}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}

L 7.3
Method Overloading
• It is legal for a class to have two or more methods
with the same name.

• However, Java has to be able to uniquely associate


the invocation of a method with its definition
relying on the number and types of arguments.

• Therefore the same-named methods must be


distinguished:

1) by the number of arguments, or


2) by the types of arguments

• Overloading and inheritance are two ways to


implement polymorphism.
L 7.1
Example: Overloading
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}

void test(int a)
{
System.out.println("a: " + a);
}

void test(int a, int b)


{
System.out.println("a and b: " + a + " " + b);
}

double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
}
L 7.2
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}

L 7.3
Parameter Passing

Two types of variables:


1) simple types
2) class types

Two corresponding ways of how the arguments are


passed to methods:

1)by value a method receives a cope of the original


value; parameters of simple types

2) by reference a method receives the memory


address of the original value, not the value itself;
parameters of class types
L 7.4
Call by value
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: “);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}

L 7.5
Objects as Parameters
(Call by reference)

class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}

boolean equals(Test o)
{
if(o.a == a && o.b == b)
{
return true;
}
else
{
return false;
}
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Call by reference
• As the parameter hold the same address as the argument, changes to the
object inside the method do affect the object used by the argument:
class CallByRef {
public static void main(String args[ ]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}

L 7.6
Returning Objects
class Test {
int a;
Test(int i) {
a = i;
} Output:
Test incrByTen() { ob1.a: 2
Test temp = new Test(a+10); ob2.a: 12
return temp; ob2.a after second increase: 22
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
Command-Line Arguments
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
} javac CommandLine
} java CommandLine this is a test 100 -1
} output
output
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
Recursion
• A method that calls itself is said to be
recursive class Factorial
{
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
o/p
class Factorial
{
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
Factorial of 3 is 6 }
Factorial of 4 is 24 }
Factorial of 5 is 120
class RecTest
{
int values[];
RecTest(int i) {
values = new int[i];
}
// display array -- recursively
void printArray(int i) { [0] 0
if(i==0) return; [1] 1
else printArray(i-1); [2] 2
System.out.println("[" + (i-1) + "] " + values[i-1]); [3] 3
} [4] 4
} [5] 5
class Recursion2 { [6] 6
public static void main(String args[]) {
RecTest ob = new RecTest(10);
int i;
for(i=0; i<10; i++) ob.values[i] = i;
ob.printArray(10);
}
}
Introduction to Wrapper Classes
Java provides 8 primitive data types.
• They are called “primitive” because they are not
created from classes.
• Java provides wrapper classes for all of the
primitive data types.
•A wrapper class is a class that is “wrapped
around” a primitive data type.
• The wrapper classes are part of java.lang so to
use them, there is no import statement required.
Wrapper Classes
• Wrapper classes allow you to create objects to
represent a primitive.

• Wrapper classes are immutable, which means that once


you create an object, you cannot change the object’s value.

• To get the value stored in an object you must call a method.

• Wrapper classes provide static methods that are very useful


Wrapper classes
• Character
• String
• Byte
• Integer
• Long
• Double
• Float
• Short
Character Testing and Conversion
With The Character Class
• The Character class allows a char data type to
be wrapped in an object.
• The Character class provides methods that
allow easy testing, processing, and conversion
of character data
The Character Class
Creating a Wrapper Object
• To create objects from these wrapper classes,
you can pass a value to the constructor:

Integer number = new Integer(7);

• You can also assign a primitive value to a


wrapper class object:
The Parse Methods
• A string containing a number, such as “127.89,
can be converted to a numeric data type.
• Each of the numeric wrapper classes has a
static method that converts a string to a
number.
• The Integer class has a method that converts a
String to an int
• The Double class has a method that converts
a String to a double
• The parse methods all throw a
NumberFormatException if the String object does
not represent a numeric value
The toString Methods

• Each of the numeric wrapper classes has a


static toString method that converts a umber
to a string.
• The method accepts the number as its
argument and returns a string representation
of that number.
– int i = 12;
– double d = 14.95;
– String str1 = Integer.toString(i);
– String str2 = Double.toString(d);
MIN_VALUE and MAX_VALUE

• The numeric wrapper classes each have a set


of static final variables
– MIN_VALUE and
– MAX_VALUE
• These variables hold the minimum and
maximum values for a particular data type.
Array of Objects
Public static void main(String[]args)
{
Student[] studentArray=newStudent[7];
for(inti=0;i<studentArray.length;i++)
{
studentArray[i]=new Student();
} public class Student
} {

}
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables and
methods.

• Encapsulation, safely sealing data within the capsule of


the class Prevents programmers from relying on details
of class implementation, so you can update without
worry

• Helps in protecting against accidental or wrong usage.

• Keeps code elegant and clean (easier to maintain)


Access Modifiers: Public, Private,
Protected
• Public:
– Keyword applied to a class, makes it available / visible
every where . Applied to a method or variable,
completely visible.
• Default(Novisibilitymodifierisspecified):
– It behaves like public inits package and private in
other packages.
• Default Public key word applied to aclass, makes
it available / visible every where. Applied to a
method or variable, completely visible.
• Private fields or methods for a class only
visible within that class. Private members are
not visible within subclasses ,and are not
inherited.
• Protected members of a class are visible
within the class , subclasses and also within all
classes that are in the same package as that
class.
Garbage Collection
finalize() Method
public class TestGarbage1
{  
 public void finalize()
{
System.out.println("object is garbage collected");
}  
 public static void main(String args[]){  
  TestGarbage1 s1=new TestGarbage1();  
  TestGarbage1 s2=new TestGarbage1();  
  s1=null;  
  s2=null;  
  System.gc();  
 }  
}  
Inheritance
• Definitions: A class that is derived from another class is
called a subclass (also a derived class, extended class,
or child class). The class from which the subclass is derived
is called a superclass (also a base class or a parent class).

• When you want to create a new class and there is already a


class that includes some of the code that you want, you can
derive your new class from the existing class.

• A subclass inherits all the members (fields, methods, and


nested classes) from its superclass.

• Constructors are not members, so they are not inherited by


subclasses
public class Bicycle {

// the Bicycle class has three fields


public int cadence;
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int startCadence, int startSpeed,
int startGear) {
gear = startGear;
cadence = startCadence; public void setGear(int newValue) {
speed = startSpeed; gear = newValue;
} }

// the Bicycle class has four methods public void applyBrake(int decrement) {
public void setCadence(int newValue) { speed -= decrement;
cadence = newValue; }
}
public void speedUp(int increment) {
speed += increment;
}

}
public class MountainBike extends Bicycle {

// the MountainBike subclass adds one field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}

// the MountainBike subclass adds one method


public void setHeight(int newValue) {
seatHeight = newValue;
}
}
• The inherited fields can be used directly, just like any other fields.

• You can declare a field in the subclass with the same name as the one in the
superclass, thus hiding it (not recommended).

• You can declare new fields in the subclass that are not in the superclass.

• The inherited methods can be used directly as they are.

• You can write a new instance method in the subclass that has the same signature
as the one in the superclass, thus overriding it.

• You can write a new static method in the subclass that has the same signature as
the one in the superclass, thus hiding it.

• You can declare new methods in the subclass that are not in the superclass.

• You can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.
Casting Objects
• public MountainBike myBike = new MountainBike();
– MountainBike is descended from Bicycle and Object. Therefore,
a MountainBike is a Bicycle and is also an Object
– it can be used wherever Bicycle or Object
– The reverse is not necessarily true: a Bicycle may be a MountainBike, but
it isn't necessarily.
• Object obj = new MountainBike();//implicit casting
– then obj is both an Object and a MountainBike

• MountainBike myBike = obj; //error


– because obj is not known to the compiler to be a MountainBike

• MountainBike myBike = (MountainBike)obj; //explicit


Overriding and Hiding Methods
• An instance method in a subclass with the same signature
and return type as an instance method in the
superclass overrides the superclass's method.
• Static Methods

– If a subclass defines a static method with the same signature as a


static method in the superclass, then the method in the
subclass hides the one in the superclass

– The version of the overridden instance method that gets invoked


is the one in the subclass.

– The version of the hidden static method that gets invoked


depends on whether it is invoked from the superclass or the
subclass.
public class Animal {
public static void testClassMethod() {
System.out.println("The static method in Animal");
}
public void testInstanceMethod() {
System.out.println("The instance method in Animal");
}
}
public class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The static method in Cat");
}
public void testInstanceMethod() {
System.out.println("The instance method in Cat");
}

public static void main(String[] args) {


Cat myCat = new Cat();
Animal myAnimal = myCat;
Animal.testClassMethod();
myAnimal.testInstanceMethod();
} The static method in Animal
} The instance method in Cat
Polymorphism
• Subclasses of a class can define their own
unique behaviors and yet share some of the
same functionality of the parent class.

public void printDescription(){


System.out.println("\nBike is " + "in gear " + this.gear
+ " with a cadence of " + this.cadence +
" and travelling at a speed of " + this.speed + ". ");
}
public class MountainBike extends Bicycle {
private String suspension;

public MountainBike(
int startCadence,
int startSpeed,
int startGear,
String suspensionType){
super(startCadence,
startSpeed,
startGear);
this.setSuspension(suspensionType);
}
public void setSuspension(String suspensionType) {
this.suspension = suspensionType;
public String getSuspension(){
}
return this.suspension;
}
public void printDescription() {
super.printDescription();
System.out.println("The " + "MountainBike has a" +
getSuspension() + " suspension.");
}
}
public class RoadBike extends Bicycle{
// In millimeters (mm)
private int tireWidth;

public RoadBike(int startCadence,


int startSpeed,
int startGear,
int newTireWidth){
super(startCadence,
startSpeed,
startGear);
this.setTireWidth(newTireWidth);
}

public int getTireWidth(){ public void setTireWidth(int newTireWidth){


return this.tireWidth; this.tireWidth = newTireWidth;
} }

public void printDescription(){


super.printDescription();
System.out.println("The RoadBike" + " has " + getTireWidth() +
" MM tires.");
}
}
public class TestBikes {
public static void main(String[] args){
Bicycle bike01, bike02, bike03;

bike01 = new Bicycle(20, 10, 1);


bike02 = new MountainBike(20, 10, 5, "Dual");
bike03 = new RoadBike(40, 20, 8, 23);

bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}

Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10.

Bike is in gear 5 with a cadence of 20 and travelling at a speed of 10.


The MountainBike has a Dual suspension.

Bike is in gear 8 with a cadence of 40 and travelling at a speed of 20.


The RoadBike has 23 MM tires.
A Superclass Variable Can Reference a
Subclass Object
class Box {
double width;
double height; class BoxWeight extends Box {
double depth; double weight;
// construct clone of an object
BoxWeight(double w, double h,
double d, double m) {
Box(double w, double h, double d) { width = w;
width = w; height = h;
height = h; depth = d;
depth = d; weight = m;
} }
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class RefDemo
{
public static void main(String args[])
{
BoxWeight weightbox = new BoxWeight( 5.0, 7.0, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();

// assign BoxWeight reference to Box reference


plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
Using super
• Whenever a subclass needs to refer to its
immediate super class, it can do so by use of the
keyword super
• Two forms
– The first calls the super class’ constructor.
– The second is used to access a member of the super
class that has been hidden by a member of a subclass.

• super(parameter-list);
• super.member
Dynamic Method Dispatch
Final
• Class (prevents from extending)
• Method(Prevents overriding ,definition is un
changeable)
• Variable (unchangeable ,constant value)
• Blank variable can be initialized only in the
constructor
Class ant{
final int no;//not initialized
ant(){ no=10;} }
• Static final variable can be initialized only in the
static block
Static final int no;//not initialized
Static { no=10;}
Using final to Prevent Overriding
Using final to Prevent Inheritance
Using Abstract Classes
Interfaces

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
• Interface can contain variables initialized with
value
• For implementing class these variables are
constants like final
• Interface can be extended

Nested and Inner Classes
• defining a class within another class
• The scope of a nested class is bounded by the scope of
its enclosing class
• class B is defined within class A, then B is known to A,
but not outside of A.
• A nested class has access to the members, including
private members, of the class in which it is nested
• The enclosing class does not have access to the
members of the nested class
• While nested classes are not used in most day-to-day
programming, they are particularly helpful when
handling events in an applet
• An inner class is a non-static nested class.
• It has access to all of the variables and methods of its outer
class
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) { Output from this application is shown here:
Outer outer = new Outer(); display: outer_x = 100
outer.test();
} }
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
void showy()
{
System.out.println(y); // error, y not known here!
} class InnerClassDemo {
} public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
// This program will not compile. }
Packages
• Java provides a mechanism for partitioning the class name
space into more manageable chunks
• The package is both a naming and a visibility control
mechanism.
• Java uses file system directories to store packages.
• Avoiding naming conflicts
• Package in java can be categorized in two form, built-in
package and user-defined package
• Defining a Package
– package pkg;
• can create a hierarchy of packages
– package pkg1[.pkg2[.pkg3]];
– package java.awt.image;
// A simple package
class AccountBalance {
package MyPack;
public static void main(String args[]) {
class Balance {
Balance current[] = new Balance[3];
String name;
current[0] = new Balance("K. J. Fielding", 123.23);
double bal;
current[1] = new Balance("Will Tell", 157.02);
Balance(String n, double b) {
current[2] = new Balance("Tom Jackson", -12.33);
name = n;
for(int i=0; i<3; i++) current[i].show();
bal = b;
}
}
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
How to compile java package
Javac -d classes directory java filename
•Eg:
Javac -d classes /home/Balance.java(linux)
Or
Javac -d classes c:/home Balance.java (windows)

Dot is used to store in the working directory

The -d switch specifies the destination where to put the


generated class file
How to run java package program
• Eg: java mypack.Balance
• Hero Honda motor bike company is planning for “Bikes
for the Future” in which they are going to launch Low
Cost to high cost bikes with Ultra Low emission to Low
Emission vehicles. The bikes are also designed to run
under Petrol. The Cubic capacity varies from 99.2cc to
120.9cc. Create a class BikeDesign with data members
like bike model, cost and no. of gears as class variables.
Store the details of bikes using array of objects. Write a
java program that accepts inputs as cost and number
of gears and displays the model of the bike with all its
features. ( Abstract Class is Mandatory).
I/O in java
• used to process the input and produce the
output
• Java uses the concept of stream to make I/O
operation fast
• Java.io package
• file handling
Stream
• A stream is a sequence of data composed of
bytes
• A stream is linked to a physical device by the Java
I/O system
• OutputStream
– output stream to write data to a destination, it may
be a file, an array, peripheral device or socket
• InputStream
– to read data from a source, it may be a file, an array,
peripheral device or socket
Byte Streams and Character Streams
• Java 2 defines:byte and character stream
• Byte streams provide a convenient means for
handling input and output of bytes.
• Eg:reading or writing binary data
• Character streams provide a convenient
means for handling input and output of
characters
• They use Unicode
Byte stream
• Defined by two abstract class hierarchies
– Input Stream
– OutputStream

• Read(),write() important methods that can be


overridden by the derived stream classes
Char stream
• Reader and Writer are two abstract classes
handle unicode stream
• Read(),write() are the two important methods
OutputStream Hierarchy
Outputstream Methods

Method Description
is used to write a byte to the current output
public void write(int)throws IOException
stream.
is used to write an array of byte to the
public void write(byte[])throws IOException
current output stream.

public void flush()throws IOException flushes the current output stream.

public void close()throws IOException is used to close the current output stream.
FileOutputStream class methods

Method Description

It is sued to clean up the connection with


protected void finalize()
the file output stream.

It is used to write ary.length bytes from


void write(byte[] ary)
the byte array to the file output stream.

It is used to write len bytes from the byte


void write(byte[] ary, int off, int len) array starting at offset off to the file
output stream.
It is used to write the specified byte to
void write(int b)
the file output stream.

It is used to return the file channel object


FileChannel getChannel()
associated with the file output stream.

It is used to return the file descriptor


FileDescriptor getFD()
associated with the stream.
Reading Console Input
• console input is accomplished by reading from
System.in
• BufferedReader object is used to create a
character stream.
• BuffereredReader supports a buffered input
stream
• Constructor BufferedReader(Reader inputReader)
• Reader is an abstract class. its concrete
subclasses is InputStreamReader
• InputStreamReader object that is linked to
System.in
Reading Characters

• read() method is used which throws


IOException and returns integer.
Reading Strings

• readLine() method from BufferedReader class


Reading and Writing Files
• In Java, all files are byte-oriented
• methods to read and write bytes from and to
a file.
• to wrap a byte-oriented file stream within a
character-based object is possible
• Two of the most often-used stream classes are
– FileInputStream
– FileOutputStream
Methods defined by InputStream :
• read(), read(byte[] r), available(), close(), etc.
• read() method returns -1 when the end of
file(EOF) is encountered ,It throws
IOException

Methods defined by OutputStream :


• write(int w), write(byte[] w), finalize(), close(),
etc
write byte to a File
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Constructors:
FileInputStream(File file)
FileInputStream(String name)
FileOutputStream(File file)
FileOutputStream(File file, boolean append)
FileOutputStream(String name)
FileOutputStream(String name, boolean append)
Write a String to File

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
It is used to write ary.length bytes from
void write(byte[] ary):
the byte array to the file output stream.

It is used to write len bytes from the


void write(byte[] ary, int off, int len): byte array starting at offset off to the
file output stream.

It is used to write the specified byte to


void write(int b):
the file output stream.
InputStream Hierarchy
Inputstream Methods

Method Description

1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of file.

returns an estimate of the number of


2) public int available()throws IOException bytes that can be read from the current
input stream.

3) public void close()throws IOException is used to close the current input stream.
read single character from file

import java.io.FileInputStream;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileInputStream fin=new FileInputStream("D:\\testout.txt");    
            int i=fin.read();  
            System.out.print((char)i);    
  
            fin.close();    
          }catch(Exception e){System.out.println(e);}    
         }    
        }  
read all characters from a file

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Using FileInputStream
public class FileReaderExample {

    public static void main(String args[]) {


        try {
            //opening file for reading in Java
            FileInputStream file = new FileInputStream("C:/test.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(file));
     
            //reading file content line by line
            String line = reader.readLine();
            while(line != null){
                System.out.println(line);
                line = reader.readLine();
      }
         
        } catch (FileNotFoundException ex) {  }
catch (IOException ex) {                  } 
 }
}
Using BufferedReader

public class BufferedReaderExample {  

    public static void main(String args[]) {


              //reading file line by line in Java using BufferedReader      
        FileInputStream fis = null;
        BufferedReader reader = null;
              try {
            fis = new FileInputStream("C:/sample.txt");
            reader = new BufferedReader(new InputStreamReader(fis));
                      System.out.println("Reading File line by line using BufferedReader");
                      String line = reader.readLine();
          while(line != null){
                System.out.println(line);
                line = reader.readLine();
      }   
                  } catch (FileNotFoundException ex) {
                   } catch (IOException ex) {
                       } finally {         
  try {
                reader.close();                fis.close();            } catch (IOException ex) {
                          }        }  }
Using Scanner Class
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerExample {

    public static void main(String args[]) throws FileNotFoundException {


 
        //creating File instance to reference text file in Java
        File text = new File("C:/temp/test.txt");
   
        //Creating Scanner instnace to read File in Java
        Scanner scnr = new Scanner(text);
   
        //Reading each line of file using Scanner class
        int lineNumber = 1;
        while(scnr.hasNextLine()){
            String line = scnr.nextLine();
            System.out.println("line " + lineNumber + " :" + line);
            lineNumber++;
    }     
  }  
}
--------------------- START-----------------------------------------------------
Java provides several way to read files.
You can read file using Scanner, FileReader, FileInputStream and BufferedReader.
This Java program shows How to read file using java.util.Scanner class.
--------------------- END--------------------------------------------------------
Char Stream vs Byte Stream
Data Streams
• Data streams support binary I/O of primitive
data type values (boolean, char, byte, short,
int, long, float, and double) as well as String
values
• All data streams implement either the
DataInput interface or the DataOutput
interface
• Classes :DataInputStream ,DataOutputStream
• DataInputStream wraps an InputStream
Object and let the application read the Java
primitive data types from the wrapped input
stream.
• DataOutputStream wraps an OutputStream
Object and let the application write Java
primitives to the wrapped output stream.
Constructor with wrap
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(dataFile)));

DataInputStream in = new DataInputStream(


new BufferedInputStream(
new FileInputStream(dataFile)));

DataStreams detects an end-of-file condition by


catching EOFException
import java.io.*;
public class DataOutputStreamExample {
static final double[] price = { 15.43, 10.12, 50.8, 249.56, 18.99 };
static final int[] qty = { 10, 23, 45, 14, 2 };
static final String[] items = { "keyboard", "mouse", "core java ebook", "ups", "pen drive", }

public static void main(String[] args) {


try {
OutputStream os = new FileOutputStream("data.txt");
BufferedOutputStream bos = new BufferedOutputStream(os);
DataOutputStream out = new DataOutputStream(bos)
for (int i = 0; i < price.length; i++) {
out.writeUTF(items[i]);
out.writeInt(qty[i]);
out.writeDouble(price[i])
System.out.println("Data successfully written to a file");
} catch (IOException e) {
} }}
import java.io.*;
public class DataInput_Stream { `
public static void main(String args[])throws IOException {

// writing string to a file encoded as modified UTF-8


DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
dataOut.writeUTF("hello");

// Reading data from the same file


DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));

while(dataIn.available()>0) {
String k = dataIn.readUTF();
System.out.print(k+" ");
}
}
}
DataInputStream:Methods
DataOutputStream:Methods
int read(byte[] b)
void write(byte[] b, int off, int
boolean readBoolean()
len)
byte readByte()
void write(int b)
char readChar()
void writeBoolean(boolean v)
double readDouble()
void writeChar(int v)
float readFloat()
void writeBytes(String s)
int readInt()
void writeUTF(String str)
Object Streams
• support I/O of objects
• Classes:ObjectInputStream and ObjectOutputStream.
• writeObject() and readObject() methods
• readObject() method read an object from the
ObjectInputStream
import java.io.*;
public class ObjectInputStreamExample
{
public static class Person implements Serializable {
public String name = null;
public int age = 0;
}

public static void main(String[] args) throws IOException, ClassNotFoundException


{
ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(“c://person.bin"))
Person person = new Person();
person.name = "Jakob Jenkov";
person.age = 40;
obj.writeObject(person);
obj.close()
ObjectInputStream objin =new ObjectInputStream(new FileInputStream(“c://person.bin")
Person personRead = (Person) objin.readObject();
objin.close();
System.out.println(personRead.name);
System.out.println(personRead.age);
} }
Exception Handling
• Java exception is an object that describes an
exceptional (that is, error) condition that has occurred
in a piece of code.
• Exceptions can be generated by the Java run-time
system, or they can be manually generated by your
code.
• System-generated exceptions are automatically
thrown by the Java run-time system.
• To manually throw an exception, use the keyword
throw.

• try, catch, throw, throws, and finally


try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}

• Any code that absolutely must be executed before


a method returns is put in a finally block.
Exception Types
• All exception types are subclasses of the built-
in class Throwable.
• RuntimeException :Exceptions of this type are
automatically defined for the programs
• division by zero and invalid array indexing.
• Error:Stack overflow is an example of error
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

• Java run-time system detects the attempt to


divide by zero, it constructs a new exception
object and then throws this exception.
• the execution of Exc0 stops
class Exc2
{
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Multiple catch Clauses
• can specify two or more catch clauses
• each catching a different type of exception
• When an exception is thrown, each catch
statement is inspected in order, and the first
one whose type matches that of the exception
is executed.
Java’s Built-in Exceptions
unchecked exception
• java.lang
Cont..

unchecked exceptions because the


compiler does not check to see if a method handles or throws these exceptions
Checked
User Defined Exceptions
class UserDefinedException
{
//MyException.java static void compute(int num) throws MyException {
class MyException extends Exception { System.out.println("Called computer(" + num + "]");
private int detail; if (num < 10)
{
MyException(int a) { System.out.println("Number Is Less Than 10");
detail = a; }
} else
throw new MyException(num);
public String toString() { }
return "MyException[" + detail + "}";
public static void main(String args[]) {
} try {
} compute(9);
compute(10);

} catch (MyException me) {


System.out.println("Caught " + me);
}
}}
Methods in Throwable class
• String toString( ) : Gives you a String object and description of the exception.
This  method is called by the println ( ) method when an object of Throwable is
passed to it as argument.
 
• String getMessage( ) : Gives you the description of the exception in program
 
• Throwable fillInStackTrace( ) :  Gives you aThrowable Object that contains a stack
trace.
 
• void print StackTrace( ) :  Gives you and print the stack trace.
 
• void printStackTrace(PrintStream stream) :  Return the stack trace to a specific
defined stream
 
• String getLocalizedMessage() : Return the Localized description of the exception
Java Swing
• Javax.swing
Java Applet Programing
• Runs on the browser
• Embedded in the web page
• Extends Applet class ot Japplet(Swing)
• Overide
• public void init()
• public void paint(Graphics g)
• Start()
• Stop()
• Destory()
Life Cycle of an Applet
• An applet can react to major events in the
following ways:
• It can initialize itself.
• It can start running.
• It can stop running.
• It can perform a final cleanup, in preparation
for being unloaded.
2D graphics
drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

drawLine(int x1, int y1, int x2, int y2)

drawOval(int x, int y, int width, int height)

drawPolygon(int[] xPoints, int[] yPoints, int nPoints)

drawRectvoid (int x, int y, int width, int height)

drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

drawString(String str, int x, int y)

fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)

fillOval(int x, int y, int width, int height)

fillPolygon(int[] xPoints, int[] yPoints, int nPoints)

fillRect(int x, int y, int width, int height)

fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Java Networking
• TCP/IP
• SOCKET Programming
• Ports
• 21-FTP,23-Telnet,25-Mail,80 for HTTP etc
• Client/Server
• Internet Addressing IPv4 & IPv6
• Java.net
• Java.rmi
Java.net
• Classes and Interfaces
• Classes listed below
• Interfaces listed below
Sockets
• A socket is one endpoint of a two-way communication link between two programs
running on the network.
• A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent to.
• Server and client

• Server sockets constrcutors


– ServerSocket(int port)
– ServerSocket(int port, int backlog)
• backlog: the maximum length of the queue of clients waiting to be processed
(default is 50).
• Socket accept()
• void close()
try { ! !
ServerSocket s = new ServerSocket(port);
while (true) { ! !
Socket incoming = s.accept();
«Handle a client»
incoming.close();
}
s.close(); ! !
} catch (IOException e) {
«Handle exception»
}
Client Socket
• Socket(String host, int port)
• host: the address of the host port: the port
number
• getInputStream()
• getOutputStream()
try { ! !
Socket socket = new Socket(host, port);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()));
«Send and receive data»
in.close(); ! !
out.close(); ! !
socket.close(); ! !
} catch (IOException e) {
«Handle exception»
}
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
){
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
} } catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) { System.err.println( "Usage: java
EchoClient <host name> <port number>"); System.exit(1); }
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
){
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine()); }
}
catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}

You might also like