Java Notes
Short Description
Download Java Notes...
Description
Chapter 1
Introduction to java Java is language for the development of Enterprise applications, and it was developed at Sun Microsystems as a platform-independent language primarily aimed at controlling appliances such as video game consoles VCRs, bread toasters . “Sun” , later modified the language to take advantage of World Wide Web. Java is an object-oriented language, and very similar to C++.
Java Features 1. PlatformIndependent The concept of Write-once-run-anywhere is one of the important key feature of java language that makes java as the most powerful language. 2. Simple Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system. 3. ObjectOriented java is a fully Object Oriented language because, object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into objects. 4. Robust Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust. 5. Distributed Internet programmers can call functions on HTTP , FTP protocols and can get access to the files from any remote machine rather than writing codes on their local system. 6. Portable The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. 7. Secure Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to 1
transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading.
2
8. Performance Java uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted in slow performance but the advanced versions of JVM uses just in time compilation technique that improves the performance. 9. Multithreaded Multithreading programming is a very interesting concept in Java. 10. Interpreted One of the advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. 11. Architecture Neutral Java was designed to support applications on network. The Java compiler generates byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly.
What is Java Virtual Machine? Languages like C and Pascal converts the source code into machine code for one specific type of machine and the machine language vary from system to system . But Java compiler produce code for a virtual machine . JVM converts the byte code into machine code for the computer one wants to run. The JVM is a part of JRE that is required by every operating system.
Each operating system and CPU architecture requires a JRE. JRE consists of a set of base classes i.e. Java API as well as a JVM. JVM is java interpreter as it converts the byte code into machine code for the computer one wants to run. JRE consists of a number of classes based on JavaAPI and JVM, and without JRE, it is impossible to run Java. How to write First Java program public class FirstProgram { public static void main(String arr[] ) { System.out.println(" Hello Java World"); } } 3
Save the file with same name as the public class just adding the extension “.java” e.g. FirstProgram.java. Now compile as: c:\ javac FirstProgram.java This creates a class file in bytecode form as FirstProgam.class How to execute this code: c:\ java MyFirstProgram OUTPUT ::
Hello Java World
Different Editions of Java Technology a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to create desktop applications, applets, server applications. These programs developed using Java SE can be run on almost every popular operating system. b) JEE - Java Enterprise Edition helps in web application service, component model and enterprise class service oriented architecture(SOA). c) JME - Java Micro Edition or JME is an accumulation of Java APIs that are used for the development of software for devices like mobile phones, PDAs, TV set-top boxes, game programming. Demonstartion Programs
Example 1 : Demo of a Simple java program public class FirstProg { public static void main(String args[]) { System.out.println( “welcome to the java SE 6”); } } Example 2 : Demo of if statement through a java program public class DemoIf { public static void main(String args[]) { int a = 10, b = 15, m; if (a > b) m = a; else m = b; 4
System.out.println( “max number = “+m); } } Example 3 : Demo of while.. loop through a java program public class DemoWhile { public static void main(String args[]) { int n = 257, s =0, d; while (n !=0) { d = n % 10; s = s +d ; n = n / 10; } System.out.println( “sum of digits = “+s); } } Example 4 : Demo of for.. loop public class DemoFor { public static void main(String args[]) { int n = 30, i; for (i = 1; i Example 50 :: demo of Throwtest public class Testthrow { public static void main(String args[]) throws Exception { int i1 = 15; int i2 = 20; if (i1 > i2) throw new Exception("First numb can not be more"); else System.out.print("ok"); } } Throwing custom (user defined) Exception :: Usefull to handle business specific error conditions.For Ex, while withdrawal from bank, an Exception MinBal may be created. Such Exceptions are placed as a subclass of Exception under Throwable class. They can be created using any method as below 1.
Throwable Uexcep = new Throwable( );
2.
Throwable Uexcep = new Throwable("message");
3.
class Uexcep extends Exception { public Uexcep() { ... } public Uexcep(String s) { ... 61
} } It is thrown by using keyword throw. It is also possible methods such as getmessage(), toString() etc. Example 51 : demo of custom exceptions import java.io.*; class AgeException extends Exception { int age; AgeException(String mesg) { super(mesg); } AgeException( ) { super( ); } } class youngAgeException extends AgeException { youngAgeException(int a1, String mesg) { super("you are too young for" + mesg); age = a1; } youngAgeException( ) { super( "too young"); } } class invalidAgeException extends AgeException { invalidAgeExecption(String mesg) { super(mesg); } invalidAgeException(int a1 ) { super( "Invalidformat"); age = a1; } } 62
to override the
public Testcustom { public static void main(String args[]) { int sAges = { 21,12,18,-5,45}; int i, n=sAges.length; try { for( i=0; i 0; i--) array[i] = -i; for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); Arrays.sort(a); for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); System.out.print("Found -5 at position " + Arrays.binarySearch(a, -5)); } } Example 57 : Demo of Vector class A Vector class is similar to ArrayList except that Vector class is synchronized. Multiple threads can not access it simultaneously. It implement the dynamic array. It predates collection framework. It has been rewritten to be compatible with collection framework import java.util.*; class Testvector { public static void main(String args[]) { Vector v = new Vector(5); System.out.println("Capacity: " + v.capacity()); v.addElement(new v.addElement(new v.addElement(new v.addElement(new v.addElement(new
Integer(10)); Integer(11)); Integer(22)); Integer(33)); Integer(44));
v.addElement(new Double(3.14)); v.addElement(new Float(3.14)); 73
System.out.println("Capacity: " + v.capacity()); System.out.println("Size: " + v.size()); System.out.println("First item:"+(Integer)v.firstElement()); System.out.println("Last item:" + (Float) v.lastElement()); if(v.contains(new Integer(33))) System.out.println("Found 3."); Iterator e = v.iterator(); while (e.hasNext()) { s = (String)v.next(); System.out.print(s); } } } output : capacity : capacity : size :7 First item Last item
5 10 0 3.14
Found a 3 10 11 22 33 44 3.14 3.14 Example 58 : Demo of ArrayList ( Dynamic and can grow ) It holds only the objects, and it can grow or shrink at run time. import java.util.*; class arraylist { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("Red"); al.add("Blue"); al.add("Yellow"); al.add(1, "White"); 74
System.out.println("Using the add method"); System.out.println(al); al.remove("White"); System.out.println(al); String l = al.get(1); System.out.println(l); System.out.println("Using the Iterator interface"); String s; Iterator e = al.iterator(); while (e.hasNext()) { s = (String)e.next(); System.out.print(s); } } }
75
Example 59 : Demo of linkedlist import java.util.*; class linkedlist { public static void main(String args[]) { LinkedList ls = new LinkedList(); ls.add("Blue"); ls.add("Green"); ls.add("Yellow"); ls.add("Orange"); ls.addFirst("Red"); ls.addLast("Black"); ls.add(1, "Grey"); System.out.println(ls); ls.remove("Black"); System.out.println(ls); ls.removeLast(); System.out.println(ls); System.out.println("Updating linked list items"); ls.set(0, "java"); ls.set(1, "C"); ls.set(2, "C++"); ls.set(3, "Oracle"); ls.set(4, "ASP.net"); System.out.println(ls); } }
76
Example 60 : Demo of HashSet class It is set of unique elements, and it uses a hash for storing data. As it uses hash methods such as add, remove, size etc and they take same amount of time. No gurantee of order of storage. import java.util.*; class hashset { public static void main(String args[]) { HashSet h1 = new HashSet(); h1.add("Red"); h1.add("Blue"); h1.add("Green"); System.out.println(h1); int s = h1.size() ; System.out.println(s); if( h1.contains("Red")) System.out.print("Red present" ); } } Example 61 : Demo of looping over all elements in a list ( Iterator ) import java.util.*; class iterator { public static void main(String args[]) { LinkedList l = new LinkedList(); l.add("Item 0"); l.add("Item 1"); l.add("Item 2"); Iterator it = l.iterator(); while(it.hasNext()) { 77
System.out.print(it.next()); } } } Example 55: Demo of ListIterator It can Loop over in both the directions import java.util.*; class listiterator { public static void main(String args[]) { LinkedList li = new LinkedList(); li.add("Item li.add("Item li.add("Item li.add("Item
0"); 1"); 2"); 3");
ListIterator lite = li.listIterator(); while(lite.hasNext()) { lite.set("This is " + lite.next()); /* set() is used to replace the element which is returned by next() or previous() by the current */ } while(lite.hasPrevious()) { System.out.println(lite.previous()); } } } Example 62 : Demo of HashMap Hash Maps allow the data to be stored as key/value pairs where key,value are objects. Map can be indexed with strings instead of numbers. On such Maps it is possible to access elements using strings or search them using string value. 78
import java.util.*; class hashmap { public static void main(String args[]) { HashMap hm = new HashMap(); hm.put("Item hm.put("Item hm.put("Item hm.put("Item
0", 1", 2", 3",
"Value "Value "Value "Value
0");// to add key,value pair to map 1"); 2"); 3");
Set s = hm.entrySet();// get corresponding set Iterator it = s.iterator(); while(it.hasNext()) { Map.Entry mp = (Map.Entry) it.next(); System.out.println(mp.getKey() + "/" + mp.getValue()); // it prints the key, value pairs } System.out.print(hm.get("Item 0"));//search for corresponding value } }
79
Example 63
: Demo of Hashtable class
It imple the interfaces such as Map,Clonable,Serializable. It is used to store values, in the form of map key with a value. The "key" should implement the hashcode, and equals method to store and retrieve values in a hashtable. It was how maps were implemented before collection framework. import java.util.*; class Testhashtable { public static void main(String args[]) { Hashtable ht = new Hashtable(); ht.put("B1", "Billgates"); ht.put("C2", "Chouhan"); ht.put("P3", "Pushkal"); ht.put("A4", "Anuj Singh"); Enumeration e = ht.keys(); while(e.hasMoreElements()) { String s = (String) e.nextElement(); System.out.println("key " + s + "/" + "Val" + ht.get(s)); } } } output : key C2 / val Chouhan key A4 / val Anuj ...e t c...
80
Example 64 : Demo of Hashtable class import java.util.*; class Testhashtable { public static void main(String args[]) { Hashtable ht = new Hashtable(4); ht.put("Billgates", Integer(55)); ht.put("Chouhan",Integer( 60)); ht.put("Pushkal", Integer(52)); ht.put("Anuj", Integer(46)); Vector v = ht.keySet(); Collection.sort(v); Enumeration e = v.elements(); // sorted list while(e.hasMoreElements()) { String s = (String) e.nextElement(); System.out.println("key " + s + "/" + "Val" + ht.get(s)); } } } output : key Anuj / val 46 key Billgates / val 55 ...e t c... sorted on key (string)
81
Example 65 : Demo of enumeration enum Mango { Brooks, Manilla, Alphanso, Kesar, Maya } class TestMango { public static void main (String args[]) { Mango ap; System.out.println("Here are all Mango constant:"); Mango allmangos[] = Mango.values(); for(Mango a : allmangos) System.out.println(a); System.out.println(); ap = Mango.valueOf(" Kesar"); System.out.println("ap contains"+ap); } }
Chapter 7
Multi Threading 82
Multithreading is a concept, where by it is possible to achieve concurrent execution of multiple units of a single program. A program in java can have multiple flow of controls and each flow of control is nothing but a small unit of execution, known as a thread. Thus a thread can run in parallel to the other threads. In the multithreading concept, several multiple lightweight processes are run in a single process/task or program by a single processor. For Example, When you use a word processor you perform a many different tasks such as printing, spell checking and so on. Multithreaded software treats each process as a separate program. In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time. For example, look at the diagram shown as:
In this diagram, two threads are being executed having more than one task. The task of each thread is switched to the task of another thread. Advantages of multithreading over multitasking : • • • •
Reduces the computation time. Improves performance of an application. Threads share the same address space so it saves the memory. Context switching between threads is usually less expensive than between processes.
A Thread runs inside a process and a process can contain one or more threads. Multithreading allows a program to do more than one task at a time. This means that one process can have a thread that performs a calculation, another thread that performs a service, and so forth. A thread is not a complete program by itself, and can not run on its own. However, each thread has a begining, and an end, and a sequential flow of execution at a single point of time. 83
At any given point of time within the run time of the program, only one thread will be executed by the processor. The CPU time will be divided into slices, and it switches between threads and runs so fast that it appears as if all threads are running at the same time. Differences between multiprocesing and multithreading : Both fall in the category of Multitasking. They differ in the level at which concurrency is done. Concurrent processes in Multiprocesing have their own separate address space and hence they can not access memory or files of other processes. Threads share resources like memory space, opened files. Though they are running seperately, they also work together to form a greater unit. It is better as a programming practice , to identify different parts of a program that can perform in paralell, and implement them into independent threads. In Java Programming language, thread is a sequential path of code execution within a program. Each thread has its own local variables, program counter and lifetime Main Thread When any standalone application is running, it firstly execute the main() method which runs in a thread, called the main thread. If no other threads are created by the main thread, then program terminates when the main() method complete its execution. The main thread creates some other threads called child threads. The main() method execution can finish, but the program will keep running until the all threads have completed its execution.
Creating Threads Thread can be implemented through any one of two ways: • •
Extending the java.lang.Thread Class Implementing the java.lang.Runnable Interface
84
I. Extending the java.lang.Thread Class For creating a thread a class have to extend the Thread Class. For creating a thread by this procedure you have to follow these steps: 1. Extend the java.lang.Thread Class. 2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. 3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. 4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. The following program demonstrates a single thread creation extending the "Thread" Class: class MyThread extends Thread{
String s=null; MyThread(String s1){ s=s1; start(); } public void run(){ System.out.println(s); } } public class RunThread{ public static void main(String args[]){ MyThread m1=new MyThread("Thread started...."); } }
Example 66 : Demo of creating a thread by extending Thread class class SampThread extends Thread { public Sampthread(String name) { super ( name ); } 85
public void run() { System.out.println("Now in: " +Thread.currentThread() ); for(int i = 0; i
View more...
Comments