DOC PREVIEW
Princeton COS 333 - Java in 21 minutes

This preview shows page 1-2-3 out of 10 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Java in 21 minutes• hello world• basic data types• classes & objects• program structure• constructors• garbage collection• I/O• exceptions• StringsHello worldimport java.io.*;public class hello {public static void main(String[] args){System.out.println("hello, world");}}• compiler creates hello.classjavac hello.java• execution starts at main in hello.classjava hello• filename has to match class name• libraries in packages loaded with import– java.lang is core of languageSystem class contains stdin, stdout, etc. – java.io is basic I/O packagefile system access, input & output streams, ...2Basic data typespublic class fahr {public static void main(String[] args){for (int fahr = 0; fahr < 300; fahr += 20)System.out.println(fahr + " " +5.0 * (fahr - 32) / 9.0);}}• basic types: – boolean true / false– byte 8 bit signed– char 16 bit unsigned (Unicode character)– int 32 bit signed– short, long, float, double• String is sort of built in– "..." is a String–holds chars, NOT bytes– does NOT have a null terminator– + is string concatenation operator• System.out.println(s) is only for a single string– formatted output is a total botch2 versions of echopublic class echo {public static void main(String[] args) {for (int i = 0; i < args.length; i++)if (i < args.length-1)System.out.print(args[i] + " ");elseSystem.out.println(args[i]);}}public class echo1 {public static void main(String[] args) {String s = "";for (int i = 0; i < args.length-1; i++)s += args[i] + " ";if (args.length > 0)s += args[args.length-1];if (s != "")System.out.println(s);}}• arrays have a length field (a.length)– subscripts are always checked• Strings have a length() function (s.length() )3Classes, objects and all that• data abstraction and protection mechanism• originally from Simula 67, via C++ and othersclass thing {public part: methods: functions that define what operations can be done on this kind of objectprivate part: functions and variables that implement the operation}• defines a new data type "thing"– can declare variables and arrays of this type, pass to functions, return them, etc.• object: an instance of a class variable• method: a function defined within the class– (and visible outside)• private variables and functions are not accessible from outside the class• not possible to determine HOW the operations are implemented, only WHAT they doClasses & objects• in Java, everything is part of some object– all classes are derived from class Objectpublic class RE {String re; // regular expressionint start, end; // of last matchpublic RE(String r) {...} // constructorpublic int match(String s) {...}public int start() { return _start; }int matchhere(String re, String text) {...}// or matchhere(String re, int ri, String text, int ti)}• member functions are defined inside the class– internal variables defined but shouldn't be public– internal functions shouldn't be public (e.g., matchhere)• all objects are created dynamically• have to call new to construct an objectRE re; // null: doesn't yet refer to an objectre = new RE("abc*"); // now it doesint m = re.match("abracadabra");int start = re.start();int end = re.end();4Constructors: making a new objectpublic RE(String re) {this.re = re;}RE r; r = new RE(s);• "this" is the object being constructed or running the code• can use multiple constructors with different arguments to construct in different ways:public RE() { /* ??? */ }Class variables & instance variables• every object is an instance of some class– created dynamically by calling new• class variable: a variable declared static in class– only one instance of it in the entire program– exists even if the class is never instantiated– the closest thing to a global variable in Javapublic class RE {static int num_REs = 0;public RE(String re) {num_REs++;...}• class methods– most methods associated with an object instance– if declared static, associated with class itself– e.g., main()5Program structure• typical structure isclass RE {private variablespublic RE methods, including constructor(s)private functionspublic static void main(String[] args) {extract refor (i = 1; i < args.length; i++)fin = open up the file...grep(re, fin)}static int grep(String regexp, FileReader fin) {RE re = new RE(regexp);for each line of finif (re.match(line)) ...}}• order doesn't matterDestruction & garbage collection• interpreter keeps track of what objects are currently in use• memory can be released when last use is gone– release does not usually happen right away– has to be garbage-collected• garbage collection happens automatically– separate low-priority thread manages garbage collection• no control over when this happens– can set object reference to null to encourage it• Java has no destructor (unlike C++)– can define a finalize() method for a class to reclaim other resources, close files, etc.– no guarantee that a finalizer will ever be called• garbage collection is a great idea– but this is not a great design6I/O and file system access• import java.io.*• byte I/O– InputStream and OutputStream• character I/O (Reader, Writer)– InputReader and OutputWriter– InputStreamReader, OutputStreamWriter– BufferedReader, BufferedWriter• file access• buffering• exceptions• in general, use character I/O classesCharacter I/O • InputStreamReader reads Unicode chars• OutputStreamWriter write Unicode chars• use Buffered(Reader|Writer)– for speed– because it has a readLine methodpublic class cp4 {public static void main(String[] args) {int b;try {BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(args[1])));while ((b = bin.read()) > -1)bout.write(b);bin.close();bout.close();} catch (IOException e) {System.err.println("IOException " + e);}}7Line at a time I/Opublic class cat3 {public static void main(String[] args) {BufferedReader in = new BufferedReader(new InputStreamReader(System.in));BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));try {String s;while ((s = in.readLine()) != null) {out.write(s);out.newLine();}out.flush(); // required!!!} catch (Exception e) {System.err.println("IOException " + e);}}Exceptions• C-style error handling– ignore errors -- can't happen– return a special value from functions,


View Full Document

Princeton COS 333 - Java in 21 minutes

Download Java in 21 minutes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java in 21 minutes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java in 21 minutes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?