Upload
ramesh158
View
1
Download
0
Embed Size (px)
DESCRIPTION
core java ppt
Citation preview
April 18, 2023 2
Objectives of Session
• Introduction to OOPs(Object Oriented Programming)• Why JAVA?• Learning JAVA
April 18, 2023 3
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
April 18, 2023 4
Why JAVA? - Features
• Simple and Familiar
• Portable
• Object Oriented
• Interpreted and Platform Neutral
• Secure
• Multithreaded
• High Performance
• Dynamic
• Garbage Collected
• Versatile
April 18, 2023 5
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.
April 18, 2023 6
JAVA Programming•Primitive Data Types
– Integers byte 8-bit Short 16-bit int 32-bit long 64-bit– Real Numbers float 32-bit double 64-bit– Other Types char 16-bit Boolean true/false
•Reference Data Types– Arrays– Strings– Objects– Interfaces
April 18, 2023 7
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.
April 18, 2023 8
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 don’t 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/Methodso Class Methods can access ->Class variable/Methods & Cannot access Instance
variable/methods
April 18, 2023 9
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 no methods & 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
April 18, 2023 10
JAVA Exception Handling
Throwable
Exception Error
AWTError ThreadDeathIOExceptionRuntimeException OutOfMemoryError
April 18, 2023 11
JAVA Exception Handling
• Exception & Error ??Abnormal Condition that occurs during the program executionErrors 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 scopeMethod TerminatesAnother attempt to catch the exceptionStack unwinding occurs
April 18, 2023 12
Threads
Ready
Running
BlockedSleepingWaiting
start
issue I/O
requestwait
notify
notifyAll
time
ou
t e
xpire
sinterrupt
thread dispatch(assign a processor)
quantum expirationyield
sleep
complete
sleep interval expires
interrupt
Born
enter synchronized
statementI/O
com
ple
tes
acq
uire
lock
interrupt
When a thread completes (returns from its run method), it reaches the Dead state (shown here as the final state)
Thread LifecycleThread States (Life Cycle of Thread)
Born state (Thread was just created)
Ready state (Thread's start method invoked &Thread can now execute)
Running state (Thread is assigned a processor and running)
Dead state (Thread has completed or exited & Eventually disposed of by system)
Sleep state (Thread sleeps for set time interval then awakes)
April 18, 2023 13
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 – Priority in range 1-10 (Default Priority 5)
• Thread creation – 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
April 18, 2023 14
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)
April 18, 2023 15
Applet
• Applet??• Applet LifeCycleInit ->start->stop->destroyApplets run in
• appletviewer (test utility for applets)• Web browser (IE, Communicator)
April 18, 2023 16
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