Download Java Programming

Document related concepts
no text concepts found
Transcript
Java Language
Java Basics
1
Java is Familiar, Simple & Small
 Java is familiar because it looks like C/C++. Having Java
retain the “look and feel” of C/C++ enables programmers
to migrate easily.
 Java is simple and small (there are only 49 keywords in
Java). This is because Java removes many of the complex,
redundant, dubious and error-prone features of C/C++,
such as pointer, multiple inheritance, operator overloading,
memory management (malloc, free), preprocessor
(#define, typedef, header files), struct, union, enum,
goto, automatic coercions, and etc.
The number of language constructs you need to
understand to get your job done in Java is minimal.
2
A First Program in Java
1
2
3
4
5
6
7
8
9
10
11
12
13
// Fig. 2.1: Welcome1.java
// Text-printing program.
public class Welcome1 {
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1
3
Compile and execute
4
Statements
 A single statement ends with a semi-colon ‘;’, just like
C/C++.
 A block statement consists of many statements surrounded
by a pair of braces {statement(s)} as in C/C++.
// Declaration statements
int score;
boolean validScore;
// Assignment statements
score = 70;
validScore = true;
// Conditional if statement
if ((score < 0) || (score > 100)) {
validScore = true;
System.out.println("valid score");
}
5
Comments
 Multi-line comments: begin with /* and end with */ (like
C/C++). Eg:
/* I learn Java
because I’ve been told that
Java is Kool!
*/
 Single-line comments: begin with // and end at the end-
of-line (like C++).
int len = 5; // Declare, init len to 5
len = 10;
// Set len to 10
6
Variables (or Fields)
 Variables are “typed” and must be declared with a type
and a name (like C/C++) as follows:
Type
String
int
double
boolean
Name;
myName;
myAge;
myWeight;
isMarried;
//
//
//
//
"Tan Ah Teck"
18
103.33
false or true
 Java is case sensitive!!!!!!
A rose is NOT a Rose and is NOT a ROSE
 Variable Naming Convention: nouns, made-up of
several words. First word is in lowercase and the rests are
initial capitalized. Eg. thisIsALongVariableName.
 The type can either be a build-in primitive type (eg. int,
double) or an object class (eg. String, Circle).
7
Primitive Data Types
Type
Meaning
byte
8-bit signed integer
short
16-bit signed integer
int
Integer
64-bit signed integer
long
float
32-bit signed integer
Floating point
(IEEE 754 spec)
32-bit single precision
null
64-bit double precision
16/32-bit “Unicode” character for “Internationalization”
(Unlike C/C++, which uses 8-bit ASCII code)
Logical of either “true” or “false”
(In C/C++, integer 0 for false, non-zero for true)
null pointer, no storage allocated.
void
Return type for methods: returns nothing
double
char
boolean
8
Assignment, Increment/Decrement
 Examples:
i = 4;
x = y = z = 0;
x += y;
x *= y;
x++;
--x;
//
//
//
//
same
same
same
same
as
as
as
as
x
x
x
x
=
=
=
=
x
x
x
x
+
*
+
-
y;
y;
1;
1;
 What is the difference between:
y = x++;
y = ++x;
9
Operators - Arithmetic & Comparison
Operator
+
*
/
%
==
!=
<
>
<=
>=
Meaning
addition
subtraction
multiplication
division
modulus (reminder)
equal
not equal
less than
more than
less than or equal to
more than or equal to
Example
3 + 4 (=7)
6 - 4 (=2)
3 * 5 (=15)
9 / 2 (=4)
9 % 2 (=1)
1==2 (false)
1!=2 (true)
1<2 (true)
1>2 (false)
1<=2 (true)
1>=2 (false)
10
Operators - Arithmetic
Operator
Meaning
Example
+
addition
3 + 4 (=7)
-
subtraction
6 - 4 (=2)
*
multiplication
3 * 5 (=15)
/
division
9 / 2 (=4)
%
modulus (remainder)
9 % 2 (=1)
11
Arrays
 An array is a list of elements of the same type.
 Identified by a pair of square brackets [ ].
 Must be declared with a type and a name.
 Storage must be allocated using operator new or during
initialization. E.g.,
int[] temps; // Declare an int array temps
int temps[]; // Same as above
temps = new int[5];
// Allocate 5 items
// Declare & allocate array in one statement,
// initialize to default value.
int[] temps = new int[5];
// Declare, allocate & initialize an array
int[] temps = {1, 2, 3, 4, 5};
12
Array (cont.)
First Index
Index: 0
1
2
Last Index
3
n-1
arrayName
length
n
13
Arrays (cont.)
 Array index begins with 0 (like C/C++) and must be of type
int, e.g.,
temps[4] = temps[2];
 The length of array is kept in an associated variable called
length and can be retrieved using dot ‘.’ operator.
int[] temps = new int[5]; // 5-item array
int len = temps.length;
// len = 5
(How to find the array length in C?)
 Build-in array bounds check: index out-of-bound triggers an
ArrayIndexOutOfBoundsException at runtime. (Software
Engineering more important than execution speed!)
 Multidimensional arrays, eg,
int[][] matrix = new int[10][10];
14
Flow Control - Conditional
 if: if (booleanExpression) trueCase
if (x < y) System.out.println("x < y");
 if-else: if (booleanExp) trueCase else falseCase
if (x == 0) {
System.out.println("x is 0");
} else {
System.out.println("x is not zero");
x = 0;
// set it to zero
}
15
Flow Control - Conditional (cont.)
 switch-case (Selection)
switch (theOperator) { // type char or int
case('+'):
result = x + y;
break;
case('-'):
result = x - y;
break;
default:
System.out.println("unknown operator");
}
16
Flow Control - Loop
 for: for (initialization; test; increment) statements
int[] temps = new int[5];
for (int i=0; i<temps.length; i++) {
System.out.println(temps[i]);
}
 while: while (booleanExpression) trueCase
int[] temps = new int[5];
int i=0;
while (i < temps.length) {
System.out.println(temps[i]);
i++;
}
17
Flow Control - Loop (cont.)
 do-while: do trueCase while (booleanExpression)
int[] temps = new int[5];
int i=0;
do {
System.out.println(temps[i]);
i++;
} while (i < temps.length);
 What is the difference between while and do-while?
 break: break and exit the innermost loop.
 continue: abort the current iteration and continue to the
next iteration of the loop.
18
Class String
is a sequence of 16-bit Unicode characters
enclosed with a pair of double quotes (" "), eg.
 String
"Hi, I'm a string!"
""
// single quote OK
// an empty string
 A Java String is NOT an array of characters (unlike
C/C++), but an object class. (Classes and OOP will be
covered later).
 Need to use the escape sign (\) for special characters such
as new-line (\n), tag (\t), double-quote (\"), backslash
(\\), carriage-return (\r), form-feed (\f), Unicode
character (\uhhhh), e.g.,
"A \"string\" nested inside a string."
"Hello, \u4f60\u597d!"
// 4f60H & 597dH are Unicode
 Single-quote (') does not require escape sign.
19
String Concatenation – ‘+’ operator
 You can use operator plus ‘+’ to concatenate multiple
Strings together into a longer String.
 ‘+’ is the only overloaded operator in Java. Overloading
means different actions will be taken depending on the
operands given to the ‘+’ operator. For example,
•1 + 2 is 3 (int + int gives int)
•1.0 + 2.1 is 3.1 (double + double gives double)
•1.1 + 2 is 3.1 (double + int: the int will be promoted to
double, resulted in double + double gives double)
•"Hello " + "world" is "Hello world" (String +
String: concatenate two Strings and give a String)
•"Hello " + 5 is "Hello 5" (String + int: the int will
be converted to String, and the two Strings concatenated)
•"Hello " + 1.1 is "Hello 1.1" (String + double: the
double will be converted to String, and the two Strings
concatenated)
20
String Concatenation Example
String str1 = "Java is hot!";
// String literal in common pool
String str2 = new String("I'm kool!");
// new String object in heap
int len;
System.out.println(str1 + " and " + str2);
// Gives "Java is hot! and I'm kool!"
len = str1.length();
// Get the length of str1
System.out.println("Counted " + len
+ " characters.");
// Gives "Counted 12 characters."
// int len is converted to String
// automatically.
21
Class String - Examine strings
 Methods to examine String (refer to Java API):
int length();
String substring(int startIdx, int endIdx);
char charAt(int index);
int indexOf(char leftMostChar);
int lastIndexOf(char rightMostChar);
boolean endsWith(String rightMostSubstring);
String str = "Java is cool!";
str.length();
// return
str.charAt(2);
// return
str.substring(0, 3);
// return
str.indexOf('a');
// return
str.lastIndexOf('a'); // return
str.endsWith("cool!"); // return
int 13
char 'v'
"Jav"
1
3
true
22
Class String - Conversion
is a class in java.lang.String. Many useful
methods (or functions) provided in class String for
manipulating strings (see Java API). (We will discuss
classes & methods later in OOP).
 Converting a String to other primitive types:
 String
int
float
long
double
 Converting
String
String
String
String
anInt
aFolat
aLong
aDouble
=
=
=
=
Integer.parseInt(aStr);
Float.parseFloat(aStr);
Long.parseLong(aStr);
Double.parseDouble(aStr);
a primitive type to String:
str
str
str
str
=
=
=
=
Integer.toString(anInt);
Long.toString(aLong);
Float.toString(aFloat);
Double.toString(aDouble);
23
Type Casting for Primitives
 Any numeric type (integer and floating point) can be cast
(transformed) to anther type, but some precision may be
lost. For example:
double f = 3.5;
int i;
i = (int) f;
f = (double) i;
// i = 3, cast optional
// f = 3.0, cast required
 Java prohibits C/C++ style of “automatic type coercions”.
Explicit casting is needed if type conversion would result in
a loss of precision, e.g., from int to double.
24
Exercise 4d: Command-line Arguments
 You can supply command-line arguments when invoking an
application. For example,
> java Arithmetic 1234 456 +
Command-line Arguments
 In Java, command-line arguments are packed into a
String array and passed into the main(String[] args)
method, as the sole parameter args.
 In the above example, the 3 String arguments "1234",
"456" and "+" are packed into a String[], where:
•args.length is 3
// Length of the array args
•args[0] is "1234"
// Item 0 of the array
•args[0].length() is 4 // Length of String of Item 0
•args[1] is "456"
// Item 1 of the array
•args[1].length() is 3 // Length of String of Item 1
25
Exercise 4e: Inputs From Keyboard
import java.io.*;
public class NumberGuess {
public static void main(String[] args)
throws IOException {
int numberIn;
String inStr;
// Chain the System.in to a Reader and buffered.
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// Read the guess
System.out.print("Enter your guess: ");
inStr = in.readLine(); // return input String
numberIn = Integer.parseInt(inStr);
...
26
Java Language
Object-Oriented Programming
(OOP)
27
Object-oriented Programming (OOP)
 Objects are reusable software components that model
items in the real world, e.g., student, car, rectangle,
computer, purchase order etc.
 OOP Analogy 1: PC = motherboard + CPU + monitor +
hard disk + ... To assemble a PC, you need not understand
each part in depth or how the parts are manufactured, but
merely the interfaces between parts. You can build the
part by yourself or get it off the shelve.
 OOP Analogy 2: LOGO set.
 OOP Analogy 3: A car is made up of engine, transmission,
body etc. Do you have to know the details of the engine to
drive the car?
 Objects are like “software” ICs (Integrated Circuits).
 Question: How to program a soccer computer game?
28
Why OOP?
 Modular and reusable software components.
No need to re-invent the wheel!
 Enable programmer to think of program element as real
world objects, and model them accordingly.
 More productive in software development.
 Ease in software maintenance.
“SOFTWARE ENGINEERING”
 OOP is in contrast to “Procedural Programming” (in C,
Pascal, Basic), and was adopted in C++, Java, C#.
 Procedural Programming forces the programmers to think
in terms of machine's bits and bytes, object-oriented
programming lets the programmers to think in the problem
space.
29
Class & Instance
 A class is a definition, implementation, template, or
blueprint of “objects of the same kind”.
 An instance is a “concrete realization” of a particular item
of a class. An instance of class is referred to as an object.
 Example:
• class: Student
• instances: “Tan Ah Teck”, “Mohammed Ali”, “Raja Kumar”.
30
Class
 A class has 3 components:
1. Name (Identity): a unique identifier.
2. Variables (state): static properties, attributes, state, data.
Java API docs call fields.
3. Methods (behavior): dynamic behaviors. Also called
function, procedure or operation.
Name
Student
Circle
Variables
(or Fields)
id=1888
radius=1.4
name="Tan Ah Teck"
color="red"
(or Attributes)
...
Methods
getName()
(or operations) printGrades()
...
...
getRadius()
computeArea()
...
31
Encapsulation
 A class in a self-contained 3-compartment box of name,
variables and methods.
 A class encapsulates variables (static attributes) and
methods (dynamic operations) inside a 3-compartment
box. The variables and methods are intimately tied
together.
 Procedural language like C is made up of functions. Data
are separated from the functions (in the header files and
global variables). Procedural language components are
hard to reuse in a new application.
 OOP program is made up of classes, which are selfcontained and encapsulate both the data and methods.
You can reuse OOP classes in a new application easily.
32
Class Declaration - Examples
public class Circle {
private double radius;
private String color;
// class name
// variables
public double computeArea() {...}
public double getRadius() {...}
//methods
}
public class Student {
private int id;
private String name;
// class name
// variables
public String getName() {...}
// methods
public void printGrades() {...}
}
33
Class Naming Convention
 Class Naming Convention: nouns, in mixed case with
the first letter of each internal word capitalized, e.g.,
RasterImage, PrintStream.
34
Creating Instances of a Class
 To create an instance of a class:
1. Declare a name of the instance, belonging to a particular
class.
2. Allocate storage for the instance using the new operator.
// 1. Declare 3 instances of class Circle.
Circle c1, c2, c3;
//
c1
c2
c3
2.
=
=
=
Allocate using new, with different initial constructions.
new Circle();
new Circle(2.0);
new Circle(3.0, "red");
Circle c4 = new Circle();
// Combine declare & allocate in one statement, same as:
//
Circle c4;
//
c4 = new Circle();
35
Dot Operator
 To refer to the variables and methods of an object, use dot
‘.’ operator, e.g.,
// Declare & allocate an instance of class Circle.
Circle c1 = new Circle();
// Invoke methods of the class using dot operator.
c1.getRadius();
c1.computeArea();
// Modify public variables with dot operator.
c1.radius = 5.0;
c1.color = "green";
Math.PI
// Constant PI in class Math.
36
Methods (Dynamic Behaviors)
 Methods receive arguments (or parameters), perform some
operations and return a single result (or void i.e.,
nothing).
 You have been using main() method, which is a public
method accessible by all classes, takes an array of String
(command-line arguments) as argument, performs the
operations specified in the method's body, and return void
(or nothing) to the caller.
public static void main (String[] args) {
...method's body...
}
37
Method (cont.)
 Method naming convention: verbs, in mixed case with
the first letter lowercase and the first letter of each internal
word capitalized. E.g., getBackground(), setColor().
 Examples:
public double computeArea () {
return radius*radius*Math.PI;
}
38
Constructor Methods
 A constructor is a special method that shares the same
name as the class in which it is defined.
 Constructor is to initialize the instance variables of an
object when a new object is first instantiated.
 Constructor has no return type (or implicitly return void).
Hence, no return statement is needed in the body of
constructor.
39
OOP Basics - Example
 A class called Circle is declared with:
• 3 constructor methods,
• 2 private variables radius (double), color (String)
• 3 public methods getRadius(), getColor(), computeArea().
Three instances of the class c1, c2 and c3 are to be created in
another class called TestCircle.
Circle
double radius
String color
getRadius()
getColor()
computeArea()
Class
C1:Circle
radius=2.0
color="blue"
methods
C2:Circle
radius=2.0
color="red"
C3:Circle
radius=1.0
color="red"
methods
Instances
methods
40
public class Circle {
private double radius;
private String color;
// private variables
public Circle ()
{ radius=1.0; color="red" }
// constructors
// overloading
public Circle (double r)
{ radius=r; color="red" }
public Circle (double r, String c)
{ radius=r; color=c }
public double getRadius ()
{ return radius; }
// assessor methods
public String getColor ()
{ return color; }
public double computeArea ()
{ return radius*radius*Math.PI; }
}
41
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle(2.0, "blue");
System.out.println(
"Radius = " + c1.getRadius()
+ " Color = " + c1.getColor()
+ " Area = " + c1.computeArea());
Circle c2 = new Circle(2.0);
System.out.println(
"Radius = " + c2.getRadius()
+ " Color = " + c2.getColor()
+ " Area = " + c2.computeArea());
Circle c3 = new Circle();
System.out.println(
"Radius = " + c3.getRadius()
+ " Color = " + c3.getColor()
+ " Area = " + c3.computeArea());
}
}
42
Method Overloading
 More than one methods may share the same name as long
as they may be distinguished either by the number of
parameters, or the type of parameters. E.g.,
int average(int n1)
{ return n1; }
int average(int n1, int n2)
{ return (n1+n2)/2; }
int average(int n1, int n2, int n3)
{ return (n1+n2+n3)/3; }
average(1)
average(1, 2)
average(1, 2, 3)
// A
// B
// C
// Use A, returns int 1
// Use B, returns int 1
// Use C, returns int 2
43
Access Control
 Access-control modifiers are used to control the
accessibility (or visibility) of the variables/methods by other
classes.
•public: accessible by any class.
•private: accessible only from within the same class.
 Examples:
private double radius; // Within the class only
public int count;
// Accessible by all classes
44
Information Hiding
 Variables are usually hidden from outside class, with
modifier private.
 Access to the variables is provided through the public
accessor's methods defined in the class, e.g., getName(),
getRadius(), comupteArea().
 In the previous exercise, can you change the radius with
c1.radius=2.0? How to change the radius?
 Objects communicate with each others using well-defined
interfaces, objects are not allowed to know how the other
objects are implemented – implementation details are
hidden within the objects themselves.
 Rule of thumb: Don't make any variable public without
good reason.
45
Get and Set Methods
 To allow others to read the value of a private variable,
the class can provide a “get” method (or accessor
method). A get method need not expose data in the raw
format. It can edit the data and limit the view of the data
others will see.
 To enable others to modify a private variable, the class
can provide a “set” method (or mutator method). A set
method can provide data validation (such as range
checking), or translate the format of data used inside the
class to another format used by outsiders.
46
Inheritance
 Classes are organized in strict hierarchy. The classes in the
lower hierarchy inherit all the variables (attributes) and
methods (behaviors) from the upper hierarchy, e.g.,
Student
Undergraduate
Yr 1
Yr 2
Circle
radius
color
Cylinder
radius
color
height
Graduate
Yr 3
Yr 4
47
Superclass and Subclass
 The existing class is called superclass (or parent class, base
class). The class derived is called subclass (or child,
extended, derived class).
 In Java, each class has one and only one superclass. Each
superclass can have one or many subclasses.
 Java does not support multiple inheritance (i.e., multiple
parents) as in C++.
 Subclass is not a “subset” of superclass. In fact,
subclass usually contains more detailed information
(variables and methods) than its superclass.
 To define a subclass, use extends operator:
class UnderGraduate extends Student {...}
class Cylinder extends Circle {...}
class MyApplet extends java.applet.Applet {...}
48
Inheritance - Example
 In this exercise, a subclass called
Cylinder is derived from
superclass Circle as shown.
Figure out how the subclass
Cylinder uses the superclass’s
constructors (thru the super()
method) and inherits variables
and methods from its superclass
Circle.
Re-use the Circle class defined
in the earlier exercise.
Superclass
Circle
double radius
String color
getRadius()
getColor()
computeArea()
Subclass
Cylinder
double height
getHeight()
computeVolume()
49
public class Circle {
private double radius;
// private variables
private String color;
public Circle ()
// constructors
{ radius=1.0; color="red" } // overloading
public Circle (double r)
{ radius=r; color="red" }
public Circle (double r, String c)
{ radius=r; color=c }
public double getRadius () // assessor methods
{ return radius; }
public String getColor ()
{ return color; }
public double computeArea ()
{ return radius*radius*Math.PI; }
}
50
public class Cylinder extends Circle {
private double height;
public Cylinder () {
super();
// call superclass Circle()
height = 1.0;
}
public Cylinder (double r, double height) {
super(r);
// call superclass Circle(r)
this.height = height;
// “this” class
}
public double getHeight () {
return height;
}
public double computeVolume () {
return computeArea()*height;
}
}
51
public class TestCylinder {
public static void main (String[] args) {
Cylinder c1 = new Cylinder();
System.out.println("Radius=" + c1.getRadius()
+ " Height=" + c1.getHeight()
+ " Base area=" + c1.computeArea()
+ " volume=" + c1.computeVolume());
// Methods getRadius() and computeArea()
// inherited from superclass Circle
Cylinder c2 = new Cylinder(5.0, 2.0);
System.out.println("Radius=" + c2.getRadius()
+ " height=" + c2.getHeight()
+ " base area=" + c2.computeArea()
+ " volume=" + c2.computeVolume());
}
}
52
super and this
 Keywords this can be used to refer to a variable/method
in this class, or to call another constructor of the same
class. “this” is useful in resolving naming conflict
between local variables and instance variables. E.g.,
public class Circle {
private int radius;
public Circle (int radius)
{ this.radius = radius; }
}
 Keyword super can be used to refer to a variable/method
of the superclass, or to call a constructor of the superclass
within the subclass’s constructor (via super(...)).
53
Method Overriding
 You can override a method inherited from the superclass by
providing your implementation in the subclass. When an
instance of the subclass calls this method, the method in
the subclass will be invoked instead of the one in the
superclass.
 Exercise: Try overriding the method computeArea() of
class Cylinder to compute the surface area of the
Cylinder instead of the base area as in its superclass
Circle.
You can still invoke the Circle’s computeArea(), instead
of the overridden one in the subclass Cylinder by calling
super.computeArea().
54
Packages
 A package is a collection of classes (like libraries).
 Provide a convenient way to organized classes. Eg, you can
put the classes that you developed in packages, and
distribute the packages.
 To “locate” a class from a package other than java.lang,
use import statement, eg,
import java.applet.Applet
// import class Applet from package java.applet
import java.awt.Graphic
// import class Graphic from package java.awt
import java.awt.*
// import all classes from package java.awt
// (Abstract Windowing Toolkit)
55
Java API Packages
 java.lang: contains core Java classes such as System,
String,Integer. Implicitly imported into every Java
program. (i.e. No import needed).
 java.awt: Abstract Windowing Toolkit, contains classes
for GUI components such as Button, TextField, Choice,
Label.
 java.awt.event: for handling events in GUI.
 java.applet: for supporting Java applets.
 java.io: for input and output streams and files
 java.sql: for accessing relational databases.
 java.util: utility such as date, vectors, hashing.
 java.net: for networking.
 many many others.
56