100 Minute Java

Share Embed Donate


Short Description

For Begineers to learn Basic Java...

Description

Overview

Before we start with Object Oriented Features, you should know...  History of Java  Features of Java  J2SE, J2EE, J2ME  Difference between Procedure oriented and Object oriented languages (Also Object based language)  JDK, JVM, JRE  Java Bytecode

Things you should know...  Octal and Hexadecimal representation of numbers.  Unicode representation of characters (char).  Naming conventions  Arrays and its methods.  Control statements and Iteration statements - if - else (different forms) - switch - case - for loop - while loop - do while loop - break, continue, label - labeled break, labeled continue, return

Things you should know...  Installing JDK, Setting path, compiling and running simple Java Program.  Whitespace, Comments  Identifiers, keywords and Literals  Data types  Operators – (their precedence and associativity) - Arithmetic - Assignment - Arithmetic-Assignment - Relational - Bitwise - Boolean logical - Short circuit logical - Ternary  Widening and narrowing conversions

Installing JDK JDK stands for Java Development Kit. A software development package from Sun Microsystems that implements the basic set of tools needed to compile, test and debug Java applications and applets. It contains tools such as javac, java, appletviewer etc. Set PATH in Environment Variable as \\bin e.g.: C:\Jdk1.4\bin

Execution cycle of ‘C’ Program FirstProgram.c

FirstProgram.obj

FirstProgram.exe

Execution cycle of Java Program

Source file

File in ByteCode format

Compiler (javac) converts it into byteCode. FirstProgram.java

FirstProgram.class

JVM uses this for execution.

Simplest Java Program class FirstProgram { public static void main(String args[]) { System.out.println("Hello World"); } }

You can not write ‘C’ program without main(). Similarly, you can not write Java program without “class”. We will study about “Class” in detail in the subsequent lectures.

Compiling and running Java Program Go to Command Prompt : To compile the Java Program javac e.g:- javac FirstProgram.java To run the Java Program java e.g:- java

FirstProgram Initially keep FileName and ClassName same. Later we will study about the correlation between -FileName and ClassName.

Using EditPlus You can use EditPlus to write and execute Java program. You can also use EditPlus for programs in different languages like – C, C++, HTML, JavaScript, VBScript, JSP, Perl, PHP, CSS, XML, C#. For this follow below instructions – Tools --> Configure User Tools --> Add Tool

Initially always use Command Prompt to execute Java programs. If you use EditPlus, then you tend to forget syntax of javac and java commands.

Using EditPlus

Using EditPlus

WhiteSpace ASCII space, horizontal tab or form feed and terminators are considered as whitespaces. Java is a free-form language. This means you need not follow any indentation rules. You can even write an entire program on one line, and still execute it successfully. A Java program is a free-format sequence of characters that is tokenized by the compiler (broken into a stream of tokens) for further analysis. White spaces help not only in separating tokens, but also in formatting the program so that it is easy to read. The compiler ignores the white spaces once the tokens are identified. It is always a good practice to indent the program properly.

Identifiers Identifiers are used for class names, method names and variables names. • It may be any descriptive sequence of characters (uppercase and lowercase), numbers, _ (underscore) and dollar sign. • They should not begin with numbers. i.e.: A-Z, a-z, 0-9, _ , $

AvgTemp, count, a4, $test, _tmp

Valid

2count, high-temp, Not/ok

Invalid

Literals A constant value in Java is created by using a literal representation. 500

88.2

Integer

Floating-point

‘S’

Character

“Welcome”

String

Java also has escape sequences. Study various characters escape sequences in Java.

Comments /* This is traditional multi-line comment */ You can not have nested multi-line comments.

// Single line comment These are single line comments.

/** * This is JavaDoc comment. */ These comments are used for documentation purpose.

Keywords in Java

Apart from these 49 keywords, Java Language Specification also has 3 reserved words - null, true, and false as literal values (sometimes referred to as manifest constants) and not keywords. Remember: All the Java keywords are in lower-case.

You should know significance and usage of each of the keyword in the above list. You might be tempted to think - include, overload, unsigned, virtual, friend - are Java keywords, but in fact they are not !! Remember - "Java is not C / C++."

Will this compile? class Foo { public int break(int b) { System.out.print(“break something”); } }

break is a reserved word and can not be used as a method name. class Foo { public int break(int b) { // code that appears to break something } }

Ranges of Primitive Data Type

Formula to determine data-type range: -2

(bits-1)

to +2

(bits-1)

-1

Default values of Primitive and Reference Data Types

Home Work

Study various Operators in Java, namely – Arithmetic, Assignment, Arithmetic-Assignment, Relational, Bitwise, Boolean logical, Short circuit logical, Ternary.

Look for numeric literals that include a comma, for example, int x = 25,343; // Won't compile because of the comma Remember this is Java and not C: int x = 1; if (x) { } // Compiler error! In Java, condition has to be boolean int x =1; while (x) { }

// Won’t compile; x is not a boolean

while (x = 5) { } //Won’t compile; resolves to 5 (result of assignment) while (x == 5) { }

// Legal, equality test

while (true) { }

//Legal

Remember, characters are just 16-bit unsigned integers under the hood. That means you can assign a number literal, assuming it will fit into the unsigned 16-bit range (65535 or less). For example, the following are all legal: char a = 0x892; // octal literal char b = 982; // int literal char c = (char) 70000; // The cast is required; 70000 is out of char range char d = (char) -98; // Ridiculous, but legal  And the following are not legal and produce compiler errors: char e = -29; // Possible loss of precision; needs a cast char f = 70000 // Possible loss of precision; needs a cast

Command Line Arguments class TestMain { public static void main (String [] args) { System.out.println("First arg is :" + args[0]); } } Unlike C++, + operator is overloaded by default, you need not write any code for this.

When invoked at the command line as follows, java TestMain Hello the output is - First arg is : Hello

Command Line Arguments (continued...) •

args[0] is first argument supplied and not the program name (Java is not ‘C’).



The String array parameter does not have to be named args or arg. It can be named anything (of course excluding keywords and following variable declaration rules). Remember that the main argument is just an array! There’s nothing special about it, other than how it gets passed into main (i.e. from the JVM).

What is wrong with this program? int str = 2; String i = “Hello”; System.out.println(str); System.out.println(i);

Arithmetic Operators Operator

Description

+

Addition

-

Subtraction (also unary minus)

*

Multiplication

/

Division

%

Modulus

++

Increment (pre – post)

--

Decrement (pre - post)

+=

Addition Assignment

-=

Subtraction Assignment

*=

Multiplication Assignment

/=

Division Assignment

%=

Modulus Assignment

Bitwise Operators Operator

Description

~

Unary NOT

&

AND

|

OR

^

X-OR

>>

Right Shift

>>>

Right Shift Zero fill

>=

Right Shift assignment

>>>=

Right Shift Zero fill assignment

=

Greater than or equal to

Collection

> List

> Set

LinkedList

> SortedSet

Vector

ArrayList

TreeSet

HashSet

LinkedHashSet

> Map

> SortedMap

TreeMap

HashMap

Hashtable

LinkedHashMap

Remember : An interface Map and its descendants do not inherit Collection interface.

Concrete Classes at a glance

Concrete Classes at a glance

Collection Interface • The Collection interface specifies the contract that all collections should implement. • Collection interface contains two types of operations i.e. methods • The basic operations are used to query a collection about its contents and allow elements to be added and removed from a collection. • The bulk operations are performed on a collection as a single unit.

Basic operations int size() boolean isEmpty() boolean contains(Object element) boolean add(Object element) boolean remove(Object element) The add() and remove() methods return true if the collection was modified as a result of the operation. By returning the value false, the add() method indicates that the collection excludes duplicates, and that the collection already contains an object equal to the argument object. The contains() method checks for membership of the argument object in the collection using object value equality.

Bulk operations boolean containsAll(Collection c) boolean addAll(Collection c) boolean removeAll(Collection c) boolean retainAll(Collection c) void clear() The containsAll() method returns true if all elements of the specified collection are also contained in the current collection. The addAll(), removeAll(), and retainAll() methods are destructive in the sense that the collection on which they are invoked can be modified.

Enumeration • The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection. • This interface has been superseded by Iterator interface. • Although not deprecated, Enumeration is considered obsolete for the new code. boolean hasMoreElements() This returns true, when there are still more elements in the collection you are enumerating. Returns false, when all the elements have been enumerated. Object nextElement() Returns the next object in the enumeration as a generic Object reference.

Iterator • A collection provides an iterator which allows sequential access to the elements of a collection. • An iterator can be obtained by calling the following method of the Collection interface : Iterator iterator() - Returns an object which implements the Iterator interface. Iterator provides following methods boolean hasNext() :Returns true if the underlying collection still has elements left to return.

Object next() :Moves the iterator to the next element in the underlying collection, and returns the current element. If there are no more elements left to return, it throws a NoSuchElementException. Object remove() :Removes the element that was returned by the last call to the next() method, from the underlying collection. Invoking this method results in an IllegalStateException, if the next() method has not yet been called, or when the remove() method has already been called after the last call to the next() method. This method is optional for an iterator, that is, it throws an UnsupportedOperationException if the remove operation is not supported.

Set • Implementations of the Set interface do not allow duplicate elements. • This also means that a set can contain at most one null value. • add() and addAll() methods will not store duplicates. • An element is not currently in the set, two consecutive calls to the add() method to insert the element will first return true, then false.

Set • The HashSet class implements the Set interface. • A HashSet does not guarantee any ordering of the elements. • A HashSet relies on the implementation of the hashCode() and equals() methods of its elements. • LinkedHashSet is a subclass of the HashSet class. • LinkedHashSet guarantees that the iterator will access the elements in insertion order, that is, in the order in which they were inserted into the LinkedHashSet.

HashSet Constructors HashSet() Constructs a new, empty set. HashSet(Collection c) Constructs a new set containing the elements in the specified collection. The new set will not contain any duplicates. This offers a convenient way to remove duplicates from a collection. HashSet(int initialCapacity) Constructs a new, empty set with the specified initial capacity. HashSet(int initialCapacity, float loadFactor) Constructs a new, empty set with the specified initial capacity and the specified load factor. initial capacity - The number of buckets in the hash table. load factor - the ratio of number of elements stored to its current capacity.

Collections Framework

List • Implementation of List maintain their elements in order, and can contain duplicates. • The elements in a list are ordered. Each element, therefore, has a position in the list. • A zero-based index can be used to access the element at the position designated by the index value. The position of an element can change as elements are inserted or deleted from the list. • The List interface also defines operations that work specifically on lists: position-based access of the list elements, searching in a list, creation of customized iterators, and operations on parts of a list.

List methods Object get(int index) Returns the element at the specified index. Object set(int index, Object element)            Replaces the element at the specified index with the specified element. It returns the previous element at the specified index. void add(int index, Object element)              Inserts the specified element at the specified index. If necessary, it shifts the element previously at this index and any subsequent elements one position toward the end of the list. The inherited method add(Object) from the Collection interface will append the specified element to the end of the list.

List methods Object remove(int index)                          Deletes and returns the element at the specified index, contracting the list accordingly. The inherited method remove(Object) from the Collection interface will remove the first occurrence of the element from the list. // Element Search int indexOf(Object o) int lastIndexOf(Object o) These methods respectively return the index of the first and the last occurrence of the element in the list if the element is found; otherwise, the value –1 is returned.

List (continued…) • The ArrayList and Vector classes implement the List interface. • The Vector and ArrayList classes are implemented using dynamically resizable arrays, providing fast random access and fast list traversal—very much like using an ordinary array. • Unlike the ArrayList class, the Vector class is thread-safe, meaning that concurrent calls to the vector will not compromise its integrity. • The LinkedList implementation uses a doubly-linked list. Insertions and deletions in a doubly-linked list are very efficient elements are not shifted, as is the case for an array. • When frequent insertions and deletions occur inside a list, a LinkedList is the best choice to be used.

ArrayList Constructors ArrayList() Constructs a new, empty ArrayList. An analogous constructor is provided by the LinkedList and Vector classes. ArrayList(Collection c) Constructs a new ArrayList containing the elements in the specified collection. The new ArrayList will retain any duplicates. The ordering in the ArrayList will be determined by the traversal order of the iterator for the collection passed as argument. An analogous constructor is provided by the LinkedList and Vector classes. ArrayList(int initialCapacity) Constructs a new, empty ArrayList with the specified initial capacity. An analogous constructor is provided by the Vector class.

Map • A Map defines mappings from keys to values. The pair is called an entry in a Map. • A Map does not allow duplicate keys, in other words, the keys are unique. • Both the keys and the values must be objects. This means that primitive values must be wrapped in their respective wrapper objects, if they are to be put in a map. • A map is not a collection and the Map interface does not extend the Collection interface.

Map methods Object put(Object key, Object value) Inserts the entry into the map. It returns the value previously associated with the specified key, if any. Otherwise, it returns the null value. Object get(Object key) Returns the value to which the specified key is mapped, or null if no entry is found. Object remove(Object key) The remove() method deletes the entry for the specified key. It returns the value previously associated with the specified key, if any. Otherwise, it returns the null value. void putAll(Map t) Copies all entries from the specified map to the current map.

Map methods boolean containsKey(Object key) Returns true if the specified key is mapped to a value in the map. boolean containsValue(Object value) Returns true if there exists one or more keys that are mapped to the specified value. int size() These methods return the number of entries (i.e., number of unique keys in the map) boolean isEmpty() Returns true / false depending upon whether map is empty or not. void clear() deletes all the entries from the current map.

Map (continued…) • The classes HashMap and Hashtable implement unordered maps. The class LinkedHashMap is ordered. • HashMap class is not thread-safe and permits one null key. • Hashtable class is thread-safe and permits non-null keys and values. • The LinkedHashMap is a subclass of the HashMap class. • By default, the entries of a LinkedHashMap are in key insertion order, that is, the order in which the keys were inserted in the map. This order does not change if a key is re-inserted, because no new entry is created if the key's entry already exists.

HashMap Constructors HashMap() HashMap(int initialCapacity) HashMap(int initialCapacity, float loadFactor) Constructs a new, empty HashMap, using either specified or default initial capacity and load factor. HashMap(Map otherMap) Constructs a new map containing the elements in the specified map.

Properties • Properties is a subclass of Hashtable. • It is used to maintain list of values in which, key is also a String and value is also a String. • Properties class is used by many other Java classes. E.g. System.getProperties() is used to get environmental values. String getProperty(String key) Returns the value associated with key. A null object is returned if key is neither in the list nor in the default property list. Object setProperty(String key, String value) Associates value with a key. Returns the previous values associated with key, or returns null if no such association exists. We will study more about Properties class, during File handling and IO.

TreeSet and TreeMap • TreeSet is a sorted Set. • TreeSet guarantees that the elements will be in ascending order, according to the natural order of the elements. • Optionally, you can construct a TreeSet with a constructor that lets you define your own rules for what the natural order should be (rather than relying on the ordering defined by the elements’ class) • TreeMap is a sorted Map. • TreeMap guarantees that the elements will be in ascending order of keys, according to the natural order of the elements. • Similar to TreeSet, TreeMap lets you pass your own comparison rules in when you construct a TreeMap, to specify how the elements should be compared to one another when they’re being ordered.

Study various Constructors / Methods of ArrayList, LinkedList, Vector. HashSet, LinkedHashSet, TreeSet Hashtable, HashMap, LinkedHashMap, TreeMap Enumeration, Iterator, Properties

Always Remember this !!!

Threads

Multiprocessing • This allows many processes to run simultaneously. • Process is a running instance of the program. i.e. an operating system process. • CPU time is shared between different processes. • OS provides context switching mechanism, which enables to switch between the processes. • Program’s entire contents (e.g. variables, global variables, functions) are stored separately in their own context. • Example:- MS-Word and MS-Excel applications running simultaneously. (or any two applications for that matter)

Multithreading • This allows many tasks within a program (process) to run simultaneously. • Each such task is called as a Thread. • Each Thread runs in a separate context. • Example:- Lets take a typical application like MS-Word. There are various independent tasks going on, like displaying GUI, auto-saving the file, typing in text, spell-checking, printing the file contents etc… • In Java, main() is considered as a main thread. GC which runs as a background task can be considered as another thread.

Multiprocessing • Each process has a complete set of its own variables. • It takes more overhead to launch new processes. • Inter-process communication is slower & restrictive.

Multithreading • Threads may share the same data. • It takes much less overhead to create & destroy threads. • Inter-thread communication is easier.

Processes vs. Thread • Processes are heavyweight. • Require their own address space. • Inter-process communication is expensive. i.e. Context switching between the processes is expensive in terms of CPU time. • Threads are lightweight. • Share same address space and share same heavyweight process. • Inter-thread communication is inexpensive. i.e. Context switching between the threads is inexpensive in terms of CPU time.

Thread • Thread is an independent sequential path of execution within a program. i.e. separate call stack. • Many threads run concurrently within a program. • At runtime, threads in a program exist in a common memory space and can share both data and code. • Multithreading enables you to write efficient programs that make maximum use of CPU, keeping the idle time to a minimum.

Java supports multi-threading

In Java, you really can walk and chew gum at the same time.

Multi-threading in Java means, your program can perform many things simultaneously.

Multi-threading in Java • Java supports multi-threading. • But Java is totally platform-dependent as far as threading is concerned. • Threading is controlled by thread scheduling algorithm which is dependent on the underlying OS. OS • So inconsistent behavior may be observed in the programs using threads.

User threads and daemon threads • Java runtime system distinguishes between the user threads and daemon threads. As long as user thread is alive, JVM does not terminate. • Daemon thread is at the mercy of the runtime system: it is stopped if there are no more user threads running, thus terminating the program. Daemon threads exist only to serve user threads. • When a stand-alone application runs, user thread is automatically created to execute the main() method. This is called as a main thread. • All other threads (child threads) are spawned from this main thread inheriting user-thread status.

• setDaemon(boolean) method in the Thread class, can be called to change the status of user-defined thread to either user thread or daemon thread. • This method must be called before thread is started. Any attempt made to call this method, after the thread has been started, throws IllegalThreadStateException.

Thread Creation • In Java, thread is represented by an object of the Thread class. Using threads can be achieved in one of the two ways – - Extending java.lang.Thread class. - Implementing java.lang.Runnable interface.

Implementing java.lang.Runnable interface • The Runnable interface has the following specification, comprising one method prototype declaration: public interface Runnable { void run(); } • A thread, which is created based on an object that implements the Runnable interface, will execute the code defined in the public method run(). • In other words, the code in the run() method defines an independent path of execution and thereby the entry and the exits for the thread. The thread dies when the run() method ends, either by normal completion or by throwing an uncaught exception.

Implementing java.lang.Runnable interface (continued…) • The procedure for creating threads based on the Runnable interface is as follows: - A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object. - An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. - The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. • The run() method of the Runnable object is eventually executed by the thread represented by the Thread object on which the start() method was invoked.

UML : Sequence diagram – Using Runnable interface

Extending java.lang.Thread class • A class can also extend the Thread class to create a thread. A typical procedure for doing this is as follows – - A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread. - This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call. - The start() method (inherited from the Thread class) is invoked on the object of the class to make the thread eligible for running.

Some important constructors and methods from the java.lang.Thread Thread(Runnable threadTarget) Thread(Runnable threadTarget, String threadName) The argument threadTarget is the object whose run() method will be executed when the thread is started. The argument threadName can be specified to give an explicit name for the thread, rather than an automatically generated one. A thread's name can be retrieved by using the getName() method. static Thread currentThread() This method returns a reference to the Thread object of the currently executing thread.

Methods from the java.lang.Thread (continued…) final String getName() final void setName(String name) The first method returns the name of the thread. The second one sets the thread's name passed as an argument. void run() The Thread class implements the Runnable interface by providing an implementation of the run() method. This implementation does nothing. Subclasses of the Thread class should override this method. If the current thread is created using a separate Runnable object, then the Runnable object's run() method is called.

Methods from the java.lang.Thread (continued…) final void setDaemon(boolean flag) final boolean isDaemon() The first method sets the status of the thread either as a daemon thread or as a user thread, depending on whether the argument is true or false, respectively. The status should be set before the thread is started. The second method returns true if the thread is a daemon thread, otherwise, false. void start() This method spawns a new thread, that is, the new thread will begin execution as a child thread of the current thread. The spawning is done asynchronously as the call to this method returns immediately. It throws an IllegalThreadStateException if the thread was already started.

Coffee Cram



Why do we need to implement Runnable interface, when we can create threads by extending Thread class ?

Threads http://www.docjar.com

Coffee Cram



Why do we need to implement Runnable interface, when we can create threads by extending Thread class ?

Choosing an approach between Thread Class and Runnable Interface • Extending Thread class means, subclass can not inherit any other class (as Java does not allow multiple inheritance through classes) • Many Java programmers feel that classes should be extended only when they are being enhanced or modified in some way. When you extend Thread class, you are not really enhancing Thread class and or not adding any new functionality in it. Instead you are only interested in being runnable.

Thread Life Cycle Understanding the life cycle of a thread is valuable when programming with threads. Threads can exist in different states. Just because a thread's start() method has been called, it does not mean that the thread has access to the CPU and can start executing straight away. Several factors determine how a thread will proceed. Threads can exist in different states:-

Thread Life Cycle

Ready-to-run state A thread starts life in the Ready-to-run state.

Running state If a thread is in the Running state, it means that the thread is currently executing.

Thread Life Cycle Dead state Once in this state, the thread cannot ever run again.

Non-runnable states A running thread can transit to one of the non-runnable states, depending on the circumstances. A thread remains in a non-runnable state until a special transition occurs. A thread does not go directly to the Running state from a nonrunnable state, but transits first to the Ready-to-run state.

Thread Life Cycle The non-runnable states can be characterized as follows: • Sleeping: The thread sleeps for a specified amount of time. • Blocked for I/O: The thread waits for a blocking operation to complete. • Blocked for join completion: The thread awaits completion of another thread. • Waiting for notification: The thread awaits notification from another thread. • Blocked for lock acquisition: The thread waits to acquire the lock of an object.

We will study more about these states later.

Thread Scheduling Schedulers in JVM implementations usually employ one of the below given strategies: 1) Preemptive scheduling: If a thread with a higher priority than the current running thread moves to the Ready-to-run state, then the current running thread can be preempted (moved to the Ready-to-run state) to let the higher priority thread execute. 2) Time-Sliced or Round-Robin scheduling: A running thread is allowed to execute for a fixed length of time, after which it moves to the Ready-to-run state to await its turn to run again.

Remember - Thread schedulers are implementation and platform-dependent; therefore, how threads will be scheduled is unpredictable, at least from platform to platform.

Hey Thread 4, you’ve had enough time…go back to runnable state. Thread 2 you take his place. Thread 2

Thread 1

Thread 4

Thread 3

Thread Scheduler

Thread Priorities • Threads are assigned priorities that the thread scheduler can use to determine how the threads will be scheduled. • The thread scheduler can use thread priorities to determine which thread gets to run. The thread scheduler favors giving CPU time to the thread with the highest priority in the Readyto-run state. This is not necessarily the thread that has been the longest time in the Ready-to-run state. • Heavy reliance on thread priorities for the behavior of a program can make the program unportable across platforms, as thread scheduling is platform–dependent. • Priorities are integer values from 1 (lowest priority given by the constant Thread. MIN_PRIORITY) to 10 (highest priority given by the constant Thread.MAX_PRIORITY). The default priority is 5 (Thread.NORM_PRIORITY).

Thread Priorities • A thread inherits the priority of its parent thread. • Priority of a thread can be set using the setPriority() method and read using the getPriority() method, both of which are defined in the Thread class. • The following code sets the priority of the thread myThread to the minimum of two values: maximum priority and current priority incremented to the next level: myThread.setPriority(Math.min(Thread.MAX_PRIORITY, myThread.getPriority()+1));

Unary and Binary Numeric Promotions (continued...) Floating-Point Arithmetic • If any of the operands is a floating-point type, the operation performs floating-point division. int

i1 = 4 / 5;

// result: 0

int

i2 = 8 / 8;

// result: 1

double d2 = 4.0 / 8;

// result: 0.5

double d3 = 8 / 8.0;

// result: 1.0

double d4 = 12.0F / 8; // result: 1.5F

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF