0% fanden dieses Dokument nützlich (0 Abstimmungen)
7 Ansichten60 Seiten

Java Unit 45 PDF

Das Dokument behandelt das Collection Framework in Java, das eine Architektur zur Speicherung und Manipulation von Objekten bietet. Es beschreibt verschiedene Interfaces und Klassen wie ArrayList, Vector und Hashtable sowie deren Eigenschaften und Unterschiede. Zudem werden grundlegende Konzepte wie Iteratoren, Enumeration und die Verwendung von Scanner und Random zur Eingabe und Zufallszahlengenerierung erläutert.

Hochgeladen von

santoshkumarganga
Copyright
© All Rights Reserved
Wir nehmen die Rechte an Inhalten ernst. Wenn Sie vermuten, dass dies Ihr Inhalt ist, beanspruchen Sie ihn hier.
Verfügbare Formate
Als PDF herunterladen oder online auf Scribd lesen
0% fanden dieses Dokument nützlich (0 Abstimmungen)
7 Ansichten60 Seiten

Java Unit 45 PDF

Das Dokument behandelt das Collection Framework in Java, das eine Architektur zur Speicherung und Manipulation von Objekten bietet. Es beschreibt verschiedene Interfaces und Klassen wie ArrayList, Vector und Hashtable sowie deren Eigenschaften und Unterschiede. Zudem werden grundlegende Konzepte wie Iteratoren, Enumeration und die Verwendung von Scanner und Random zur Eingabe und Zufallszahlengenerierung erläutert.

Hochgeladen von

santoshkumarganga
Copyright
© All Rights Reserved
Wir nehmen die Rechte an Inhalten ernst. Wenn Sie vermuten, dass dies Ihr Inhalt ist, beanspruchen Sie ihn hier.
Verfügbare Formate
Als PDF herunterladen oder online auf Scribd lesen
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY UNIT-4 Collection Framework in Java Collections in java is a framework that provides an architecture to store and manipulate the group of objects. All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections. Java Collection simply means a single unit of objects. Java Collection framework provides many imerfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). What is framework in java © provides readymade architecture © represents set of classes and interface. © is optional. What is Collection framework Collection framework represents a unified architecture for storing and manipulating group of objects. It has: 1. Interfaces and its implementations i.e. classes 2. Algorithm JAVA PROGRAMMING Hierarchy of Collection Framework J extends Gi interface a class | implements Java ArrayList class Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractL ist class and implements List interface The important points about Java ArrayList class are: Java ArrayList class can contain duplicate elements, Java ArrayList class maintains insertion order. Java ArrayList class is non synchronized. Java ArrayList allows random access because array works at the index basis. In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred iff any element is removed from the array list. JAVA PROGRAMMING ArrayList class declaration Lot's see the declaration for [Link]. ArrayList class Constructors of Java ArrayList Constructor Description ArrayList() Itis used to build an empty array list. ArrayList(Collection It is used to build an array list that is initialized with the °) elements of the collection c. AnrayList(int It is used to build an array list that has the specified capacity) initial capacity. Java ArrayList Example import [Link]; class TestCollection| { public static void main(String args{)){ ArrayList list=new ArrayList(Q)y/Creating arraylist [Link]("Ravi")://Adding object in arraylist listadd("Vija [Link]("Ravi"); [Link](""Ajay"); 1/Traversing list through Iterator Iterator itr=listiterator(); while([Link]()){ [Link] [Link]); } }} Ravi Vijay Ravi Ajay JAVA PROGRAMMING vector ArrayList and Vector both implements List interface and maintains insertion order. But there are many differences between ArrayList and Vector classes that are given below. ArrayList Vector 1) ArrayList is not synchronized. Vector is synchronized. 2)ArayList inerements 0% of Vector increments 100% means doubles the array current array size if number of size if total number of element exceeds than its element exceeds from its capacity. capacity. 3)ArayList is mot a legacy class, Vector is a legacy class. it is introduced in JDK 1.2. 4) ArrayList is fast because it is Vector is slow because it is synchronized ic. in non-synchronized. multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object. 5) ArrayLis tuses Iterator interface Vector uses Enumeration interface to traverse the to traverse the elements, elements. But it can use Iterator also. Example of Java Vector Let's see a simple example of java Vector class that uses Enumeration interface. import [Link].*; class TestVectorl ( public static void main(String args{]){ Vector v=new Vector();//creating vector [Link]("umesh");//method of Collection [Link]("irfan");//method of Vector [Link]("kumat Ihraversing elements using Enumeration JAVA PROGRAMMING 9. 10. uw 12. Enumeration e=[Link](); while([Link]()){ [Link]([Link]()); 1)d Outp Java Hashtable class Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface. ‘The important points about Java Hashtable class are: A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. It contains only unique elements. © Ttmay have not have any null key or value, © Itis synchronized. Hashtable class declaration Let's sce the declaration for [Link]. Hashtable class, public class Hashtable extends Dictionary implements Map, Cloneable, Ser ializable Hashtable class Parameters Let's sce the Parameters for [Link]. Hashtable class, Ki Itis the type of keys maintained by this map. V: Itis the type of mapped values. JAVA PROGRAMMING Constructors of Java Hashtable class Constructor Description HashtableQ It is the default constructor of hash table it instantiates the Hashtable class. Hashtable(int size) Tris used to accept an integer parameter and creates a hash table that has an initial size specified by integer value size. Hashtable(int size, float It is used to create a hash table that has an initial size specified by fillRatio) size and a fill ratio specified by fillRatio, Java Hashtable Example import [Link] class TestCollection16{ public static void main(String args{]){ Hashtable hm=new Hashtable(); ham put(100,"Amit"); hm put(102,"Ravi"); hm put(101," Vijay"; hm. put(103,"Rahul"), for([Link] m:[Link]()){ System out printin([Link](+" "-+[Link]()); yh) Output: 103 Rahul 102 Ravi 101 Vijay 100 Amit Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. JAVA PROGRAMMING Stack() Example ‘The following program illustrates several of the methods supported by this collection ~ import [Link].*; public class StackDemo [ static void showpush(Stack st, int a) ( [Link](new Integer(a)); [Link]("push(” +a +")"); [Link]( "stack: " + st):) static void showpop(Stack st) [ [Link]("pop -> "); Integer a = (Integer) [Link](); [Link](a); System,[Link]("stack: "+ st); } public static void main(String args(]) { Stack st = new Stack); [Link] printin( "stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st): showpop(st): showpop(st): ty f showpop(st): } catch (EmptyStackException e) { [Link] printin(“empty stack’ JAVA PROGRAMMING Wy This will produce the following result ~ Output stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop > 99 stack: (42, 66] pop > 66 stack: [42] pop > 42 stack: [] pop > empty stack Enumeration ‘The Enumeration Interface ‘The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. ‘The methods declared by Enumeration are summarized in the following table — [Link]. Method & Description boolean hasMoreElements( ) When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated. Object nextElement() ‘This returns the next object in the enumeration as a generic Object reference, Example JAVA PROGRAMMING Following is an example showing usage of Enumeration. import [Link]. Vector; import [Link]. Enumeration; public class EnumerationTester { public static void main(String args||) ( Enumeration days; Vector dayNames = new Vector(); [Link]("Sunday"); [Link]("Monday"); [Link]("Tuesday"); [Link]("Wednesday"); [Link](""Thursday"); [Link]("Friday [Link]("Saturday"): days = [Link](); while ([Link]()) { [Link] printin([Link]()); in This will produce the following result ~ Output Sunday Monday Tuesday Wednesday Thursday Friday Saturday Iterator JAVA PROGRAMMING It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is improved version of Enumeration with additional functionality of remove-ability of a element, Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework. Iterator object can be created by calling iterator() method present in Collection interface. i Here "c" is any Collection object. itr is of i type Iterator interface and refers to "e' Iterator itr = [Link](); Iterator interface defines three methods: // Returns true if the iteration has more elements public boolean hasNext(); /( Returns the next element in the iteration 11 It throws NoSuchElementException if no more // element present public Object next(); / Remove the next element in the iteration #1 This method can be called only once per call M0 next) public void remove(); remove() method can throw two exceptions + UnsupportedOperationException : If the remove operation is not supported by this iterator + MllegalStateException : If the next method has not yet been called, or the remove method ‘has already been called after the last call to the next method Limitations of Iterator: + Only forward direction iterating is possible. + Replacement and addition of new element is not supported by Iterator StringTokenizer in Java The [Link]. StringTokenizer class allows you to break a string into tokens. It is simple way to break string, It doesn't provide the facility to differentiate numbers, quoted strings, identifiers ete Constructors of StringTokenizer class There are 3 constructors defined in the StringTokenizer class. JAVA PROGRAMMING Constructor StringTokenizer(String str) StringTokenizer(String String delim) StingTokenizer(String str, String delim, boolean return Value) Description creates StringTokenizer with specified string, creates. StringTokenizer with specified string and creates StringTokenizer with specified string, delimeter and rewumValue. If retum value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens. Methods of StringTokenizer class ‘The 6 useful methods of StringToke Public method boolean hasMoreTokens() String nextToken() String nextToken(String delim) boolean hasMoreElements() Object nextElement() int countTokens() Simple example of St er class are as follows: Description checks if there is more tokens available. retums the next token from the String Tokenizer object. retums the next token based on the delimeter. same as hasMoreTokens() method. same as nextToken() but its return type is Object. returns the total number of tokens. Tokenizer class Let's see the simple example of StringTokenizer class that tokenizes a string “my name is khan" on the basis of whitespace. import [Link]; public class Simple public static void main(String argsf|){ JAVA PROGRAMMING String Tokenizer st = new StringTokenizer('my name is khan’ while (st-hasMoreTokens()) { System. [Link]([Link]()); phd Output:my name is khan Example of nextToken(String delim) method of StringTokenizer class import [Link]”; public class Test { public static void main(String{] args) { StringTokenizer st = new StringTokenizer("my,name,is,khan"); printing next token [Link] println("Next token is : " + stnextToken(",")); ) 4 Output:Next token is : my [Link] + For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDoubleQ), nextLong() etc using that instance. ‘We can generate random nunibers of types integers, float, double, long, booleans using this class. We can pass arguments to the methods for placing an upper bound on the range of the numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5 both inclusive. // A Java program to demonstrate random number generation /Husing [Link] Random; import [Link]. Random; public class generateRandom( public static void main(String args{]) { J/ create instance of Random class Random rand = new Random(); 1/ Generate random integers in range 0 to 999 int rand_int! = rand nextInt( 1000); int rand_int2 = [Link](1000); JAVA PROGRAMMING 1/ Print random integers [Link]("Random Integers: "+rand_int1); [Link]("Random Integers: "+rand_int2); 1/ Generate Random doubles double rand_dub! = [Link](); double rand_dub2 = [Link](); 1/ Print random doubles [Link]("Random Doubles: "+rand_dub1); [Link]("Random Doubles: "+rand_dub2); iN Output: Random Integers: 547 Random Integers: 126 Random Doubles: 0.8369779739988428 Random Doubles: 0.5497554388209912 Java Scanner class There are various ways to read input from the keyboard, the [Link]. Scanner class is one of them. The Java Scanner class breaks the input into tokens using a delimiter that bydefault. It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using regular expression, Java Scanner class extends Object class and implements Iterator and Closeable interfaces. Commonly used methods of Scanner class There is a list of commonly used Scanner class methods: Method Description public String next() it retums the next token from the scanner. public String nextLine() it moves the scanner position to the next line and returns the value asa string, public byte nextByte() it scans the next token as a byte JAVA PROGRAMMING public short nextShort() it scans the next token as a short value. public int nextInt() it scans the next token as an int value. public long nextLong() it scans the next token as a long value. public float nextFloat() it scans the next token as a float value public double it scans the next token as a double value, nextDouble() Java Scanner Example to get input from console Let's see the simple example of the Java Scanner class which reads the int, string and double valve as an input: import [Link]. Scanner; class ScannerTest{ public static void main(String args[]){ Scanner se=new Scanner([Link]); [Link] printin("Enter your rollno [Link] printin("Enter your name"); String name=[Link](); [Link] printin("Enter your fee"); double fee=[Link](); [Link] printin("Rolino:"+rolno+” name:"+name+"” fee:"+fee); close(): 3} Output: Enter your rollno m1 Enter your name Ratan Enter 450000 Rolino: 111 name:Ratan fee:450000 JAVA PROGRAMMING Java Calendar Class Java Calendar class is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, ete. It inherits Object class and implements the Comparable interface. Java Calendar class declaration Let's sce the declaration of [Link]. Calendar class. . public abstract class Calendar extends Object . implements Serializable, Cloneable, Comparable Java Calendar Class Example import [Link]; public class CalendarExample| { public static void main(String{] args) ( Calendar calendar = Calendar. getinstance(); [Link]("The current date is : " + [Link]()): [Link]([Link], -15); [Link] printin("15 days ago: " + calendar. getTime()); [Link](Calendar. MONTH, 4); [Link] printin("4 months later: " + [Link]); [Link](Calendar. YEAR, 2); [Link] printin("2 years later: " + calendar. getTime()); y) Output: ‘The current date is : Thu Jan 19 18:47:02 IST 2017 15 days ago: Wed Jan 04 18:47:02 IST 2017 4 months later: Thu May 04 18:47:02 IST 2017 2 years later: Sat May 04 18:47:02 IST 2019 JAVA PROGRAMMING Java - Files and YO ‘The [Link] package contains nearly every class you might ever need to perform input and output (VO) in Java. All these streams represent an input source and an output destination. The stream in the [Link] package supports many data such as primitives, object, localized characters, ete. Stream A stream can be defined as a sequence of data. There are two kinds of Streams — + InPutStream — The InputStream is used to read data from a source. * OutPutStream — The OutputStream is used for writing data to a destination. Java provides strong but flexible support for /O related to files and networks but this tutorial covers very basic functionality related to streams and /O. We will see the most commonly used, examples one by one ~ Byte Streams Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileIputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file— Example import [Link].*; public class CopyFile ( public static void main(String args||) throws IOExceptios FileInputStream in = null; FileOutputStream out = null; try { in = new FilelnputStream("[Link]"); out = new FileOutputStream(“[Link]"); inte; while ((c = [Link]()) != -1) { JAVA PROGRAMMING [Link](c); } finally { if (in '= null) ( [Link](); } if (out != null) { [Link](); she Now let's have a file [Link] with the following content — ‘This is test for copy file. Asa next step, compile the above program and execute it, which will result in creating [Link] file with the same content as we have in [Link], So let's put the above code in CopyFile,java file and do the following — $javac [Link] $java CopyFile Character Streams Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FilelnputStream and FileWriter uses FileQutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time. We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file ~ Example import [Link].*; public class CopyFile ( public static void main(String args{]) throws IOException { JAVA PROGRAMMING FileReader in = null FileWriter out = null; try { in = new FileReader("[Link]"); out = new FileWriter(“[Link]"); inte: while ((c = [Link]()) != -1) { out. write(c);] finally { if (in t= null) { [Link]():} if (out != null) ( [Link](); Wot Now let's have a file [Link] with the following content — This is test for copy file. As a next step, compile the above program and execute it, which will result in creating [Link] file with the same content as we have in inputxt, So let's put the above code in CopyFile,java file and do the following — S$javac CopyFile,java $java CopyFile Standard Streams All the programming languages provide support for standard VO where the user's program can take input from a keyboard and then produce an output on the computer screen. Java provides the following three standard streams — + Standard Input ~ This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented asSystem. JAVA PROGRAMMING Standard Output ~ This is used to output the data produced by the user's program and usually @ computer screen is used for standard output stream and represented as [Link]. Standard Error ~ This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as Systemerr. Following is a simple program, which creates InputStreamReader to read standard input stream until the user types a" Example import [Link].* public class ReadConsole { public static void main(String args|]) throws IOException { InputStreamReader cin = mull; try ( cin = new InputStreamReader([Link]); [Link] printin("Enter characters, 'q' to quit.”); char ¢; do [ = (char) [Link](); [Link] print(c): } while(c !="q"); finally { if (cin != null) ( [Link](); yyy this program continues to read and output the same character until we press q!— $javac ReadConsole,java $java ReadConsole JAVA PROGRAMMING s. 'q'to quit. e e q q Reading and Writing Files As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams, The two important streams are FileInputStream and FileOutputStream FileInputStream This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available. Following constructor takes a file name as a string to create an input stream object to read the file — InputStream f = new FileInputStream(""C:/java/hello"); JAVA PROGRAMMING Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows ~ File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f); Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream © ByteArrayInputSiream + DatalnputStream FileOutputStream FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object. Following constructor takes a file name as a string to create an input stream object to write the file — OutputStream f = new FileOutputStream("C:/java/hello") Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows — File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(); Once you have OusputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream. « = ByteArrayOutputStream ~DataOutputStream Example Following is the example to demonstrate InputStream and OutputStream ~ import [Link].*; public class fileStreamTest { public static void main(String args| |) ( uy t JAVA PROGRAMMING byte bWrite [] = (11,21,3,40.5}; OutputStream os = new FileOutputStream("[Link]"); for(int x = 0; x < [Link] ; x+) { [Link]( bWrite[x] ): // writes the bytes) [Link](): InputStream is = new FileInputStream("[Link]"); int size = [Link](); for(int i =0; i < size: i++) ( [Link](([Link]() + " [Link](); } catch (OException e) { System. out print("Exception”); it [Link] Class ‘The [Link] class file behaves like a large array of bytes stored in the file system Instances of this class support both reading and writing to a random access file. Class declaration Following is the declaration for [Link] class — public class RandomAccessFile extends Object implements DataQutput, Datalnput, Closeable ‘Class constructors SN. Constructor & Description RandomAccessFile(File file, String mode) ‘This creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. JAVA PROGRAMMING RandomAccessFile(File file, String mode) This creates a random access file stream to read from, and optionally to write to, a file with the specified name, Methods inherited ‘This class inherits methods from the following classes — + [Link] [Link] Class in Java The File class is Java's representation of a file or directory path name. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. The File class contains several methods for working with the path name, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories, + It is an abstract representation of file and directory pathnames. * A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname may be obtained by invoking the getParent() method of this class. First of all, we should create the File class object by passing the filename or directory name to it. A file system may implement restrictions to certain operations on the actual file- system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. How to create a File Object? A File object is created by passing in a String that represents the name of a file, ora String or another File object. For example, File a = new File("/ust/local/bin/gecks"); defines an abstract file name for the geeks file in directory /usr/local/bin. This is an absolute abstract file name, Program to check if a file or directory physically exist or not. / In this program, we accepts a file or directory name from // command line arguments. Then the program will check if / that file or directory physically exist or not and /1 itdisplays the property of that file or directory. import [Link]; #1 Displaying file property class fileProperty { public static void main(String[] args) { JAVA PROGRAMMING Haccept file name or directory name through command line args String fname =args{0]; pass the filename or directory name to File object File f= new File(fname); Happly File class methods on File object System_out printin("'File name :"4f getName()); System out printin(" Path: "+f. getPath()); [Link](” Absolute path:" +[Link]()); [Link] printin("Parent:"+f getParent()); [Link] printin(" Exists :"[Link](); if(fexists) { [Link] printin("Is writeable:"+[Link]()) readable"+[Link](); [Link] printin("Is a directory:"+LisDirectory()); [Link]("File Size in bytes "+[Link]()); Output: File name :[Link] Path: [Link] Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\[Link] Parent: null Exists :true Is writeable:true Is readabletrue Is a directory:false File Size in bytes 20 Connceting to DB What is DBC Driver? JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your database server For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java, JAVA PROGRAMMING ‘The [Link] package that ships with IDK, contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the [Link] interface in their database driver. JDBC Drivers Types JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2,3, and 4, which is explained below — ‘Type 1: JDBC-ODBC Bridge Driver In a Type I driver, a JDBC bridge is used to access ODBC drivers installed on each client machine, Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the target database. When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available, Local Computer Java Application Application Code { Typed JDBC ODBC Bridge Notwork ‘Communication (Database Server The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver. Type 2: JDBC-Native APT In a Type 2 driver, IDBC API calls are converted into native C/C++ API calls, which are unique to the database. These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine, JAVA PROGRAMMING If we change the Database, we have to change the native API, as it is specific to a database and they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead. Local Computer Java Application Application Code The Oracle Call Interface (OCI) driver is an example of a Type 2 driver. ‘Type 3: JDBC-Net pure Java In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server, The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server. This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases. JOBE Typo 2 Drivor ‘JDBC Type 4 Driver Proprietary Vondor Specific Proteco! JAVA PROGRAMMING You can think of the application server as a JDBC "proxy," meaning that it makes calls for the clicnt application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type. ‘Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful. Type 4: 100% Pure Java In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself. This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically. ‘Local Computer Java Application ‘Application Code ! Proprietary Vendor ‘Specific Protocol Database Server MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers. Which Driver should be Used? ssing one type of database, such as Oracle, Sybase, or IBM, the preferred driver If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database. JAVA PROGRAMMING ‘The type I driver is not considered a deployment-level driver, and is typically used for development and testing purposes only. Example to connect to the mysql database in java For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity. In this example we are using MySq] as the database. So we need to know following informations for the mysql database: Driver class: The driver class for the mysql database is [Link]. Connection URL: The connection URL for the ~—mysql_— database is jdbe:mysql:/Mocalhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, you need to replace the sonoo with your database name. . Username: The default username for the mysql database is root. Password: Password is given by the user at the time of installing the mysql database. In this example, we are going to use root as the password. Let's first create a table in the mysql database, but before creating table, we need to create database first. create database sonoo; use sonoo; create table emp(id int(10),name varchar(40),age int(3)); Example to Connect Java Application with mysql database In this example, sonoo is the database name, root is the username and password. import [Link]."; class MysqlCon{ main(String argst)}{ [Link]("[Link]] jdbe- Driver"); Connection con=DriverManager. getConnection( *jdbe:mysql:/Mocalhost:3306/sonoo", "root", "root"; here sonoo is database name, root is username and password JAVA PROGRAMMING Statement stmt=[Link](); ResultSet rs=stmtexecuteQuery("select * from emp"); while([Link]()) [Link]([Link](1)+" "“[Link](2)+" "[Link](3)); [Link](); Jeatch(Exception e){ [Link] printin(e);} Vt ‘The above example will fetch all the records of emp table. To connect java application with the mysql database [Link] file is required to be loaded. ‘Two ways to load the jar file: 1. paste the mysqlconnector jar file in jreflib/ext folder 2. set classpath paste the [Link] file in JRE/lib/ext folder: Download the [Link] file. Go to jre/lib/ext folder and paste the jar file here. 2) set classpath: There are two ways to set the classpath: [Link] [Link] How to set the temporary classpath open command prompt and write: . C2>set classpath=c:\folder\mysql-connector-java-5.0.8. How to set the permanent classpath Go to environment variable then click on new tab, In variable name write classpath and in variable value paste the path to the mysqlconnector jar file by appending [Link];.; as CMolder\mysq]-connector-java-5,0.8-bin jar; JDBC-Result Sets ‘The SQL statements that read data from a database query, return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The [Link] interface represents the result set of a database query. JAVA PROGRAMMING A ResultSet object maintains a cursor that points to the current row in the result set, The term "result set" refers to the row and column data contained in a ResultSet object. ‘The methods of the ResultSet interface can be broken down into three categories — + Navigational methods: Used to move the cursor around. Get methods: Used to view the data in the columns of the current row being pointed by the cursor. Update methods: Used to update the data in the columns of the current row. The updates can then be updated in the underlying database as well. ‘The cursor is movable based on the properties of the ResultSet. These properties are designated when the corresponding Statement that generates the ResultSet is created. JDBC provides the following connection methods to create statements with desired ResultSet — + createStatement(int RSType, int RSConcurreney + prepareStatement(String SQL, int RSType, int RSConcurrency); © prepareCall(String sql, int RSType, int RSConcurrency); ‘The first argument indicates the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable. ‘Type of ResultSet The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one that is TYPE_LFORWARD_ONLY. ‘Type Description ResultSet. TYPE_FORWARD_ONLY ‘The cursor can only move forward in the result sel. ResultSet. TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, and the result set is not sensitive to changes made by others to the database that oceur after the result set was created, JAVA PROGRAMMING ResultSet. TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result set is sensitive to changes made by others to the database that occur after the result set was created. Concurrency of ResultSet ‘The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY Coneurreney Description ResultSet,CONCUR_READ_ONLY Creates a read-only result set. This is the default ResultSet CONCUR_UPDATABLE. Creates an updateable result set Viewing a Result Set ‘The ResultSet interface contains dozens of methods for getting the data of the current row. There is a get method for each of the possible data types, and each get method has two versions © One that takes in a column name. © One that takes in a column index, For example, if the column you are interested in viewing contains an int, you need to use one of the getlnt() methods of ResultSet — S.N. Methods & Description public int getInt(String columnName) throws SQLException Returns the int in the current row in the column named columnName. public int getIntint columnindex) throws SQLException Returns the int in the current row in the specified column index. The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on, JAVA PROGRAMMING Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java-lang String, [Link], and [Link]. There are also methods for getting SQL datatypes [Link]-Date, [Link]:Time, [Link]-TimeStamp, [Link], and [Link]-Blob. Check the documentation for more information about using these SQL data types. Fora better understanding, let us study Viewing - Example Code. Updatinga Result Set ‘The ResultSet interface contains a collection of update methods for updating the data of a result set As with the get methods, there are two update methods for each data type — ‘© One that takes in a column name. ‘© One that takes in a column index. JAVA PROGRAMMING For example, to update a String column of the current row of a result set, you would use one of the following updateString() methods ~ S.N. Methods & Description public void updateString(int columnindex, String s) throws SQLException Changes the String in the specified column to the value of s. public void updateString(String columnName, String s) throws SQLException Similar to the previous method, except that the column is specified by its name instead of index. ‘There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL data types in the [Link] package. Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods. S.N. Methods & Description public void updateRow() Updates the current row by updating the corresponding row in the database public void deleteRow() Deletes the current row from the database public void refreshRow() Refreshes the data in the result set to reflect any recent changes in the database, public void cancelRowUpdates() Cancels any updates made on the current row. public void insertRow() Inserts a row into the database. This method can only be invoked when the cursor is pointing to the insert row. JAVA PROGRAMMING MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY UNIT-5 GUI Programming with java The AWT Class hierarchy Java AWT (Abstract Window Toolkit) isan API to develop GUI or window-based applications in java. Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight icc. its components are using the resources of OS. The [Link] package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox,. Choice, List etc. Java AWT Hierarchy ‘The hierarchy of Java AWT classes are given below. Object Label ‘Checkbox choice ust Container f JAVA PROGRAMMING Container ‘The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel. Window ‘The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window. Panel The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield ete. Frame ‘The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield ete. Useful Methods of Component class Method Description public void add(Component c) inserts a component on this component. public void setSizetint width,int height) _sets the size (width and height) of the component. public void setLayout(LayoutManager defines the layout manager for the component. m) public void setVisible(boolean stat changes the visibility of the component, by default false. Java AWT Example To create simple awt example, you need a frame, There are two ways to create a frame in AWT. © By extending Frame class (inheritance) co By-creating the object of Frame class (association) JAVA PROGRAMMING AWT Example by Inheritance Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame. import [Link].*; class First extends Frame{ Finst(){ Button b=new Button("‘elick m b setBounds(30,100,80,30),/ setting button posit add(b)y//adding button into frame setSize(300,300):/frame size 300 width and 300 height setLayout(null};//no layout manager setVisible(true)//now frame will be visible, by default not visible } public static void main(String args{)){ First f=new First(); n ‘The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the position of the awe button, Java Swing Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window- based applications. Iis built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java, Unlike AWT, Java Swing provides platform-independent and lightweight components. The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc. JAVA PROGRAMMING Difference between AWT and Swing. No. Java AWT Java Swing 1) AWT — components are platform. Java swing components are platform. dependent. independent. AWT components are heavyweight Swing components are lightweight. AWT doesn't support pluggable look Swing supports pluggable look and and feel. feel AWT provides less components than Swing provides more_—_powerful Swing componentssuch as tables, lists, scrolipanes, colorchooser, tabbedpane ete. AWT doesn't follows MVC(Model View Swing follows MVC. Controller) where model represents data, view represents presentation and. controller acts as an interface between model and view. Commonly used Methods of Component class Method Description public void add(Component e) add a component on another component. public void setSizetint width,int height) _sets size of the component. public void setLayout(LayoutManager sets the layout manager for the component. Je(boolean b) lity of the component. It is by default JAVA PROGRAMMING Hierarchy of Java Swing classes The hierarchy of java swing API is given below. me] sable onent | IComboBox slider Menu F sutton Java Swing Examples There are two ways to create a frame: © By creating the object of Frame class (association) © Byextending Frame class (inheritance) We can write the code of swing inside the main(), constructor or any other method. Simple Java Swing Example Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method. File: FirstSwingExample java JAVA PROGRAMMING import [Link]. public class FirstSwingExample { public static void main(String{] args) { JFrame f=new JFrame()y//creating instance of JFrame JButton b=new JButton("click");//ereating instance of JButton bsetBounds(130,100,100, 40);//x axis, y axis, width, height fadd(b);//adding button in JFrame [Link](400,500);//400 width and 500 height [Link](null)//using no layout managers [Link](true)://making the frame visible i} Containers Java JFrame The [Link] JFrame class is a type of container which inherits the [Link] class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI. Unlike Frame, JFrame has the option to hide or close the window with the help of setDefaultCloseOperation(int) method. JFrame Example import [Link] FlowLayout; import [Link]; import [Link]; import [Link]; import [Link]: public class JFrameExample { public static void main(String sl) ( JFrame frame = new JFrame("JFrame Example"); JPanel panel = new JPancl(); [Link](new FlowLayout()); JLabel label = new JLabel(""JFrame By Example"): JButton bution = new JButton(); [Link]("Button"); [Link](label); JAVA PROGRAMMING [Link](button); [Link](panel); [Link](200, 300); [Link](null); frame. setDefaultCloseOperation(JFrame,EXIT_ON_CLOSE); [Link](tru Vt JApplet As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. ‘The JApplet class extends the Applet class. Example of EventHandling in JApplet: import [Link].*; import [Link].*; import [Link].% public class EventJ Applet extends JApplet implements ActionListener{ sButton b; JTextField tf; public void init tf=new JTextFieldQ; [Link](30,40,150,20); b=new JButton("Click"); [Link](80,150,70,40); add(b):adaat); badd ActionListener(this); setLayout(null); 1 public yoid actionPerformed(ActionEvent e){ [Link]("Welcome"), 1) In the above example, we have created all the controls in init() method because it only onee. myapplet html JAVAPROGRAMMING Page 0 JDialog The JDialog control represents a top level window with a border and a title used to take some form of input from the user. It inherits the Dialog class. Unlike JFrame, it doesn't have maximize and minimize buttons. JDialog class declaration Let's see the declaration for [Link] class. public class Dialog extends Dialog implements WindowConstants, Accessible, RootPaneConta iner Commonly used Constructors: Constructor Description IDialog() It is used to create a modeless dialog without a title and without a specified Frame owner. IDialog(Frame owner) It is used to create a modeless dialog with specified Frame as its owner and an empty title. IDialog(Frame owner, String title, It is used to create a dialog with the specified title, boolean modal) owner Frame and modality. JAVA PROGRAMMING Page 102 Java JDialog Example import [Link].*; import [Link]."; import [Link].*; public class Dialogkxample { private static JDialog d; DialogExample() ( IFrame f= new JFrame(); d= new JDialog(f , "Dialog Example", true); [Link]( new FlowLayout() ); JButton b = new JButton ("OK"); [Link] istener ( new ActionListener() { public void actionPerformed( ActionEveat e ) { [Link]( al Ds [Link]( new JLabel ("Click button to continue.")); dade); disetSize(300,300); Click button to continue. |_OK | disetVisible(true); } public static void main(String args(1) { new DialogExample(); Vy JPanel The JPanel is a simplest container class, It provides space in which an application can attach any other component. It inherits the JComponents class. Tt doesn't have title bar. JAVA PROGRAMMING JPanel class declaration 1. public class JPanel extends JComponent implements Accessible Java JPanel Example import [Link].*; import [Link].*; public class PanelExample { PanelExample() C JFrame f= new JFrame("Panel Example"); JPanel panel=new JPanel(); [Link](40,80,200,200); panel setBackground([Link]); JButton bl =new JButton("Button 1"); [Link](50,100,80,30); b1 setBackground(Color yellow); ‘BButton b2=new JButton("Button 2"); [Link](100,100,80,30); [Link](Color green); [Link](b1 ; [Link](b2); [Link](panel); fesetSize(400,400), fsetLayout(null); [Link](true); 1 public static void main(String argst]) t new PanelExample(); 1) Overview of some Swing Components Java JButton ‘The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class. JAVA PROGRAMMING JButton class declaration Let's see the declaration for [Link] JButton class. 1, public class Button extends AbstractButton implements Accessible Java JButton Example import [Link].*; public class ButtonExample { public static void main(String[] args) { JFrame f=new JPrame("Button Example"); JButton b=new JButton("Click Here"); b,setBounds(50, 10.95.30): [hex Here Fadd(b); [Link](400,400); f'setLayout(null): FsetVisiblettrue); } Java JLabel The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text, The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class. JLabel class declaration Let's see the declaration for [Link] class. public class JLabel extends JComponent implements SwingConstants, Accessible Commonly used Constructors: Constructor Description JLabel() Creates a JLabel instance with no image and with an empty string for the title JLabel(String s) Creates a JLabel instance with the specified text ILabel(leon i) Creates a JLabel instance with the specified image. JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, horizontalAlignment) image, and horizontal alignment, JAVA PROGRAMMING Commonly used Methods: ‘Methods Description String getText0) {returns the text string that a label displays. void setText(String text) It defines the single line of text this component will display. void setHorizontalAlignmentint It sets the alignment of the label's contents along alignment) the X axis Teon getfeon() returns the graphic image that the label displays. int getHorizontalAlignment() It returns the alignment of the label's contents along, the X axis Java JLabel Example import [Link]. class LabelExample ( public static void main(String args{]) { IFrame f= new JFrame("Label Example"); ILabel 11.12; Z] label bape L=new JLabel( First Label."); [Link](50,50, 100,30); I2=new JLabel( "Second Label."); [Link](50,100, 100,30); fadd(l!); [Link](l2); [Link](300,300); [Link](null); First Label fsetVisible(true); } 4 JAVA PROGRAMMING

Das könnte Ihnen auch gefallen