You are on page 1of 12

1

CS 101 Data Structures and Algorithms

Cecil Jose A. Delfinado

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

CS 101 Data Structures and Algorithms Java Notes

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.

Java Installation Notes


Download latest Java 2 Standard Edition Software Development Kit (SDK or JDK) and Documentation http://www.oracle.com/technetwork/java/index.html http://www.oracle.com/technetwork/java/javase/downloads/index.html Download: JDK 6 Update 25 with NetBeans 7.0 (a .exe file) Download: Java SE 6 Documentation (a .zip file) (Optional:Library Source) Download: Java SE 6 JDK Source Code Run downloaded JDK+Netbeans .exe file and install Java JDK in a directory like C:\Program Files\Java\jdk1.6.0_25 or simply in C:\Program Files\Java\jdk Set The Execution PATH and JAVA_HOME Navigate: Control Panel > System > Advanced System Settings > Advanced Tab > Environment Variables > System Variables > Select Path > Click Edit > Add the installation directory. blah;blah;C:\Program Files\Java\jdk\bin;more blah > Click OK Test it: Open Command Prompt : Run > cmd > java version > (java version must be displayed.) Add a new system variable > System Variables > Click New Variable Name : JAVA_HOME Variable Value : C:\Program Files\Java\jdk (wherever you installed JDK) Unzip Documentation Unzip downloaded Java SE6 Documentation zip file creating\jdk\docs folder. Bookmark in your browser the application programming interface (API) \jdk\docs\api\index.html (Optional) Unzip Library Source to \jdk\src folder. (Optional) textpad text file editor download from http://www.textpad.com/download/ Use textpad for editing, compiling and running Java code outside IDE. For toolbar icons: > Configure > Preferences > Tools > Add > Java SDK Commands > Ok You may now compile and run programs via > Tools > External Tools > Hammer Icons (or add the icons to the toolbar)

CS 101 Data Structures and Algorithms Java Notes

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.

Running Java Programs


File organization source code : *.java byte code : *.class package : containing folder structure (relative to class path) from command line at directory of source code Windows Start > Run > cmd > cd to source/class directories >javac hello.java (compiles into hello.class bytecodes file) >java hello (runs (interprets) the hello.class file) >java com.cjd.hello (if hello.class is in package com.cjd) If running from a different directory, a path may be included when specifying the class. Alternatively, the environment variable CLASSPATH may be set to include the folders containing the classes and packages. from textpad with source code open click hammerIcon1(Compile Java) or Ctrl+1 click hammerIcon2(Run Java) or Ctrl+2 or via > Tools > External Tools > Hammer Icons using Netbeans IDE Create new project (i.e. a new Java Application) Example: name it CS101 to be located in subdirectory \Netbeans under your home directory. So the files will be in <home dir>\Netbeans\CS101. Dont setup a main class and a main project yet. Create new file (i.e. a new Java Class) Build project automatically done when file is saved. Run project runs the projects main class (specified in projects properties.) Command line arguments may be specified in projects Run properties. To run the main method of current code being edited, type Shift-F6.

CS 101 Data Structures and Algorithms Java Notes

CJD

Part II. Basic Java Programming


1. Programming Constructs
Primitive Data Types, byte 1 byte; short 2 bytes; int 4 bytes; long 8 bytes; float 4 bytes; double 8 bytes; char 2 bytes; boolean 1 bit; Variables strongly typed Operator Precedence
Associativity L to R R to L L to R L to R L to R L to R L to R L to R L to R L to R L to R L to R L to R R to L

-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

CS 101 Data Structures and Algorithms Java Notes

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 ?

Multidimensional arrays array of arrays


double[][] matrix = new double[10][20]; matrix[5][15] = Math.PI;

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()

Comparison: s.equals(t), s.compareTo(t) and s.equalsIgnoreCase(t)

CS 101 Data Structures and Algorithms Java Notes

CJD

5.

Classes and Objects


Read the API documentation for standard library classes. Java classes fields or variables instance variables each instance or object of the class has its own. final variables instance constants (immutable fields) static variables shared by all objects (instances) of the class final static variables class constants methods or procedures or subroutines operate on fields by accessing or mutating them. constructors initialize a new object instance of the class static methods do not operate on objects; dont have implicit this parameter main method: public static void main(String[] args) {} Java objects instances of classes; created with new can be referenced by variables of the class type

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

CS 101 Data Structures and Algorithms Java Notes

CJD

Part III. Java Input/Output


1. Formatting:
Use Formatter class for System.out.format, String.format and similar methods. Time Stamps are useful for monitoring for program executions Code:
import java.util.GregorianCalendar; System.out.format("Test of formatter:%n"); System.out.format("--- Date and Time formatter:%n"); System.out.format(" Old Date was %tB %<te, %<tY or %<tD or %<tF. Time was %<tT or %<tr%n", new GregorianCalendar(2009,1,7,13,4,5)); System.out.format(" Today is %tY-%<tb-%<td. It is now %<tH:%<tM:%<tS.%<tL %<tZ%n", new GregorianCalendar()); System.out.format("--- Boolean formatter:%n"); System.out.format(" p and q is %1$B but p or q is %2$b%n", true && false, true || false); System.out.format("--- String and char formatter:%n"); System.out.format(" %16s converted to upper case is %<-16S, ok %c?%n", "Hello, world!", 106); System.out.format("--- Number formatter:%n"); System.out.format(" %,+8d times %-8d is %0+8d%n", 5000, -3, -15000); System.out.format(" -1000pi is %,15.4f or %<15.4e%n",Math.PI*-1000); System.out.format(" 1.0/700 is %0,15.4f or %<-15.4e or %2$15.9f%% %n", 1.0/700, 1.0/700*100);

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%

CS 101 Data Structures and Algorithms Java Notes

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:

CS 101 Data Structures and Algorithms Java Notes

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:

Output to file Primitive types or flat objects Parts of code:


import java.io.*; // must catch IOException PrintWriter out = new PrintWriter(new FileWriter("filename.txt")); out.println(field1Str+"|"+field2Int+"|"+field3Dbl+"|"+field4Bln); out.close();

Nested objects efficiently stored Parts of code:


import java.io.*; class ClassName implements Serializable{} // must catch IOException ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("filenested.txt")); out.writeObject(obj1); // obj1, obj2 instanceof ClassName out.writeObject(obj2); out.close;

CS 101 Data Structures and Algorithms Java Notes

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"); }

Read one byte at a time Code:


import java.io.*; BufferedReader bin = new BufferedReader(new InputStreamReader(System.in)); int cint = 0; try { //-1 is end of stream while ( (cint = bin.read()) != -1) { //or test against '\n' System.out.println((char)cint); } } catch (IOException e) { e.printStackTrace(); } if (cint == -1) { System.out.println("EOF"); }

Use Scanner class


Scanner sc = new Scanner(System.in); int i = sc.nextInt(); String st1 = sc.next(); String st2 = sc.nextLine(); //may need to use StringTokenizer // or String.split()

CS 101 Data Structures and Algorithms Java Notes

CJD

11 How to get input from GUI use JOptionPane.showInputDialog(prompt string) example :


import javax.swing.*; String input = JOptionPane.showInputDialog(Enter a = ); input = JOptionPane.showInputDialog(Enter n = ); int n = Integer.parseInt(input); System.exit(0);

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;

CS 101 Data Structures and Algorithms Java Notes

CJD

12

Part IV. Packaging and Running Applications


1. Using Netbeans :
In projects properties, Run category, choose Main Class Then click Clean and Build Main Project icon (or click Run then Clean and Build Main Project) This generates an executable jar file in \Netbeans\<project name>\dist\<project name>.jar Double-click the jar file to run it, or on command shell, issue \dist>java jar "<project name>.jar"

2.

From command shell :


edit a manifest text file, say manifest.mf specify the main class without the extension. end last line with EOL character.
Manifest-Version: 1.0 Main-Class: HelloCecil

to archive with a manifest file


>jar cvfm TestJar.jar manifest.mf *.class

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

CS 101 Data Structures and Algorithms Java Notes

CJD

You might also like