JAVA Tutorial
JAVA Tutorial
Lokendra Singh
Introduction to Java
What is Java?
An Object-Oriented Programming language that is developed by sun Microsystems. A Virtual machine(run time environment) that can be embedded in web browsers (e.g. Netscape Navigator, Microsoft Internet Explorer) and Operating Systems. A set of standardized Class libraries (packages), that support :
Creating user interfaces Communicating over network etc.
Features of Java
Java is Simple
Java is not just a language for use with Internet. It is a full featured Object-Oriented Programming Language (OOPL). Java is a bit easier than the popular OOP language C++. Java use automatic memory allocation and garbage collection.
Java is Object-Oriented
Provides great flexibility, modularity, and reusability.
Java is Distributed
Distributed computing involves several computers working together on a network.
Java is Robust
Robust means reliable. Java puts a lot of emphasis on early checking for possible errors, because Java compilers can detect many problems that would first show up at execution time in other languages. Also it has runtime exception handling feature to provide programming support for robustness.
Features of Java
Java is Interpreted & Architecture-Neutral
Java is compiled to byte-codes whose target architecture is the Java Virtual machine (JVM) These byte codes are portable across architecture boundaries. The virtual machine is embeddable within other environments, e.g. web browser and operating systems. Utilize a byte-code verifier when reading in byte-codes. The class loader is employed for classes loaded over the network (enhances security)
Features of Java
Multithreaded
It is a programs capability to perform several tasks simultaneously.
C++ Architecture
.cpp (Source Code) Compiler .obj (Binary Code) LIBRARY Linker .obj (Binary Code)
.exe (Installable)
Operating System
Java Architecture
.java (Source Code) Compiler .class (Byte Code) .class (Byte Code) LIBRARY
JVM
Operating System
Dotnet Architecture
vb.net (Source Code) Compiler .cs (Source Code) cobol.net (Source Code)
CLR
Operating System
JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone applications.
} }
byte
Size : 1 byte, Range : -128 to 127, Default Value : 0
short
Size : 2 bytes, Range : -32768 to 32767, Default Value : 0
int
Size : 4 bytes, Range : -231 to 231-1 , Default Value : 0 Default integral type
long
Size : 8 bytes, Range : -263 to 263-1 , Default Value : 0
float
Size : 4 bytes, Precision : 7 to 8 , Default Value : 0.0
double
Size : 8 bytes, Precision : 15 to 16 , Default Value : 0.0 -Default decimal type
char
Size : 2 bytes, Unicode support , Default Value : \u0000
bool
true / false , Default Value : false
Variables
Basic Vs. Reference
Basic : Stores value itself. Reference : Points to the value (Object)
Operators
Arithmetic Operators
+, -, *, /, %, ++, +=, - =, *=, /=, --
Assignment Operator
=
Conditional Operator
(expression1 ? expression2 : expression3)
Conditional constructs
The if construct
if (expression)
Statement;
else
Statement;
Iteration construts
while while (n>0) { statements; } do-while do{ statements; }while (n>0) for for (initialization; condition; iteration) { statements; }
Jump statements
break
while() { statements; if (condition) break; statements; }
continue
while() { statements; if (condition) continue; statements; }
Arrays
An Array is a named set of variables of the same type. Each variable in an array is called an array element. To reference a particular element in an array, you need to use array name combined with an integer value of type int called an index.
Arrays
Declaration of an array int [] primes; or int primes[]; Construction of an array int [] primes = new int[10]; Initializing an array for (int i=0;i<10;i++) { primes[i]=i; } double [] inputArray = new double[5]; double [] temp = inputArray; * *
Arrays
Array length
A data member of the array
Quiz
How do you think an array type variable differs from a primitive type variable?
1. Its value must be string 2. It can be used only in calculations containing other non primitive types 3. Its value is a reference to an object.
Introduction to Objects
This is the formal definition of the shape and functionality of the objects to be created later. No memory allocated.
object
class
girl
Rose
Sheral
Triza
Juli
Understanding OO Concepts
Class BankAccount
account_number owner balance type_of_account makeDesposit transfer withDraw getBalance
1.
Many objects can be said to be of the same type or class My bank account, your bank account, Bill Gates bank account We call the object type a class An Object is instantiated from a Class BankAccount myAccount; myAccount = new BankAccount();
2. 3.
Understanding OO Concepts
Object Interactions and Messages
The means by which objects interact Example: User initiates interaction via messages to GUI objects GUI objects interact with problem domain objects via messages Problem domain objects interact with each other and GUI objects via messages GUI objects respond to user via messages
Encapsulation
Encapsulation
Encapsulation
Objects have attributes and methods combined into one unit.
Information Hiding
Hiding the internal structure of objects, protecting them from corruption
Advantages Of Encapsulation
Data Protection Consistency Maintenance
Encapsulation
Interface & Implementation Two views of an object
Internal (The structure of its data, the algorithms used by its methods) External (The interaction of the object with other objects in the program.)
From the external view, an object is an encapsulated entity, providing services. These services define the interface to the object. The user, or client of an object can request its services, but it should not have to be aware of how those services are accomplished. (abstraction hide details)
Encapsulation
An encapsulated object can be thought of as a black box or an abstraction Its inner workings are hidden to the client, which only invokes the interface methods.
Client
Methods
Data
Inheritance
Inheritance
Is the process by which one object acquires the properties of another object. Superclass/ Baseclass Subclass/ Derivedclass Generalization/specialization hierarchy Extension and Redefinition Benefits of Inheritance
Saves effort of reinventing the wheel. Allows us to build on existing code, specializing without having to copy it, rewrite it etc. Allows for the flexibility in the class definitions.
Inheritance
Manager
Non Manager
Inheritance
Hierarchical classification: Is-a relationship : inheritance One class inherits the abilities of another class
Inheritance
Hierarchical classification: Has-a relationship : containment One class can provide services to another, acting as an attribute.
Has-A
Human Being
Heart
Part-Of
Inheritance Example
Example : Bank Accounts Consider a primitive bank account which allows only three kind of transactions :
Deposits Withdrawals Ability to check current balance
Class BankAccount
account_number owner balance type_of_account makeDesposit withdraw getBalance
Inheritance Example
Inheritance by Extension Imagine that we wish to create a new kind of Bank Account that is
Identical to the base class in all respects except one. We want to add the ability for the account to earn interest.
Without inheritance, wed have to write it from scratch, duplicating code etc. With inheritance, we need to code only the new capability and inherit the rest.
Class BankAccount
account_number owner balance type_of_account makeDesposit transfer withDraw getBalance
Class SavingAccount
Rate MIN_BALANCE Cal Interest
Inheritance Example
Inheritance by Redefinition Imagine that we wish to create a new kind of Savings Account that is identical to the 4ving Account in all respects except one. We want to change the way in which withdrawals are handled. The base class already handled withdrawals but now we want a subclass that does them differently. Without inheritance, wed have to rewrite it from scratch. With inheritance, we need to code only the new way that we want withdrawals to work.
Class SavingAccount
Rate MIN_BALANCE Cal Interest
Class CoolSavingAccount
withdrawal
Inheritance Example
The Banking Class Hierarchy Class BankAccount
account_number owner balance type_of_account makeDesposit transfer withDraw getBalance
Class SavingAccount
Rate MIN_BALANCE Cal Interest
extension
Inheritance
Summary Declare common methods/attributes as high in the class hierarchy as possible. All subclasses will inherit these capabilities. Specialize (extend and redefine) in subclasses. When a method is invoked, the request is serviced by the lowest, most specific class and moves up as needed to find a match
Polymorphism
Polymorphism
The ability of different objects to perform the appropriate method in response to the same message is known as polymorphism. The ability for a variable (of a superclass type) to contain different objects of a subclass type at different points in time. Results in different functionality being executed for the same method call Allows for runtime (dynamic) instead of compile time (static) binding
Polymorphism
Let us consider the inheritance structure connecting various different types of bank accounts, such as Saving, Current, Fixed deposit.
BankAccount
SavingAccount
CurrentAccount
FixedDepositAccount
Polymorphism
Suppose the BankAccount class has a function called calculate_interest, which is not overridden by any of its derived classes.
BankAccount b1 = new BankAccount(); b1.calculate_interest(); SavingAccount s1 = new SavingAccount(); s1.calculate_interest(); CurrentAccount c1 = new CurrentAccount(); c1.calculate_interest();
Polymorphism
Now let us consider the possibility the derived classes implement their own version of the calculate_interest function. We could consider having a single Linked List of various types of Bank Account objects, and process it in one iteration, as follows :
BankAccount[] bankaccounts = new BankAccount[1000]; //Add various SavingAccount, CurrentAccount, etc. to this //Process all bankaccounts for calculating interest for(i=1;i<=totalCount;i++) { } b=bankAccounts.get[i]; b.calculateInterest();
In the above code, calls to calculate_interest function are dynamically bound at run time, as compiler cannot know what a particular BankAccount type will exactly be. This ability of using a single name (here BankAccount) for denoting objects of different classes that are related by some common superclass is known as polymorphism.
Circle
radius calculateArea()
Square
side calculateArea()
Polymorphism
class Shape { private String name; public Shape(String aName) { name=aName; } public String getName( ) { return name; } public float calculateArea( ) { return 0.0f; } } // End Shape class
class Circle extends Shape { private float radius; public Circle(String aName) { super(aName); radius = 1.0f; } public Circle(String aName, float radius) { super(aName); this.radius = radius; } public float calculateArea() { return (float)3.14f*radius*radius; } } // End Circle class
Overriding
Polymorphism
public class ShapeDemoClient { public static void main(String argv[ ]) { Shape c1 = new Circle("Circle C1"); Shape c2 = new Circle("Circle C2", 3.0f); Shape s1 = new Square("Square S1"); Shape s2 = new Square("Square S2", 3.0f); Shape shapeArray[ ] = {c1, s1, c2, s2}; for (int i = 0; i < shapeArray.length; i++) { System.out.println("The area of " + shapeArray[i].getName( ) + " is " + shapeArray[i].calculateArea( ) + " sq. cm."); } } // End main } // End ShapeDemoClient1 class
rule of subtype
Dynamic Binding
Polymorphism
Polymorphism is possible because of
inheritance:
subclasses inherit attributes and methods of the superclass.
public class Circle extends Shape { }
method overriding:
subclasses can redefine methods that are inherited from the superclas,
public class Shape { public float calculateArea( ) { return 0.0f; } } public class Circle extends Shape { public float calculateArea( ) { return (float) 3.14f*radius*radius; } }
Polymorphism
rule of subtype:
reference variables of superclass can be used to refer object instances of its subclasses
Shape c = new Circle(Circle C); Shape s = new Square(Square S); Shape shapeArray[ ] = {c, s, };
dynamic binding:
method invocations are bound to methods during execution time
for(int i = 0; i < shapeArray.lenth; i++) shapeArray[i].calculateArea( ) ;
shapeArray
c s
Polymorphism
Impact of polymorphism on software development incremental development adding new class is made easy with inheritance and polymorphism
name getName( ) calculateArea( )
Shape
Circle
Square
Triangle
Polymorphism
class Triangle extends Shape { private float base, height; public Triangle(String aName) { super(aName); base = 1.0f; height = 1.0f; } public Triangle(String aName, float base, float height) { super(aName); this.base = base; this.height = height; } public float calculateArea( ) { return (float) 0.5f*base*height; } } // End Triangle class public class ShapeDemoClient { public static void main(String argv[ ]) { Shape t = new Triangle(Triangle T, 4.0f, 5.0f); Shape shapeArray[ ] = {c1, c2, s1, s2, t}; for (int i = 0; i < shapeArray.length; i++) System.out.println("The area of " + shapeArray[i].getName() + " is " + shapeArray[i].calculateArea( ))+"); } // End main } // End ShapeDemoClient class
Polymorphism
increased code readability polymorphism also increases code readability since the same message is used to call different objects to perform the appropriate behavior.
for (i = switch c: s: } 0; i < numShapes; i++) (shapeType[i]) { calculateCircleArea( ); break; calculateSquareArea( ); break;
versus
for(int i = 0; i < shapeArray.lenth; i++) shapeArray[i].calculateArea( );
Polymorphism
Polymorphism is the fundamental mechanism for generic programming Changing the implementation of inherited methods to be more specific for a derived class. Allows objects of different classes related by inheritance to respond differently to the same message.
Multithreading
Introduction to threads
What are Threads?
A piece of code that run in concurrent with other threads.
Java has built in thread support for Multithreading. Java Garbage Collector is a low-priority thread.
Thread States
Creating Thread
Create a class that extends the Thread class Create a class that implements the runnable interface
} Creating Thread
MyThread thr1 = new MyThread();
Start execution
thr1.start();
An Example
class MyThread extends Thread {
public void run() {
// thread body of execution
// the thread
class Demo {
public static void main (String args[]) { MyThread thr1 = new MyThread(); thr1.start(); } // end main()
} Creating Thread
MyThread thr1 = new MyThread();
Start execution
thr1.start();
An Example
class MyThread implements Runnable
{ Thread t; public MyThread() { t = new Thread (this); } public void start() { t.start(); }
public void run() {
// thread body of execution
class Demo {
public static void main (String args[]) { MyThread thr1 = new MyThread(); thr1.start(); } // end main()
Thread Synchronisation
Accessing Shared Resources
Applications Access to shared resources need to be coordinated.
Printer (two person jobs can not be printed at the same time) Simultaneous operations on your bank account.
Thread Synchronisation
Thread Synchronisation
Shared Resources
If one thread tries to read the data and other thread tries to update the same data, it leads to inconsistent state. This can be prevented by synchronizing access to the data.
JDBC
Introduction to JDBC
JDBC is a standard interface for accessing databases from Java applications It is a Java API for connecting programs written in Java to the data in relational databases.
Java code calls JDBC library JDBC loads a driver Driver talks to a particular database. Can have more than one driver (more than one database) Can change database engines without changing any application code.
JDBC Architecture
Connect
Query
Process results
Close
Using Connection
java.sql.Connection
createStatment() prepareStatment(String) prepareCall(String) commit() rollback() getMetaData() close() isClosed()
Connect
Query
Create a statement
Process results
Close
Statement Object
A statement object sends your SQL statement to the database. You need an active connection to create a JDBC statement. Statement has three methods to execute a SQL statement.
executeQuery() for QUERY statements executeUpdate() for INSERT, UPDATE, DELETE, or DDL statements. execute() for either type of statement.
Connect
Query
Process results
Close
ResultSet Object
JDBC returns the results of a query in a ResultSet Object. A ResultSet maintains a cursor pointing to its current row of data. Use next() to step through the result set row by row. getString(), getInt() and so on assign each value to a Java variable.
while(rs.next()) { String title = rs.getString(TITLE); String author = rs.getString(AUTHOR); //process or display the data }
Connect
Query
Process results
Close
Seven steps
1. Load the driver try
{
Class.forName(oracle.jdbc.driver.OracleDriver);
} Catch (ClassNotFoundException e) {
System.out.println(Error loading Driver . + e)
Seven steps
4. Execute a query
ResultSet rs= stmt.executeQuery(query);
ResultSetMetaData Object
The ResultSet object can be used to get a ResultSetMetaData object. ResultSetMetaData object provides metadata, including:
Number of columns in the result set Column type Column name
ADDITEM + "(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER); cStmt.registerOutParameter(3,Types.DOUBLE);
Thank You