Core JAVA Programming I
KarimullaBasha (TechnoSchool)
October 17, 2015 TCS Confidential
Objectives of Session
Introduction to OOPs(Object Oriented Programming)
Why JAVA?
Learning JAVA
October 17, 2015
Object Oriented Programming
Classes &Objects
Object Creation
New operator
Cloning
Serialization
Class.forName("classname").newInstance()
Inheritance
Single,Multiple,Multilevel,Hybrid
Data Abstraction
Data Encapsulation & Data Hiding
Polymorphism
Static (Overloading Early Binding),
Dynamic( Overriding Late Binding)
Reusability
October 17, 2015
Why JAVA? - Features
Simple and Familiar
Portable
Object Oriented
Interpreted and Platform Neutral
Secure
Multithreaded
High Performance
Dynamic
Garbage Collected
Versatile
October 17, 2015
Why JAVA ?
C++ Vs JAVA
Java is faster than other interpreter-based languages like BASIC.
Pointers are used in C++ but not in Java.
Multiple inheritance is supported by C++ but not directly in Java.
In C++ dynamically allocated objects must be manually released using
delete operator but in Java it happens automatically by using Garbage
Collector.
In C++, we can write programs with out class but in Java any code that we
write, must be inside a class and the name should be same as program
name.
Applets are supported by Java but not by C++.
Java programs are platform independent where as C++ programs are
platform dependent.
Java programs are slower than C++ because
Interpreting byte code is slower than executing the machine code of C+
+.
Java checks for null values for all objects at runtime.
Garbage collector concept.
All the variables are checked for type at runtime.
October 17, 2015
JAVA Programming
Primitive Data Types
Integers
byte
Short
int
long
Real Numbers
float
double
Other Types
char
Boolean
8-bit
16-bit
32-bit
64-bit
32-bit
64-bit
16-bit
true/false
Reference Data Types
Arrays
Strings
Objects
Interfaces
October 17, 2015
JAVA Programming
Java variable Modifiers
public : Anyone can access public instance variables.
protected : Only methods of the same package or of subclasses can access protected instance variables.
private: Only methods of the same class ( not methods of a subclass) can access private instance variables.
If none of the above modifiers are used, the instance variable is considered friendly. Friendly instance variables can be
accessed by any class in the same package.
static: It is used to declare a variable that is associated with the class. Static variables are used to store global
information about a class.
final: One that must be assigned an initial value, and then can never be assigned a new value after that.
Java Method Modifiers
public : Anyone can call public methods
protected : Only methods of the same package or of subclasses can call a protected method.
private: Only methods of the same class can call a private method.
friendly: If none of the above modifiers are used.
abstract: A method declared as abstract will have no code.
public abstract void setHeight( double newHeight);
final: This is a method that cannot be overridden by a subclass.
static: This is a method that is associated with the class itself, not with a particular instance of the class.
October 17, 2015
JAVA Programming
Local variables
Instance variables & Instance Methods
Static variables(Class variables or Global variables)
It is shared among all instance of a class. A local variable declared within a method cannot be
static.
Static Methods(Class Methods)
Static methods can be invoked through the class name. We dont have to instantiate an object of
the class in order to invoke the method.
Ex:The main( ) method of a Java program must be declared with the static modifier. That main can
be executed by the interpreter without instantiating an object from the class that contains main( ).
Static methods are methods that do not operate on objects
Static methods are used
When a method does not need to access the object state
When a method only needs to access static fields of the class.
o Instance Methods can access ->Instance variable/Methods &Class variable/Methods
o Class Methods can access ->Class variable/Methods & Cannot access Instance
variable/methods
October 17, 2015
JAVA Programming
Arrays
Wrapper Classes
Integer, Float, String (immutable) & String Buffer (mutable)
Abstract & Concrete Classes & Final Classes
Nested Classes (Static, Non-static or Inner Classes) & Anonymous Inner Classes
Object creation for Static Nested Classes & Inner classes
Inner classes cannot have static declarations (variable/method)
Interfaces
can contain only constants & method signatures
implicitly variables are public ,static ,final & methods are public
Markup Interfaces (SingleThreadModel, Serializable, Cloneable)
Markup Interface is a Java Interface which has nomethods & and whole responsibilty on you to create method
super
Final
Native Method JNI(Java Native Interface)
Volatile (This variable modified by other parts of the program un expectedly ex:Threads)
persistence & serialization(Ex:RMI)
Serialization is the process of wiring the state of an object to a byte stream.
static and transient variables are not saved by the serialization facilities.
Object Graph (All Base Classes which extends Serialized will be serialized)
transient
This
Reflection
Packages & import
Java.lang(classloader,object,process,runtime classes Runnable,Clonable Interfaces)
java.util(Date,Calender,Random)
java.io(Bytes-I/OStreams,Character-Reader/writer)
java.sql,java.net
Java.awt,java.swing
October 17, 2015
JAVA Exception Handling
Throwable
Exception
RuntimeException
IOException
Error
AWTError
ThreadDeath
OutOfMemoryError
October 17, 2015
10
JAVA Exception Handling
Exception & Error ??
Abnormal Condition that occurs during the program execution
Errors describes the problem related to system which are difficult to recover
and need not be handled by the code
Checked Exceptions(IOException) Compile Time Occurs
RunTime/Unchecked Exceptions(Arithmetic & Nullpointer Exceptions) RunTime
Occurs
try
catch
throw
throws
finally
Exceptions not caught in scope
Method Terminates
Another attempt to catch the exception
Stack unwinding occurs
October 17, 2015
11
Threads
Thread Lifecycle
Born
Born state (Thread was just
created)
start
ep
sl
e
I/O completes
acquire lock
interrupt
en
te
Running
r
stasyn
iss
te chr
re ue
m on
qu I
en iz
es /O
t ed
t
Running state (Thread is assigned a
processor and running)
Dead state (Thread has completed
or exited & Eventually disposed of
by system)
te
sleep interval
expires
interrupt
thread dispatch
(assign a
processor)
ple
Waiting
it
wa
Ready state (Thread's start method
invoked &Thread can now execute)
com
notify
notifyAll
timeout expires
interrupt
Ready
quantum expiration
yield
Thread States (Life Cycle of
Thread)
Sleeping
Blocked
Sleep state (Thread sleeps for set
time interval then awakes)
When a thread completes
(returns from its run method),
it reaches the Dead state
(shown here as the final
state)
October 17, 2015
12
Threads
Methods in Threads
start(): is responsible for starting a thread and calls the run() method of the thread.
run(): contains all the activities of a thread. It usually contains a loop.
sleep(): put the thread into sleeping mode.
join() : is used to wait for a thread to finish.
isAlive(): returns true if the thread is alive.
wait(): is used to synchronize the threads.
notify(): is used to wake up a thread that is waiting.
notifyAll(): is used to wake up all the threads that are waiting.
yield(): is used to allocate processor time to a low priority thread.
stop(): used to stop the thread.
Java thread priority
Thread creation
Priority in range 1-10 (Default Priority 5)
By extending Thread class
By implementing Runnable interface
Monitor &Thread Synchronization
Java uses monitors for thread synchronization
The monitor is used to protect a shared asset from being manipulated by more than one thread at a time.
Every synchronized method of an object has a monitor
One thread inside a synchronized method at a time
All other threads block until method finishes
Next highest priority thread runs when method finishes
October 17, 2015
13
Collection Framework
Collection Framework Asynchronous (Java.util)
List (ArrayList,LinkedList)
- Allows duplicate elements
- Array List -> implements a dynamic array. Fast iteration and fast random access. It can be created with
an initial size. When this size is exceeded, the collection is automatically enlarged and when objects are
removed the array may be shrunk.
Hashing
Set (HashSet,TreeSet)
- No duplicate elements
Map (HashMap,TreeMap)
- Key/value pair * No duplicate keys
- Hash Map -> allows one null key, many null values
Collection
Iterator
Legacy Classes
Vector -slower Array List, mainly due to its synchronized methods(Threadsafe).
Hash Table No null values or null keys allowed
Properties
Stack
Dictionary
Design Patterns
Creational (Cloning),Behavioral(Iterator) & Singleton(PrivateConstructor)
October 17, 2015
14
Applet
Applet??
Applet LifeCycle
Init ->start->stop->destroy
Applets run in
appletviewer (test utility for applets)
Web browser (IE, Communicator)
October 17, 2015
15
JDBC
JDBC??
Drivers & Types
Type1: JDBC-ODBC Bridge
This driver translates all JDBC calls into ODBC calls & sends them to ODBC driver
Type2: Native-API/Partly Java driver
This driver converts JDBC calls into database-specific calls such as SQL server,Oracle,sybase.This driver communicates directly
with the database server.
Type3:Net-Protocal/Pure java driver
JDBC requests are passed through the n/w to middle-tier server. This server translates to db specific connectivity interface to
further the request to db server.
Type4:Native-Protocal(Pure Java Driver)
It converts JDBC calls into vendor specific DBMS protocol, so that client applications can communicate directly with DB server.It
pure jave driver to achieve platform independence.
Simple JDBC Connectivity
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url,"North","Ken"); //Register Driver with DriverManager
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Surname,FirstName,Category FROM Per");
PreparedStatement pstmt=Con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
CallableStatement cstmt = con.prepareCall( "{call getTestData(?, ?)}"); //call Stored Procedures
cstmt.registerOutParameter(1, java.sql.Types.TINYINT);
cstmt.registerOutParameter(2, java.sql.Types.DECIMAL, 3);
while (rs.next()) {
}
Connection/Statement/PreparedStatement/CallableStatement/Resultset
October 17, 2015
16
Thank You
October 17, 2015 TCS Confidential