Unit 2 Java Programming Concepts .pdf - Google Drive

1 downloads 43 Views 2MB Size Report
Boxing, unboxing. Object serialization, de-serialization. Important Java utility classes. Java collection framework. Dis
Unit No: 2 Java Programming Concepts Pavan R Jaiswal

 

   

Introduction Reflections Boxing, unboxing Object serialization, de-serialization Important Java utility classes Java collection framework

Distributed Programming

2

Introduction High level programming language Buzzwords 

Simple Object oriented Architectural neutral Distributed Portable Secure, etc 

Java Programming Concepts

3

Introduction

Fig 1 Overview of software development process

Java Programming Concepts

4

Introduction

Fig 2 Java application running on multiple platforms by making use of JVM

Java Programming Concepts

5

Java reflection API Java reflection is a process of examining or modifying the runtime behaviour of class at runtime Packages providing classes for reflections 

java.lang.class Java.lang.reflect





Reflection API mainly used in IDE, debugger, test tools, etc



Java Programming Concepts

6

Java reflection API Reflection scans your classpath Indexes the metadata Allows you to query it on runtime Saves and collects information to be used for modules in project Reflections consists of two components 

Object that represents various parts of class file A mean for extracting those objects in secure way

Java Programming Concepts

7

Concerns of using reflection Reflections are powerful, but shall not be used indiscriminately Remember the following concerns while accessing it 1. Performance overhead •Certain JVM optimizations can not be performed 2.Security restrictions •Runtime permission may not be available when running under security manager 3.Exposure of internals •Reflective code breaks abstractions 

Java Programming Concepts

8

Java.lang.Class class 

Performs mainly two tasks Provides methods to get matadata of a class at runtime Provides methods to examine and change the runtime behaviour of a class 



Methods of Class class Public string getName() public static Class forName(String className)throws ClassNotFoundException 

Java Programming Concepts

9

Java.lang.Class methods public Object newInstance()throws InstantiationException,IllegalAccessException public boolean isInterface() public boolean isArray() public boolean isPrimitive() public Class getSuperclass() 

Java Programming Concepts

10

Java.lang.Class methods public Field[] getDeclaredFields()throws SecurityException public Method[] getDeclaredMethods()throws SecurityException public Constructor[] getDeclaredConstructors()throws SecurityException public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException 

Java Programming Concepts

11

forName() method example class Simple{} class Test{ public static void main(String args[]) throws Exception{ Class c=Class.forName("Simple"); System.out.println(c.getName()); } } Output: Simple

Java Programming Concepts

12

getClass() method example class Simple{} class Test{ void printName(Object obj){ Class c=obj.getClass(); System.out.println(c.getName()); } public static void main(String args[]){ Simple s=new Simple(); Test t=new Test(); t.printName(s); } } Output: Simple

Java Programming Concepts

13

The .class syntax class Test{ public static void main(String args[]){ Class c = boolean.class; System.out.println(c.getName()); Class c2 = Test.class; System.out.println(c2.getName()); } } Output: boolean Test

Java Programming Concepts

14

Determining the class object class Simple{} interface My{} class Test{ public static void main(String args[]){ try{ Class c=Class.forName("Simple"); System.out.println(c.isInterface()); Class c2=Class.forName("My"); System.out.println(c2.isInterface()); }catch(Exception e){System.out.println(e);} } } Output: false true

Java Programming Concepts

15

Javap tool Javap command disassembles a class file. It displays information about 

Fields Constructors Methods present in a class file 



Syntax $ javap fully_class_name



Example $ javap -c Test $ javap -c java.lang.String

Java Programming Concepts

16

Options of javap tool Options

Description

-help

prints the help message

-l

prints line number and local variable

-c

disassembles the code

-s

prints internal type signature

-sysinfo

shows system info (path, size, date, MD5 hash)

-constants

shows static final constants

-version

shows version information

Java Programming Concepts

17

Java boxing and unboxing 

Java have eight primitive types



Each one has corresponding library class of

reference type 

E.g. class java.lang.Integer => type int



These kinds of classes are called as wrapper



Wrapper classes are immutable and final

Java Programming Concepts

18

Java boxing and unboxing Conversion of primitive type to corresponding reference



type is

called boxing

Conversion of reference type to primitive type is called



unboxing Advantage: no need of conversion between primitives



and wrappers manually, so less coding is required

Java Programming Concepts

19

Java boxing example class BoxingExample1{ public static void main(String args[]){ int a=50; Integer a2=new Integer(a);//Boxing Integer a3=5;//Boxing System.out.println(a2+" "+a3); } } Output: 50 5

Java Programming Concepts

20

Java unboxing example class UnboxingExample1{ public static void main(String args[]){ Integer i=new Integer(50); int a=i; System.out.println(a); } } Output: 50

Java Programming Concepts

21

Unboxing with comparison operator class UnboxingExample2{ public static void main(String args[]){ Integer i=new Integer(50); if(i=0; period--) { setChanged(); notifyObservers(new Integer(period)); try { Thread.sleep(100); } catch(InterruptedException e) { System.out.println("Sleep interrupted"); } }} }

Java Programming Concepts

33

Observable class example ObserverDemo.java class ObserverDemo { public static void main(String args[]) { BeingWatched observed = new BeingWatched(); Watcher observing = new Watcher(); /* Add the observing to the list of observers for observed object. */ observed.addObserver(observing); observed.counter(10); } }

Java Programming Concepts

34

Observable class example // Output [pavan@localhost Observable]# javac ObserverDemo.java [pavan@localhost Observable]# java ObserverDemo update() called, count is 10 update() called, count is 9 update() called, count is 8 update() called, count is 7 update() called, count is 6 update() called, count is 5 update() called, count is 4 update() called, count is 3 update() called, count is 2 update() called, count is 1 update() called, count is 0 [pavan@localhost Observable]#

Java Programming Concepts

35

java.util.StringTokenizer class It allows application to break a string into tokens It is a legacy class and retained for compatibility reasons Its methods do not distinguish among identifiers, numbers and quoted strings Its methods do not even recognize and skip comments Declaration 

public class StringTokenizer extends Object implements Enumeration 

Java Programming Concepts

36

StringTokenizer class methods int countTokens() boolean hasMoreElements() boolean hasMoreTokens() Object nextElement() String nextToken() String nextToken(String delim) 

Java Programming Concepts

37

StringTokenizer class example // Demonstrating StringTokenizer class import java.util.StringTokenizer; class MyStringTokenizer { public static void main(String a[]){ String msg = "This program gives sample code for String Tokenizer"; StringTokenizer st = new StringTokenizer(msg," "); while(st.hasMoreTokens()){ System.out.println(st.nextToken()); } } }

Java Programming Concepts

38

StringTokenizer class example // Output [pavan@localhost StringTokenizer]# javac MyStringTokenizer.java [pavan@localhost StringTokenizer]# java MyStringTokenizer This program gives sample code for String Tokenizer [pavan@localhost StringTokenizer]#

Java Programming Concepts

39

Java collection Collection in Java is a framework. It provides an architecture to store and manipulate group of objects Operations like searching, sorting, insertion, deletion, manipulation etc can be performed by Java collection It is like a single unit of objects It have many interfaces (Set, List, Queue etc) and classes (ArrayList, Vector, LinkedList etc) 

Java Programming Concepts

40

Hierarchy of collection framework

Fig 4 Hierarchy of collection framework Java Programming Concepts

41

Collection interface methods public boolean add(Object element)



public boolean addAll(Collection c)



public boolean remove(Object element)



public boolean removeAll(Collection c)



public boolean retainAll(Collection c)



public int size()



public void clear()



Java Programming Concepts

42

Collection interface methods public boolean contains(Object element)



public boolean containsAll(Collection c)



public Iterator iterator()



public Object[] toArray()



public boolean isEmpty()



public boolean equals(Object element)



public int hashCode()



Java Programming Concepts

43

LinkedList class 

It uses doubly linked list to store elements



It can contain duplicate elements



It maintains insertion order



In this manipulation is fast as no shifting needed

in case of element removal 

It can be used as list, stack or queue

Java Programming Concepts

44

LinkedList example import java.util.*; public class LinkedListDemo{ public static void main(String args[]){ LinkedListal=new LinkedList(); al.add("David"); al.add("Solomon"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }

Java Programming Concepts

45

ArrayList class     



It uses dynamic array for storing the elements It extends AbstractList and implements List It can contain duplicate elements It maintains insertion order It allows random access as it makes use of index Manipulation as lot of shifting needs to be done in case of element removal

Java Programming Concepts

46

ArrayList example import java.util.*; class ArrayListDemo{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add("David"); al.add("Solomon"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }

Java Programming Concepts

47

HashSet class 

It uses hashtable to store elements



It extends AbstractSet and implements Set



Contains unique elements only

Java Programming Concepts

48

HashSet hierarchy

Fig 5 HashSet hierarchy Java Programming Concepts

49

HashSet example import java.util.*; class HashSetDemo{ public static void main(String args[]){ HashSet al=new HashSet(); al.add("David"); al.add("Solomon"); al.add("David"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }

Java Programming Concepts

50

TreeSet class 

It contains unique elements only like HashSet



It implements NavigableSet interface



It extends SortedSet interface

Java Programming Concepts

51

TreeSet hierarchy

Fig 6 TreeSet hierarchy Java Programming Concepts

52

TreeSet example import java.util.*; class TreeSetDemo{ public static void main(String args[]){ TreeSet al=new TreeSet(); al.add("David"); al.add("Solomon"); al.add("Italy"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }

Java Programming Concepts

53

HashMap class 

It contains value based on the key



It implements Map interface



It extends AbstractMap class



It contains only unique elements



It may have one null key and multiple null values



It maintains no order

Java Programming Concepts

54

HashMap hierarchy

Fig 7 HashMap hierarchy

Java Programming Concepts

55

HashMap example import java.util.*; class HashMapDemo{ public static void main(String args[]){ HashMap hm=new HashMap(); hm.put(100,"David"); hm.put(101,"Solomon"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }

Java Programming Concepts

56

TreeMap class It contains values based on the key It implements NavigableMap interface It extends AbstractMap class It contains only unique elements It can not have null key but can have multiple null values It is same as HashMap instead maintains ascending order 

Java Programming Concepts

57

TreeMap hierarchy

Fig 8 TreeMap hierarchy

Java Programming Concepts

58

TreeMap example import java.util.*; class TreeMapDemo{ public static void main(String args[]){ TreeMap hm=new TreeMap(); hm.put(101,"Solomon"); hm.put(100,"David"); hm.put(102,"Italy"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Java Programming Concepts

59

Vector class It implements growable array of objects Similar to array, its elements can be accessed by using integer index Size of vector can grow or shrink as needed It is synchronized, means it is suitable for threadsafe operations  It is a legacy class It used Enumeration interface to traverse the elements, but it can use iterator also 

Java Programming Concepts

60

Vector example import java.util.*; class VectorDemo{ public static void main(String args[]){ Vector v=new Vector(); v.add("Italy"); v.addElement("Solomon"); v.addElement("David"); Enumeration e=v.elements(); while(e.hasMoreElements()){ System.out.println(e.nextElement()); } } }

Java Programming Concepts

61

Stack class 

It is subclass of Vector class



It implements standard last-in first-out stack



It only defines default constructor, which creates

an empty stack 

It includes all the methods defined by Vector, as

well as adds several of its own

Java Programming Concepts

62

Stack class methods 

boolean empty()



Object peek( )



Object pop( )



Object push(Object element)



int search(Object element)

Java Programming Concepts

63

Stack example import java.util.*; class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } Java Programming Concepts

64

Stack example public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } }

Java Programming Concepts

65

Dictionary class It is an abstract class It represents a key/value storage repository and operates much like Map Given a key and value, you can store the value in dictionary After value is stored, it can be retrieved by using key Like Map, this can be though as a list of key/value pairs 

Java Programming Concepts

66

Dictionary class methods Enumeration elements( )



Object get(Object key)



boolean isEmpty( )



Enumeration keys( )



Object put(Object key, Object value)



Object remove(Object key)



int size( )



Java Programming Concepts

67

HashTable class It is an array of List Each list is known as bucket hashCode() method identifies position of bucket It implements Map interface It extends Dictionary class It contains only unique elements It may not have any null key or value It is synchronized 

Java Programming Concepts

68

HashTable example import java.util.*; class HashTableDemo{ public static void main(String args[]){ Hashtable hm=new Hashtable(); hm.put(100,"David"); hm.put(102,"Solomon"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }

Java Programming Concepts

69

Iterator in Java To generate successive elements from series, we can use Java iterator Its an improvement over Enumeration interface Important points We can iterate only in one direction Iteration can only be done once If you reach end of series, its done. In case of restart, get a new iterator again 

Java Programming Concepts

70

Iterator methods 

boolean hasNext()



Object next()



void remove()

Java Programming Concepts

71

Iterator example import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class MyListIterator { public static void main(String a[]){ List li = new ArrayList(); ListIterator litr = null; li.add(23); li.add(98); li.add(29); litr=li.listIterator(); System.out.println("Elements in forward directiton \n"); while(litr.hasNext()){ System.out.print(" "+ litr.next()); } System.out.println("\n Elements in backward while(litr.hasPrevious()){ System.out.print(" " + litr.previous()); } }}

Java Programming Concepts

directiton

\n");

72

Reference 1. 2.

3. 4.

5. 6. 7. 8.

9.

Java Complete Reference by Herbert Schiedlt Web Technologies: HTML, JS, PHP, Java, JSP, ASP.NET, XML, AJAX, Black Book, DreamTech, ISBN: 978-81-7722-997-4 http://www.javatpoint.com/java-reflection https://docs.oracle.com/javase/tutorial/java/data/autoboxing.ht ml http://www.tutorialspoint.com/java/util/ https://docs.oracle.com/javase/tutorial/collections/intro/ http://www.javatpoint.com/collections-in-java http://www.tutorialspoint.com/java/java_collections.htm http://beginnersbook.com/2014/07/hashtable-in-java-withexample/

Java Programming Concepts

73

Thank You

Java Programming Concepts

74