1. Trang chủ
  2. » Công Nghệ Thông Tin

Secrets of java

102 323 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 102
Dung lượng 11,87 MB

Nội dung

SECRETS OF JAVA SECRETS OF JAVA A Self Learning Approach for Students, Academic and Industrial Professionals By Er R Kabilan, M.E Senior Lecturer Thi ru valluvar College of Engg and Tech Vandavasi (Chennai) FIREWAL MEDIA (An Imprint of Laxmi Publications Pvt Ltd.) BANGALORE e CHENNAI • COCHIN • JALANDHAR • • LUCKNOW • KOLKATA NEW DELHI GUWAHATI MUMBAI • • HYDERABAD RANCHI Published by : FIREWAL MEDIA (An Imprint of Laxmi Publications Pvt Ltd.) 113, Golden House, Daryaganj, New Delhi-110002 Phone: 011-43 53 25 00 Fax : 011-43 53 25 28 www laxmipublications.com info@laxmipublications.com Copyright© 2008 by Laxmi Publications Put Ltd All rights reserved No pmt of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior written permission of the publishe r First Edition : 2009 OFFICES Bangalore Cochin Hyderabad Kolkata Mumbai 080-26 61 15 61 0484-239 70 04 040-24 65 23 33 033-22 27 43 84 022-24 91 54 15, 24 92 78 69 FSE-3032-085-SECRET OF JAVA Typeset at : ABRO Enterprises, Delhi Chennai Guwahati J alandhar Lucknow Ranchi 044-24 34 47 26 0361-254 36, 69, 251 38 81 0181-222 12 72 0522-220 95 78 0651-221 47 64 CPrinted at : L.B Enterprises ~etficatetf !Mj; to ~arents/ t1Jrotfiers & Sisters/ !A& !A& UJift & K._idS K.: K._avini K.: K._aviram and especia!{y to m!J 5e!ovetf foend$ CoNTENTS Pages INTRODUCTION 1-3 History of Java OOPS Concept Definition of Java JDK-Tools 2 WORLD WIDE WEB(WWW) BASICS of WWW Definition E-mail 4-6 HYPER TEXT MARKUP LANGUAGE (HTML) Introduction HTML Tags Types of HTML DTD Browser 7-8 4 FUNDAMENTALS OF JAVA 7 8 9-17 Introduction Data Types 10 Special Operator Typecasting 12 Command Line Arguments 15 14 INHERITANCE 18- 19 Introduction Single and Multiple Inheritance 18 18 INTERFACE Introduction 2o-21 PACKAGES Introduction 22-23 20 22 (vii) (viii) EXCEPTIONS Concept of Exceptions 10 STREAMS Definition Top Level Classes of 10 Package 10 AWT Introduction Layout Managers Event Handlers 11 APPLET Introduction Life Cycle of Applet 12 SWINGS Introduction Comparison with AWT 24-26 24 27- 32 27 27 33- 42 33 33 34 44- 49 44 44 50-60 50 50 13 NETWORKING Introduction Types of Networking Programs 61-66 14 THREADS Definition Life Cycle of Thread Thread Priority 67-73 15 JDBC (Java Database Connectivity) 74-80 Introduction JDBC VS ODBC 16 THE JAVA.UTIL * PACKAGE Basics of Util Package INDEX 61 61 67 68 70 74 75 81- 85 81 86-87 76 Secrets of Java Ex amples : import java sql * ; public c l ass jdbcl public static void rnain(String args[ J ) { try Cl ass forName( "sun jdbc odbc JdbcOdbcDriver"); Connection conn=Dri verManager get Connection ( "j dbc: odbc : kabi", "scott","tiger"); Statement stnt=conn createStatement() ; int x = stnt e x ecuteUpdate( "update kab set age=lO where age=200"); System out println("rowsupdated"); }catch (Except ion e) { System out println ( " Error ·" + e); import java sql *; class j dbc2 public static voi d rna i n(Stri ng args[])throws SQLExcepti on, Cl assNotFoundEx cept i on Class forName ( "sun j dbc odbc JdbcOdbcDri ver" ) ; try Connection conn=Dri verManager get connection ( "j dbc : odbc : sanj ay" , "dummy", "ssi"); Statement stnt=conn createStatement ( ) ; ResultSet rs=stnt executeQuery("select * from tz2" ) ; whi le (rs next()) System.out println(rs getint(l)); System out println(rs getString(2)) ; rs c l ose (); stnt close() ; ]DBC Oava Database Connectivity) 77 conn close(); }catch(Exception exl{} import java sql.*; class jdbc3 { public static void main(String args[])throws SQLException, ClassNotFoundException Class forName ("sun j dbc odbc JdbcOdbcDri ver") ; Connection conn=DriverManager getConnection("jdbc :odbc :sanjay" , ''dummy'./, "ssi"); System out println ("connected successfully to the database") ; System out println ("creating table master_ details3"); Statement stnt=conn.createStatement(); String sqlstring="create table master_ detailsl (shareid number(3) ,compname varchar2(20),noofshares number(4 ) ,purrate number(6,2) ,purdate date, currrate number (6, 2)) "; String sqlstringb" create table detailslll (shareid number (3), certno varchar2(10) ,noofshares number(3),firstholder varchar2(15) ,secondholder varchar2(15))"; stnt execute(sqlstring); stnt execute(sqlstringl) ; System out println ("table created master_ details3"); System out println ("table created _detailsll"); I* sqlstring="select * from master_details33"; sqlstring="select * from detailsll"; ResultSet rs=stnt executeQuery(sqlstring); i f (rs! =null) { while (rs next ()) { System out println(rs getString(l)); System.out println(rs getstring(2)); *I import java.sql.*; import java io *; import java.lang String; class jdbc4 78 Secrets of Java public static void main(String args[]) throws Exception { Class forName ( "s un j dbc odbc JdbcOdbcDri ver") ; Connect ion conn=Dri verManager get Connect ion ( "j dbc: odbc : sanj ay", "dummy", "ssi"); System out println (" connected succes.sfully to the database") ; System out.println("Do you want to continue ?" ) ; Statement stnt=conn createStatement() ; try { c har resp= 'y'; wh ile ((char) System in read()== 'y') BufferedReader b=new BufferedReader(new InputStreamReader(System in)); String chk=b readLine(); String str=readEntry ( "enter the insert statement " ) ; stnt executeUpdate(str) ; System out println ("one row inserted") ; System out println("Do you want to insert another row(y/n) ?") ; }catch(SQLException ex){ System out println ( "the SQL Exception raised is" +ex) ; stnt c l ose() ; conn c l ose() ; stati c String readEn try(Stri ng prompt) try { StringBuffer buffer=new StringBuffer(); System out print(prompt); System out flush(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); St r ing c=br.readLine(); return c ; }catch(IOException e) { return \\e "; import java sql.*; c lass customer public static void main(String args[])throws SQLException,ClassNotFoundException ]DBC Oava Database Connectivity) 79 Class forName ("sun j dbc odbc JdbcOdbcDri ver") ; Connection conn= DriverManager get Connection ( "jd!bc: odbc: sanjay", "dummy","ssi"); System out println ("connected succes.sfully to the database"); try { Statement stnt=conn createStatement(); ResultSet rs=stnt executeQuery("select 'connected' rs.next (); String s=rs.getString(l); System out println(s); stnt.close(); conn close(); }catch(Exception ex){ System out println ("the exception raised is" +ex) ; from dual"); import java sql.*; class jdbc6 { public static void main(String args[))throws Exception { Class forName ("sun j dbc odbc JdbcOdbcDri ver") ; Connect ion conn=Dri verManager getConnection ( "j dbc: odbc : madhuri" , "dummy", "ssi"); try{ System out println("connected successfully to the database"); System.out println("altering table detailsll" ) ; Statement stnt=conn createStatement(); stnt executeUpdate ("alter table tel modify (address varchar2 (70)) "); System out println ("table tel altered") ; }catch (Exception er){ System.out println("the exception is raised"+er); import java sql.*; public class jdbc { public j dbc () { try { 80 Secrets of Java String dn = "sun.jdbc odbc.JdbcOdbcDriver"; Driver dd = (Driver)Class forName(dn) newinstance() ; String dburl = "jdbc:odbc:student"; if(dd acceptsURL(dburl)) { System out println("url is val id") ; e l se System.out println( "url is not valid" ) ; catch(Exception el{} public static void main(String args[]) { jdbc jd =new jdbc() ; import java sql *; public class drop { public static void main(String arg[]) { try { Cl ass forName ("sun jdbc odbc JdbcOdbcDriver") ; Connection c = DriverManager.getConnection("jdbc:odbc:g", "dummy", "ssi"); Statement s = c createStatement(); s execute ("drop table ssi3") ; System out println ( "Table draped ") ; s close() ; c close(); }catch(Exception e) { System out println ("Some error" +e) ; ODD Chapter The java uti/.* 16 package BASICS OF UTIL PACKAGE The java.util package provides 34 classes and 13 interfaces that support Collection API., date/ ca~endar operations, internationalization, parsing, and basic event processing The package is used to work mainly with date and calendars The example of classes is GregorianCalendar, SimpleTimeZone and Timezone The Date class is responsible for encapsulating date and time information The StringTokenizer class provides methods to parse a string Examples : Import java lang *; Import java util *; (default package) Public class StrToken public static void main(String args(]) StringTokenzier token = new StringTokenizer (" This is a test for tokens") : While(token hasMoreTokens() ) System out println(token nextToken()); Output this is 81 82 Secrets of Java a test for tokens //Example for Aloirthms class of java util *; import java uti l.*; public c l ass alog public static void main(String pp[]); LinkedLi st 1 = new LinkedList(); ll.add(new Integer( - 8)); ll add(new Integer(20)); ll.add(new Integer(-20)); ll.add(new Integer(B)) ; Comparator co = new Collections.reverseOrder(); Collections sort(ll,co) ; Iterator li = ll iterator(); System o u t println( " List sorted in reverse :• ) ; while(li.hasNext()) System out print(li.next() + "• ) ; System out println(); Collections shuffle(ll); li = ll iterator(); System out println ( " Li st shuffled :" ) ; while(li.hasNext()) System out.print(li n ext() + "" ) ; System out println() ; System out println ( "Minimum · " + Collections min(ll)); System out pri n t ln ( " Maximum ·" + Collections max ( ll )) ; public class ru public stati c void main(String at[) )throws Exception The java util * package Runtime rn = Runtime getRuntime(); rn exec ( "c : /windows 000 /notepad exe") ; / *String sl = new String ("abc"); String s2 = new String ( "ABC") ; System out println(sl compareTo(s2)) ;*/ import java util *; public class SetExample public static void main (String args[]) Set set= new HashSet(); set.add("Bernadine"); set add ("Elizabeth"); set.add("Gene"); set add ("Elizabeth" l ; set.add("Clara"l; System out println(set) ;//no duplicates Set sortedSet = new Treeset(set); System out println(sortedSet) ;//sorted /*[Gene, Clara , Bernadine, Elizabeth] [Bernadine , Clara , Elizabeth, Gene] */ //Example for Hashtable class of java.util.*; import java.util.*; public class hashtdemo public static void main(String pp[)) Hashtable hs =new Hashtable(); Enumeration enu; String str; double bal; 83 84 Secrets of Java hs put("John" ,new Double(3456.2)); hs put ( "Sara", new Double(6734 232)); hs put ( "Naren", new Double (6876 122)) ; hs put("Nithya",new Double(3344.56)); hs.put("Sasi" ,new Double(539 84)); enu = hs keys ( ) ; while (enu.hasMoreElements()) str = (String) enu nextElement() ; System out println(str + " :" + h s get(str)) ; System out println () ; bal = ((Double)hs.get("Sara")).doubleValue(); hs put ( "Sara", new Double (bal+lOOO)); System out println ("Sara • s new balance : " + hs get ( "Sara") ) ; //Example for vector class of java util*; import java util *; class vectordemo public static void main(String pp[)) Vector ve =new Vector(3,2); System out println("Initial size : " + ve size()); System o u t println (" Initial capacity :• + ve capacity()) ; ve.addElement(new Integer (l )); ve.addElement(new Integer(2)); ve addElement(new Integer(3)); ve addElement(new Integer (4)); System out.println("Capacity after additions ·" + ve capacity()); ve.addElement(new Double(5.451)); System out println ("Current capacity ·" + ve capacity()); ve addElement(new Double(6.081)); ve addElement(new Integer (?)) ; System out println ( "Current capacity · • + ve capacity()) ; The java.util.* package 85 ve.addElement(new Float (9 41 )) ; ve.addElement(new Integer(l9)); System.out println("current capacity ·" + ve.capacity()); ve.addElement(new Integer (lO)) ; ve.addElement(new Integer (ll)) ; System out.println("First element :" + System out.println("Last element :" + (Integer)ve firstElement()); (Integer)ve lastElement()); if(ve contains(new I nteger(30))) System out prin t ln ( " Vector contains 3") ; Enumeration enu = ve e l ements(); System out.println("\n Elements in Vector :"); while(enu.hasMoreElements()) System out print (enu nextElement () +" "); System out.println(); I* Iterator ite = ve.iterator(); System out.println ("\n Elements in Vector :"); while(ite.hasNext()) System.out print (ite next() +" "); System.out.println(); */ 000 Index Dot Operator, 12 Driver Managers, 75 DTD, Dynamic Binding, Access Modifier, 16 AclionListener, 34 Applet Type, Applet, 44 [I] E-mail, Exceptions, 24 Exteranet, Application IYPe, Arrays, 15 AWT, 33 [I] File, 27 Final, 17 Finally Block, 25 Finally, 24 FlowLayout, 33 FocusListeners, 34 Blocked State, 69 BorderLayout, 33 Browser, CardLayout, 34 @] Catch, 24 CERN, GridBagLayout, 34 GridLayout, 34 GUI, 33 Class, Client/Server, 61 Constructor, 16 [BJ @] Hot Java, 44 HTML, Data Abstraction, Datagram, 62 [!] DatagramPacket, 62 DatagramSocket, 62 Dead State, 70 Inheritance, 2, 18 Input streams, 27 86 Index Interface, 20 Internet Explorer, 44 Internet, Intranet, IP Address, 61 OJ Port Number, 61 Private, 17 Protected, 16 Public, 16 ~ RandomAccessFile, 27 JAVA, Java.util, 81 Runnable Interface, 68 Runnable State, 69 JDBC, 74 Running State, 69 [I] JDK, [I] Keywords, 12 [I] Life Cyde uf Applel, 44 Life Cycle of Thread, 68 Lynx, 44 [ill Message Passing, MouseListener, 34 ~ Netscape, 44 Networking, 61 New Operator, 12 @] Oak, Object, Search Engine, ServerSocket, 62 Socket, 62 Static, 17 String, 13 StringBuffer, 14 Swing, 50 Synchronization, 70 [!] Tags, TCP/IP, 61 Thread Class, 67 Thread Priority, 70 Thread, 67 Throw, 24, 26 Try, 24 @] UDP, 61 ODBC, 75 Output Streams, 27 Package, 22 Polymorphism, 87 URL, ~ WindowListeners, 34 ODD ... SECRETS OF JAVA SECRETS OF JAVA A Self Learning Approach for Students, Academic and Industrial Professionals By Er R Kabilan, M.E Senior Lecturer Thi ru valluvar College of Engg and... destructor( ) in c+ + Java is an pure object-oriented language Software Installa tion The software jdk (java development kit) can be downloaded from sun.com or javasoft.com web sites This software is compatible... wrapping up of data and method into a single unit is known as data encapsulation Secrets of Java Inheritance : Inheritance is the process by which object of one class acquire the properties of another

Ngày đăng: 04/03/2019, 08:57