• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Java Technicalities
 

Java Technicalities

on

  • 6,010 views

淺談 Java 的技術層面。

淺談 Java 的技術層面。

Statistics

Views

Total Views
6,010
Views on SlideShare
6,004
Embed Views
6

Actions

Likes
3
Downloads
111
Comments
0

1 Embed 6

http://www.slideshare.net 6

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Java Technicalities Java Technicalities Presentation Transcript

    • Java Technicalities From a C/C++ Programmer’s View yen3 Dept. of Computer Science and Information Engineering, Chang Gung University April 15, 2009 . . . . . . Java Technicalities 1/58
    • Introduction About About Author Computer Science Student Blog: No title, no thinking, no meaning E-mail: yen3rc gmail C, C++, Java, Haskell, LTEX A . . . . . . Java Technicalities 2/58
    • Introduction Outline Introduction About Introduction Technicalities Type Class and Object Generic in Java (igonred) Exception Library and Programming String Container and HashTable Java I/O JDBC — Java Database Connectivity Conclusion Conclusion Reference . . . . . . Java Technicalities 3/58
    • Introduction Outline About Slide Josh Ko (Joshsoft) XD The slide is made by XELTEX and Beamer. XD A The Color Theme designed by Josh Ko uses Oxford brand colors1 . 1 http://www.ox.ac.uk/staff/branding toolkit/the brand colours/index.html . . . . . . Java Technicalities 4/58
    • Introduction Outline Something About Guang-Wu Chen’s Requirement He hopes you understand the following topics. String (all kinds of string/character processing stuff) StringTokenizer Hashtable (or other containers such as Vector, etc.) JDBC related ones, including Connector, Statement, ResultSet. I/O classes, of course. . . . . . . Java Technicalities 5/58
    • Introduction Introduction But ... XD XD . . . . . . Java Technicalities 6/58
    • Introduction Introduction But ... XD XD Josh Ko and yen3’s Talking yen3: Java ...Orz Josh Ko: XD yen3: Java Functional Programming XD Josh Ko: , Java OO XD . . . . . . Java Technicalities 6/58
    • Introduction Introduction Everything is an Object. Thinking in Java 4/e . . . . . . Java Technicalities 7/58
    • Introduction Introduction Programming By Compiler Compiled Programming language Interpreted Programming language (Script Programming Language) By Machine Imperative Programming (Turing Machine) Functional Programming (λ-calculus) By Model Procedural Programming Object-Based Programming (Abstract Data Type) Object-Oriented Programming Generic Programming . . . . . . Java Technicalities 8/58
    • Introduction Introduction TIOBE Programming Community Index for March 2009 . . . . . . Java Technicalities 9/58
    • Introduction Introduction About Java James Gosling, 1995, Sun Microsystems a pure Object-Oriented Programming Language Everything is an object. Java Virtual Machine and Just-In-Time Compiler XD Java SE, Java EE, Java ME The language has already been developed for over 10 years and become a complete programming language. So, What do we know from Java ? . . . . . . Java Technicalities 10/58
    • Technicalities Type Type Java has two different types. primitive type: int, char, double, balabala pointer type: class type(user-defined type) We know that Java doesn’t have “pointers” Java has “new”, but no “delete” keyword. What is Garbage Collection? What is Java’s memory management mechanism? (It’s an important factor about Java’s program efficiency.) . . . . . . Java Technicalities 11/58
    • Technicalities Type String Type String has build-in type’s interface with pointer type’s implementation. String vs. StringBuffer2 What does the language do in background? Let’s talk about an example. 2 In Java, StringBuilder provides an API compatible with StringBuffer, but with no guarantee of synchronization. . . . . . . Java Technicalities 12/58
    • Technicalities Type Type-Casting Java is strongly-typed programming language. void* vs. java.lang.Object In Java, every class inherits from java.lang.Object. It means we can cast an object to java.lang.Object type and cast again to other arbitrary class type . Compiler doesn’t check the situation because it seems legal from the syntactical perspective. You have to check the situation by yourself. . . . . . . Java Technicalities 13/58
    • Technicalities Class and Object Thinking about The Problems What is a “type”? A Type just like requirement.3 (in Functional Programming) What is a “object”? OO is claimed to be closer to human thoughts. However, is it true ? Object vs java.lang.Object Why doesn’t Java support “Operator Overloading”? “Operator Overloading is syntax sugar. You don’t know how efficient you cost in using.” 3 Think about “Rules” . . . . . . Java Technicalities 14/58
    • Technicalities Class and Object Class and Object A Class has ... data member (Data) – Record States member function(Method) A Class has three modes public – interface private – implements protected – for some reasons XD We have to pay attention to two keywords, but the slide doesn’t mention. static final . . . . . . Java Technicalities 15/58
    • Technicalities Class and Object Class There are several kinds of classes. Normal Class – There’s nothing to say. XD Interface – Think about multiple-inheritance. anonymous Class – Think about the relationship about function pointer and call-back function. . . . . . . Java Technicalities 16/58
    • Technicalities Class and Object Back to C — Function Pointer Von Neumann’s Model says program can be saved in memory. If we ruled the function’s interface, we can show difference functionality by replacing functions rely on function pointer. For Example: C’ stdlib.h — qsort() protype void qsort(void* base, size_t n, size_t size, int (*cmp)(const void*, const void*)); /* function pointer */ . . . . . . Java Technicalities 17/58
    • Technicalities Class and Object Back to C++ — Function Object The most difference between Function Object and Function Pointer is Function Object has own states(variable). Implementation: Class with Operator Overloading “()” If we implemented function object with template. It stars the Generic Programming’s first step. For Example: C++ — Function Object template<typename T> class Less{ public: bool operator()(const T& x, const T& y){ return x < y;} } . . . . . . Java Technicalities 18/58
    • Technicalities Class and Object λ Function (Lambda Function) base on lambda-expressions from Functional Programming,. no side-effect function. an unnamed function for temporary uses Haskell n´ive support a C++’s support: Boost::lambda For Example: C++ — Boost::lambda std::sort(v.begin(), v.end(), std::greater<iterator_traits(v.begin())::value_type>()); std::sort(v.begin(), v.end(), *_1 > *_2); . . . . . . Java Technicalities 19/58
    • Technicalities Class and Object Call-Back Function — Anonymous Class with Interface What is “Call-Back Function”? How does JavaScript support the Call-Back Function? Class-Based vs Prototype-Based Java uses anonymous class and interface(Runnable) to support call-back property. For Example: Java — anonymous class with interface Thread newTask = new Thread(new Runnable(){ public void run(){ System.out.println("Hello World!"); }}); . . . . . . Java Technicalities 20/58
    • Technicalities Class and Object Interface and Abstract Class interface and abstract are keywords. Interface and abstract classes provide a more structured way to separate interface from implementation. In begin, we always have no idea to use them. It’s show time to use “Refactoring”. We can extract to super class, abstract class, or interface from the same functionality classes. Button-Up Design vs Top-Down Design . . . . . . Java Technicalities 21/58
    • Technicalities Class and Object Object-Oriented Class For efficient reason, C++ default member function mode is non-virtual, but Java is not. Please read the relational books to get more details about Java’s Class. The feature is implemented by function pointer table. Think about the relation of RTTI and function pointer table. How to Design Class? Traditional OO Design vs eXtreme Programming4 4 We will discuss the issue next week. . . . . . . Java Technicalities 22/58
    • Technicalities Generic in Java (igonred) Generic in Java Let’s ignore the topic. We can discuss the topic if we have a basic knowledge for C++ Generic Programming. C++’s STL is made from some Functional Programming concepts. Java’s Generic is made by Java OO method. In fact, Java’s Generic is still a OO paradigm. You can play the paradigm using Haskell. It’s more interesting than C++ and Java. XD . . . . . . Java Technicalities 23/58
    • Technicalities Exception Exception What is a “Exception”? “GOTO Considered Harmful.”5 Think about the relation between “goto” and “exceptions”. We have to know program execute the exception block means low efficiency. But we couldn’t ignore writing exception when using some library(ex: I/O, Socket, Thread) 5 Edsger W. Dijkstra, Turing Award 1972 . . . . . . Java Technicalities 24/58
    • Library and Programming Library Muti-Threading Programming – java.util.concurrent.* GUI Programming – javax.swing.* Socket Programming – java.net.* Generic Container – java.util.* (just for some classes) 6 I/O – java.io.* (It is a good OO design example. balabala Don’t forget gwchen’s requirements. XD 6 In C++, Generic Container is more interesting than Java. . . . . . . Java Technicalities 25/58
    • Library and Programming How to find Java Document ? Please have a book named “Thinking in Java 4/e”. XD Google Keyword – “your keywords site:http://java.sun.com/javase/6/docs/” Eclipse code completes Google XD . . . . . . Java Technicalities 26/58
    • Library and Programming String What is a String? What is a “char”? What is a “string” ? What’s difference between “char array” and “string” ? char’s size is 1 byte. string’s element is not always using 1 byte for saving information. Maybe using 2 bytes, or ... Java’s String uses UTF-8 as default encoding. . . . . . . Java Technicalities 27/58
    • Library and Programming String String method charAt & indexOf isEmpty startsWith & endsWith getBytes & getChars subString toCharArray contains toLowerCase & toUpperCase replace & replaceAll & format replaceFirst trim matchs . . . . . . Java Technicalities 28/58
    • Library and Programming String java.util.StringTokenizer http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html It can break a string into tokens. If you want to complexing method for separating string, you can using “Regular Expression” and java.lang.String.split(). . . . . . . Java Technicalities 29/58
    • Library and Programming String Example: java.util.StringTokenizer For Example: evaluate the sum of numbers String s="123 456 789"; StringTokenizer token = new StringTokenizer(s, " "); int sum=0; while(token.hasMoreTokens()){ sum += Integer.parseInt(token.nextToken()); } System.out.println("The sum is: " + sum + "n"); . . . . . . Java Technicalities 30/58
    • Library and Programming String Example: java.lang.String.split() Attention: the argument using “Regular Expression”. For Example: evaluate the sum of numbers String s = "123 456 789"; String[] split = s.split(" "); int sum=0; for(int i=0;i<split.length;i++){ sum += Integer.parseInt(split[i]); } System.out.println("The sum is: " + sum + "n"); . . . . . . Java Technicalities 31/58
    • Library and Programming Container and HashTable Java Container In Java 1.0/1.1, Java uses “Object Container”, but not suggests using for now. Java uses “Generic Container” instead of “Object Container” in Java 1.4 and after. Why does Java do? Please first consider “Array” unless you have enough reasons to use Java Container. And you can’t use primitive type in Generic Container, please use “type wrapper class” instead of “primitive type”. For example: type wrapper class List<int> u = new ArrayList<int>; // wrong List<Integer> u = new ArrayList<Integer>; // right . . . . . . Java Technicalities 32/58
    • Library and Programming Container and HashTable Class Hierarchy Tree java.util.Arrays java.util.Collection<E> java.util.List<E> java.util.Queue<E> java.util.Deque<E> java.util.Set<E> java.util.SortedSet<E> java.util.Map<K, V> java.util.SortedMap<K, V> java.util.Dictionary<K, V> java.util.Hashtable<K, V> java.util.AbstractMap<K, V> java.util.HashMap<K, V> java.util.LinkedHashMap<K, V> java.util.TreeMap<K, V> . . . . . . Java Technicalities 33/58
    • Library and Programming Container and HashTable Vector — java.util.List<E> java.util.List<E> is an interface class. The Most frequently using List is java.util.List.ArrayList In interface, like C++’s std::vector<typename T> add() vs. push back() get() vs. operator[] size() vs. size() Although “Vector<E>” can be used, but Java’s doc suggests using “List” instead of “Vector”. . . . . . . Java Technicalities 34/58
    • Library and Programming Container and HashTable Example: java.util.List<E> For Example: Count words of a file (1–2) public int fileWordCount(String filename){ try{ List<String> fileList = readFile(filename); int totalWords =0; for(int i=0;i<fileList.size();i++){ totalWords += fileList.get(i).split(" ").length; } return totalWords; } catch(Exception e){ System.out.println(e); } return -1; } . . . . . . Java Technicalities 35/58
    • Library and Programming Container and HashTable Example: java.util.List<E> (2–2) For Example: Count words of a file public ArrayList<String> readFile(String filename) throws IOException{ try{ ArrayList<String> u = new ArrayList<String>(); BufferedReader in = new BufferedReader(new FileReader(filename)); String readLine = null; while((readLine = in.readLine())!=null){ u.add(readLine); } in.close(); if(u.isEmpty()) return null; else return u; } catch(FileNotFoundException e){ System.out.println(e); } return null; } . . . . . . Java Technicalities 36/58
    • Library and Programming Container and HashTable HashTable — java.util.HashMap<K, V> HashMap can support the same functionality as HashTable. Please use java.util.HashMap<K, V> instead of java.util.HashTable<K, V> K is key, V is Value If you want use some class as a key, please check the class override “Object.hashCode()” and “Object.equals()”. . . . . . . Java Technicalities 37/58
    • Library and Programming Container and HashTable Example: HashMap For Example: HashMap list all entries HashMap<String, Integer> nameAge = new HashMap<String, Integer>(); nameAge.put("John", 15); nameAge.put("Mary", 17); Set<Map.Entry<String, Integer>> set = nameAge.entrySet(); Iterator<Map.Entry<String, Integer>> iter = set.iterator(); while(iter.hasNext()){ Map.Entry<String, Integer> e = iter.next(); System.out.println(e.getKey() + " " + e.getValue()); } . . . . . . Java Technicalities 38/58
    • Library and Programming Java I/O Java I/O What is a “Stream”? In Unix/Unix-like, everything is a file. Java I/O Library is a pure OO paradigm example, and C++ is too. You can get an overview by java.io.* hierarchy tree.7 It will helps you to understand how to write I/O codes. 7 http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-tree.html . . . . . . Java Technicalities 39/58
    • Library and Programming Java I/O Java I/O: Two Methods Java has “InputStream/ OutputStream”, “Reader/ Writer” InputStream/ OutputStream read 1 byte at a time. Reader/ Writer read a char at a time.8 Reader/ Writer default encoding is UTF8. Recall: Java’s String type default encoding is UTF8. Which can be used depends on your source. 8 a char can be 1 byte, 2 bytes, ... . . . . . . Java Technicalities 40/58
    • Library and Programming Java I/O Java I/O: InputStream/ OutputStream InputStream/ OutputStream ByteArrayInputStream/ ByteArrayOutputStream — for String.getBytes(); (1 byte string) FileInputStream/ FileOutputStream — for files Socket.getInputStream()/ Sokcet.getOutputStream() — for Socket Process.getInputStream()/ Process.getOutputStream() — for Process Control You can use the above to adapt to the following BufferedInputStream/ BufferedOutputStream — Support readLine() DataInputStream/ DataOutputStream — Support readInt() ... . . . . . . Java Technicalities 41/58
    • Library and Programming Java I/O Java I/O: Reader/Writer Reader/ Writer StringReader/ StringWriter — for a String. FileReader/ FileWriter — for a file. CharArrayReader/ CharArrayWriter – for memory You can use the above to adapt to the following BufferedReader/ BufferedWriter — Support readLine() Scanner/ not support . . . . . . Java Technicalities 42/58
    • Library and Programming Java I/O Java I/O: Others The Bridge between InputStream/ OutputStream and Reader/ Writer InputStreamReader/ OutputStreamWriter — Stream translate to Reader/Writer For Example: Socket BufferedReader br = new BufferedReader( new InputStreamReader(Socket.getInputStream())); The following is not maintained. RandomAccessFile ObjectInputStream/ ObjectOutputStream Java.nio (New I/O) . . . . . . Java Technicalities 43/58
    • Library and Programming Java I/O Example: evaluate the sum For Example: evaluate the sum public int evaluateSumByScanner(String s){ StringReader sr = new StringReader(s); Scanner scanner = new Scanner(sr); int sum = 0; while(scanner.hasNext()){ sum += scanner.nextInt(); } sr.close(); return sum; } . . . . . . Java Technicalities 44/58
    • Library and Programming Java I/O Socket Programming Socket Programming is the same as writing to files because we consider socket as a file stream. use “Buffered I/O” (ex: class java.io.BufferedWriter, class java.io.BufferedReader) We have to be care about the message’s format.(fixed format or XML formt) Please don’t use “n” as a message’s end! Please remember “Base64” format when you send binary messages.9 Reference: yen3’s blog – File I/O (1) , (2) Binary File, (3) XML 9 http://en.wikipedia.org/wiki/Base64 . . . . . . Java Technicalities 45/58
    • Library and Programming Java I/O Socket Programming Client – java.net.Socket Server – java.net.ServerSocket Usually, We use Socket Programming together with Multi-threading Programming in Server. Don’t forget “ThreadPool”(java.util.concurrent.Executors) . . . . . . Java Technicalities 46/58
    • Library and Programming JDBC — Java Database Connectivity JDBC — Java Database Connectivity an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. Reference: Wiki: Java Database Connectivity Reference: caterpillar: Java (JDBC) How To use? . . . . . . Java Technicalities 47/58
    • Library and Programming JDBC — Java Database Connectivity JDBC Example: MySQL Please install MySQL. XD Please download MySQL Connector/J 5.1, the offical JDBC driver, you will get a “jar” file. In Eclipse, press “Add External JARs...”, choose the file you downloaded. Have fun! . . . . . . Java Technicalities 48/58
    • Library and Programming JDBC — Java Database Connectivity JDBC Example: Java and MySQL For Example: List a table public void testMySQL(){ String driver = "com.mysql.jdbc.Driver"; String serverName = "localhost"; String databaseName = "information_schema"; String tableName = "TABLES"; String user = "yourname"; String password = "yourpassword"; String url = "jdbc:mysql://"+ serverName +"/" + databaseName; . . . . . . Java Technicalities 49/58
    • Library and Programming JDBC — Java Database Connectivity JDBC Example: Java and MySQL For Example: List a table try { Class.forName(driver); Connection conn = (Connection) DriverManager.getConnection(url, user, password); Statement stmt = (Statement) conn.createStatement(); ResultSet result = stmt.executeQuery("SELECT * FROM" + " " + tableName); while (result.next()) { int numColumns = result.getMetaData().getColumnCount(); for (int i = 1; i <= numColumns; i++) { System.out.println("COLUMN " + i + " = " + result.getObject(i)); } } conn.close(); } catch(ClassNotFoundException e) { System.out.println("Can not find JDBC driver"); } catch (SQLException e) { e.printStackTrace(); } } . . . . . . Java Technicalities 50/58
    • Conclusion Conclusion Conclusion We go through Java from different parts, especially from C/C++. We go through some Java Library ... There are a lot of examples. Please review it. XD Java is a noun-kingdom XDXD. (What do you think about when seeing “ArrayIndexOutOfBoundsException” first time?) Please love “Eclipse IDE” when developing Java programs. XD Let’s expect the interesting issue next week . XD . . . . . . Java Technicalities 51/58
    • Conclusion Conclusion Do you have any problem ? I am glad you have listened the slides from start to now. XD . . . . . . Java Technicalities 52/58
    • Conclusion Reference Reference — Website Java SE Documentation – http://java.sun.com/javase/downloads/index.jsp Eclipse.org – http://www.eclipse.org – http://caterpillar.onlyfun.net/Gossip/ C++ Boost Library – http://www.boost.org SGI STL – http://www.sgi.com/tech/stl/ TIOBE Software: Tiobe Index – http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html . . . . . . Java Technicalities 53/58
    • Conclusion Reference Reference — Java Thinking in Java 4/e, Bruce Eckel, ISBN: 0131872486 The Java Programming Language 4/e, Ken Arnold, James Gosling, David Holmes , ISBN: 0321349806 Effective Java 2/e, Joshua Bloch, ISBN: 0321356683 Practical Java(TM) Programming Language Guide, Peter Haggar, ISBN: 0201616467 The Art of Java, Herbert Schildt, James Holmes, ISBN: 0072229713 Java Network Programming 3/e, Elliotte Rusty Harold, ISBN: 0596007213 Java Swing 2/e, James Elliott, Robert Eckstein, Marc Loy, David Wood, Brian Cole, ISBN: 0596004087 . . . . . . Java Technicalities 54/58
    • Conclusion Reference Reference — Object Oriented Analysis/ Design/ Programming Object-Oriented Analysis and Design with Applications 3/e, Grady Booch, Robert A. Maksimchuk, Michael W. Engel, Bobbi J. Young, ISBN: 020189551 Design Patterns: Elements of Reusable Object-Oriented Software, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, ISBN: 0201663612 Refactoring: Improving the Design of Existing Code, Martin Fowler, Kent Beck, John Brant, William Opdyke, don Roberts, ISBN: 0201485672 Refactroing to Pattens, Joshua Kerievsky, ISBN: 0321213351 Agile Software Development, Principles, Patterns, and Practices, Robert C. Martin . . . . . . Java Technicalities 55/58
    • Conclusion Reference Reference — C/C++ and Other Real World Haskell, Bryan O’Sullivan, John Goerzen, Don Stewart, ISBN: 0596514980 The C++ Programming Language 3/e, Bjarne Stroustrup, ISBN: 0201700735 The C Programming Language 2/e, Brian W. Kernighan, Dennis M. Ritchie, ISBN: 0131193716 C++ Primer 4/e, Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo, ISBN: 0201721481 Effective C++ 3/e: 55 Specific Ways to Improve Your Programs and Designs, Scott Meyers, ISBN: 0321334876 Generic Programming and the STL: Using and Extending the C++ Standard Template Library, Matthew H. Austern, ISBN: 0201309564 . . . . . . Java Technicalities 56/58
    • Conclusion Reference Appendix A: How to get a html String For Example: How to get a html String public String getHtmlString(String inputUrl){ try{ URLConnection url = (new URL(inputUrl)).openConnection(); BufferedReader br = new BufferedReader( new InputStreamReader(url.getInputStream())); int length=-1; StringBuffer sb = new StringBuffer(); char[] temp = new char[1024]; while((length=br.read(temp, 0, 1024))!= -1){ sb.append(temp, 0, length); } br.close(); return sb.toString(); }catch (MalformedURLException ex) { System.err.println(inputUrl + "is not parseable URL"); }catch (IOException ex) { System.err.println(ex); } return null; } . . . . . . Java Technicalities 57/58
    • Conclusion Reference Appendix B: How to write Java Program Please install “Java Developer Kit(JDK)” and “Java Runtime Environment” Please set “PATH” and “CLASSPATH” in Windows. You can download “Eclipse” as your default Java Develop IDE. Have fun! . . . . . . Java Technicalities 58/58