0% found this document useful (0 votes)
25 views

Object-oriented Programming Language (JAVA) : 李建欣 (Jianxin Li)

Uploaded by

creation portal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Object-oriented Programming Language (JAVA) : 李建欣 (Jianxin Li)

Uploaded by

creation portal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Object-oriented Programming

Language (JAVA)
(面向对象程序设计)

李建欣(Jianxin Li)
[email protected]
School of Computer,
Beihang University

© Beihang University
Chapter 2 Review
Object
Class
Inheritance
Interface

2
© Beihang University
Exercise
extends
implements

Fields:
Shape public float area;

extends

triangle rectangle ellipse

3
© Beihang University
Chapter-3

Java Language Basic

4
© Beihang University
programming language

A programming language is an artificial language


designed to communicate instructions to a machine,
particularly a computer. Programming languages can be
used to create programs that control the behavior of a
machine and/or to express algorithms precisely.

A programming language is usually split into the two


components of syntax (form) and semantics (meaning).
Some languages are defined by a specification document
(for example, the C programming language is specified by
an ISO Standard),

5
© Beihang University
Agenda

Identifier, Keyword, Data type


Operator
Statements, and Control Flow
Statements
Array

6
© Beihang University
Identifier
Identifier Convention
The name of variable, class, method (function)
A variable's name can be any legal identifier — an
unlimited-length sequence of Unicode letters and
digits, beginning with a letter, the dollar sign "$", or the
underscore character "_".
Variable names are case-sensitive
E.g.,
Value
VAlue
userName
userPassword

7
© Beihang University
Try to write down some variables!
Some variables declaration

public int xxx123;


public String USERNAME;
public float float;
public String anameofuserid;

Please help me to declare some variable names


public int ? //a loop counter number
public String ? // a user name for web
public float ? //the speed of a bicycle
speed
public String ? Userid? userID?

8
© Beihang University
Some Conventions
The rules and conventions for naming your variables can be
summarized as follows:
The convention, however, is to always begin your
variable names with a letter, not "$" or "_". Additionally,
the dollar sign character, by convention, is never used at
all.
When choosing a name for your variables, use full words
instead of cryptic abbreviations. Doing so will make
your code easier to read and understand. In many cases it
will also make your code self-documenting; fields named
cadence, speed, and gear, for example, are much more
intuitive than abbreviated versions, such as s, c, and g.
Also keep in mind that the name you choose must not
be a keyword or reserved word

9
© Beihang University
Some Conventions
If the name you choose consists of only one word, spell
that word in all lowercase letters. If it consists of more than
one word, capitalize the first letter of each subsequent
word. The names print, gearRatio and currentGear are
prime examples of this convention.
 If your variable stores a constant value,
such as static final int NUM_GEARS = 6,
the convention changes slightly, capitalizing every letter and
separating subsequent words with the underscore character.

10
© Beihang University
Keywords

http://en.wikipedia.org/wiki/List_of_Java_keywords

11
© Beihang University
Primitive Data Types
The Java programming language is strongly-typed,
which means that all variables must first be declared
before they can be used. This involves stating the
variable's type and name.
Four types
Logical type
boolean
Character type
char
Integer type
byte, short, int, long,
Floating type
float, double

12
© Beihang University
Logical type
Boolean
 The boolean data type has only two possible values:
true and false.
Use this data type for simple flags that track true/false
conditions. This data type represents one bit of
information.

13
© Beihang University
Character Type
Char
The char data type is a single 16-bit Unicode
character.
 It has a minimum value of '\u0000' (or 0) and a
maximum value of '\uffff' (or 65,535 inclusive).
One useful class: String
Java programming language also provides special support for
character strings via the java.lang.String class.
 Enclosing your character string within double quotes will
automatically create a new String object;
for example, String s = "this is a string"; String objects are
immutable, which means that once created, their values cannot be
changed.
Notice: The String class is not technically a primitive data type
14
© Beihang University
Integer Type

type length range

byte 8 bits -27 ~27-1


short 16 bits -215 ~215-1
int 32 bits -231 ~231-1
long 64 bits -263 ~263-1

15
© Beihang University
Floating Type
Float
The float data type is a single-precision 32-bit floating
point
float x=1.2;
Double
The double data type is a double-precision 64-bit
floating point
double x=1.212321;

16
© Beihang University
Default Value

17
© Beihang University
Summary

18
© Beihang University
Declarations

int index = 1.2; // compiler error


boolean retOk = 1; // compiler error
double fiveFourths = 5 / 4; //no error!
float ratio = 5.8; // correct
double fiveFourths = 5.0 / 4.0; // correct
1.2f is a float value accurate to 7 decimal places.
1.2 is a double value accurate to 15 decimal places.

19
© Beihang University
Assignment

All Java assignments are right associative


int a = 1;
int b = 2;
int c = 5;
a = b = c;
System.out.print(“a= “ + a + “b= “ + b + “c= “ + c);

What is the value of a, b & c


Done right to left: a = (b = c);

20
© Beihang University
A class example
public class Date{
private int day;
private int month;
private int year;
void setDate( int a, int b, int c){... }
}

A new type can been created based on a class

21
© Beihang University
Declaration and Reference for Variables

A class member is declared, it only can been


referred after it been instantiation (initialization).
The memory is default allocated when a
primitive data type is declared.
e.g., int a;
 a=5;
Non-primitive data type
Only reference memory is allocated, not data
memory. The data memory is allocated when used
new keyword.
String userName= new String();

22
© Beihang University
Declaration and Reference for Variables

EXAMPLE:1 Date today;


2 today = new Date( );

today 0xabcd

0xabcd
day 0
month 0
year 0

23
© Beihang University
Reference Assignment

1 Date a, b ;
2 a=new Date( );
3 b=a;

0xabcd
a 0xabcd
0 day
0 month
b 0xabcd
0 year

24
© Beihang University
Agenda

Identifier, Keyword, Data type


Operator
Statements, and Control Flow
Statements
Array

25
© Beihang University
Operators
Now that we can learn how to declare and initialize
variables, you probably want to know how to do
something with them.
Learning the operators of the Java programming
language is a good place to start.

26
© Beihang University
Operators Table

27
© Beihang University
Operators Table

28
© Beihang University
Summary of Operators
Arithmetic Operators
+,-,*,/, %, ++, - -
Equality and Relational Operators
>, >=, < <=, ==, !=
Bitwise and Bit Shift Operators
>>, <<, >>>, & , |, ^,~
~ Unary bitwise complement
 << Signed left shift
 >> Signed right shift
 >>> Unsigned right shift
& Bitwise AND
 ^ Bitwise exclusive OR
| Bitwise inclusive OR

29
© Beihang University
Summary of Operators (cont.)
Conditional Operators
&& Conditional-AND
|| Conditional-OR
Assignment Operator
=, +=, -=, *=, /=, %=,&=, |=, ^=, <<=,
>>=, >>>=
Type Comparison Operator
instanceof Compares an object to a specified type
Other Operators
?: , [], . , ( ),(type), new,
D

30
© Beihang University
Arithmetic Operator

String salutation = “Dr. ”;


String name = “Pete ” + “Seymour” ;
String title = salutation + name ;

So the value of title is:Dr. Pete Seymour

31
© Beihang University
Bitwise Operator Example

32
© Beihang University
What is the Java equivalent of unsigned

to store an unsigned int, we would use a Java long;


to store an unsigned byte, we could use any other integer
type, but an int is generally convenient (it is likely to give
faster arithmetic);
if we want an unsigned long, we may be a bit stuck,
although we could use a BigInteger object.

C/C++ Java
unsigned byte b = ...; int b = ...;
b += 100; b = (b + 100) & 0xff;

unsigned int v = ...; long v = ...;


v *= 2; v = (v * 2) & 0xffffffff;

33
© Beihang University
Agenda

Identifier, Keyword, Data type


Operator
Statements, and Control Flow
Statements
Array

34
© Beihang University
Statements & Blocks

A simple statement is a command terminated by a


semi-colon:
name = “Fred”;
A block is a compound statement enclosed in brace:
{
name1 = “Fred”;
name2 = “Bill”;
{
statement;
}
}
Blocks may contain other blocks

35
© Beihang University
Flow of Control
Java executes one statement after the other in the
order they are written
Many Java statements are flow control statements:
Alternation: if, if else, switch
Looping: for, while, do while
jump: break, continue, return

36
© Beihang University
IF-THEN-ELSE
if (<condition expression>)
<statement 1>;
else
<statement2>;

37
© Beihang University
IF…ELSE Example
int temperature = 35;
if (temperature>35){
System.out.println(“It’s too hot!”);
System.out.println(“I want to go home!”);
}
else
{
System.out.println(“Have a nice day.”);
System.out.println(“Let’s stay here.”);
}

38
© Beihang University
Nested If statements
If (<condition expression1>)
{…
if (<condition expression 2>)
<statement 2>;

}

39
© Beihang University
While
Format:

while (<condition expression>)


<statement>;
Notice:when <condition expression> is true, the
<statement> will be executed until <condition
expression> is false.

40
© Beihang University
while Statement
public class WhileDemo {
public static void main(String[] args) {

String copyFromMe = "Copy this string until you " +


"encounter the letter 'g'.";
StringBuffer copyToMe = new StringBuffer();

int i = 0;
char c = copyFromMe.charAt(i);
Results:
while (c != 'g') {
copyToMe.append(c); Copy this strin
c = copyFromMe.charAt(++i);
}
System.out.println(copyToMe);
}
}

41
© Beihang University
do-while Statement
public class DoWhileDemo {
public static void main(String[] args) {

String copyFromMe = "Copy this string until you " +


"encounter the letter 'g'.";
StringBuffer copyToMe = new StringBuffer();

int i = 0;
char c = copyFromMe.charAt(i);
Results:
do {
copyToMe.append(c); Copy this strin
c = copyFromMe.charAt(++i);
} while (c != 'g');
System.out.println(copyToMe);
}
}
42
© Beihang University
Jump statement
break
Jump from switch, loop statements
Continue
Jump from the following parts of the loop
statement

43
© Beihang University
Examples

1 Loop: while (true){


2 for( … ){
3 switch( ){
4 case -1:
5 case ‘\n’:
6 break loop ;
7 …
8 }
9 }
10 }
11 test: for( … ){
12 …
13 while(… ){
14 if( …){
15 …
16 continue test ;
17 }
18 }
19 }
44
© Beihang University
Identifier, Keyword, Data type
Operator
Statements, and Control Flow
Statements
Array

45
© Beihang University
Array

Declaring a Variable to Refer to an Array


Creating, Initializing, and Accessing an Array
Copying Arrays

46
© Beihang University
Array
An array is a container object that holds a fixed
number of values of a single type.
The length of an array is established when the
array is created. After creation, its length is fixed.
You've seen an example of arrays already, in the
main method of the "Hello World!" application.

47
© Beihang University
Array Example
An array of ten elements
Each item in an array is called an element, and
each element is accessed by its numerical index. As
shown in the above illustration, numbering begins
with 0.
The 9th element, for example, would therefore be
accessed at index 8.

48
© Beihang University
Declaring a Variable to Refer to an Array

As with variables of other types, the declaration


does not actually create an array — it simply tells the
compiler that this variable will hold an array of the
specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
char[] anArrayOfChars;
String[] anArrayOfStrings;

49
© Beihang University
Creating, Initializing an Array

Int[] anArray;
anArray = new int[10]; // create an array of integers If
this statement were missing,
The next few lines assign values to each element of
the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
Alternatively, you can use the shortcut syntax to
create and initialize an array:
String names[ ] = { “Jack”, “Wang”, “Lee”};
int a[ ] = {1, 2, 3};
Date d[] = { new Date( ), new Date( ), new Date( )} 50
© Beihang University
Object Array Demo
public class ArrayOfStringsDemo {
public static void main(String[] args) {
String[] anArray = { "String One", "String Two",
"String Three" };
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i].toLowerCase());
}
}
}

51
© Beihang University
Multidimensional Array
Declaration
 int a[ ][ ]; 或int [ ][ ] a;
Instance
a = new int[4][4]; //allocate a square array
a = new int[4][ ]; // the latter dimension is not given
a[0] = new int[10] ;
a[1] = new int[5];
…
Get the length of array
 a = new int [10][12];
 a.length = 10 ;
 a[0].length = 12 ;
52
© Beihang University
Example of Multidimensional Array

public class ArrayOfArraysDemo2 {


public static void main(String[] args) {
int[][] aMatrix = new int[4][];
//populate matrix
for (int i = 0; i < aMatrix.length; i++) {
aMatrix[i] = new int[5]; //create sub-array
for (int j = 0; j < aMatrix[i].length; j++) {
aMatrix[i][j] = i + j; }
}
//print matrix
for (int i = 0; i < aMatrix.length; i++) {
for (int j = 0; j < aMatrix[i].length; j++){
System.out.print(aMatrix[i][j] + " "); }
System.out.println(); }
}
}
53
© Beihang University
Copying Arrays

If an array is created, the length of this array is unvarying,


But an existing array can point to a new array, and the
original information will be lost;
int a[ ] = new int[6];
a = new int[10] ; // no need to redeclare a new array
array variable assignment is reference assignment.
1 int a[ ] = new int [6];
2 int b[ ]; a
3 b=a; b

54
© Beihang University
Copying Array Function
Array copying function
System.arrayCopy(Object source, int srcIndex,
Object dest, int destIndex,
int length)

55
© Beihang University
Copying Array Demo

public class ArrayCopyDemo {


public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n',
'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}

56
© Beihang University
Results
Results:

57
© Beihang University
Exercise (for everyone)

1. Writing a program to output followings:


1
12
123
1234
12345
123456
2. The results?

58
© Beihang University
Following Lessons
Chapter4
Java OOP Features
Chapter 5

59
© Beihang University

You might also like