360 likes | 552 Views
Java Introduction. CMSC 432 Shon Vick. Introduction. This lecture introduces the basic ideas and constructs of the Java programming language and reiterates some constructs we have already spoken about.
E N D
Java Introduction CMSC 432 Shon Vick
Introduction • This lecture introduces the basic ideas and constructs of the Java programming language and reiterates some constructs we have already spoken about. • It is not intended as a complete treatment of any of the ideas presented but rather an introduction • A fuller treatment may be found in : The Java Tutorial, 3rd, by Mary Campione, Kathy Walrath, Alison Huml, Tutorial Team, Addison-Wesley Pub Co; ISBN: 0201485583, also available online
Comparison with C++ • What are some the differences from C++? • What are some of the similarities? • How are Java programs created? • How are Java programs compiled? • What is the result of the compilation? • How is this approach different from C++?
Introduction to JavaBasic Ideas • All Java Programs , unlike C++ are built from classes, in this way Java is more strictly an OOP • A class is said to contain fields (members in C++) and methods (member functions in C++)
Fundamental Ideas • Java was designed with security and portability in mind • Supports standard length built in types • Java source gets translated into something called Java byte code that is run on something called the Java virtual machine. • Java bytecode is the machine language of the Java virtual machine • The virtual machine assigns each application its own runtime, which isolates applications from each other.
A Code Example Type this in , compile it, and add Java to your resume ;) class HelloWorld { public static void main(String[] args) { System.out.println(“Hello mom”); } }
Java Infrastructure .class file produced .java bytecode java javac This is the JVM
What does the JVM do with the Byte Code? • Portability of the Java programs into the architectural neutral bytecode of the JVM rather than into native machine code. • Bytecode runs on any platform that supports an implementation of the JVM. • Although the interpretation of bytecode is substantially faster than the interpretation of most high level languages, still a performance penalty must be paid for this portability.
JITC • For most apps it would be a win to reduce this performance penalty without giving up portability of the language. One • One way to do this is to do just-in-time compilation (JITC), where, at run-time, bytecode is compiled into native machine code.
Different Approaches • Eager • Lazy • Hot spot optimization • No absolute standard – but there are standard compilation techniques • See article for a discussion of one implementation • Other reference
Similarities and differences from C++? • The Built In Types • Comments • Named Constants • Flow of Control
Comments • Are identical to C++ except for javadoc • // Comment till end of line • /* Comments spanning a line */ • /** */ javadoc comment • javadoc produces html documentation on methods , constructors and so on • See javadoc homepage for complete details
Named Constants class CircleStuff { public static final double p = 3.1416; } class Suit { public final static int CLUBS = 1; public final static int DIAMONDS = 2; public final static int HEARTS = 3; public final static int SPADES = 4; } What’s the visibility here? Really would use java.lang.Math.PI What’s the visibility here?
Classes and Objects • Java classes have fields and methods • Fields and Methods in Java can have associated visibility • Public • Private • Package • Protected
Methods class Point { // .. public void clear() { x = 0; y = 0; } public double distance(Point other) { double xdiff , ydiff; xdiff = x - other.x; ydiff = y - other.y; return Math.sqrt(xdiff * xdiff + ydiff * ydiff); } } Note use of static method
Self Reference • Java unlike C++ has no notion of a pointer • There is still a this construct however - an example will suffice class Point { // ... public void clear () { this.x = 0; this.y = 0; } // ... }
Creating Objects • Use new • Invokes constructor • No destructor • Super and this
Arrays class Deck { final int DECK_SIZE = 52; Card[ ] cards = new Card[DECK_SIZE]; // .... Init the array somewhere public void print() { for (int i = 0; i < cards.length; i++) System.out.println(cards[i]); } // ... }
Strings are Built In Java class Yadayadayada { public static void main (String[ ] args ) { /// yada yadayada } // }
Tokenizing Strings import java.util.*; String stg = “when the going gets weird the weird turn pro”; StringTokenizer tokens = new StringTokenizer (stg); while (tokens.hasMoreElements() ) { String next = tokens.nextToken(); System.out.println(next); }
Inheritance • One of major aspects of OOP is inheritance - lets look at an example in Java • You can inherit , override , or reuse behavior of parent class • Note that Pixel objects can be used by any code designed to work with Point objects. • If a method expects a parameter of type Point, you can hand it a Pixel object instance and it still works just fine.
Inheritance of Implementation class Pixel extends Point { Color color; public void clear() { super.clear(); color = null; } }
Java Doesn't support MI (of implementation) interface Lookup { // Return the value associated w/ name or null Object find (String name); } class Foo implements Lookup extends Bar { // Foo must provide all the Lookup methods }
Using an Interface • Now lets look at some code that that uses the Lookup interface void processValues (String[] names, Lookup table) { for (int i = 0; i<names.length; i++) { Object value = table.find(names[i]); if (value != null) processValue(names[i], value); } }
A Class that Implements the Lookup Interface • Now lets look at a class that implements the interface class SimpleLookup implements Lookup { private String[] Names; private Object[] Values; public Object find(String name) { for (int i = 0; i<Names.length; i++) { if (Names[i].equals(name)) return Values[i]; } } // .... }
Exceptions • Java uses checked exceptions to manage error handling. Exceptions force a programmer top deal with errors. If a checked exception is not handled, this noticed when the error happens, not latter when problems have potentially compounded. • A method that detects an unusual error condition throws an exception. Exceptions in turn may be caught by code further back on the calling stack - this prior code can handle the exception and continue processing. • Un-handled exceptions are handled by a default handler in the Java implementation which may report the exception and terminate the thread of execution.
More General Ideas About Exceptions in Java • Exceptions in Java are objects , with type , methods and fields of data. This representation is handy because an exception can include data or methods to report or recover from certain conditions. • Exceptions are generally extensions of the Exception class which provides a string field to describe the error.
An Example of Exceptions class IllegalAverageException extends Exception {}; class MyUtilities { public double averageOf ( double[] vals , int i , int j) throws IllegalAverageException { try { return (vals[i] + vals[j]) / 2; } catch (IndexOutOfBoundsException e) { throw new IllegalAverageException(); } } }
Packages • Used to avoid name conflicts • Java has adopted a more formal notion of a package that has a set of types and subpackages as members. • Packages are named and can be imported - we'll look at a few examples. • Package names form a hierarchy with parts separated by dots. • When you use part of a package , either you use its fully qualified name or you import all or part of the package. • Using packages – the CLASSPATH variable
Examples class Date1 { public static void main(String[] args) { java.util.Date now = new java.util.Date(); System.out.println(now); } } import java.util.Date; class Date2 { public static void main(String[] args) { Date now = new Date(); System.out.println(now); } }
Text Input • System.in is a java.io.InputStream reads raw bytes BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); • InputStreamReader coverts from bytes to Unicode • BufferedReader supports String readLine() returns null at EOF
File Text I/O PrintWriter out = new PrintWriter(new FileWriter(fileName)); BufferedReader in = new BufferedReader( new FileReader(fileName));
References • Java Tutorial