CS101 Java Notes
CS101 Java Notes
JAVA NOTES
Table of Contents
Part I. Java Set-up ............................................................................................................2 1. Why Java ? ................................................................................................................2 2. Java Installation Notes ...............................................................................................2 3. Java Environment ......................................................................................................3 4. Running Java Programs .............................................................................................3 Part II. Basic Java Programming ........................................................................................4 1. Programming Constructs............................................................................................4 2. Control Flow..............................................................................................................5 3. Arrays ........................................................................................................................5 4. Strings .......................................................................................................................5 5. Classes and Objects ...................................................................................................6 6. Generic classes ..........................................................................................................6 Part III. Java Input/Output ...............................................................................................7 1. Formatting: ................................................................................................................7 2. Generating Output .....................................................................................................8 3. Getting Input............................................................................................................ 10 Part IV. Packaging and Running Applications ............................................................... 12 1. Using Netbeans : ...................................................................................................... 12 2. From command shell : ............................................................................................. 12 Part V. References ........................................................................................................... 12
CJD
Part I.
1.
Java Set-up
Why Java ?
Runtime environment that provides platform independence Syntax similarity to C++ and C Fully object oriented Reduced program bugs by having automatic memory management no pointer arithmetic assignment (=) operator different from equality test (==) interfaces instead of multiple inheritance
2.
CJD
3.
Java Environment
The Java Compiler generates intermediate bytecodes (*.class) from java source codes (*.java) that could be interpreted (and executed) according to the requirements of different machines The Java Virtual Machine (JVM) a generic platform-independent machine that serves as a common intermediary from which java codes are interpreted to execute in a variety of machines. Java Just-In-Time (JIT) compiler frequently used bytecodes may be compiled into native codes specific to the machine. Caching these native codes significantly improves run time on subsequent executions. The Java Runtime Environment (JRE) the bundling of Java libraries, JVM, and other components for Java programming and execution.
4.
CJD
-128 to 127 -32,768 to 32767 -2.1+x109 to 2.1+x109 -9.2+Lx1018 to 9.2+Lx1018 3.4Fx1038 with 6-7 significant digits 1.7x10308 with 15 significant digits unicode; ex. C \u0043 true or false
Operators [] (array element) . (field or method) () (method call) ! (not) ~ (bit complement) ++ (add 1 to itself) (minus 1 from itself) + (unary +) - (unary minus) () (cast) new (instantiation) * (times) / (floating point or integer division) % (modulo-remainder) + (plus) (minus) << (bits shift left) >> (bits shift right) >>> (unsigned shift right) < <= > >= (order comparators) instanceof == (is equal?) != (is not equal ?) & (bitwise and) ^ (bitwise xor) | (bitwise or) && (logical and) || (logical or) ?: (if then else) = (assignment) += = *= /= %= &= |= ^= <<= >>= >>>= (operate value on right with left var, result to left var)
Note on ++, -n++ evaluates to n, then add 1 to n; ++n adds 1 to n and evaluates to new value Useful Functions and Mathematical constants Math.sqrt, Math.sin, Math.atan, Math.exp (e), Math.log (ln), Math.random Math.PI, Math.E long System.currentTimeMillis() and long System.nanoTime() Get these values before and after a section of code. Compute the difference to get the elapsed time to execute that code. Data Type conversions automatic : ex: char to int; or int to double; or long to float casts : int n = (int) Math.round(x); // x is a double; round returns a long
CJD
2.
Control Flow
Main method All classes may have their own main methods. Useful for unit testing. Running a file or class starts by running its main method. Running an application starts with the main method of its main class. Main methods of referenced classes are not executed. Statements terminated by ; (semicolon) Block Scope delineated by {} (curly braces) Conditional Statements if (condition) thenstmt else elsestmt condition ? ifTrueStmt : ifFalseStmt switch (choice) {case val1: stmts1; break; case val2 : stmts2; break; default: stmtsdflt; break } Loop Constructs while (condition) stmt do stmt while (condition) for (var = startValue; whileCond; endStmt) stmt
3.
Arrays
Collections of values of the same type Declaration, Initialization and Length int[] a = new int[100]; // declares and creates an array a[0..99] of int int[] digits = {0,1,2,3,4,5,6,7,8,9}; // declares, creates & initializes a.length // size of array (not necessarily filled) Convenience classes and methods : Do not use in class without prior permission
System.arraycopy(from, fromIndex, to, toIndex, count); Arrays.sort(a); // uses quicksort version for arrays of primitive types Arrays.equals(a,b); // is array a equal to array b ?
Vectors and the ArrayList class we will not need these in class
4.
Strings
String is a predefined class for a sequence of characters. It is immutable. Each string is delimited by double quotes Concatenation: use + operator Methods ex. String s = "pineapple" s.substring(1,6) // prints chars from position 1 to 5 = ineap
s.length(), s.toUpperCase(), s.charAt(4), s.trim()
CJD
5.
6.
Generic classes
new in Java J2SE 5.0 allows underlying class(es) of a generic class to be specified at runtime. allows class to be reused by different applications for varying underlying class(es). Note: cannot create generic arrays, or the generic object within the defining class. example :
public class Test1<T,U> { private T info; private U data; public Test1(T a,U b) { info = a; data = b; } public static void main(String[] args) { Integer i = new Integer(20); Character c = new Character('C'); Test1<Integer,Character> n = new Test1<Integer,Character>(i,c); System.out.println(n.info+n.data.toString()); } } Output: 20C
CJD
Output:
Test of formatter: --- Date and Time formatter: Old Date was February 7, 2009 or 02/07/09 or 2009-02-07. Time was 13:04:05 or 01:04:05 PM Today is 2011-May-15. It is now 12:44:08.178 CST --- Boolean formatter: p and q is FALSE but p or q is true --- String and char formatter: Hello, world! converted to upper case is HELLO, WORLD! , ok j? --- Number formatter: +5,000 times -3 is -0015000 -1000pi is -3,141.5927 or -3.1416e+03 1.0/700 is 0000000000.0014 or 1.4286e-03 or 0.142857143%
CJD
2.
Generating Output
Output to console/System.out System.out.println(string) or System.out.print(string) System.out.printf(format string, args) or its equivalent System.out.format(format string, args) Output to GUI Using JOptionPane.showMessageDialog does not show scrollbars, so limited to screen height. Code:
import javax.swing.*; /* blah */ String s = " i sqrt(i) \n"; for (int i=1; i<=5; i++) { s = s + String.format("%2d %7.4f%n",i,Math.sqrt(i)); } JOptionPane.showMessageDialog(null,s,"Square Roots", JOptionPane.INFORMATION_MESSAGE); System.exit(0);
Output:
CJD
9 Using JTextArea and JScrollPane with scrollbars, but not much better than System.out console output. Code:
import javax.swing.*; import java.awt.Font; public static void main(String[] args) { JFrame frame = new JFrame(); JTextArea textArea = new JTextArea(); textArea.setFont(new Font("Monospaced",Font.PLAIN,12)); frame.setTitle("Program Output"); frame.setSize(200,100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); textArea.append("Hello, Customer!\n"); textArea.append("The cost is "+new java.text.DecimalFormat("$0.00").format(Math.PI*1000)+"\n"); textArea.append(String.format("The change is $%,10.2f%n",Math.PI*100)); frame.getContentPane().add(new JScrollPane(textArea)); frame.setVisible(true); }
Output:
CJD
10
3.
Getting Input
Hardcode inputs in code like the main method or field declarations Input from command line In command shell window, issue command: java <program> <arguments> In Netbeans IDE, Right click the project, select Properties, select Run category, enter arguments on input text field labeled Arguments. Input from keyboard (System.in) In windows cmd window, Ctrl-Z by itself in console to indicate EOF From Netbeans, there is no way to specify EOF. Instead, terminate your loop when a special character like newline ('\n') in input. Read one line at a time Code:
import java.io.*; BufferedReader bin = new BufferedReader(new InputStreamReader(System.in)); String sLine = ""; try { while ( (sLine = bin.readLine()) != null ) { System.out.println(sLine.toUpperCase()); } } catch (IOException e) { e.printStackTrace(); } if (sLine == null) { System.out.println("EOF"); }
CJD
Part of Dialog :
How to get input from file Primitive types or flat objects Parts of code:
import java.io.*; import java.util.*; // must catch IOException BufferedReader in = new BufferedReader(new FileReader("filename.txt")); String s = in.readLine(); StringTokenizer t = new StringTokenizer(s,"|"); String field1Str = t.nextToken(); int field2Int = Integer.parseInt(t.nextToken()); double field3Dbl = Double.parseDouble(t.nextToken()); boolean field4Bln = Boolean.parseBoolean(t.nextToken()); in.close();
Note: Alternative to tokenizer is String.split() that stores the tokens separated by delimiter into an array of tokens. Nested objects Parts of code:
import java.io.*; class ClassName implements Serializable{} // must catch IOException ObjectInputStream in = new ObjectInputStream(new FileInputStream("filenested.txt")); ClassName obj1 = (ClassName)in.readObject(); ClassName obj1 = (ClassName)in.readObject(); in.close;
CJD
12
2.
to run
>java -jar TestJar.jar
Part V. References
[1] Horstmann, C and Cornell, J, Core Java 2, Volume I and II. Sun Microsystems Press, 2003. [2] http://sun.java.com [3] JavaTM Platform, Standard Edition 6 API Specification
CJD