COSC 2006 Data Structures I Instructor: S. Xu URL:

Slides:



Advertisements
Similar presentations
Basic Java Constructs and Data Types – Nuts and Bolts
Advertisements

Object Oriented Programming with Java
Arrays.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Programming Languages and Paradigms The C Programming Language.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Written by: Dr. JJ Shepherd
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 2: Object Oriented Programming I
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
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.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
CS0007: Introduction to Computer Programming Introduction to Arrays.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
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.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Programming in Java CSCI-2220 Object Oriented Programming.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
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.
OOP Basics Classes & Methods (c) IDMS/SQL News
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Java Primer 1: Types, Classes and Operators
Lecture 2: Data Types, Variables, Operators, and Expressions
Starting JavaProgramming
null, true, and false are also reserved.
Java Programming Language
Conditional Statements
Introduction to Java Programming
Group Status Project Status.
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Classes, Objects and Methods
Chap 2. Identifiers, Keywords, and Types
Corresponds with Chapter 5
Presentation transcript:

COSC 2006 Data Structures I Instructor: S. Xu URL:

Topics Syllabus Java review

Java Review

What’s in what? Program [Packages (each in its own directory) ] Classes (each in own.java file) Data Fields Methods (if it is an application, one main)

Packages package Package; - first line in file Each its own directory; can be nested java.lang, java.io, java.util, etc. are each directories in the java directory

Import and Type References Importing classes from packages import com.ibm.xml.parser.Parser; import com.ibm.xml.parser.*;

Classes Is this legal in the file name “Test.java”? Import java.io.*; public class Test{ public static void main (…){ } } class Lab1 { …… }

Classes Is this legal in the file name “Test.java”? Import java.io.*; public class Test{ public static void main (…){ } } public class Lab1 { …… }

Classes A file can contain 0 to many top-level classes, but only one can be declared as public. A top-level class can only be public or default.

Classes Classes are data types: they specify data and methods for instances of the type [subclassing-modifier] [access-modifier] class ClassName [ extends Class] [ implements Interface] { body } abstract public class OrderedTree extends BinaryTree implements OrderedSequence {... } Make instances (objects) with new new OrderedTree() … (why is this wrong?)

Parts of a Class Definition [subclassing-modifier] abstract - must be extended final - cannot be extended [access-modifier] public - available outside package protected private class ClassName [ extends Class] - inherits some data, methods [ implements Interface] - conforms to method signatures

Data Fields Variables and Constants [ access-modifier] use-modifier* type name [ = initializer]; public static final double DEFAULT_RADIUS = 1.0;

Parts of a Data Declaration [ access-modifier] private - available only within the class None - available within class and package protected - available within class, other classes in same package, and subclasses public - available everywhere the class is (exported) use-modifier* static - one field shared across instances final - cannot be modified there are others...

Methods Operations [access-modifier] use-modifier* return-type methodName ( formal-parameter-list ){ body } public static int max(int x, int y){... } Parameters and actual values Call by value (except that only references to objects are copied) return-type can be void or a type

Parts of a Method Declaration [ access-modifier] private - available only within the class None - available within class and package protected - available within class, other classes in same package and subclasses public - available everywhere the class is use-modifier* static - one shared across instances final - cannot be overridden by subclass abstract - must be overridden by subclass there are others...

Referencing Members Referencing Static Members: class.memberName SimpleSphere.DEFAULT_RADIUS Or use object to access Referencing Public Members: object.memberName SimpleSphere ball = new SimpleSphere() Ball.getVolume();

Comments Javadoc Documentation /** * Prints out "Hello World" and the command line arguments. arg A string array containing the arguments. No return value. Exception if the file is not found or other error. */ Inline comments // this is inline Disabling code /* … code … */

Identifiers Identifiers: A-Z, a-z, 0-9, _, $ _ or letter first Keywords: reserved identifiers Literal Constants: 12, 87.31, 8.7e-3, 'a', \n, '\'' Variables int x; Named Constants final int MAX_SIZE = 512;

Primitive Types and Wrappers

References Assigning with new int x = 10; Integer intObject = new Integer(x) Primitives versus References Comparing with == Passing as arguments

References & Objects How many objects and how many references have been created? Worker wk1,wk2; Adult ad1, ad2; Wk1 = new Worker(); Wk2=wk1; Ad1= new Adult (); Ad2= wk1;

Operators for Primitives Assignment = Arithmetic + - * / % usual precedence, left associative Use () for clearer associativity Combined: +=, -=, *=, /=, %= x += y; Incrementing/Decrementing: ++, -- ++x; x++; x += ++y; //?

Boolean Operators Relational: =, > Equality: ==, != Logical: &&, ||

Selection: if if ( expression ){ statement+ } if ( expression ){ statement+ } else { statement+ } if ( expression ){ statement+ } else if ( expression ){ statement+ } else { statement+ }

Selection: switch switch ( integer-expression ){ case value1: statement+ // continues executing below! case value2: case value3: … statement+ break; // exits switch … default: statement+ // often an exception }

Iteration: while, do, for // 0 or more times while ( expression ){ statement+ } // at least once do { statement+ } while ( expression ); for ( initialize* ; [test] ; update* ){ statement* } // equivalently initialize ; while ( test ) { statement* ; update* ; } break and continue can be used in any iterator

Arrays Ordered collection of elements of uniform type with random access by index final int NUM_STUDENTS = 70; int [] grades = new int[NUM_STUDENTS]; Can initialize with values int [] grades = {92, 56, 87, 79, …}; Indices 0 to length-1 grades[0], grades[k], grades[k++], etc

More Arrays Any wrong with this? int myArray[3]={1, 2, 3}; int myArray[]=new int [] {1,2,3} ; An array object (as distinct from reference) is always initialized with zeroes for primitive type With nulls for object

More Arrays Array of objects SimpleSphere[] myMarbles = new SimpleSphere[BAG_CAPACITY]; Passing Arrays - Given: public int maxMarble(SimpleSphere[] bag) { … }; You can call it like this: int biggestMarble = maxMarble(myMarbles);

Abstract Classes This is an abstract class public abstract class myClass { abstract void print (); int calculate (int x, int y) { return x+y; }

Abstract Classes Is this an abstract class public abstract class myClass { int calculate (int x, int y) { return x+y; }

Abstract Classes What’s an abstract class? If have abstract method, then class must be declared abstract If you define the class as abstract, this is abstract class even there is no abstract method Abstract forces the class to be subclassed Can’t make instance of abstract class

Java interfaces What is the difference between abstract class and interface? Interface provides a way to have multiple inheritance You can only inherit one abstract/normal class; but you can implements many interfaces Abstract class can have partial behavior, but interface cannot

Java interfaces Interfaces just indicate what methods must be supplied public interface Enumeration { boolean hasMoreElements(); Object nextElement(); }

Exception Object-oriented generalization of “errors” try { statement* } catch ( exceptionClass1 identifier ) { statement*, e.g., identifier.printStackTrace() } // Zero or more of these finally { statement*, e.g., closing open files } // zero or one of these

Exceptional! try can be followed by zero or more catch blocks and zero or one finally block (at least one of catch or finally) Finally block always be executed except for other reasons (such as machine crash)

Throwing Your Own Class MyException extends Exception { public MyException(String s){ super(s); }} public void myMethod() throws MyException { // … code … throw new MyException("Indigestible argument”); }

More info Java 1.4/1.5 API cs/api/index.html nterview.PDF

39 Review _________Which order is correct for the access modifiers? A. public, default, protected, private B. private, default, protected, public C. default, private, protected, public D. protected, private, default, public

40 Review __________Which statement is wrong? int myarray [3]={1,2,3}; int myarray []=new int []{1,2,3}; int [] myarray ={1,2,3}; int myarray []=new int [3];

41 Review _____ What is the common pattern of class definitions A. Methods and instance variables are both private. B. Methods are private, and instance variables are public. C. Methods are public, and instance variables are private. D. Methods and instance variables are both public.

42 Review ______The Java statement Object element = new Object(); creates a: new class new object new reference variable new container to hold objects

43 Review _______Can two different classes contain methods with the same name? A. No. B. Yes, but only if the two classes have the same name. C. Yes, but only if the main program does not create objects of both kinds. D. Yes, this is always allowed.

Attentions Assignment 1 Start as early as possible