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

Slides:



Advertisements
Similar presentations
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Advertisements

Lab Information Security Using Java (Review) Lab#0 Omaima Al-Matrafi.
Final Review.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Lecture 2: Object Oriented Programming I
Lab#1 (14/3/1431h) Introduction To java programming cs425
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
ISE 582: Web Technology for Industrial Engineering University of Southern California DJE Dept of Industrial and Systems Engineering Lecture 6 JAVA Cup.
Classes and Instances. Introduction Classes, Objects, Methods and Instance Variables Declaring a Class with a Method and Instantiating an Object of a.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java and C++, The Difference An introduction Unit - 00.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIT 590 Intro to Programming First lecture on Java.
Java Introduction 密碼學與應用 海洋大學資訊工程系 丁培毅.
Chapter 2: Java Fundamentals
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Introduction IS Outline  Goals of the course  Course organization  Java command line  Object-oriented programming  File I/O.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Programming in Java CSCI-2220 Object Oriented Programming.
Introduction to Generics
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CS 11 java track: lecture 2 This week: more on object-oriented programming (OOP) objects vs. primitive types creating new objects with new calling methods.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.
Java Package Advantage of Java Package
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
 2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
JAVA MULTIPLE CHOICE QUESTION.
University of Central Florida COP 3330 Object Oriented Programming
Objects, Classes, Program Constructs
I/O Basics.
Java Programming Language
Introduction to Java Programming
Applying OO Concepts Using Java
Presentation transcript:

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.

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

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)

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.

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 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 + "."); }

Output /home/vzaychik/cs390/>javac example2.java /home/vzaychik/cs390/>java example2 The 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.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()); }

In Symphony.java /* Definition of symphony class */ public class Symphony { public int music, playing, conducting; public int rating() { return music + playing + conducting; }

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 example3 The rating of the movie is 24 The 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 script public 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 caps final int BOARD_SIZE;

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

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

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); ….} }

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.

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.

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 arguments from the terminal from files

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

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

Execution results In input.data file in current working directory: Output: /home/vzaychik/cs390/>java example5 java example5 Integer: 4 Integer: 7 Integer: 3

File output example PrintWriter writer = new PrintWriter(new FileOutputStream(“output.data”)); …. writer.println( );

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.

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

Built-in data types ints, floats, chars, boolean, Strings arrays Vectors (lists)

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

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.

Execution In input2.data: Output: /home/vzaychik/cs390/>java vectorExample input2.data java vectorExample input2.data read: read: read: