46
Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Embed Size (px)

DESCRIPTION

Java is syntactically similar to C++ Built-in types: int, float, double, char. Control flow: if-then-else, for, switch. Comments: /*.. */ but also // …. (to end of line) Exceptions: throw …; try {} catch{}.

Citation preview

Page 1: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Lecture 5: Java IntroductionAdvanced Programming TechniquesSummer 2003

Lecture slides modified from B. Char

Page 2: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Java is object orientedEverything belongs to a class (no global variables, directly).Main program is a static method in the class that you run with the java command.

Page 3: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Java is syntactically similar to C++

Built-in types: int, float, double, char.Control flow: if-then-else, for, switch.Comments: /* .. */ but also // …. (to end of line)Exceptions: throw …; try {} catch{}.

Page 4: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Locations of Java codeWriting the code. Suppose we have a program that consists of just one class foo and a main procedure that uses it. Write the main procedure as a static method in that class. The source code must be in a file named foo.java in your current working directory.Compilation. Create the file foo.class via the command

javac foo.java

Page 5: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Running java code (default)

To execute the main procedure in foo.class, give the command

java foo

Page 6: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Multi-file definitionsIf you use several classes foo1, foo2, foo3, … create several files in the same directory foo1.java, foo2.java, foo3.java. Compile each one. The compiler will automatically look for other classes in the same directory.Sometimes the compiler can figure out that foo1 requires foo2, so that compiling foo1.java will automatically cause foo2.java to be compiled… but explicit compilation means you can be sure that a file has been compiled or recompiled.

Page 7: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

More multi-file definitionsimport bar;

means that bar.class should be consulted to find definitions of classes/definitions mentioned in the current file’s programming, such as the class bar.

Page 8: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Classes assembled at compilation, and at run time

Contrast with C or C++ which tends to collect all classes needed into a single executable (binary) file, before execution.

Page 9: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Classpath specified on the command line

Java will look in other directories, and Java archive files (.jar files) besides the standard Java system directories and your current working directory

Page 10: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Classpath command line option for javac or java specifies a list of directories

Separated by semi-colons on Windowsjavac -classpath .;E:\MyPrograms\jena.jar;E:\utilities

foo1.java (Windows)Separated by colons on Solarisjava -classpath

.:/home/vzaychik/jena.jar:/home/vzaychik/utilities foo1 (Unix)

Page 11: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

CLASSPATH environment variable

Value is used if there is no classpath command option.setenv CLASSPATH .:/pse/:/pse1/corejini: (on Unix)javac example1.java

Compilation will look in current working directory /pse and /pse1/corejini directories for other class definitions.set CLASSPATH .;E:\PSE\; E:\jini1_0\lib\jini-core.jar; (on Windows)

Page 12: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

classpath command option vs environment variable

Software engineering considerations: explicit invocation of the classpath on the

command line means it’s easier for programmers to remember or readers to discover what you set the classpath to. With fewer mistakes or misunderstandings, one has easier to maintain code

Can put compilation directions into a make file, will work for anyone regardless of how they set their classpath variables. This also avoids the problem of typing in a long classpath repeatedly during development: just type “make asmt1” or whatever.

Page 13: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Many similarities to C++ in built-in data types, syntax

if, for, while, switch as in C++Strings a first-class data objects. “+” works with Strings, also coerces numbers into strings.Arrays are containers. Items can be accessed by subscript. There is also a length member.

Page 14: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Array exampleimport java.io.*;

/* Example of use of integer arrays*/

public class example2{ public static void main(String argv[]) {

int sum = 0;int durations [] = {65, 87, 72, 75};for (int counter = 0; counter < durations.length; ++counter)

{ sum += durations[counter];};// Print out overall result.System.out.print("The average of the " + durations.length);System.out.println(" durations is " + sum/durations.length +

"."); }}

Page 15: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Output/home/vzaychik/cs390/>javac example2.java/home/vzaychik/cs390/>java example2The average of the 4 durations is 74.

Page 16: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Static methods, static data members

class foo {…

static public int rand(int r) { …};// static methodstatic public int i; // static data

}

all objects of that type share a common i and a common version of the method.Methods can be invoked without creating an instance of the class.

Page 17: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Example of non-static use of classes:In example3.javaimport java.io.*;

/* Simple test program for Java (JDK 1.2) */

public class example3{ // by default classes are protected (known to “package”) public static void main(String argv[]) {

Movie m = new Movie();m.script = 9; m.acting = 9; m.directing = 6;Symphony s = new Symphony();s. music = 7; s.playing = 8; s.conducting = 5;// Print out overall results.System.out.println("The rating of the movie is " +

m.rating());System.out.println("The rating of the symphony is "

+ s.rating()); }}

Page 18: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

In Symphony.java/* Definition of symphony class */

public class Symphony { public int music, playing, conducting; public int rating() {

return music + playing + conducting; }}

Page 19: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

In Movie.java/* Definition of Movie class for example 3.*/

public class Movie { public int script, acting, directing; public int rating() {

return script + acting + directing; }}

Page 20: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Compiling and running on Unix% javac Movie.java

% javac Symphony.java

% javac example3.java

% java example3The rating of the movie is 24The rating of the symphony is 20

Page 21: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Protection in methods and data members

Can be public, protected, private as in C++.

Page 22: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Constructors, protection/* Definition of Movie2 class: two constructors.*/

public class Movie2{private int script, acting, directing;public Movie2() {

script = 5; acting = 5; directing = 5;}public Movie2(int s, int a, int d) {

script =s; acting = a; directing = d; }public int rating() {

return script + acting + directing; }// mutator/access methods for scriptpublic void setScript(int s) { script = s; }public int getScript() {return script;};// mutator/access methods for acting, directing here }

}

Page 23: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Naming conventions for classes, variables

These are rules borrowed from Reiss’ “Software Design” textbook used in cs350. Java does not insist on them but we recommend following coherent naming rules to reduce software engineering costs.

Page 24: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Naming conventions for classes, variables, constants

Names of classes: First letter capitalized, e.g. class Movie { ….}Names of methods: first letter lower case; multi-word method names capitalized second and successive words:

public int getTime();public void clear();

Names of constants: all capsfinal int BOARD_SIZE;

Page 25: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Inheritanceto have class B be a subclass of class A, write “public class B extends A {….”

Page 26: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

abstract classesSubclasses used in program, inherit methods and fields of superclass.But you can’t create an instance of an abstract class.

Page 27: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Abstract class examplepublic abstract class Attraction{

public int minutes;public Attraction() {minutes = 75;}public int getMinutes() {return minutes;}public void setMinutes (int d) { minutes = d;}

}

then class definitions for Movie and Symphony:public Movie extends Attraction { ….}

andpublic Symphony extends Attraction { …}

can use Attraction x; x = new Movie() or x = new Symphony; in a program

Page 28: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

InterfacesJava does not have general multiple inheritance. It does have limited multiple inheritance.An interface B is a class that has only class declarations.public class A implements B, C, D {…} means that A inherits the methods of B,C, and D (and can have methods and members of its own).

Page 29: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Defining an abstract classpublic abstract class GeometricObject{

// class definition goes here as normal

…}

Page 30: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Defining an interface class//Definition starts with “interface” instead

of “class”interface FloatingVessel {

int navigate(Point from, Point to);// Point is another user-

defined classvoid dropAnchor();void weighAnchor();

}

Page 31: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Superclass, subclassclass A1 implements A {….}class B1 extends B {….}class C {

public int method1(A a, B b) {…}…public method2(…) {int result; B1 b1Object; A1 a1Object;b1Object = new B1(…);a1Object = new A1(…):result = method1(a1Object, b1Object);….}

}

Page 32: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Packagespackage onto.java.entertainment;public abstract class Attraction {….}

Attraction.java must be in an onto/java/entertainment subdirectory. If this file is in /home/vzaychik/cs390/asmt4/onto/java/entertainment

The value of the CLASSPATH variable should include the value /home/vzaychik/cs390/asmt4.

Page 33: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Package invocationIf a class example7 is in the package onto.java.entertainment,

invoke through the full package name

java onto.java.entertainment.example7

even if you’re in example7’s directory.

Page 34: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Importing classes that belong to packages

import onto.java.chapter7.entertainment;// imports entertainment class that // belongs to onto.java package

import java.io.ObjectInputStream;// imports ObjectInput class from java.io

// packageimport java.net.*; // imports any class

// needed from java.net package

Page 35: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

What does “final” mean?public final class FinalCircle extends GraphicCircle { … }When a class is declared with the final modifier, it means that it cannot be extended.It’s a way of declaring constants for a class:

final int BUFFERSIZE = 10;

Page 36: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

I/Ofrom command line argumentsfrom the terminalfrom files

Page 37: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

I/O stream classesCompose them together to read/write to/from files: text, binary data, other kinds.

Page 38: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

File input exampleimport java.io.*;

public class example5 { public static void main(String argv[]) throws IOException {

FileInputStream stream = new FileInputStream("input.data");InputStreamReader reader = new InputStreamReader(stream);StreamTokenizer tokens = new StreamTokenizer(reader);

while(tokens.nextToken() != tokens.TT_EOF) {// TT_EOF built-in for tokens

System.out.println("Integer: " + (int) tokens.nval); // nval built-in for tokens

}stream.close();

}}

Alternative: compose constructors together:

StreamTokenizer tokens = new StreamTokenizer(new InputStreamReader( new FileInputStream(“input.data”)));

Page 39: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Execution resultsIn input.data file in current working directory:4 7 3

Output:/home/vzaychik/cs390/>java example5java example5Integer: 4Integer: 7Integer: 3

Page 40: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

File output examplePrintWriter writer = new PrintWriter(new FileOutputStream(“output.data”));

….

writer.println(< whatever needs to be written to file>);

Page 41: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

File input also works with standard input redirection

Idea: use “System.in” stream to do reading. By default, this reads from the keyboard. But if you invoke the program using “<“ for standard input redirection

javac –classpath … Example1 < inputFile

then System.in will read from the inputFile instead.

Page 42: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Composing constructorsStreamTokenizer tokens =

new StreamTokenizer(new InputStreamReader(

new FileInputStream(“input.data”)));

Page 43: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Built-in data typesints, floats, chars, boolean, StringsarraysVectors (lists)

Page 44: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Vector exampleimport java.io.*;import java.util.*;

public class vectorExample { public static void main(String argv[]) throws IOException{

FileInputStream stream = new FileInputStream(argv[0]);InputStreamReader reader = new InputStreamReader(stream);StreamTokenizer tokens = new StreamTokenizer(reader);Vector v = new Vector();

while(tokens.nextToken() != tokens.TT_EOF) {// TT_EOF a system constant int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; tokens.nextToken(); System.out.println("read: " + x + " " + y + " " + z); v.addElement(new Movie2(x,y,z));};stream.close();for (int counter = 0; counter < v.size(); counter++) { System.out.println(

((Movie2) (v.elementAt(counter))).rating());}

}}

Page 45: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

Vector elementsimport java.util.Vector;

class Test {

public static void main(String argv[]) {Vector v;v = new Vector(0);v.addElement(new Integer(1));// creates integer

// objectv.addElement("abc");for (int i=0; i<v.size(); i++) { System.out.println("item " + i + " is: "+ v.elementAt(i));};}

}Anything except a primitive type (int, float, boolean, char) is a

subclass of Object. 

Page 46: Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char

ExecutionIn input2.data:4 7 93 2 61 1 1

Output:/home/vzaychik/cs390/>java vectorExample input2.datajava vectorExample input2.dataread: 4 7 9read: 2 6 1read: 1 1 12093