Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction...

8
1 Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java is object oriented Everything belongs to a class (no global variables, directly). Main program is a static method in the class that you run with the java command. 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{}. Locations of Java code Writing 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 Running java code (default) To execute the main procedure in foo.class, give the command java foo Multi- file definitions If 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.

Transcript of Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction...

Page 1: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

1

Lecture 5: Java Introduction

Advanced Programming TechniquesSummer 2003

Lecture slides modified from B. Char

Java is object oriented

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

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{}.

Locations of Java code

Writing the code. Suppose we have a program that consists of just one class fooand 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

Running java code (default)

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

java foo

Multi-file definitions

If 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 2: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

2

More multi-file definitions

import 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.

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.

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

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)

CLASSPATH environment variable

Value is used if there is no classpathcommand 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)

classpath command option vsenvironment 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 codeCan 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 3: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

3

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.

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 +

".");}

}

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

Static methods, static data members

class foo {…

static public int rand(int r) { …};// static method

static 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.

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

}

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

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

return music + playing + conducting;}

}

Page 4: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

4

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

}

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

Protection in methods and data members

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

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 }

}

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.

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 5: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

5

Inheritance

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

abstract classes

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

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

Interfaces

Java 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).

Defining an abstract class

public abstract class GeometricObject{

// class definition goes here as normal

…}

Defining an interface class

//Definition starts with “interface” instead of “class”

interface FloatingVessel {int navigate(Point from, Point to);

// Point is another user-defined class

void dropAnchor();void weighAnchor();

}

Page 6: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

6

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

….}}

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.

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.

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// package

import java.net.*; // imports any class// needed from java.net package

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;

I/O

from command line argumentsfrom the terminalfrom files

Page 7: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

7

I/O stream classes

Compose them together to read/write to/from files: text, binary data, other kinds.

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”)));

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

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

File output examplePrintWriter writer = new PrintWriter(new

FileOutputStream(“output.data”));

….

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

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 inputFileinstead.

Composing constructorsStreamTokenizer tokens =

new StreamTokenizer(new InputStreamReader(

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

Page 8: Lecture 5 - cs.drexel.eduumpeysak/Classes/cs451/pdf/introJava.pdfLecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char Java

8

Built-in data types

ints, floats, chars,boolean, StringsarraysVectors (lists)

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

}}

}

Vector elements

import 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.

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