Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented...

43
Java Lecture 1 Introduction John Black CS 425
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    214
  • download

    0

Transcript of Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented...

Page 1: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Java Lecture 1

Introduction

John Black

CS 425

Page 2: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Overview

• Java is: – Like C/C++– Object-Oriented– Interpreted– Portable– Multi-Threaded

Page 3: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Types of Java Programs

• Standalone (has main())

• Applet– A dynamically loaded class (so no main())– Special environment (browser or applet viewer)– Restricted (memory, disk access, screen area)

• Servlet– Java program which runs on Server– Dynamically loaded (so no main() again)

Page 4: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Standalone Java Program

• Collection of “class” files– Each class file has one public class– This class is the same as the filename of this

class file– Exactly one file contains main()– Prototype for main() is

public static void main(String args[])

(You can’t omit the parameters or the interpreter will consider this a different method!!)

Page 5: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

More on main()

• Notice that main has type void– Cannot “return(val)” from main()– Use System.exit(val) instead

• Interpreter runs until main() exits and then waits for all threads to complete before terminating

Page 6: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Example: echo.java

echo.java:public class echo { public static void main(String argv[]) { for (int i=0; i < argv.length; i++) System.out.print(argv[i] + “ “); System.out.print(“\n”); System.exit(0); }}

You can find this example on the web page.

Page 7: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Compiling and Running

• Say we have this echo class in a file called echo.java% javac echo.java // compiles

% ls echo.class // is the class file there?

echo.class

% java echo hello world // now run it!

hello world

%

Page 8: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

The CLASSPATH variable

• All public classes are in different files, so how does the compiler find them?– class file containing main() must import them

import echo;

– javac looks in directories indicated in CLASSPATH environment variable

ex. % setenv CLASSPATH /home/jrb/java/classes:.

set CLASSPATH C:\java\classes;.

Page 9: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

CLASSPATH (cont.)

• If javac doesn’t find class file, it makes one– If echo.class doesn’t exist and echo.java does,

javac compiles echo.java for you

• At run-time classes must be available also% java echo // looks for echo.class in

// CLASSPATH list

• All classes used must be available for java interpreter at run-time

Page 10: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Packages

• A package is a set of associated classes– Package names are words separated by dots

ex: java.lang.String.substring()

– System classes (like java.lang.String) are automatically found by the compiler/interpreter

– User-defined packages must be in a directory within CLASSPATH following package name

package class method

Page 11: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Packages (cont.)

– Ex: cs425.std.echo

must be in a directory cs425/std rooted in some CLASSPATH directory

• The “package” statement must appear first– The package statement tells the compiler which

package this class belongs to– If no package statement, classes are placed in a

default package

Page 12: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Packages (cont.)

• Semantics of Packages– A class can access any other class in the same

package (public or non-public)– A class can access any non-private fields or

methods in the other classes of the package

• Let’s look at an example.

Page 13: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

The import Statement

• import provides a shorthand for class names

• Details:– must appear after optional “package” statement– has two forms:

• import utils.echo; // import just this class

• import utils.*; // import all classes in this pkg

– let’s you refer to classes directly by class name– import java.lang.*; is automatic

Page 14: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

A Brief Tour of java.lang

• java.lang is the package containing the “core classes” of the language (kind of like the stdlib of C)Contains routines to manipulate: Boolean,

Character, Numbers, Strings, has Math routines, Threading library, Exception Handling

• Check the JDK 1.1 API doc for details

Page 15: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Storage Classifiers for Classes

• All classes in a package are visible to all others in that same package. You can’t change this!

• Other than “public” your only other option for declaring a class is <nothing>; this means the class is visible only within the same package.

• Only one class may be declared public in a given java source file.

Page 16: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Visibility of Class Members

• Storage classes for class members (ie, variables and methods)– private: only members of the same class– package: only classes within the same package

(this is the default)

– protected: only classes within the same package or any subclass of host class

– public: visible everywhere

Page 17: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Comments and Preprocessor

• Three comment styles, but we’ll use only 2:– /* comment */ nesting not allowed– // comment just like C++

• There is no preprocessor – No #include, #define, #if, etc.

Page 18: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Declaring Constants

• Use “static final” to declare constants– ex: public final class Math {

public static final double PI = 3.141592653589…;

}

• Always use all CAPS for constants

• (Note: we can use Math.PI instead of java.lang.Math.PI. Why?)

Page 19: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Primitive Data Types

Type Contains Default Sizeboolean true/false false 1 bitchar Unicode \u0000 16 bitsbyte Signed int 0 8 bitsshort Signed int 0 16 bitsint Signed int 0 32 bitslong Signed int 0 64 bitsfloat IEEE 754 0.0 32 bitsdouble IEEE 754 0.0 64 bits

Page 20: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Primitive Data Types (cont.)

• boolean type; assume int i and boolean b– i = (i != 0); // illegal!– i = (i != 0) ? 1 : 0; // that’s more like it– b = (i != 0); // that’s ok too

• char type– just like C: ‘h’ is a char– the usual escape codes: ‘\n’, ‘\”’, etc.

Page 21: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Primitive Data Types (cont.)

• Integer Types– All integer types are signed– long literals are signaled by appending l or L

• Floating Point Types– for float literals append f or F– for double literals append d or D

Page 22: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

The String type

• Unlike C, “String” is a supplied type in Java– Note that it is not a primitive type, but has extra

support nonetheless (for convenience)– Note the capitalization: String is a class

(What package is the class in?)

– String literals are enclosed in quotes: “hi”

(This automatically creates a String object.)

Page 23: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Reference Data Types

• If it’s not primitive, it’s an object or array– Passing a primitive type is by value

int i = 2; j = i; j = 3; // i = = 2, j = = 3

– Passing a reference type is by referenceButton p, q; p = new Button();

q = p; // q refers to same object as p

p.setLabel(“Ok”);

String s = q.getLabel(); // s contains “Ok”

Page 24: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Pop Quiz on Object References

• Does this work?public void swap(Object a, Object b) {

Object temp = a;a = b;b = temp;

}

• Does Not Work! Each parameter is passed in as the value of a reference, these values are rearranged with no outside effects!

Page 25: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Misc. Reference Issues

• If a and b are objects, what does a = = b mean? (Use strcmp() or equals() instead)

• How do you copy objects (no copy constructors in java)

• No pointers at all! (Fewer bugs!?)

• null is a reserved keyword, not a value which is #defined to 0

Page 26: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

A First Look at Objects

• Object Creation:– Window w; // does NOT create an object– Window w = new Window(); // this does– Special shortcut for Strings:

String s = “This creates a string”;

// The above is shorthand for

// String s = new String(“This creates a string”);

• Object members accessed with ‘.’ operator

Page 27: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

What about Arrays?

• Arrays are objects, but with special syntax:– byte b[] = new byte[10]; // no constructor

// Elements initialized to default for this datatype

– char c[] = {‘h’,’i’}; // initialize to ‘h’ ‘i’

• In both cases, array is dynamically allocated

• Initialization values need not be constant since array is allocated and initialized at runtime

Page 28: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

More on Arrays

• Access array elements with arr[x] as usual– Bounds-checking done at runtime; is this good?– To get an array’s length, use arr.length

(“length” is the only field allowed for array objects and is declared “final” so you cannot change it)

• Quiz: what does this declaration do?byte[] row, column, matrix[];

Page 29: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

More on Strings

• The String class is immutable– Use class StringBuffer if you want to change

the contents of a string:StringBuffer sb = new StringBuffer(“Hi”);

• Strings are NOT arrays (so don’t use s[x])

• String concatenation is done with +System.out.println(“hi there, “ + name);

Page 30: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Common String Methods

Assume s and t are Strings and i and j are ints;(strings indices start at 0)

s.length() // # chars in string

s.charAt(i) // return character at index i of s

s.equals(t) // returns true iff s and t are equal

s.compareTo(t) // return strcmp(s,t) (ie, -1, 0, 1)

s.indexOf(t) // return index of first t within s

s.lastIndexOf(t) // return index of last t within s

s.substring(i) // return String from index i to end, incl

s.substring(i,j) // return String from index i to j-1, incl

Page 31: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Operators

• Basically the same as C; table on the web– + is String concatenation; for primitive types

operands are implicitly converted– Note >> is with sign extension; >>> is not– o instanceof C returns true if o is object of

class C (or subclass of C); true means o is assignable to objects of type C

– boolean & and | do not short-circuit

Page 32: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Statements

• if/else, while, do/while same as in C• switch statement is the same also (case labels must

be constants or “final” variables)• for loops are different from C in two ways:

– comma separated init and increment sections:for (i=0, j=0; i+j < 10; i++, j++)

– loop declarations in init section:for (int i=0, j=0; …)

Page 33: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Labeled break Statement

• Used alone, “break” works the same as in C

• But in Java we can have labels attachedtest: for (j=0; j < 10; j++) {

for (i=0; i < 10; i++) {if (a[i][j] == null) break test; // break out of BOTH

loops}

}

Page 34: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Labeled continue Statement

• Used alone, “continue” works just like in C

• In Java, we can have labels:resume: for (j=0; j < 10; j++) {

for (i=0; i < 10; i++) {if (a[i][j] == null) continue resume; }

}

Page 35: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

The synchronized Statement

• Used to synchronize multiple threads which share data

• Syntax: synchronized (expr) statement

• expr must resolve to an object or array

public static void SortIntArray(int[] a) {

synchronized (a) {// sort the array

}}

Page 36: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exceptions, Exceptions...

• An exception in Java is much like C++: a signal that some important event (like an error) has occurred– To “throw” an exception is to signal that it has

occurred– To “catch” an exception is to handle this

occurrence

Page 37: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exceptions Propagate

• If an exception is not caught within a local block, it propagates– First propagates through enclosing blocks– Then propagates up the method call stack– If propagates all the way to main() and main() does

not catch it, the java interpreters prints an error msg and a stack trace

• Well-designed code has centralized exception-handling!

Page 38: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exception Objects

• An exception is an object– Its class is some subclass of java.lang.Throwable

– Two common subclasses are java.lang.Error and java.lang.Exception

– java.lang.Error indicates a serious problem (eg, out of memory) and should not be caught

– Subclasses of java.lang.Exception are often caught and recovered from (eg, the exception java.lang.ArrayAccessOutOfBounds)

Page 39: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exceptions (cont.)

• Since an exception is an object, it has fields– To get a description, call Throwable.getMessage()

• Handling is done via try/catch/finallytry {

// some block of code} catch (SomeException e1) {

// handle SomeException or a subclass of this type} finally {

// always execute this code}

Page 40: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exceptions (cont.)

• A try block is followed by zero or more catch blocks– exception is caught by the first catch() which

matches in type

• finally clause should do clean-up work– a finally block is always executed if any part of

the try block is executed, even if exit is via a break, continue, or return statement

Page 41: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exceptions (cont.)

• “Normal Exceptions” must be caught or propagated by your methods

public void open_file() throws IOException {// code that might cause an uncaught java.io.IOException

}

• Some exceptions you don’t have to declare– eg, InternalError (that would be ridiculous)– How do we know when we have to declare it?

• Just try it and let the compiler tell you

Page 42: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Exceptions (cont.)

• To generate your own exceptions, use Throw– Often the exception object is allocated as it is

thrown:throw new MyException(“bad thing happened”);

• Let’s look at a detailed example.

Page 43: Java Lecture 1 Introduction John Black CS 425. Overview Java is: –Like C/C++ –Object-Oriented –Interpreted –Portable –Multi-Threaded.

Conclusion