Java basics
Upcoming SlideShare
Loading in...5
×
 

Java basics

on

  • 258 views

 

Statistics

Views

Total Views
258
Views on SlideShare
256
Embed Views
2

Actions

Likes
0
Downloads
5
Comments
0

1 Embed 2

http://www.linkedin.com 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Java basics Java basics Presentation Transcript

    • 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