Академический Документы
Профессиональный Документы
Культура Документы
Java Fundamentals
Unit 1
Syllabus
1 Review of OOP
7 Comments
Profound effect
Introduction
vJava Environments
q Java software is available as JDK (Java
Development Toolkit) version 1.0 or 1.1 or 1.2…
1.7
q Development environments
ØJava Workshop
ØBorland JBuilder
ØVisual Java (VJ++)
ØNetBeans
ØEclipse
ØWeb sphere etc.,
Features
v Architectural Neutral
q Java gained huge popularity due to its platform
independence.
Features
v Architectural Neutral
q One can make the web page using HTML and call
the “.class” file inside it. This web page is then
transported over internet
Class lib
loaded
Java
Compiler Interpreted
001100
Rejected
010001
101101 Exception Handled
010101
Executable code
Features
v Robust
q Most of the programs are leads to failure if there is
no focus paid on memory management or
exceptional behavior of the program.
Features
v Reliable, Safe and Secure
q Java program is capable of being transported over
internet and running on anybody’s machine.
Features
v Simple and easy to learn
q Java will be very simple once the basics of OOPs
are clear
v Powerful
q Java unleashes the its power thro the classes in
the library
Platform Independence
JAVA COMPILER
(translator)
JAVA INTERPRETER
(one for each different system)
Java Application
v Key points to be remembered
Save the name of the file
as class name with
“.java” extension
import java.lang.*;
public class Class_name{
public static void main(String a[]){
----
- - - - needed statements- - -
----
}
}
OOP
v Key points to be remembered
q Issues with C
q Is C++ a completely OOP?
q Why OOP
q OOP Paradigm
q Features of OOP
q OOP Concepts
Ø Class
Ø Abstraction
Ø Encapsulation
Ø Inheritance
Ø polymorphism
10
OOP
v Why OOP?
q Example: Assemble
Ø your own PC
Ø car
11
OOP
v OOP Paradigm
q OOP is introduced to solve the problems of
procedural approach
12
Data Data
Object A
Communication
methods methods
Object C
methods
Data
OOP
v Features of OOP
q Program is divided into objects
13
OOP
v OOP Concepts
q OOP is introduced to solve the problems of
procedural approach
q They are:
1. Objects
2. Classes
3. Data Abstraction & Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Communication
14
OOP Concepts
v Class
q “Class” is a collection of Similar objects
15
OOP Concepts
v Class
Prototype
class class-name {
//members of a class
public static void main(String s[ ]){
// - - - -
// needed statements
// - - - -
}
};
16
v Object
q Runtime entity
q It can be instantiated (created) from the class
Ex:
test t1 = new test();
17
Ex:
test t1 = new test();
t1.name=“Third CSE B”;
t1.total=57;
t1.display();
Examples
v Do it yourself
1. Write a simple java Program to print “name and
age of the person”
18
Encapsulation
v Key points to be remembered
q Striking feature of OOP
Insulated data
19
q Example?
Inheritance
v Key points to be remembered
q It is the process of sharing attributes and
operations among classes based on a hierarchical
relationship
20
Inheritance
v Example 1
q Assume you have 2 classes namely A and B.
21
Inheritance
v Example 2
q Consider a company dealt with the hardware.
Assume this item is classified into 3 sub-classes
namely Printer, Stationery and floppy disk
22
Printer
Type Capacity
Size
Pagesperminute Size
Stationery Floppy disk
Polymorphism
v Key points to be remembered
q Important feature of OOP
23
show
Polymorphism
v Key points to be remembered
q It allows an entity to take a variety of
representations
24
Draw()
Dynamic Binding
v Key points to be remembered
q “Binding” is the process of linking a procedure
call to the code to be executed in response to the
call.
q 2 types:
1. Static Binding
2. Dynamic Binding
25
Draw()
Each object has its own draw() method. For every successive invocation
the draw() will be refined for each class. During run time,
the code matching the object under the current reference will be called
Message Passing
v Key points to be remembered
q An OOP allows the user to create a program with
objects
q Example:
compute.add(10,20);
26
q Applications
Ø Real Time Systems
Ø Simulation and Modeling
Ø Object Oriented databases
Ø Hypertext, Hypermedia and expertext
Ø AI and Expert Systems
Ø Neural Networks and parallel Programming
Ø CIM/CAD system
27
}
:
:
}
28
int area(){
return length * width;
}
int perim(){
return 2 * (length + width);
}
}
29
30
Classes Objects
System out
String println
DataInputStream readLine
InputStreamReader readInt
Example
31
32
“set Path=%path%.;c:\jdk1.6\bin;”
33
javac filename.java
java filename
q Example
java filname 10 20
34
java filname 10 20
S [0] - 10
S [1] - 20
Example ?
35
Strings
v Key points to be remembered
q String is a sequence of characters enclosed within
double quotes
q Example:
36
Strings
v Key points to be remembered
q “String” object can be created by 2 forms
1. By using literal
2. By new key word
37
Classes
String()
String(byte bytes[ ])
String(byte bytes[ ], Charset charset)
String(byte[ ] bytes, int offset, int length, Charset charset)
String(String original)
String(StringBuffer buffer)
Strings
v Key points to be remembered
Methods
int length() int lastIndexOf(int ch)
String concat(String str) int lastIndexOf(int ch, int fromIndex)
Int indexOf(int ch) int lastIndexOf(String str)
Int indexOf(int ch, int from) int lastIndexOf(String str, int fromIndex)
Int indexOf(String str) String substring(int beginIndex)
String intern() String substring(int beginIndex, int
endIndex)
int indexOf(String str,
char[] toCharArray()
int fromIndex)
boolean isEmpty() String toLowerCase()
38
Methods
int length() returns the length of this string
String concat(String str) concatenates the specified string to the end
of this string
Int indexOf(int ch) returns the index within this string of the
first occurrence of the specified character.
Int indexOf(int ch, int returns the index within this string of the
from) first occurrence of the specified character,
starting the search at the specified index.
Int indexOf(String str) returns the index within this string of the
first occurrence of the specified substring
String intern() This method returns a canonical
representation for the string object.
Strings
v Key points to be remembered
Methods
int indexOf(String str, int This method returns the index within this
fromIndex) string of the first occurrence of the
specified substring, starting at the specified
index.
boolean isEmpty() This method returns true if, and only if,
length() is 0.
int lastIndexOf(int ch) This method returns the index within this
string of the last occurrence of the
specified character
int lastIndexOf(int ch, int This method returns the index within this
fromIndex) string of the last occurrence of the
specified character, searching backward
starting at the specified index.
39
Methods
int lastIndexOf(String This method returns the index within this
str) string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String This method returns the index within this
str, int fromIndex) string of the last occurrence of the
specified substring, searching backward
starting at the specified index.
String substring(int returns a new string that is a substring of
beginIndex) this string
String substring(int
returns a new string that is a substring of
beginIndex, int
this string.
endIndex)
Strings
v Key points to be remembered
Methods
char[ ] toCharArray() converts this string to a new character
array.
String toLowerCase() converts all of the characters in this String
to lower case using the rules of the default
locale
String converts all of the characters in this String
toLowerCase(Locale to lower case using the rules of the given
locale) Locale.
String toString() returns the string itself
40
Methods
static String returns the string representation of the char
valueOf(char c) argument.
Example?
StringBuffer
v Key points to be remembered
q “StringBuffer” is a peer class of “String” that
provides much of the functionality of strings.
41
Constructors
StringBuffer() Creates empty String Buffer with the
initial capacity of 16
StringBuffer(String) Creates a String object with the
specified String
StringBuffer(int) Creates empty String Buffer with the
specific capacity
StringBuffer
v Key points to be remembered
Methods
setCharAt(n, ‘X’) Modifies the “n” th character to X
append(String) Appends the specified string
Inserts the specified String at nth
insert(n,String)
position
Returns the allocated capacity of
capacity()
Stringbuffer object
Returns the actual length of the
length()
string object
Set the length of StringBuffer
setLength()
object
42
Methods
reverse() Used to reverse the String
capacity() Used to return the current capacity
length() Used to return the actual length of
the string
substring()
Used to separate the String
Access Specifiers
v Key points to be remembered
q “Access Specifier” is a concept that helps one to
restrict the access to members of the class
q Offers 4 types
Ø public
Ø default (no specifier or friendly access)
Ø protected
Ø private
43
Access Specifiers
v public
44
Access Specifiers
v Friendly access
q In many programs, programmer may failed to set
of variables or functions declared as “public”. At
this instant still the members will be accessible to
other classes in the program
45
Access Specifiers
v protected
q This visibility lies between “public” and “friendly
access”
46
Access Specifiers
Private
Accessibility Public Protected Friendly private
protected
Same class Yes Yes Yes Yes Yes
Sub-class in same
Yes Yes Yes Yes No
package
Other classes in the
Yes Yes Yes No No
same package
Sub-classes in other
Yes Yes No Yes No
packages
Non subclasses in
Yes No No No No
other packages
47
Use When
public If the field is to be visible everywhere
protected If the field is to be visible everywhere in the
current package & sub-classes in other
packages
default If the field is to be visible everywhere in the
current package
private protected
If the field is to be visible only in subclasses
Constructors
v Key points to be remembered
Data member
class personal{
String name;
int age;
void getDetails() throws Exception{
DataInputStream di = new DataInputStream(System.in);
name = di.readLine();
age=di.readInt();
}
}
class profile{
Function member
public static void main(String s[ ]) throws Exception{
personal p = new personal();
p.getDetails();
} Here, member function getdetails() can be accessed via
} the instance of class “personal” like p.getDetails() where by
Data can be assigned
48
class profile{
public static void main(String s[ ]) throws Exception{
personal p = new personal();
p.getDetails();
}
}
Constructors
v Key points to be remembered
q These functions can not be used to initialize the
member variables at the time of creation
49
Constructors
v Synonym
q “Constructor” is a method which are used to
initialize object automatically when the instance of
the appropriate class is created
50
Constructors
v Types
1. Default Constructor
2. Parameterized Constructor
3. Copy constructor
4. Multiple Constructors in a class
51
Constructors
v Default Constructor
class assign{ “assign()” is default constructor
double length, width; that accepts no arguments
assign(){
length=2.0;width=3.0;
}
double area(){
return ½* length * width;
}
Invokes the default constructor
}
& initialize the values
class rectangle{
public static void main(String s[ ]){
assign a=new assign();
double res = a.area();
}
}
52
Constructors
v Parameterized Constructor
q A constructor that can take arguments for its
initialization are referred as “Parameterized
Constructor”
53
Examples
v Do it yourself
q Implement a java application using constructor to:
1. Create a class called employee that will have
the following attributes. Employee no., name,
address, dob, hiredate. The class must have the
following methods also;
a) A constructor that accepts nothing and initializes
all numeric attributes with “0” and string with null
b) A constructor that accepts all attribute values
c) A method called display() that displays all the
attributes
d) A method called changeAddress(String address)
that changes the address of an employee
54
Polymorphism
v Key points to be remembered
Polymorphism
Operator Function
Virtual Function
Overloading Overloading
55
Function Polymorphism
Polymorphism
v Function Overloading
q i.e., Using the concept of “Function Overloading”,
one can design a family of functions with one
function name but with different argument list.
56
Polymorphism
v Function Overloading
q For the best illustration consider a function
“add()” can handle different types of data:
Function Prototype
57
q Example:
test(int a, int b)
test(double a, double b)
test(double a, double b, double c)
Constructor Chaining
v Key points to be remembered
q Consider the scenario where a base class is
extended by its child class. Whenever an object of
child class is created, the constructor of parent
class will be invoked first. This is called
“Constructor chaining”
58
Example?
Copy Constructor
v Key points to be remembered
q If a constructor accepts a “reference” to its own
class as a parameter. Then it is referred as “Copy
Constructor”
59
class classname{
classname(classname obj){
// needed statements
}
}
Examples
v Do it yourself
1. Write a program to find the volume of the room
using copy constructor
60
Array
v Key points to be remembered
61
q Demerits
1. Size is limited - one can store fixed size of
elements ; does not grow at run time
Array
v Key points to be remembered
q Types
1. Single dimensional array
2. Multi dimensional array
62
datatype[ ] var;
or
datatype [ ]var;
or
datatype var[ ];
Array
v One dimensional array
Syntax
datatype var[ ];
var = new datatype[size];
instantiation
63
Declare,
instantiation and
intialize
Examples
v Do it yourself: Write a program
1. To read and print the n elements using an array
2. To display the sum and average of n elements
3. To sort the given elements in ascending order
64
datatype[ ][ ] var;
or
datatype [ ][ ]var;
or
datatype var[ ][ ];
Array
v One dimensional array
Syntax:
instantiate
datatype var[ ];
var = new datatype[row][column];
instantiation
65
a[0][0]=1;
a[0][1]=2;
a[0][2]=3;
a[1][0]=4;
a[1][1]=5;
int a[ ][ ]={{1,2,3},{2,4,5},{4,4,5}};
a[1][2]=6;
a[2][0]=7;
a[2][1]=8;
a[2][2]=9;
Arrays
v Key points to be remembered
q “Arrays” is a static block – available in “java.util”
package. It permits arrays to be viewed as list
Object
Arrays
66
Example:
int a[ ] = {10, 2, 5};
Arrays.sort(a)
Arrays
v Key points to be remembered
Methods
sort(array[ ]) Used to sort in ascending order
sort(double[ ]) Sort the array of doubles in asc. Order
67
Static Members
v Key points to be remembered
Data member
class person{
char name[20];
int age;
void getdetails(void){ }
void display(void){ }
};
Function member
68
69
q i.e.,
Ø Boolean – false
Ø Numeric – 0
Ø String – null
70
classname.staticvariable;
or
objectname.staticvariable;
Example?
71
classname.staticmethodname([arguments]);
or
objectname.staticmethodname([arguments]);
Static method
v Properties of a static method
q Static method can invoke or access to only other
static members (functions /variables) declared in
the same class
72
finalize method
v Key points to be remembered
q For the best illustration, consider one have written
a Java program to access database and file
system (nonobject resources).
73
finalize method
v Key points to be remembered
q Write “finalize()” method in a class if it holds one
or more nonobject resources
74
finalize method
v Key points to be remembered
q Any exception thrown by “finalize()” method will
be taken care by GC thread
System.runFinalization()
Runtime.getRuntime().runFinalization()
or
System.gc();
or
System.getRuntime().gc();
75
Skeleton
@Override
protected void finalize() throws Throwable {
// do cleanup activity
Packages
v Key points to be remembered
q Java Package is a mechanism for organizing java
classes
76
q Example
Ø Assume one is writing a java programs and not
allowed to store under some directory
Packages
v Key points to be remembered
q Use
Ø To prevent naming conflicts
Ø To control access
Ø To make searching
q Package Examples
Package remarks
java.lang Bundles the fundamental classes
java.io Bundles the classes for input and output
functions
77
Packages
v Creating your own package
q To create own package, one must understand the
access levels / specifiers with respect to package
78
Use it as a “package”
Packages
v Creating your own package
q Similar to handling a directory in the system
package packagename;
79
Packages
v Constraints to execute your own package
q With reference to example, one need to create 2
programs
Ø In “Stack.java”, first statement should be the
package statement which defines the class
belongs to which package.
package packagename;
80
import packagename.*;
Packages
v Steps to execute your own package
1. Create needed Java programs (2 or many) with the
constraints. Example: stack
2. Create 2 folders / directories in the system
Example: c:\test\my
81
Packages
v Note
q Packages may not be visible to other folders. To
make it visible during the execution of program, it
is essential to set the path setting to the java
environment
82
C:\test\my C:\test
package my; import my.*;
public Class Stack{
Stack(int size){ public class CallStack{
--- public static void main(String a[]){
---
} Stack s=new Stack(5);
for(int i=0;i<5;i++)
public void push(int item){ s.push(i);
--- ---
} ---
public int pop(){ for(int i=0;i<5;i++)
--- System.out.println(s.pop());
} }
} }
83