introduction to the java programming language - part 2 - instructor : an, seung hun...

45
Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hu n [email protected]. kr * This transparency is based on that made by G. Fox and B. Carpenter in Florida State University

Upload: roy-cunningham

Post on 02-Jan-2016

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Introduction to the Java Programming Language

- Part 2 -

Instructor : An, Seung [email protected]

* This transparency is based on that made by G. Fox and B. Carpenter in Florida State University

Page 2: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java Language Basics

Page 3: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Obvious similarities to C, C++

• Java syntax has many similarities to C,C++.

• All variables must be declared

• Syntax of expressions and control structures almost identical to C, C++

• C or C++ style comments allowed.

Page 4: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Obvious differences from C, C++

• No low-level pointers or pointer arithmetic.– Instead have variables and expressions of reference

type.

• No malloc() or free()—instead have a “new” operator for creating objects, plus automatic garbage collection.

• Can declare variables almost anywhere (like C++).

• No struct, union, enum, typedef—classes and objects are used uniformly instead.

Page 5: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Primitive types rationalized

• Java characters use 16-bit Unicode Worldwide Character Encoding instead of 8-bit ASCII. Supports all alphabets and languages.

• Primitive types for integers and floats have machine independent semantics.

• Boolean expressions in Java have value “true” or “false” (not 0, 1, . . .)

Page 6: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Three kinds of comments in Java

• /* ignore all between stars */– As for C

• // ignore all till the end of this line– As for C++

• /** this is a documentation comment */– Should appear immediately before, eg, class or me

thod definition, and describe intended use.

Page 7: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java Keywords• Java reserves the following keywords:

abstractbooleanbreakbytecasecatchcharclassconst

continuedefaultdodoubleelseextendsfinalfinallyfloat

forgotoifimplementsimportinstanceofintinterfacelong

nativenewpackageprivateprotectedpublicreturnshortthrow

throwstransienttryvoidvolatilewhile

goto is not allowed in Java, but it’s still reserved! null, true, and false are literals with special meaning.

Page 8: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java Types

• Each Java variable or expression has a definite type, given by a declaration such as int i; double x, y, z; Color c;

• There are two sorts of type:– Primitive types like ints or booleans are built into t

he language. – Reference types. These include class types like C

olor, and array types (and also interface types).

Page 9: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Primitive Types• There are 4 integer types: byte short int long Sizes are 8, 16, 32 and 64 bits, respectively.• float is 32 bits, double is 64 bits. Floating point arith

metic and data formats are defined by IEEE 754 standard.

• char format is defined by 16 bit Unicode character set.• boolean is either true or false.

• One can use casts for arithmetic conversion, as in: int i ; float x ; i = (int) x ;

Page 10: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Reference Types• These are the types associated with

composite entities like objects and arrays.• They are called reference types because a

variable or expression in a Java program with reference type represents a reference (or pointer) to a composite entity.– Any variable of reference type may take the

value null.

• Reference types can be divided into:– Class types– Interface types (discussed later)– Array types

Page 11: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Strings—an Example of a Class Type

• Java environments provide predefined classes for common data types. Every Java environment provides a String class.

• Declaration of a String variable looks like: String s ; // variable declaration

• The variable declaration itself doesn’t create any objects. We can create a new String object by, e.g.: s = new String(“This is the text”) ; //

object creation

• These may be combined on one line: String s = new String (“This is the

text.”) ;

Page 12: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Some features of Strings.

• Strings are Java objects, but Java provides some syntax peculiar to strings.

• In fact literal string in double quotes itself refers to a pre-existing String object—so in practice we may drop new operation for string constants: String s = “This is the text.” ;

• After creation, characters of a string object never change.– In other words: string objects are immutable.

Page 13: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Operations on Strings• Although a String object is immutable, String-valued v

ariables can be reassigned to refer to new string objects:

String str = “Chicken soup with rice” ; int n = str.indexOf( ‘w’ ) ; str = str.substring(0,n) + “is n” + str.substring(n+6) ; // Result: “Chicken soup is nice”.

• The operator + is used for concatenation (special syntax for strings).

• indexOf() and substring() are methods of the String class—not special syntax!– They illustrate the general syntax of method invocation on an

object.

Page 14: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Array Types

• As for objects, declaring an array variable is distinct from creating on the array: int states[] ; // variable declaration

and: states = new int[128] ; // array creation

• Again, these can be combined: int states[] = new int[128] ;

• Alternative (better?) syntax for declaration: int[] states ;

Page 15: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Subscripts• With states is declared as above:

int states[] = new int[128] ;

it can be subscripted by integers from 0 to 127.

• Subscripts are checked at runtime: states[-1] or states[128] will immediately generate exceptions.

• Array length is given by the length instance variable: int len = states.length ; // assigns len = 128.

Page 16: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Arrays of Objects

• Arrays of arbitrary objects can be constructed, e.g.: Color manycolors[] = new Color[1024];

• This creates an array of object references. It does not create actual objects for individual elements.

• Before you use the array elements, you may need to use object constructors to allocate each object, e.g.: for (int i = 0 ; i < 1024 ; i++) manycolors [i] = new Color() ;

Page 17: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Multidimensional Arrays

• Multidimensional arrays are arrays of arrays. In general these arrays may be “ragged”:

int graph[][] = new int[2][];

graph[0] = new int[4]; // Row 0 has length 4 graph[1] = new int[7]; // Row 1 has length 7 . . . graph[1][1] = 9;

• Shorthand syntax for creating a rectangular array: char icon[][] = new char [16][16]; // 16 by 16 array

– Note icon is still logically an arrays of arrays, and nothing in Java forces it to stay rectangular. E.g. later someone might do:

icon [8] = new char [17] ; // Now ragged!

Page 18: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java Language—Expressions• Most Java expressions are similar to C. Here

are some examples:

– arithmetic:2 + 3(2 + 3) * i

– auto-increment and decrement:i++ // equivalent to i = i +1

– Boolean:((i > 0) && (j > 0)) || (state == –1)

– bit operations:i << 1 // Shift bit pattern 1 place left

– conditional expression:(i > 0) ? expression1 : expression2

Page 19: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java Language—More Expressions

• Java has some expressions of its own:

– string concatenation:“fred” + “jim” // Value is “fredji

m”

– object “instance of” test:(a instanceof B) // true iff object a

has type (class) B

Page 20: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Java Control Flow. I: if Statements

• Conditional execution of statements: if (some Boolean expression) { statements to be executed if true }

• Optional else clause: if (some Boolean expression) { statements to be executed if true } else { statements to be executed if false }

• Nested example: if (some Boolean expression) { . . . } else if (another Boolean expression) { . . . } else { . . . }

Page 21: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Control Flow II: while Loop Constructs

• Normal while loop: while (any Boolean) { Stuff to do }

Example: int i = 0 ; while(i < a.length) { a [i] = i * i ; i++ ; }

• while loop with test at end: do { What to do } while (another Boolean) ;

Page 22: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Control Flow III: The for Loop Construct

• In Java, most often use the C++-like variant: for (declaration1 ; booleanExpression ; expressionList2) { Statements to do }

The declaration declaration1 is effected at start of loop, comma-separated expressionList2 is evaluated after every iteration, and the loop terminates when booleanExpression is false.

• Typical example: for (int i = 0 ; i < a.length ; i++) a [i] = i * i ;

• The original C-like form (no declaration) also available: for (expressionList1 ; booleanExpression ; expressionList2) { Statements to do }

Page 23: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Control Flow IV: The switch Construct

• Identical to C:

switch (expression) { case Constant1: // Do following if

expression==Constant1 Bunch of Stuff break; case Constant2: // Do following if

expression==Constant2 Bunch of Stuff break; default: // Do the following otherwise Bunch of Stuff break; }

Page 24: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Control Flow V: break and continue

• Unlabeled break statement immediately exits the enclosing switch, while, do or for construct: while (true) if (++i == a.length || a[i] == v) break ;

• Labeled break statement allows to exit an arbitrary enclosing statement, provided it is labeled: assign: { if (i >= a.length) break assign ; a[i] = v ; }

(This is not the best way to do this!)

• The continue statement skips to the end of the current iteration of the enclosing while, do or for.

Page 25: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

The Java Object Model: Classes, Instances and

Methods

Page 26: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

The Java Object Model Overview

• Programs are composed of a set of modules called classes. Each class is a template specifying a set of behaviors involving the data of the class.

• Each class has variables, or fields, to hold the data, and methods—akin to functions or procedures in other languages—to define the behaviors.

• Each object in a program is created as an instance of a class. Each class instance has its own copy of the instance variables defined for the class.

• Classes can be used for data encapsulation, hiding the details of the data representation from the user of the class (e.g., by marking variables as private).

InstanceVariables

Methods

Page 27: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Defining a Class

• A class declaration consists of: – a header giving the class name, modifiers, and possible sup

erclass and interface structure. and a class body usually containing:

– declarations of fields (possibly with initializations)—class variables and instance variables.

– declarations of methods.– declarations of constructors. These “functions” look like met

hods, but have the same name as the class. They do initialization when objects—class instances—are created.

– nested class and interface definitions.– class or (rarely) instance initialization statements.

Page 28: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Instance Variables• A very simple class:

public class Complex { public double real ; public double imaginary ; }

• Essentially like a C struct. Every instance of Complex has its own real and imaginary variables. These fields are therefore called instance variables.

• Use: Complex z = new Complex() ; // Default constructor

z.real = 0.0 ; z.imaginary = 1.0 ;

Page 29: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Class Variables• Besides instance variables, a class may contain “glob

al variables” that are not associated with any instance.

• A class variable (also called a static variable) is flagged by the static modifier in its declaration:

class Potato { public String name;

static public int num = 0 ; // Class variable—number of potatoes. } Potato p = new Potato(), q = new Potato() ;

p.name = “one potato” ; q.name = “two potato” ;

Potato.num += 2 ; // static field prefix is class name.

Page 30: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Method Definitions• Subprograms in Java are called methods. In the abstr

act, the declaration format is:methodModifiers returnType methodName (parameter list){ declarations and statements}

• The parameter list contains the types and names of all the parameters.

• The declarations and statements are the body of the method. Parameter names, and variables declared in the body, are local to it.

• Control returns from a method when the body finishes execution or a return statement is executed. return statements may return a result value.

• Parameters are passed by value.

Page 31: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Local variables

• Formal parameters of methods, and variables declared inside the bodies methods, are local variables.

• These are a third kind of variable in Java: they are neither instance variables or class variables.

Page 32: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Instance Methods

• Instance methods operate in the context of a particular class instance (i.e. a particular object).

• The instance variables of the current object can be accessed without any prefix:

public class Complex {

// Adds z to the current object

public void add(Complex z) { real += z.real ; imaginary += z.imaginary ; }

public double real ; public double imaginary ; }

Page 33: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Invoking an Instance method

• This example initializes a and b, then increments the value of a by amount b:

Complex a = new Complex(), b = new Complex() ;

a.real = 0.707 ; a.imaginary = -0.707 ;

b.real = -1.0 ; b.imaginary = 0.0 ;

a.add(b) ; // Method invocation

Page 34: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Static and Non-static Methods

• Like fields, methods come in two varieties, which are properly called instance methods and class methods.

• The terms non-static methods and static methods are also commonly used.

• In all Java applications illustrated so far, the main() method had the modifier static—the main method of an application is required to be a static method.

• All other examples of methods illustrated so far were instance methods.

Page 35: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

this

• Within an instance method or constructor the keyword this refers to the current instance.– i.e. the object on which the method was invoked, or which th

e constructor is initializing.

• Appropriate usage—passing self-reference to some other method: public class Complex {

. . . Definition of add(), etc.

public void addTo(Complex accumulator) { accumulator.add(this) ; } }

– The invocation a.addTo(b) adds the value of a to b, i.e. it is equivalent to b.add(a).

Page 36: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

this as a prefix

• Some programmers will write the this prefix explicitly on every access to an instance variable, e.g.:

public void negate() { this.real = – this.real ; this.imaginary = – this.imaginary ; }

• This is legal, but ugly!

• One time you must use this as a prefix to an instance variable is when the field is hidden by declaration of a local variable with the same name.– The only common example is in constructor

declarations. A constructor parameter whose value is used to initialize a field is conventionally given the same name as the field it initializes. See examples later.

Page 37: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Static Methods

• A static method does not operate in the context of a particular instance.

• Instance variables of the class cannot be accessed inside the body of a static method unless an explicit object prefix is given.

• The keyword this cannot be used in the body of a static method.

• To invoke a static method it should be prefixed by the name of the class (similar rule to accessing class variables).– This prefix can be omitted if the method is invoked

from another method, etc, defined in the same class.

Page 38: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Constructors

• Constructors are “functions” (not, strictly speaking, methods) that have the same name as the class they belong to.

• Any number of constructors can be defined for a class, provided they can be distinguished by the number and type of their parameters (overloading).

• If no constructors are explicitly defined, the compiler generates a single default constructor with no arguments.

– Note: the default constructor disappears once any explicitly-defined constructor is given!

Page 39: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

A Better Potato

class Potato {

public Potato(String name) { this.name = name ; // Idiomatic use of this num++ ; }

public static int getNum() { // A static method return num ; }

private String name ; // Note: now private

private static int num = 0 ; // Also private}Potato p = new Potato(“one potato”), q = new Potato(“two potat

o”) ;

System.out.println(“There are ” + Potato.getNum() + “ potatoes”) ;

Page 40: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Remarks

• In the constructor, the unqualified symbol name refers to the local variable declared in the parameter list.– Because this declaration hides the declaration of name as a

n instance variable, we must prefix with this to access the latter.

• The data fields are now private. This means they can be accessed only from methods within the class, not from other classes.

• The method getNum() returns a “global” property of the class—the total number of Potato objects that have been created.– Hence it is natural to declare it as a static method—it is not

associated with any individual instance.

Page 41: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Type Conversions

• Java allows implicit type conversions in some contexts.

• Generally speaking the conversions allowed implicitly (without a cast) are what are called widening conversions.

• For primitive types, the widening conversions are from any integer type to any wider integer type, (int to long, etc) or from a float to a double.

• Narrowing conversions, by contrast, would include conversion from long to int, or from a floating point type to an integer type.

• Narrowing conversions usually have to be specified explicitly with a cast, e.g. float x ; int i = (int) x ;

Page 42: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Header of Class Definition—Details

• In the abstract, the definition format is: classModifiers class className [ extends superclass ] [ implements interfaceList ] { body of class }

• The optional extends and implements clauses will be discussed in detail in later lectures.

Page 43: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Modifiers of Classes

• Possible classModifiers are:– public—the class may be used freely by code outside the pac

kage.– abstract—the class contains abstract methods without imple

mentation (abstract classes will have subclasses that define implementation of methods—see later).

– final—this class cannot have a subclass: see later.– strictfp—all intermediate results in all float or double express

ions appearing in the class have strict IEEE 754 exponents.– private—only allowed for a nested class. Meaning as for oth

er members. – protected—only allowed for a nested class. Meaning as for o

ther members. – static—only allowed for a nested class. Meaning analogous

to other members.

Page 44: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Modifiers of Fields

• In the abstract, the declaration format is: fieldModifiers type variableDeclaratorList ;

where a variableDeclarator has the format: fieldName [ dimensionStuff ] [ = expression ]

• Possible fieldModifiers are:– public—this field is accessible from any code.– protected—accessible from code in a subclass (or the same

package—default accessibility).– private—only accessible from code in the same class.– static—this is a class variable: see earlier.– final—this field cannot be modified after it is initialized.– transient—the value of this field will not be included in a seri

alized representation of an instance.– volatile—any cached copy of the field maintained by an indivi

dual thread will be reconciled with the master copy every time the field is accessed.

Page 45: Introduction to the Java Programming Language - Part 2 - Instructor : An, Seung Hun shahn@dcslab.snu.ac.kr * This transparency is based on that made by

Modifiers of Methods• In the abstract, recall, the declaration format is:

methodModifiers returnType methodName (parameter list) [throws exceptionList ] {

declarations and statements}

• Possible methodModifiers are:– public—this method is accessible from any code.– protected—accessible from code in the same package, or a subclass.– private—only accessible from code in the same class.– abstract—the method has no implementation here—declaration has a semic

olon in place of a body.– static—this is a class method: see earlier.– final—this method cannot be overriden: see later.– synchronized—other synchronized methods are locked out while this method

is executing: see later.– native—the implementation of this method is given in a platform-dependent l

anguage. Declaration has a semicolon in place of a body.– strictfp—intermediate results in all float or double expressions appearing in t

he body have strict IEEE 754 exponents.