SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Java Basics
Objectives








Class
Objects
Identifiers
Methods
Encapsulation, inheritance,
polymorphism
Constructors
GC
Class






Template
State and behaviour of object at run
time
Abstract class
Final class
Interface






A 100% abstract class
A contact for what a implementing
class can do.
Behavioural purposes
Class can implement multiple
interfaces
Variables







Primitives
Reference
Local variables
Arrays
Final variables
Transient
Methods








Final Methods
Final Arguments
Abstract methods
Synchronized
Native
Strictfp
Var-args
Encapsulation




Keep data protected
Keep services open
Setters and getters method
Inheritance





Re-usability
Sometimes we have no
implementation
Is-a vs has-a relationship
Polymorphism



Overloading
Overridding
Constructors





Need?
Default constructor
Constructor overloading
Constructor calls in inheritance tree
Static



Functions
Variables
Memory Management




Stack
Heap
Garbage collector
Exception




What are exceptions?
Exceptions VS Program Errors
Exceptions VS Errors
Exception handling






Try catch finally block
Catching exception
Ducking exception
Creating new exceptions
Checked / Unchecked exceptions
Time for some practical example
A rudimentary banking application
Objective: Create some customers
and create their saving and current
accounts. Display them on the
screen. That’s it!
Practical Example 2
Duck simulation game once again?
Objective: To show different type of ducks
on the screen (Time being each duck can
be represented by different text). Some
of the ducks can fly / quack while some
cannot. Code should first be implemented
for Mallard and rubber duck. It should be
expandable for other duck type.
Collections – some groundwork
toString() method (To be covered later)
 “==“ VS “equals()”
== compares references. It’s a bit to bit
comparison.
However, equals method is overridden by
some classes to compares the values of
reference variables for ex: String, Integer
etc.
Example @ Eclipse

Collections – some groundwork 2
When to override equals?
For class Car?
Color
Engine
Make
2WD / 4WD
VIN
Collections – some groundwork 3
hashCode()
Object ID, not necessarily unique,
used my HashMap / HashSet etc to
store reference to the object.
hashCode is used to locate the
object in the memory.
Collections – An Introduction
What are collections?
What do we do with collections?
- Add objects
- Remove objects
- Find an Object
- Iterate through collection
Collections - continued
Key 9 interfaces:
Collection, Set, SortedSet
List, Map, SortedMap
Queue, NavigableSet, NavigableMap
Collections - continued
Ordered VS Sorted
Mainly used concrete classes:
Maps – HashMap, Hashtable, TreeMap,
LinkedHashMap
Sets – HashSet, LinkedHashSet, TreeSet
Lists – ArrayList, Vector, LinkedList
Queues – PriorityQueue
Utilities – Collections, Arrays
Collections - Sorting
Collections.sort
 OK – But what about classes – How
can we compare them?
 Comparable Interface – compareTo
method
 Comparator Interface – compare
method
Examples at Eclipse

Collections - Search







Searches are performed using binarySearch()
Successful searches return index of element being
searched
Collection / Array should be sorted to facilitate
search
If searched element is not there, then the return
value of search is = -(index at which if searched
element is inserted, sorted order will be
maintained) -1. Like a, c, d, e, f if we search for
b, return value will be -2
Array / Collection is sorted using comparator,
same comparator should be used in search.
Inner Classes
A Class can have:
 Instance variable
 Methods
 Classes????
 Yes, but what is the use?

Inner Classes – Purpose and Use
Chat client example:
 Normal operation like typing,
sending, getting messages from
server can be done in ChatClass.
But, what about even handling
messages? Where should they be?
Options are:


Same class
 Other class
 Inner class

Inner classes - types
(Regular) Inner classes
 Method local Inner classes
 Anonymous inner classes
 Static inner classes

Inner Classes
Regular Inner Class (Eclipse)
 Method Inner Class


Same as regular inner class with
following differences:
 declared inside method
 Cannot be instantiated outside method
 Cannot use method local variables
 Can not use modifiers like public,
private, protected, static

Inner Classes
Anonymous Inner classes - Example
at Eclipse
 Static Nested classes – Example at
Eclipse

Threads
A thread is a single sequential flow of
control within a program.
 Multi-threading
 Types


 Extending

thread class
 Implementing runnable interface
States of Thread






New
Runnable
Running
Waiting/Blocked/Sleeping
Dead
Waiting /
Blocked /
Sleeping

New

Runnab
le

Runnin
g

Dead
Thread execution








JVM & Scheduler
Round-robin
Time slicing scheduler
Thread priorities
Sleep
Yield
Join
Multi-Threading



Race condition
Preventing race condition




Finding atomic operations
Make variable private
Synchronize the code changing
variables
Java I/O


I/O Streams










Byte Streams handle I/O of raw binary data.
Character Streams handle I/O of character data, automatically
handling translation to and from the local character set.
Buffered Streams optimize input and output by reducing the
number of calls to the native API.
Scanning and Formatting allows a program to read and write
formatted text.
I/O from the Command Line describes the Standard Streams and
the Console object.
Data Streams handle binary I/O of primitive data type and String
values.
Object Streams handle binary I/O of objects.

File I/O



File Objects help you to write platform-independent code that
examines and manipulates files.
Random Access Files handle non-sequential file access.
Stream IO


Decendents of classes:
 InputStream
 OutputStream

For example:
 FileInputStream
 FileOutputStream
Character IO



Wraps byte stream.
All character stream classes are
descended from
 Reader
 Writer

For Example:
 FileReader
 FileWriter
Buffered IO


Buffered Streams:
 BufferedInputStream
 BufferedOutputStream
 BufferedReader
 BufferedWriter



Flush()
Scanning and formatting


Scanner API
 Breaks



input stream into Tokens

Formatting API
 PrintWriter
 PrintStream
 Format

method
Command Line IO


Standard Streams by:
 InputStreamReader(System.in)
 OutputStreamWriter(System.out)



Console class:
 C.readLine()

– String
 C.readPassword – Character[]
Data Streams




To read write primitives
DataInputStream
DataOutputStream
Object IO


To read write state of object
 ObjectInputStream
 ObjectOutputStream
File Operations


Class File




Methods:
 Create file
 Change file attributes
 Read / write operation using FileReader /
FileWriter of Buffered Readers and writer
 Delete files
 Rename files
 Create directories

Class RandomAccessFile



Constructor RandomAccessFile(filename,
mode);
Functions: skipBytes, seek, getFilePointer
Java nio operations




Speed IO
Block based IO
File read:







FileInputStream fin = new FileInputStream( "readandshow.txt" );
FileChannel fc = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
fc.read( buffer );

File Write










FileOutputStream fout = new
FileOutputStream( "writesomebytes.txt" );
FileChannel fc = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i=0; i<message.length; ++i) {
buffer.put( message[i] );
}
buffer.flip();
fc.write( buffer );
Serialization





Preserving state of object in a file
Called serialization or flattening of
objects
Three ways to do Serialization:
 using

the default protocol
 customizing the default protocol
 creating our own protocol
Serialization using the default protocol






You have to implement interface
“Serializable”
This interface has no methods. So it
is just a marker interface.
ObjectOutputStream
Serialization using Customizing the
Default Protocol - I


What will happen if our class
contains objects of some other
classes which are not serializable?
Serialization using Customizing the
Default Protocol - II



We have to mark those classes as
serializable?
What if we don’t have access to
code of those classes?
 In

case, it is not important to save
state of those objects, the way is to
mark the variables referring to those
objects as transient.
 But, what if we also want to save state
of object.
Serialization using Customizing the
Default Protocol - III






So, What should we do to
instantiate transient variables? Call
our own method after deserialization?
Of course this is a solution. But,
what if the other developers does
not know about that?
What should we do now?
Serialization using Customizing the
Default Protocol - II


Provide following two methods in
your class:










private void writeObject(ObjectOutputStream out) throws
IOException;
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException;
Do your operations and then call:
defaultWriteObject();
defaultReadObject();
Note that these methods are private. So they are not inhereted,
overloaded. In fact, when VM sees that class provides implementation
of these methods it call these methods than default methods.
Remember, VM can call private methods, any other oject cannot.
Also, they can be used to make a call non-serializable even if super
class is serializable.
Serialization using Creating our Own
Protocol


Instead of implementing the Serializable interface, you
can implement Externalizable, which contains two
methods:





public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException;

Just override those methods to provide your own
protocol. This protocol is entirely in your hands. An
example situation for that alternate type of
serialization: read and write PDF files with a Java
application. If you know how to write and read PDF
(the sequence of bytes required), you could provide the
PDF-specific protocol in the writeExternal and
readExternal methods.
References




Head First Java
SCJP Guide – Kethy Sierra
Thinking in Java vol.3
Queries
Next Sessions – Servlets and JSP


Pre-requisites:
 Basic knowledge of HTTP - http://en.wikipedia.org/wiki/HTTP
 Basic Knowledge of HTML – Youtube video Basic HTML and CSS Tutorial. Howto
make website from scratch
 Introduction to Enterprise applications http://www.scribd.com/doc/4052844/1-Introduction-to-Enterprise-A


Basic Knowledge of J2EE - Youtube videos  JEE Introduction
 JAVA Enterprise Edition Tutorial
 Using the HttpSession
Object: Servlet and JSP Tutorials J2EE

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
J. C.
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
Ravi_Kant_Sahu
 

Was ist angesagt? (20)

Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Python
PythonPython
Python
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
Comparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussionComparable and comparator – a detailed discussion
Comparable and comparator – a detailed discussion
 
Javanotes
JavanotesJavanotes
Javanotes
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Basic IO
Basic IOBasic IO
Basic IO
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
C# - Igor Ralić
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
Java platform
Java platformJava platform
Java platform
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
CORBA IDL
CORBA IDLCORBA IDL
CORBA IDL
 
Summer Training Project On Python Programming
Summer Training Project On Python ProgrammingSummer Training Project On Python Programming
Summer Training Project On Python Programming
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Javatraining
JavatrainingJavatraining
Javatraining
 
java token
java tokenjava token
java token
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 

Andere mochten auch

Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
Raghu nath
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
Jussi Pohjolainen
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 

Andere mochten auch (20)

New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of java
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Java basics
Java basicsJava basics
Java basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1
 
Java Basics
Java BasicsJava Basics
Java Basics
 

Ähnlich wie Java basics

Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 

Ähnlich wie Java basics (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
VB.net
VB.netVB.net
VB.net
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Lambdas
LambdasLambdas
Lambdas
 
Java_Interview Qns
Java_Interview QnsJava_Interview Qns
Java_Interview Qns
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import Java
 
Csci360 20 (1)
Csci360 20 (1)Csci360 20 (1)
Csci360 20 (1)
 
Csci360 20
Csci360 20Csci360 20
Csci360 20
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
Qtp syllabus
Qtp syllabus Qtp syllabus
Qtp syllabus
 
Memory models in c#
Memory models in c#Memory models in c#
Memory models in c#
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
 
Java mcq
Java mcqJava mcq
Java mcq
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Introduction to C++ Programming
Introduction to C++ ProgrammingIntroduction to C++ Programming
Introduction to C++ Programming
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Java basics

  • 3. Class     Template State and behaviour of object at run time Abstract class Final class
  • 4. Interface     A 100% abstract class A contact for what a implementing class can do. Behavioural purposes Class can implement multiple interfaces
  • 7. Encapsulation    Keep data protected Keep services open Setters and getters method
  • 8. Inheritance    Re-usability Sometimes we have no implementation Is-a vs has-a relationship
  • 13. Exception    What are exceptions? Exceptions VS Program Errors Exceptions VS Errors
  • 14. Exception handling      Try catch finally block Catching exception Ducking exception Creating new exceptions Checked / Unchecked exceptions
  • 15. Time for some practical example A rudimentary banking application Objective: Create some customers and create their saving and current accounts. Display them on the screen. That’s it!
  • 16. Practical Example 2 Duck simulation game once again? Objective: To show different type of ducks on the screen (Time being each duck can be represented by different text). Some of the ducks can fly / quack while some cannot. Code should first be implemented for Mallard and rubber duck. It should be expandable for other duck type.
  • 17. Collections – some groundwork toString() method (To be covered later)  “==“ VS “equals()” == compares references. It’s a bit to bit comparison. However, equals method is overridden by some classes to compares the values of reference variables for ex: String, Integer etc. Example @ Eclipse 
  • 18. Collections – some groundwork 2 When to override equals? For class Car? Color Engine Make 2WD / 4WD VIN
  • 19. Collections – some groundwork 3 hashCode() Object ID, not necessarily unique, used my HashMap / HashSet etc to store reference to the object. hashCode is used to locate the object in the memory.
  • 20. Collections – An Introduction What are collections? What do we do with collections? - Add objects - Remove objects - Find an Object - Iterate through collection
  • 21. Collections - continued Key 9 interfaces: Collection, Set, SortedSet List, Map, SortedMap Queue, NavigableSet, NavigableMap
  • 22. Collections - continued Ordered VS Sorted Mainly used concrete classes: Maps – HashMap, Hashtable, TreeMap, LinkedHashMap Sets – HashSet, LinkedHashSet, TreeSet Lists – ArrayList, Vector, LinkedList Queues – PriorityQueue Utilities – Collections, Arrays
  • 23. Collections - Sorting Collections.sort  OK – But what about classes – How can we compare them?  Comparable Interface – compareTo method  Comparator Interface – compare method Examples at Eclipse 
  • 24. Collections - Search      Searches are performed using binarySearch() Successful searches return index of element being searched Collection / Array should be sorted to facilitate search If searched element is not there, then the return value of search is = -(index at which if searched element is inserted, sorted order will be maintained) -1. Like a, c, d, e, f if we search for b, return value will be -2 Array / Collection is sorted using comparator, same comparator should be used in search.
  • 25. Inner Classes A Class can have:  Instance variable  Methods  Classes????  Yes, but what is the use? 
  • 26. Inner Classes – Purpose and Use Chat client example:  Normal operation like typing, sending, getting messages from server can be done in ChatClass. But, what about even handling messages? Where should they be? Options are:  Same class  Other class  Inner class 
  • 27. Inner classes - types (Regular) Inner classes  Method local Inner classes  Anonymous inner classes  Static inner classes 
  • 28. Inner Classes Regular Inner Class (Eclipse)  Method Inner Class  Same as regular inner class with following differences:  declared inside method  Cannot be instantiated outside method  Cannot use method local variables  Can not use modifiers like public, private, protected, static 
  • 29. Inner Classes Anonymous Inner classes - Example at Eclipse  Static Nested classes – Example at Eclipse 
  • 30. Threads A thread is a single sequential flow of control within a program.  Multi-threading  Types   Extending thread class  Implementing runnable interface
  • 32. Thread execution        JVM & Scheduler Round-robin Time slicing scheduler Thread priorities Sleep Yield Join
  • 33. Multi-Threading   Race condition Preventing race condition    Finding atomic operations Make variable private Synchronize the code changing variables
  • 34. Java I/O  I/O Streams         Byte Streams handle I/O of raw binary data. Character Streams handle I/O of character data, automatically handling translation to and from the local character set. Buffered Streams optimize input and output by reducing the number of calls to the native API. Scanning and Formatting allows a program to read and write formatted text. I/O from the Command Line describes the Standard Streams and the Console object. Data Streams handle binary I/O of primitive data type and String values. Object Streams handle binary I/O of objects. File I/O   File Objects help you to write platform-independent code that examines and manipulates files. Random Access Files handle non-sequential file access.
  • 35. Stream IO  Decendents of classes:  InputStream  OutputStream For example:  FileInputStream  FileOutputStream
  • 36. Character IO   Wraps byte stream. All character stream classes are descended from  Reader  Writer For Example:  FileReader  FileWriter
  • 37. Buffered IO  Buffered Streams:  BufferedInputStream  BufferedOutputStream  BufferedReader  BufferedWriter  Flush()
  • 38. Scanning and formatting  Scanner API  Breaks  input stream into Tokens Formatting API  PrintWriter  PrintStream  Format method
  • 39. Command Line IO  Standard Streams by:  InputStreamReader(System.in)  OutputStreamWriter(System.out)  Console class:  C.readLine() – String  C.readPassword – Character[]
  • 40. Data Streams    To read write primitives DataInputStream DataOutputStream
  • 41. Object IO  To read write state of object  ObjectInputStream  ObjectOutputStream
  • 42. File Operations  Class File   Methods:  Create file  Change file attributes  Read / write operation using FileReader / FileWriter of Buffered Readers and writer  Delete files  Rename files  Create directories Class RandomAccessFile   Constructor RandomAccessFile(filename, mode); Functions: skipBytes, seek, getFilePointer
  • 43. Java nio operations    Speed IO Block based IO File read:      FileInputStream fin = new FileInputStream( "readandshow.txt" ); FileChannel fc = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); fc.read( buffer ); File Write         FileOutputStream fout = new FileOutputStream( "writesomebytes.txt" ); FileChannel fc = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); for (int i=0; i<message.length; ++i) { buffer.put( message[i] ); } buffer.flip(); fc.write( buffer );
  • 44. Serialization    Preserving state of object in a file Called serialization or flattening of objects Three ways to do Serialization:  using the default protocol  customizing the default protocol  creating our own protocol
  • 45. Serialization using the default protocol    You have to implement interface “Serializable” This interface has no methods. So it is just a marker interface. ObjectOutputStream
  • 46. Serialization using Customizing the Default Protocol - I  What will happen if our class contains objects of some other classes which are not serializable?
  • 47. Serialization using Customizing the Default Protocol - II   We have to mark those classes as serializable? What if we don’t have access to code of those classes?  In case, it is not important to save state of those objects, the way is to mark the variables referring to those objects as transient.  But, what if we also want to save state of object.
  • 48. Serialization using Customizing the Default Protocol - III    So, What should we do to instantiate transient variables? Call our own method after deserialization? Of course this is a solution. But, what if the other developers does not know about that? What should we do now?
  • 49. Serialization using Customizing the Default Protocol - II  Provide following two methods in your class:        private void writeObject(ObjectOutputStream out) throws IOException; private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException; Do your operations and then call: defaultWriteObject(); defaultReadObject(); Note that these methods are private. So they are not inhereted, overloaded. In fact, when VM sees that class provides implementation of these methods it call these methods than default methods. Remember, VM can call private methods, any other oject cannot. Also, they can be used to make a call non-serializable even if super class is serializable.
  • 50. Serialization using Creating our Own Protocol  Instead of implementing the Serializable interface, you can implement Externalizable, which contains two methods:    public void writeExternal(ObjectOutput out) throws IOException; public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException; Just override those methods to provide your own protocol. This protocol is entirely in your hands. An example situation for that alternate type of serialization: read and write PDF files with a Java application. If you know how to write and read PDF (the sequence of bytes required), you could provide the PDF-specific protocol in the writeExternal and readExternal methods.
  • 51. References    Head First Java SCJP Guide – Kethy Sierra Thinking in Java vol.3
  • 53. Next Sessions – Servlets and JSP  Pre-requisites:  Basic knowledge of HTTP - http://en.wikipedia.org/wiki/HTTP  Basic Knowledge of HTML – Youtube video Basic HTML and CSS Tutorial. Howto make website from scratch  Introduction to Enterprise applications http://www.scribd.com/doc/4052844/1-Introduction-to-Enterprise-A  Basic Knowledge of J2EE - Youtube videos  JEE Introduction  JAVA Enterprise Edition Tutorial  Using the HttpSession Object: Servlet and JSP Tutorials J2EE