AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
Java Technicalities
1. 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
2. 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
3. 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
4. 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
5. 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
8. Introduction Introduction
Everything is an Object.
Thinking in Java 4/e
. . . . . .
Java Technicalities 7/58
9. 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
10. Introduction Introduction
TIOBE Programming Community Index for March 2009
. . . . . .
Java Technicalities 9/58
11. 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
12. 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
13. 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
14. 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
15. 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
16. 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
17. 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
18. 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
19. 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
20. 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
21. 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
22. 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
23. 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
24. 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
25. 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
26. 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
27. 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
28. 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
30. 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
31. 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
32. 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
33. 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
35. 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
36. 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
37. 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
38. 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
39. 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
40. 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
41. 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
42. 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
43. 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
44. 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
45. 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
46. 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
47. 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
48. 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
49. 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
50. 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
51. 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
52. 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
53. Conclusion Conclusion
Do you have any problem ?
I am glad you have listened the slides from start to now. XD
. . . . . .
Java Technicalities 52/58
55. 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
56. 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
57. 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
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
59. 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