Download presentation
Presentation is loading. Please wait.
Published byRuth Mathews Modified over 9 years ago
1
Lecture 5: Java Introduction Advanced Programming Techniques Summer 2003 Lecture slides modified from B. Char
2
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.
3
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{}.
4
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
5
Running java code (default) To execute the main procedure in foo.class, give the command java foo
6
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.
7
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.
8
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.
9
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
10
Classpath command line option for javac or java specifies a list of directories Separated by semi-colons on Windows javac -classpath.;E:\MyPrograms\jena.jar;E:\utilities foo1.java (Windows) Separated by colons on Solaris java -classpath.:/home/vzaychik/jena.jar:/home/vzaychik/utilities foo1 (Unix)
11
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)
12
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.
13
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.
14
Array example import 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 + "."); }
15
Output /home/vzaychik/cs390/>javac example2.java /home/vzaychik/cs390/>java example2 The average of the 4 durations is 74.
16
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.
17
Example of non-static use of classes: In example3.java import 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()); }
18
In Symphony.java /* Definition of symphony class */ public class Symphony { public int music, playing, conducting; public int rating() { return music + playing + conducting; }
19
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; }
20
Compiling and running on Unix % javac Movie.java % javac Symphony.java % javac example3.java % java example3 The rating of the movie is 24 The rating of the symphony is 20
21
Protection in methods and data members Can be public, protected, private as in C++.
22
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 script public void setScript(int s) { script = s; } public int getScript() {return script;}; // mutator/access methods for acting, directing here } }
23
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.
24
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 caps final int BOARD_SIZE;
25
Inheritance to have class B be a subclass of class A, write “public class B extends A {….”
26
abstract classes Subclasses used in program, inherit methods and fields of superclass. But you can’t create an instance of an abstract class.
27
Abstract class example public 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 { ….} and public Symphony extends Attraction { …} can use Attraction x; x = new Movie() or x = new Symphony; in a program
28
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).
29
Defining an abstract class public abstract class GeometricObject { // class definition goes here as normal … }
30
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(); }
31
Superclass, subclass class 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); ….} }
32
Packages package 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.
33
Package invocation If 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.
34
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
35
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;
36
I/O from command line arguments from the terminal from files
37
I/O stream classes Compose them together to read/write to/from files: text, binary data, other kinds.
38
File input example import 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”)));
39
Execution results In input.data file in current working directory: 4 7 3 Output: /home/vzaychik/cs390/>java example5 java example5 Integer: 4 Integer: 7 Integer: 3
40
File output example PrintWriter writer = new PrintWriter(new FileOutputStream(“output.data”)); …. writer.println( );
41
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.
42
Composing constructors StreamTokenizer tokens = new StreamTokenizer( new InputStreamReader( new FileInputStream(“input.data”)));
43
Built-in data types ints, floats, chars, boolean, Strings arrays Vectors (lists)
44
Vector example import 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()); }
45
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 // object v.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.
46
Execution In input2.data: 4 7 9 3 2 6 1 1 1 Output: /home/vzaychik/cs390/>java vectorExample input2.data java vectorExample input2.data read: 4 7 9 read: 2 6 1 read: 1 1 1 20 9 3
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.