0% found this document useful (0 votes)
95 views99 pages

JAVA Tutorial

This presentation provides an introduction to the Java programming language. It discusses what Java is, its main features including being simple, object-oriented, distributed, robust, interpreted and architecture neutral. It also covers Java editions, IDE tools, getting started with a simple Java application, primitive data types, variables, operators, control flow statements, arrays, objects and key object-oriented concepts like encapsulation and inheritance.

Uploaded by

Nihanth Koka
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
95 views99 pages

JAVA Tutorial

This presentation provides an introduction to the Java programming language. It discusses what Java is, its main features including being simple, object-oriented, distributed, robust, interpreted and architecture neutral. It also covers Java editions, IDE tools, getting started with a simple Java application, primitive data types, variables, operators, control flow statements, arrays, objects and key object-oriented concepts like encapsulation and inheritance.

Uploaded by

Nihanth Koka
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 99

Presentation on Core Java BY

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.

Comparisons Between Different Architectures

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)

.exe/.dll (MSIL) .exe/.dll (Byte Code) LIBRARY

CLR

Operating System

JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone applications.

Java Enterprise Edition (J2EE)


J2EE can be used to develop server-side applications like Java Servlets and JSPs

Java Micro Edition (J2ME)


J2ME can be used to develop applications for mobile devices such as cell phones.

Java IDE Tools


Forte by Sun Microsystems Borland JBuilder Microsoft Visual J++ IBM Visual Age for Java IBM Eclipse

Getting started with Java

A simple Java Application


//File: SampleApp.java class SampleApp // class name must match file name { public static void main (String args[]) {
System.out.println (Welcome To Java .);

} }

Primitive / Basic Data Types


Basic Data Types Numeric Integral byte short int long Decimal float double Non-Numeric char bool

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

User defined types


Any data type which is not inherently known to the language Any data type for which user (programmer) defines the behavior A Class defines the behavior with Java for Reference Data Types

Variables
Basic Vs. Reference
Basic : Stores value itself. Reference : Points to the value (Object)

Member Vs. Local


Member : As part of object, always created on Heap Local : As part of execution block, always created on Stack

Basic Vs Reference Variables

Member Vs Local Variables

Operators
Arithmetic Operators
+, -, *, /, %, ++, +=, - =, *=, /=, --

Relational Operators :>, >=, == , !=, <=, <

Logical Operators :&, |, ^, !

Assignment Operator
=

Conditional Operator
(expression1 ? expression2 : expression3)

Conditional constructs
The if construct
if (expression)
Statement;

else
Statement;

The switch construct


switch (var) { case __ : statements; break; .. .. default : }

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

Example int a[] = {2,3,5,6,7}; for (int i=0; i<a.length;i++) { System.out.println(a[i]); }

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

Overview of some key concepts


What is Object?
An object is any entity that a system under development is interested in.
Examples : A Book in a library application A Student in a student registration system. An Accountholder in a banking application.

Objects have attributes or characteristics that define them.


Examples : Book(title, author, price) Student(rollno, name, course details) Accountholder(account no, type of account, name, balance)

Objects have state. Values of attributes determine the state of an object.


Example : Book can have a status Issued/On shelf/Missing

Objects have behavior or operations.


Example : Saving bank account object has the behavior of calculating interest payable to the customer.

Overview of some key concepts


Objects, Attributes, and Methods
Object: Attributes Characteristics of an object that have values Behaviors (or methods) Describe what an object can do

Examples: GUI objects Problem Domain objects

Overview of some key concepts


Class
A class is a generalized description of a group of objects that share the same attributes and responsibilities.
For example : In a library management system, the book Professional JSP is an object with certain attributes and responsibilities. Another book Mastering EJB is also an object, sharing same attributes and responsibilities as the first object. So all these similar objects can be said to belong to a common class called Book

This is the formal definition of the shape and functionality of the objects to be created later. No memory allocated.

Overview of some key concepts


Classes versus Objects Class Defines what all objects of the class represent and Objects is the instance of the class

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();

account_number owner balance type_of_account

: a1 : Kapil : 50000 : Current

2. 3.

account_number owner balance type_of_account

: a2 : Madhavi : 5000 : Saving

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

The Pillars of Object Oriented Programming

Encapsulation Inheritance Polymorphism

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

Generalized Employee Specialized

Manager

Non Manager

Why Generalize? When to Generalize?

Inheritance
Hierarchical classification: Is-a relationship : inheritance One class inherits the abilities of another class

Is-A Saving Account Account

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

Class CoolSavingAccount redefinition


withdrawal

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

someanimal = somecat; someanimal.move(); someanimal = somebird; someanimal.move();

move is a method of animal class Results in call to move of cat class

Results in call to move of bird class

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();

This is valid because an instance of SavingAccount or CurrentAccount is indeed a BankAccount.

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.

Polymorphism Another Example


Shape
name getName() calculateArea()

Circle
radius calculateArea()

Square
side calculateArea()

Shape Square Circle

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

Generic Action inheritance

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

Circle Square Square Triangle Rectangle

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

base height calculateArea( )

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

no change on for loop

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.

A single threaded vs. Multithreaded program

Thread States

Creating Thread
Create a class that extends the Thread class Create a class that implements the runnable interface

1st Method of Extending Thread class


Extending the Thread Class class MyThread extends Thread {
public void run() {
// thread body of execution

} 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

} // end class MyThread

class Demo {

// a program that utilizes the thread

public static void main (String args[]) { MyThread thr1 = new MyThread(); thr1.start(); } // end main()

} // end class Demo

2nd Method by implementing Runnable interface


Implementing Runnable interface class MyThread implements Runnable {
public void run() {
// thread body of execution

} 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 {

// a program that utilizes the thread

} // end class MyThread

public static void main (String args[]) { MyThread thr1 = new MyThread(); thr1.start(); } // end main()

} // end class Demo

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.

In Java: synchronized method:


public synchronized void update() {
..

Example of three threads sharing the same object


class InternetBankingSystem {
public static void main (String args[]) { Account accountObject = new Account(); MyThread t1 = new MtThread(accountObject); MyThread t2 = new MtThread(accountObject); MyThread t3 = new MtThread(accountObject); t1.start(); t2.start(); t2.start(); // some more operations } //end main

} // end class MyThread

Account (Shared Object)

Example of three threads sharing the same object


class Account
{
float balance; // if synchronized is removed, the outcome is unpredictable

public synchronized void deposit (float amt) {


balance +=amt;

} public synchronized void withdraw (float amt) {


if (condition) {
//some operations balance -=amt;

} // end class MyThread

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

JDBC Step1 : connect

Connect

Register the driver

Query

Connect to the database

Process results

Close

JDBC Step1 : connect


How to make the connection?
Register the driver

DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());


Connect to the database

Connection conn = DriverManager.getConnection (URL, userid, password);

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");

Using Connection

java.sql.Connection
createStatment() prepareStatment(String) prepareCall(String) commit() rollback() getMetaData() close() isClosed()

Creating Statement Transaction Management Get database metadata Conneciton related

JDBC Step2 : Query

Connect

Query

Create a statement

Process results

Query the database

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.

How to query the Database?


Create an empty statement object

Statement stmt = conn.createStatement();


Execute the statement

Resultset rs = stmt.executeQuery(statement); int count = stmt.executeUpdate(statement); Boolean isQuery = stmt.execute(statement);

Querying the database: Examples


Execute a select statement
Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(Select * from emp);

Execute a delete statement


Statement stmt = conn.createStatement(); int rowCount = stmt.executeUpdate(delete from emp);

JDBC Step3 : Process the results

Connect

Query

Process results

Step through the results

Close

Assign results to Java variables

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.

How to Process the Results


Step through the result set.
while (rs.next()) {.}

Use getXXX() to get each column value.


String val = rs.getString(colName)

while(rs.next()) { String title = rs.getString(TITLE); String author = rs.getString(AUTHOR); //process or display the data }

JDBC Step4 : Close

Connect

Query

Close the result set

Process results

Close the statement

Close

Close the connection

How to close the Connection?


Close the Resultset object
rs.close();

Close the Statement object


stmt.close();

Close the connection


conn.close();

Seven steps
1. Load the driver try
{
Class.forName(oracle.jdbc.driver.OracleDriver);

} Catch (ClassNotFoundException e) {
System.out.println(Error loading Driver . + e)

2. Establish the Connection


Connection con = DriverManager.getConnection(oracleURL, username, password);

3. Create a Statement object


con.createStatement();

Seven steps
4. Execute a query
ResultSet rs= stmt.executeQuery(query);

5. Process the result


while(rs.next()) { }

6. Close the connection


con.close();

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

How to obtain the metadata?


ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < rsmd.getColumnCount(); i++) { String colname = rsmd.getColumnName(i); int coltype = rsmd.getColumnType(i); }

The PreparedStatement Object


A PreparedStatement object holds precompiled SQL statements. Use this object for statements you want to execute more than once. How to create a Prepared Statement?
PreparedStatement pstmt = conn.prepareStatement("update books set STATUS = ? where name = ?"); PreparedStatement pstmt = conn.prepareStatement("select STATUS from books where author = ?");

How to execute a Prepared Statement?


Supply values for the variables.
pstmt.setXXX(index,value);

Execute the statement.


pstmt.executeQuery(); pstmt.executeUpdate(); PreparedStatement pstmt = conn.prepareStatement("update books set STATUS = ? where name = ?"); pstmt.setSTring(1,issue); pstmt.setSTring(2,Mastering Java);

The CallableStatement Object


A CallableStatement object holds parameters for calling stored procedures. How to create a Callable Statement?

CallableStatement cstmt = conn.prepareCall("{call " +

ADDITEM + "(?,?,?)}");

cstmt.registerOutParameter(2,Types.INTEGER); cStmt.registerOutParameter(3,Types.DOUBLE);

How to Execute a Callable Statement?


Set the input parameters.
cstmt.setXXX(index,value);

Execute the statement


cstmt.execute(statement);

Get the output parameters.


var = cstmt.getXXX(index);

Thank You

You might also like