O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

Java programming notes

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
JAVA Programming Ketan Rajpal Page: 1
1st
Unit
Features of JAVA:
 Platform Independent: The concept of Write-once-run-any...
JAVA Programming Ketan Rajpal Page: 2
Java Platform: The Java platform has two components:
 The Java Virtual Machine
 Th...
JAVA Programming Ketan Rajpal Page: 3
Primitive Data Types in Java: Byte, Short, Int, Long, Float, Double, Boolean, and Ch...
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Próximos SlideShares
Java notes
Java notes
Carregando em…3
×

Confira estes a seguir

1 de 27 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Semelhante a Java programming notes (20)

Anúncio

Mais de Ketan Rajpal (20)

Mais recentes (20)

Anúncio

Java programming notes

  1. 1. JAVA Programming Ketan Rajpal Page: 1 1st Unit Features of JAVA:  Platform Independent: The concept of Write-once-run-anywhere is one of the important key features of java language that makes java as the most powerful language. The programs written on one platform can run on any platform provided the platform must have the JVM.  Simple: There are various features that make the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and de-allocation system.  Object Oriented: To be an Object Oriented language, any language must follow at least the four characteristics.  Inheritance: It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed.  Encapsulation: It is the mechanism of combining the information and providing the abstraction.  Polymorphism: As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods.  Dynamic binding: Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime.  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.  Distributed: The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.  Portable: The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM.  Dynamic: While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.  Secure: Java does not use memory pointers explicitly. Security manager determines the accessibility options of a class like reading and writing a file to the local disk.  Performance: Java uses native code usage, and lightweight process called threads.  Multithreaded: Java is also a multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time.  Interpreted: Programs run directly from the source code. The interpreter program reads the source code and translates it on the fly into computations. Java Virtual Machine (JVM): It is a virtual machine capable of executing Java byte code. JVM is a platform- independent execution environment that converts Java byte code into machine language and executes it. In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the java compiler. A .class file does not contain code that is native to your processor; it instead contains byte codes. The java launcher tool then runs your application with an instance of the Java Virtual Machine. JVM converts that byte code into the code native to the processor.
  2. 2. JAVA Programming Ketan Rajpal Page: 2 Java Platform: The Java platform has two components:  The Java Virtual Machine  The Java Application Programming Interface (API): The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. Architecture of Java Virtual Machine
  3. 3. JAVA Programming Ketan Rajpal Page: 3 Primitive Data Types in Java: Byte, Short, Int, Long, Float, Double, Boolean, and Char. Java Variables: The Java programming language defines the following kinds of variables:  Instance Variables (Non-Static Fields): An object is an instance of a class. An object is an instance variable.  Class Variables (Static Fields): A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated.  Local Variables  Parameters 1. Member variables in a class—these are called fields. 2. Variables in a method or block of code—these are called local variables. 3. Variables in method declarations—these are called parameters. Arrays: An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Creating an array: Single Dimensional: Int a[]=new int[10]; Multi Dimensional: int[][] multD = new int[9][]; Operators: The following quick reference summarizes the operators supported by the Java programming language. Type of Operator Name Operator Simple Assignment Operator Simple assignment operator = Arithmetic Operators Additive operator (also used for String concatenation) + Subtraction operator - Multiplication operator * Division operator / Remainder operator % Unary Operators Unary plus operator; indicates positive value + Unary minus operator; negates an expression - Increment operator; increments a value by 1 ++ Decrement operator; decrements a value by 1 -- Logical complement operator; inverts the value of a Boolean ! Equality and Relational Equal to ==
  4. 4. JAVA Programming Ketan Rajpal Page: 4 Operators Not equal to != Greater than > Greater than or equal to >= Less than < Less than or equal to <= Conditional Operators Conditional-AND && Conditional-OR || Ternary (shorthand for if-then-else statement) ?: Type Comparison Operator Compares an object to a specified type instanceof Bitwise and Bit Shift Operators Unary bitwise complements ~ Signed left shift << Signed right shift >> Unsigned right shift >>> Bitwise AND & Bitwise exclusive OR ^ Bitwise inclusive OR | Access Modifiers  Public modifier—the field is accessible from all classes.  Private modifier—the field is accessible only within its own class. Using the ‘this’ Keyword: Within an instance method or a constructor, this is a reference to the current object the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. Example of ‘this’ Keyword public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } Nested Classes: The Java programming language allows you to define a class within another class. Such a class is called a nested class. Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. There are several compelling reasons for using nested classes, among them:  It is a way of logically grouping classes that are only used in one place.  It increases encapsulation.  Nested classes can lead to more readable and maintainable code. Syntax of Nested Classes class OuterClass {
  5. 5. JAVA Programming Ketan Rajpal Page: 5 ... static class StaticNestedClass { ... } class InnerClass { ... } } OuterClass.InnerClass innerObject = outerObject.new InnerClass(); Byte code engineering libraries: The Byte Code Engineering Library (formerly known as Java Class) is intended to give users a convenient possibility to analyze, create, and manipulate Java class files. Classes are represented by objects which contain all the symbolic information of the given class: methods, fields and byte code instructions, in particular. Such objects can be read from an existing file, be transformed by a program and dumped to a file again. An even more interesting application is the creation of classes from scratch at run-time. The Byte Code Engineering Library (BCEL) may be also useful if you want to learn about the Java Virtual Machine (JVM) and the format of Java.class files. Java class file format: It starts with a header containing a magic number and the version number, followed by the constant pool, which can be roughly thought of as the text segment of an executable, the access rights of the class encoded by a bit mask, a list of interfaces implemented by the class, lists containing the fields and methods of the class, and finally the class attributes, e.g., the Source File attribute telling the name of the source file. Attributes are a way of putting additional, user-defined information into class file data structures. Byte Code Instruction Set: The byte code instruction set currently consists of 212 instructions, 44 opcodes are marked as reserved and may be used for future extensions or intermediate optimizations within the Virtual Machine. The instruction set can be roughly grouped as follows:  Stack operations  Arithmetic operations  Control flow  Load and store operations  Field access  Method invocation  Object allocation  Conversion and type checking Class Loader: The Java Class loader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of class loaders. Delegation is an important concept to understand when learning about class loaders. Classes are introduced into the Java environment when they are referenced by name in a class that is already running. There is a bit of magic that goes on to get the first class running (which is why you have to declare the main() method as static, taking a string array as an argument), but once that class is running, future attempts at loading classes are done by the class loader. At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is: Class r = loadClass(String className, boolean resolveIt); The Sand Box Security Model: Java's security model is one of the language's key architectural features that make it an appropriate technology for networked environments. The sandbox security model makes it easier to work with software that comes from sources you don't fully trust. Instead of security being established by requiring you to prevent any code you don't trust from ever making its way onto your computer, the sandbox model lets you
  6. 6. JAVA Programming Ketan Rajpal Page: 6 welcome code from any source. But as it's running, the sandbox restricts code from un-trusted sources from taking any actions that could possibly harm your system. The advantage is you don't need to figure out what code you can and can't trust, and you don't need to scan for viruses. The sandbox itself prevents any viruses or other malicious code you may invite into your computer from doing any damage. Interfaces: An interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Syntax of an Interface public interface OperateCar { int turn(Direction direction, double radius, double startSpeed, double endSpeed); int changeLanes(Direction direction, double startSpeed, double endSpeed); int signalTurn(Direction direction, boolean signalOn); int getRadarFront(double distanceToCar, double speedOfCar); int getRadarRear(double distanceToCar, double speedOfCar); } public class OperateBMW760i implements OperateCar { int signalTurn(Direction direction, boolean signalOn) { } } Interfaces have another very important role in the Java programming language. Interfaces are not part of the class hierarchy, although they work in combination with classes. The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative. In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface. This is discussed later in this lesson, in the section titled "Using an Interface as a Type." The public access specifiers indicate that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface. An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends. The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon, but no braces, because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public, so the public modifier can be omitted. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.  An interface defines a protocol of communication between two objects.
  7. 7. JAVA Programming Ketan Rajpal Page: 7  An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions.  A class that implements an interface must implement all the methods declared in the interface.  An interface name can be used anywhere a type can be used. Inheritance:  A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a super class (also a base class or a parent class).  Excepting Object, which has no super class, every class has one and only one direct super class (single inheritance). In the absence of any other explicit super class, every class is implicitly a subclass of Object.  Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object. The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself. A subclass inherits all the members (fields, methods, and nested classes) from its super class. Constructors are not members, so they are not inherited by subclasses, but the constructor of the super class can be invoked from the subclass. (Extends) Keyword Super: If your method overrides one of its super class's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field. Example of Super Keyword public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } } public class Subclass extends Superclass { public void printMethod() { super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } } Object Class: The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class. Every class you use or write inherits the instance methods of Object. You need not use any of these methods, but, if you choose to do so, you may need to override them with code that is specific to your class. protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object.
  8. 8. JAVA Programming Ketan Rajpal Page: 8 public boolean equals(Object obj) Indicates whether some other object is "equal to" this one. protected void finalize() throws Throwable Called by the garbage collector on an object when garbage collection determines that there are no more references to the object public final Class getClass() Returns the runtime class of an object. public int hashCode() Returns a hash code value for the object. public String toString() Returns a string representation of the object. Writing Final Classes and Methods: You can declare some or a class’s entire methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final. Syntax of Final Class class ChessAlgorithm { enum ChessPlayer { WHITE, BLACK } ... final ChessPlayer getFirstPlayer() { return ChessPlayer.WHITE; } } Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results. Abstract Methods and Classes: An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub classed. An abstract method is a method that is declared without an implementation. abstract void moveTo(double deltaX, double deltaY); Abstract Class public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void draw(); } Example of Abstract Class and its methods abstract class GraphicObject { int x, y; ... void moveTo(int newX, int newY) { ... }
  9. 9. JAVA Programming Ketan Rajpal Page: 9 abstract void draw(); abstract void resize(); } class Circle extends GraphicObject { void draw() { ... } void resize() { ... } } class Rectangle extends GraphicObject { void draw() { ... } void resize() { ... } } File Handling, String Buffer and Exception Handling Program import java.io.*; class fileOperations { String fileName; FileInputStream myFile; FileOutputStream myFile2; String firstFile; String secondFile; void getFileName(String myName) { fileName=myName; } void getTwoFileName(String f1, String f2) { firstFile=f1; secondFile=f2; } void copyFile() { int i; try { myFile=new FileInputStream(firstFile); } catch(FileNotFoundException e) { System.out.println(firstFile+ ": This file was not found."); return; } try { myFile2=new FileOutputStream(secondFile); } catch(FileNotFoundException e)
  10. 10. JAVA Programming Ketan Rajpal Page: 10 { System.out.println(secondFile+ ": This file was not found."); return; } try { do { i=myFile.read(); if(i!=-1) { myFile2.write(i); } }while (i!=-1); } catch(IOException e) { return; } } void showFile() { int i; try { myFile=new FileInputStream(fileName); do { i=myFile.read(); if(i!=-1) { System.out.print((char) i); } }while(i!=-1); myFile.close(); } catch(FileNotFoundException e) { System.out.println(fileName+ ": This file was not found."); return; } catch(IOException e) { return; } } } public class handleFile { public static void main(String s[]) { String myFileName, firstFile, secondFile, choice; int i; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); fileOperations f1= new fileOperations(); System.out.println("WELCOME TO FILE OPERATION PROGRAM"); System.out.println("What operation do you want to perform on file: "); System.out.println("1. Read a file."); System.out.println("2. Copy one file to another.");
  11. 11. JAVA Programming Ketan Rajpal Page: 11 System.out.println("0. Exit."); System.out.println("Enter your choice: "); try { choice=br.readLine(); } catch(IOException e) { return; } i=Integer.parseInt(choice); switch(i) { case 0: return; case 1: System.out.println("Welcome to read a file."); System.out.println("Enter the name of the file you want to read: "); try { myFileName=br.readLine(); } catch(IOException e) { return; } f1.getFileName(myFileName); f1.showFile(); return; case 2: try { System.out.println("Welcome to copy a file."); System.out.println("Enter the name of the FIRST file (SOURCE FILE): "); firstFile=br.readLine(); System.out.println("Enter the name of the SECOND file (DESTINATION FILE): "); secondFile=br.readLine(); f1.getTwoFileName(firstFile, secondFile); f1.copyFile(); } catch(IOException e) { return; } return; default: System.out.println("Sorry the option entered is incorrect."); return; } } } JOptionPane Program Import javax.swing.JOptionPane; Public class comparison {
  12. 12. JAVA Programming Ketan Rajpal Page: 12 Public static void main(string s[]) { Integer c1, c2; String s1, s2, message; S1=jOptionPane.showInputDialog(“Enter first number: ”); S2=jOptionPane.showInputDialog(“Enter second number: ”); C1=Integer.parseInt(s1); C2=Integer.parseInt(s2); If (C1>C2) { Message=”C1 is Greater.”; } Else { Message=”C2 is Greater.”; } jOptionPane.showMessageDialog(null,message,”Greater Value”,jOptionPane.Plain_text); } }
  13. 13. JAVA Programming Ketan Rajpal Page: 13 2nd Unit Networking Basics: Internet addresses uniquely identify each computer on the network. They use a 4 byte dot IP notation such as 220.210.34.7 Domain Name Service allows us to use an easier to remember naming scheme. DNS servers translate the domain name such as amazon.com into its dot IP address. Servers are any computer with resources (such as printers and disks) to be shared. Clients are entities that want to use these resources. Servers listen to their socket ports waiting for a client to connect with a service request. Servers are multithreaded to permit multiple services and multiple connects to the same service simultaneously. Proxy servers speak the client side of the protocol to another server. It acts as an agent of the client and can be set up to filter or cache data for it. A network socket is a standard interface that uses the TCP/IP protocol. It can be either a connection-oriented stream or connectionless (datagram packet based). Sockets use IP address extensions or ports to connect to specific services such as FTP and telnet. Each port number (below 1024) has a reserved use. You can use Sockets.com or google Well- Known Port Numbers to find the port number for a service. The java.net package provides support for the two common network protocols:  TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.  UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. Example of Networking public class MyFirstInternetAddress { public static void main(String args[]) { try { InetAddress localaddr = InetAddress.getLocalHost(); System.out.println ("Local IP Address : " + localaddr ); System.out.println ("Local hostname : " + localaddr.getHostName()); } catch (UnknownHostException e) { System.err.println ("Can't detect localhost : " + e); } } } Internet Streams: Internet streams allow you to access remote document data. The java.net package provides several objects for networking at the stream level:  URL builds a valid internet address. Methods are: getFile(), getHost(), getPort(), getProtocol(), openConnection() and toExternalForm()  URLConnection is a general purpose connection. Methods are: connect(), getContent(), getContentLength(), getContentType(), getDate(), getExpiration(), getInputStream() and getLastModified()  HttpURLConnection is an Http protocol specific connection. Methods in addition to those inherited from URLConnection are: getHeaderField(), getHeaderFieldDate(), getHeaderFieldKey(), getRequestMethod(), setRequestMethod(). Sockets: Sockets are means to establish a communication link between machines over the network. The java.net package provides 4 kinds of Sockets:  Socket is a TCP client API, and will typically be used to connect (java.net.Socket.connect(SocketAddress)) to a remote host.  ServerSocket is a TCP server API, and will typically accept (java.net.ServerSocket.accept) connections from client sockets.  DatagramSocket is a UDP endpoint API and is used to send, and receive, java.net.DatagramPackets.  MulticastSocket is a subclass of the DatagramSocket used when dealing with multicast groups.
  14. 14. JAVA Programming Ketan Rajpal Page: 14 Sending and receiving with TCP sockets is done through InputStreams and OutputStreams which can be obtained via the java.net.Socket.getInputStream and java.net.Socket.getOutputStream methods. Client Socket Programming: Sockets are either connection-oriented (streamed) or connectionless (datagram or packet-oriented). The java.net package provides Socket and DatagramSocket objects for networking at the TCP/IP level. Establishing a stream client involves four steps:  Create a new socket with a server address and a port number  Create inputstream and outputstream objects  Process stream data  Close the streams Server Socket Programming: The java.net package provides ServerSocket and DatagramSocket objects for servers at the TCP/IP socket level. Establishing a stream server involves five steps:  Create a new socket with port number and max number of clients  Set a socket connect for a client using the accept() method  Create inputstream and outputstream objects  Process stream data  Close the streams Example of Socket Programming // File Name GreetingServer.java import java.net.*; import java.io.*; public class GreetingServer extends Thread { private ServerSocket serverSocket; public GreetingServer(int port) throws IOException { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(10000); } public void run() { while(true) { try { System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); DataInputStream in = new DataInputStream(server.getInputStream()); System.out.println(in.readUTF()); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "nGoodbye!"); server.close(); }catch(SocketTimeoutException s) { System.out.println("Socket timed out!"); break; }catch(IOException e) { e.printStackTrace(); break; } } }
  15. 15. JAVA Programming Ketan Rajpal Page: 15 public static void main(String [] args) { int port = Integer.parseInt(args[0]); try { Thread t = new GreetingServer(port); t.start(); }catch(IOException e) { e.printStackTrace(); } } } // File Name GreetingClient.java import java.net.*; import java.io.*; public class GreetingClient { public static void main(String [] args) { String serverName = args[0]; int port = Integer.parseInt(args[1]); try { System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); }catch(IOException e) { e.printStackTrace(); } } } Java Networking Interface  ContentHandlerFactory: This interface defines a factory for content handlers.  DatagramSocketImplFactory: This interface defines a factory for datagram socket implementations.  FileNameMap: A simple interface which provides a mechanism to map between a file name and a MIME type string.  SocketImplFactory: This interface defines a factory for socket implementations.  SocketOptions: Interface of methods to get/set socket options.  URLStreamHandlerFactory: This interface defines a factory for URL stream protocol handlers.
  16. 16. JAVA Programming Ketan Rajpal Page: 16 3rd Unit The Collection Framework A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers). A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:  Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.  Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.  Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. The Java Collections Framework provides the following benefits:  Reduces programming effort  Increases program speed and quality  Allows interoperability among unrelated APIs  Reduces effort to learn and to use new APIs  Reduces effort to design new APIs  Fosters software reuse Java Collections are of three types  Set -> Sorted Set (Type)  List  Queue  Map -> Sorted Map (Type) public interface Collection<E>... The <E> syntax tells you that the interface is generic. When you declare a Collection instance you can and should specify the type of object contained in the collection. Specifying the type allows the compiler to verify that the type of object you put into the collection is correct, thus reducing errors at runtime. Syntax public interface Collection<E> extends Iterable<E> { int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator<E> iterator(); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional Object[] toArray(); <T> T[] toArray(T[] a); }
  17. 17. JAVA Programming Ketan Rajpal Page: 17 for (Object o : collection) System.out.println(o); The following list describes the core collection interfaces:  Collection: The root of the collection hierarchy. A collection represents a group of objects known as its elements. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered.  Set: A collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine.  List: An ordered collection. Lists can contain duplicate elements.  Queue: A collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.  Map: An object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.  SortedSet: A Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.  SortedMap: A Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories. The Collection Interface: The Collection interface is used to pass around collections of objects where maximum generality is desired. Some Collection Interface Methods  boolean add(Object obj): Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates.  boolean addAll(Collection c): Adds all the elements of c to the invoking collection. Returns true if the operation succeeded (i.e., the elements were added). Otherwise, returns false.  void clear( ): Removes all elements from the invoking collection.  boolean contains(Object obj): Returns true if obj is an element of the invoking collection. Otherwise, returns false.  boolean containsAll(Collection c): Returns true if the invoking collection contains all elements of c. Otherwise, returns false.  boolean equals(Object obj): Returns true if the invoking collection and obj are equal. Otherwise, returns false.  int hashCode( ): Returns the hash code for the invoking collection.  boolean isEmpty( ): Returns true if the invoking collection is empty. Otherwise, returns false.  Iterator iterator( ): Returns an iterator for the invoking collection.  boolean remove(Object obj): Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false.  boolean removeAll(Collection c): Removes all elements of c from the invoking collection. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.  boolean retainAll(Collection c): Removes all elements from the invoking collection except those in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false  int size( ): Returns the number of elements held in the invoking collection.  Object[ ] toArray( ): Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements.  Object[ ] toArray(Object array[ ]): Returns an array containing only those collection elements whose type matches that of array. Simple Example of Collection import java.util.*; public class CollectionsDemo { public static void main(String[] args) {
  18. 18. JAVA Programming Ketan Rajpal Page: 18 List a1 = new ArrayList(); a1.add("Zara"); a1.add("Mahnaz"); a1.add("Ayan"); System.out.println(" ArrayList Elements"); System.out.print("t" + a1); List l1 = new LinkedList(); l1.add("Zara"); l1.add("Mahnaz"); l1.add("Ayan"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("t" + l1); Set s1 = new HashSet(); s1.add("Zara"); s1.add("Mahnaz"); s1.add("Ayan"); System.out.println(); System.out.println(" Set Elements"); System.out.print("t" + s1); Map m1 = new HashMap(); m1.put("Zara", "8"); m1.put("Mahnaz", "31"); m1.put("Ayan", "12"); m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map Elements"); System.out.print("t" + m1); } } Output ArrayList Elements [Zara, Mahnaz, Ayan] LinkedList Elements [Zara, Mahnaz, Ayan] Set Elements [Zara, Mahnaz, Ayan] Map Elements {Mahnaz=31, Ayan=12, Daisy=14, Zara=8} JDBC: Java Database Connectivity in short called as JDBC. The JDBC API is the industry standard for database independent connectivity between the Java programming language and a wide range of databases. JDBC has been part of the Java Standard Edition since the release of JDK 1.1. The JDBC classes are contained in the Java package java.sql. JDBC technology allows you to use the Java programming language to exploit "Write Once, Run Anywhere" capabilities for applications that require access to enterprise data. JDBC Architecture: Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as:  Database connections (Connection – class)  SQL statements (Statement – Interface)  Result Set (ResultSet – Interface)  Database metadata ( DatabaseMetaData – Interface)  Prepared statements (PreparedStatement – Interface (subinterface of Statement))  Binary Large Objects (BLOBs) (Blob – Interface)  Character Large Objects (CLOBs) (Clob – Interface)
  19. 19. JAVA Programming Ketan Rajpal Page: 19  Callable statements (CallableStatement – Interface (subinterface of PreparedStatement))  Database drivers (Driver – Interface)  Driver manager(DriverManager Class) Driver manager: The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. The task of the DriverManager class is to keep track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the DriverManager class by calling the method DriverManager.registerDriver(). By calling the Class.forName() method the driver class get automatically loaded. The driver is loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves automatically when their driver implementation class get loads. This class has many methods. Some of the commonly used methods are given below:  deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class.  registerDriver(Driver driver) : It registers the driver with the DriverManager class.  getConnection(String url) : It tries to establish the connection to a given database URL.  getConnection(String url, Sting user, String password) : It tries to establish the connection to a given database URL.  getConnection(String url, Properties info) : It tries to establish the connection to a given database URL.  getDriver(String url) : It attempts to locate the driver by the given string.  getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class. The JDBC API uses a Driver Manager and databasespecific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. JDBC-ODBC Bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. Sun provides a JDBCODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. Client > JDBC Driver > ODBC Driver > Database JDBC API: The JDBC API makes it possible to do three things:  Establish a connection with a database or access any tabular data source  Send SQL statements  Process the results Steps in using JDBC:  Load the driver  Establish the Connection  Create a Statement object  Execute a query  Process the results  Close the connection Load the driver public static Class<?> forName(String className) throws ClassNotFoundException
  20. 20. JAVA Programming Ketan Rajpal Page: 20 Returns the Class object associated with the class or interface with the given string name The method Class.forName(String) is used to load the JDBC driver class. When a Driver class is loaded, it creates an instance of itself and registers it with the DriverManager. try { Class.forName("connect.microsoft.MicrosoftDriver"); Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("sun.jdbc.odbc.jdbcodbcDriver"); } Catch(ClassNotFoundException cnfe) { System.out.println("Error loading driver: " cnfe); } Establish the Connection Now when a connection is needed, one of the DriverManager.getConnection() methods is used to create a JDBC connection. Connection conn = DriverManager.getConnection("jdbc:somejdbcvendor:other data needed by some jdbc vendor", "myLogin", "myPassword" ); The URL used is dependent upon the particular JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is up to the particular vendor. Connection con =DriverManager.getConnection("jdbc:odbc:pooja","scott","tiger"); Create a Statement object Once a connection is established, a statement must be created. Statement stmt = conn.createStatement(); JDBC represents statements using one of the following classes:  Statement: The statement is sent to the database server each and every time. Execute simple sql queries without parameters. Creates a Statement object for sending SQL statements to the database. Statement createStatement()  PreparedStatement: The statement is cached and then the execution path is pre determined on the database server allowing it to be executed multiple times in an efficient manner. Execute precompiled sql queries with or without parameters. Creates a PreparedStatement object for sending parameterized SQL statements to the database PreparedStatement prepareStatement(String sql) PreparedStatement statement = connection.prepareStatement("UPDATE employees "+ "SET salary = ? " + "WHERE id = ?"); int[] newSalaries = getSalaries(); int[] employeeIDs = getIDs(); for(int i=0; i<employeeIDs.length; i++) { statement.setInt(1, newSalaries[i]); statement.setInt(2, employeeIDs[i]); statement.executeUpdate(); }  CallableStatement: Used for executing stored procedures on the database. CallableStatement prepareCall(String sql) Creates a CallableStatement object for calling database stored procedures. Execute a query Statement defines these three methods for executing SQL statements, which handle SQL commands returning different kinds of results:  Int executeUpdate(String sql): Execute a SQL INSERT, UPDATE, or DELETE statement, which returns either a count of rows affected or zero. Return count of the number of rows changed.
  21. 21. JAVA Programming Ketan Rajpal Page: 21  ResultSet executeQuery(String sql): Execute a SQL statement that returns a single ResultSet. Execute SELECT statement. Return a resultset that hold data extracted from the database.  Boolean execute(String sql): Execute a SQL statement that may return multiple results. Execute Stored procedure with multiple results. Return true if the first results is a resultset other wise false. int i= stmt.executeUpdate( "INSERT INTO MyTable VALUES ( 'my name' ) " ); OR ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" ); Process the results: A table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set. ResultSet provides various getXxx methods that take a column index or column name and returns the data. public interface ResultSet while(resultSet.next()) { System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3)); } First column has index 1, not 0 Close the connection connection.close();
  22. 22. JAVA 4th U Remo RMI, calls calls. RMI a Creat          Arch    A Programmin nit ote Object In is a Java app (RPC). RMI a applications o ting a remote  Create an  Create a c  Create a s  Create a c  Compile t  Run the R myRMIIm  Start the R  Start the s  Run the c itecture of RM  The serve  The client  The Stub result bac ng nvocation: Th plication prog allowed progr often compris e object interface. (in class that imp server that cr client that con these classes. RMI interface mpl"). RMI registry ( server class (" lient program MI: er must first b t lookup the s serializing the ck to the stub he Java Remo gramming inte rammer to ex se two separa n this case, th plements the eates an insta nnects to the e compiler on (on Windows "start java my m ("java myRM bind its name server name i e parameters b. Keta ote Method erface that p xecute remot ate programs he interface is interface. (in ance of this c e server objec n the .class fi s NT/95, say " yRMIServer") MIClient"). to the registr in the registry s to skeleton, an Rajpal Invocation A erforms the o te function cl s, a server and s myRMIInter this case, my class ct using Nami le of the imp start rmiregis ). ry y to establish the skeleton pplication Pr object-orient ass using the d a client. rface.java). yRMIImpl.jav ng.lookup() plementation stry"). remote refer n invoking the ogramming I ed equivalen e same sema a). class (in this rences. e remote met nterface (AP t of remote p ntics as local s case, you'd thod and seria Page: 22 I), or Java procedure functions say "rmic alizing the
  23. 23. JAVA Programming Ketan Rajpal Page: 23 The Stub and Skelton  A client invokes a remote method; the call is first forwarded to stub.  The stub is responsible for sending the remote call over to the server-side skeleton  The stub opening a socket to the remote server, marshaling the object parameters and forwarding the data stream to the skeleton.  A skeleton contains a method that receives the remote calls, unmarshals the parameters, and invokes the actual remote object implementation. Java Beans are reusable software components for Java. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object, so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serialized, has a null constructor, and allows access to properties using getter and setter methods. JavaBeans is a portable, platform-independent component model written in the Java programming language. With the JavaBeans API you can create reusable, platform-independent components. Using JavaBeans-compliant application builder tools such as Net Beans or Eclipse, you can combine these components into applets, applications, or composite components. Java Bean Architecture: Java Beans is an architecture for both using and building components in Java. This architecture supports the features of software reuse, component models, and object orientation. One of the most important features of JavaBeans is that it does not alter the existing Java language. If you know how to write software in Java, you know how to use and create Beans. The strengths of Java are built upon and extended to create the JavaBeans component architecture. Although Beans are intended to work in a visual application development tool, they don’t necessarily have a visual representation at run-time (although many will). What this does mean is that Beans must allow their property values to be changed through some type of visual interface, and their methods and events should be exposed so that the development tool can write code capable of manipulating the component when the application is executed. Packing beans: The manifest & the jar: Before you can bring a JavaBeans into a Bean-enabled visual builder tool, it must be put into the standard Bean container, which is a JAR file that includes all the Bean classes as well as a “manifest” file that says “This is a Bean.” A manifest file is simply a text file that follows a particular form. For the Bang Bean, the manifest file looks like this: Manifest-Version: 1.0 Name: bangbean/BangBean.class Java-Bean: True The first line indicates the version of the manifest scheme, which until further notice from Sun is 1.0. The second line names the BangBean.class file, and the third says “It’s a Bean.” Without the third line, the program builder tool will not recognize the class as a Bean. Manifest file must be place in the directory above the root of your package path, which in this case means placing the file in the directory above the “bang bean” subdirectory. Then we must invoke jar from the same directory as the manifest file, as follows: jar cfm BangBean.jar BangBean.mf bangbean Stub RMI Client RMI Server skeleton return call
  24. 24. JAVA Programming Ketan Rajpal Page: 24 This assumes that you want the resulting JAR file to be named BangBean.jar, and that you’ve put the manifest in a file called BangBean.mf.  JAR files: The bean class and any other utility classes that the bean needs are packaged in a JAR file.  Serialized files: The bean to be accessed is a serialized object in a file whose extension is .ser. The file was created using the java.io.ObjectOutputStream class.  XML archive: The bean was serialized using the java.beans.XMLEncoder class. This is the preferred technique to serialize a bean. Advantages of JavaBeans  A Bean obtains all of the benefits of Java's "write once, run anywhere" paradigm.  The properties, events, and methods of a Bean that are exposed to another application can be controlled.  Auxiliary software can be provided to help configure a Bean.  The configuration settings of a Bean can be saved in a persistent storage and can be restored at a later time.  A Bean may register to receive events from other objects and can generate events that are sent to other objects. Bean Development Kit: Bean Development Kit is a tool that enables to create, configure and connect a set of Beans and it can be used to test Beans without writing a code. It provides an environment to create a new bean, configure the bean & connect a set of beans. It can be used for testing the java beans. Bean Properties: A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples of bean properties include color, label, font, font size, and display size. public void setPropertyName(PropertyType value); public PropertyType getPropertyName();  Simple: A bean property with a single value whose changes are independent of changes in any other property.  Indexed: A bean property that supports a range of values instead of a single value.  Bound: A bean property for which a change to the property results in a notification being sent to some other bean.  Constrained: A bean property for which a change to the property results in validation by another bean. The other bean may reject the change if it is not appropriate. Simple Java Bean Program import java.awt.*; import java.io.Serializable; public class SimpleBean extends Canvas implements Serializable{ public SimpleBean(){ setSize(60,40); setBackground(Color.red); } } Events: An event allows your Beans to communicate when something interesting happens. There are three parts to this communication:  EventObject  EventListener - (the sink)  An Event Source (the Bean) Event Object: The java.util.EventObject class is the basis of all Beans events. Example of Event Object
  25. 25. JAVA Programming Ketan Rajpal Page: 25 public class java.util.EventObject { extends Object implements java.io.Serializable { public java.util.EventObject (Object source); public Object getSource(); public String toString(); } } Event Listener: The EventListener interface is empty, but serves as a tagging interface that all event listeners must extend; that way, Beans integration tools can work. A listener is something that desires notification when an event happens. The listener receives the specific EventObject subclass as a parameter. The name of the new listener interface is EventTypeListener. For the new HireEvent, the listener name would be HireListener. The actual method names within the interface have no specific design pattern to follow, but, should describe the event that is happening. public interface HireListener extends java.util.EventListener { public abstract void hired (HireEvent e); } Event Source: Without an event source, the HireEvent and HireListener are virtually useless. The event source defines when and where an event will happen. Classes register themselves as interested in the event, and they receive notification when the event happens. A series of methods patterns represents the registration process: public synchronized void addListenerType(ListenerType l); public synchronized void removeListenerType(ListenerType l); Net Beans: Net Beans refers to both a platform framework for Java desktop applications, and an integrated development environment (IDE) for developing with Java, JavaScript, PHP, Python, Groovy, C, C++ and others. The Net Beans IDE is written in Java and can run anywhere a compatible JVM is installed, including Windows, Mac OS, Linux, and Solaris. A JDK is required for Java development functionality, but is not required for development in other programming languages. The Net Beans platform allows applications to be developed from a set of modular software components called modules. The platform offers reusable services common to desktop applications, allowing developers to focus on the logic specific to their application. Among the features of the platform are:  User interface management (e.g. menus and toolbars)  User settings management  Storage management (saving and loading any kind of data)  Window management  Wizard framework (supports step-by-step dialogs)  Net Beans Visual Library  Integrated Development Tools Java Foundation Classes (JFC): The Java Foundation Classes (JFC) is a graphical framework for building portable Java- based graphical user interfaces (GUIs). JFC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D. The Java Foundation Classes (JFC) is a comprehensive set of GUI components and services which dramatically simplify the development and deployment of commercial-quality desktop and Internet/Intranet applications. Swing: Swing is basically a set of customizable graphical components whose look-and-feel can be dictated at runtime.  Pre-built look-and-feel: Motif, Windows, Macintosh, Metal on a any platform  Personal look-and-feel also definable Swing is actually one API in the JFC suite of libraries  AWT: Basic GUI Toolkit shipped with all versions of JDK. Swing does not reuse any AWT components but does build off some lightweight component facilities
  26. 26. JAVA Programming Ketan Rajpal Page: 26  Accessibility: Interface to alternative user interfaces e.g. audible text readers, Braille keyboards may interface via this API. All Swing Components support accessibility.  2D API: Various painting styles, drawing styles, fonts and colors. Not Part of SWING.  Drag and Drop: Click and hold of GUI objects, moving windows or objects etc. Not Part of SWING Features of Swing  Pluggable look-and feels  Lightweight components  Do not depend on native peers to render them.  Simplified graphics to paint on screen  Similar behavior across all platforms  Portable look and feel  Only a few top level containers not lightweight.  New components -- tress tables, sliders progress bars, frames, text components.  Tooltips -- textual popup to give additional help  arbitrary keyboard event binding  Debugging support AWT Vs Swing: When developing a Java program it is important to select the appropriate Java Graphical User Interface (GUI) components. There are two basic sets of components that you will most likely build your Java programs with. These two groups of components are called the Abstract Window Toolkit (AWT) and Swing. Both of these groups of components are part of the Java Foundation Classes (JFC). AWT stands for Abstract Window Toolkit. The Abstract Window Toolkit supports GUI Java programming. It is a portable GUI library for stand-alone applications and/or applets. The Abstract Window Toolkit provides the connection between your application and the native GUI. The AWT provides a high level of abstraction for your Java program since it hides you from the underlying details of the GUI your program will be running on. AWT features include:  A rich set of user interface components.  A robust event-handling model.  Graphics and imaging tools, including shape, color, and font classes.  Layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution.
  27. 27. JAVA Programming Ketan Rajpal Page: 27  Data transfer classes, for cut-and-paste through the native platform clipboard. The AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called "heavyweight" components. Positive Points of AWT  Speed: use of native peers speeds component performance.  Applet Portability: most Web browsers support AWT classes so AWT applets can run without the Java plug- in.  Look and Feel: AWT components more closely reflect the look and feel of the OS they run on. Negative Points of AWT  Portability: use of native peers creates platform specific limitations. Some components may not function at all on some platforms.  Third Party Development: the majority of component makers, including Borland and Sun, base new component development on Swing components. There is a much smaller set of AWT components available, thus placing the burden on the programmer to create his or her own AWT-based components.  Features: AWT components do not support features like icons and tool-tips. Swing implements a set of GUI components that build on AWT technology and provide a pluggable look and feel. Swing is implemented entirely in the Java programming language, and is based on the JDK 1.1 Lightweight UI Framework. Swing features include:  All the features of AWT.  100% Pure Java certified versions of the existing AWT component set (Button, Scrollbar, Label, etc.).  A rich set of higher-level components (such as tree view, list box, and tabbed panes).  Pure Java design, no reliance on peers.  Pluggable Look and Feel. Swing components do not depend on peers to handle their functionality. Thus, these components are often called "lightweight" components. Positive Points of Swing  Portability: Pure Java design provides for fewer platforms specific limitations.  Behavior: Pure Java design allows for a greater range of behavior for Swing components since they are not limited by the native peers that AWT uses.  Features: Swing supports a wider range of features like icons and pop-up tool-tips for components.  Vendor Support: Swing development is more active. Sun puts much more energy into making Swing robust.  Look and Feel: The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform (Microsoft Windows, Solaris, Macintosh, etc.). It also makes it easier to make global changes to your Java programs that provide greater accessibility (like picking a hi-contrast color scheme or changing all the fonts in all dialogs, etc.). Negative Points of Swing  Applet Portability: Most Web browsers do not include the Swing classes, so the Java plug-in must be used.  Performance: Swing components are generally slower and buggier than AWT, due to both the fact that they are pure Java and to video issues on various platforms. Since Swing components handle their own painting (rather than using native API's like DirectX on Windows) you may run into graphical glitches.  Look and Feel: Even when Swing components are set to use the look and feel of the OS they are run on, they may not look like their native counterparts. In general, AWT components are appropriate for simple applet development or development that targets a specific platform (i.e. the Java program will run on only one platform). For most any other Java GUI development you will want to use Swing components. Also note that the Borland value-added components included with JBuilder, like dbSwing and JBCL, are based on Swing components so if you wish to use these components you will want to base your development on Swing.

×