1 / 45

Introduction to the Java Programming Language - Part 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 G. Fox and B. Carpenter in Florida State University. Java Language Basics. Obvious similarities to C, C++.

Download Presentation

Introduction to the Java Programming Language - Part 2 -

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 G. Fox and B. Carpenter in Florida State University

  2. Java Language Basics

  3. Obvious similarities to C, C++ • Java syntaxhas 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.

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

  5. 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, . . .)

  6. 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 method definition, and describe intended use.

  7. Java Keywords • Java reserves the following keywords: • goto is not allowed in Java, but it’s still reserved! • null, true, and false are literals with special meaning.

  8. 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 the language. • Reference types.These include class types like Color, and array types (and also interface types).

  9. 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 arithmetic and data formats are defined by IEEE 754 standard. • char format is defined by 16 bit Unicode character set. • booleanis eithertrue or false. • One can use casts for arithmetic conversion, as in: int i ; float x ; i = (int) x ;

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

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

  12. 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 neverchange. • In other words: string objects are immutable.

  13. Operations on Strings • Although a String object is immutable, String-valued variables 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.

  14. 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 ;

  15. Subscripts • With states is declared as above: int states[] = new int[128] ; it can be subscripted by integersfrom 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.

  16. 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() ;

  17. 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!

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

  19. Java Language—More Expressions • Java has some expressions of its own: • string concatenation: “fred” + “jim” // Value is “fredjim” • object “instance of” test: (a instanceof B) //true iff object ahas type (class) B

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

  21. 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++ ; } • whileloop with test at end: do { What to do } while (another Boolean) ;

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

  23. Control Flow IV: The switch Construct • Identical to C: switch (expression) { caseConstant1: // Do following if expression==Constant1 Bunch of Stuff break; caseConstant2: // Do following if expression==Constant2 Bunch of Stuff break; default: // Do the following otherwise Bunch of Stuff break; }

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

  25. The Java Object Model: Classes, Instances and Methods

  26. 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). Instance Variables Methods

  27. Defining a Class • A class declaration consists of: • a header giving the class name, modifiers, and possible superclass 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 methods, 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.

  28. 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 ;

  29. Class Variables • Besides instance variables, a class may contain “global variables” that are not associated with any instance. • A class variable (also called a static variable) is flagged by the staticmodifier 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.

  30. Method Definitions • Subprograms in Java are called methods. In the abstract, 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.

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

  32. 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 { //Addsz to the current object public void add(Complex z) { real += z.real ; imaginary += z.imaginary ; } public double real ; public double imaginary ; }

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

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

  35. this • Within an instance method or constructor the keyword thisrefers to the current instance. • i.e. the object on which the method was invoked, or which the 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).

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

  37. 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 thiscannot 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.

  38. 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!

  39. 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 potato”) ; System.out.println(“There are ” + Potato.getNum() + “ potatoes”) ;

  40. 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 an 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.

  41. 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 anywider integer type, (int to long, etc) or from a floatto adouble. • 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 ;

  42. Header of Class Definition—Details • In the abstract, the definition format is: classModifiers class className [ extendssuperclass ] [ implementsinterfaceList ]{ body of class } • The optional extendsand implements clauses will be discussed in detail in later lectures.

  43. Modifiers of Classes • Possible classModifiers are: • public—the class may be used freely by code outside the package. • abstract—the class contains abstract methods without implementation (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 expressions appearing in the class have strict IEEE 754 exponents. • private—only allowed for a nested class. Meaning as for other members. • protected—only allowed for a nested class. Meaning as for other members. • static—only allowed for a nested class. Meaning analogous to other members.

  44. Modifiers of Fields • In the abstract, the declaration format is: fieldModifiers type variableDeclaratorList ; whereavariableDeclarator has the format: fieldName [ dimensionStuff ] [ = expression ] • Possible fieldModifiersare: • 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 serialized representation of an instance. • volatile—any cached copy of the field maintained by an individual thread will be reconciled with the master copy every time the field is accessed.

  45. Modifiers of Methods • In the abstract, recall, the declaration format is: methodModifiers returnType methodName(parameter list)[throwsexceptionList]{ declarations and statements } • Possible methodModifiersare: • 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 semicolon 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 language. Declaration has a semicolon in place of a body. • strictfp—intermediate results in all float or double expressions appearing in the body have strict IEEE 754 exponents.

More Related