0% found this document useful (0 votes)
21 views24 pages

2-Introduction To Java - Version 1.0 - 2016-12-01

Uploaded by

khuubaolong2k3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views24 pages

2-Introduction To Java - Version 1.0 - 2016-12-01

Uploaded by

khuubaolong2k3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

1/16/2017

Principles of Software Construction


(NGUYÊN LÝ XÂY DỰNG PHẦN MỀM)

Software Engineering Dept., CICT,


Cantho Unversity
Lecturer: Trương Minh Thái
email: [email protected]
Phần dành cho đơn vị

Contents

• Introduction to Java
• Object-Oriented Programming in Java
• Specification and Testing

1
1/16/2017

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

2
1/16/2017

The simplest program in java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello world!");
}
}

Complication 1: you must use a class even


if you aren’t doing OO programming

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello world!");
}
}

3
1/16/2017

Complication 2: main must be public


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

Complication 3: main must be static


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

4
1/16/2017

Complication 4: main must return void


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

Complication 5: main must declare command line


args even if unused
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

5
1/16/2017

Compile and execute a Java program

• First you compile the source file


– javac HelloWorld.java
– Produces class file HelloWorld.class
• Then you launch the program
– java HelloWorld
– Java Virtual Machine (JVM) executes main
method
• Managed runtime has many advantages
– Safe, flexible, enables garbage collection

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

6
1/16/2017

Java type system has two parts

Primitive data type summary

• int 32-bit signed integer


• long 64-bit signed integer
• byte 8-bit signed integer
• short 16-bit signed integer
• char 16-bit unsigned character
• float 32-bit IEEE 754 floating point number
• double 64-bit IEEE 754 floating point number
• boolean Boolean value: true or false

7
1/16/2017

The class hierarchy

• The root is Object (all non-primitives are objects)


• All classes except Object have one parent class
– Specified with an extends clause
class Guitar extends Instrument { ... }
– If extends clause omitted, defaults to Object
• A class is an instance of all its super classes Object

Implementation inheritance

• A class:
– Inherits visible fields and methods from its
superclasses
– Can override methods to change their behavior
• Overriding method implementation must obey
contract(s) of its superclass(es)
– Ensures subclass can be used anywhere
superclass can
– Liskov Substitution Principle (LSP)

8
1/16/2017

Liskov Substitution principle (LSP)

Methods that use references to the base classes


must be able to use the objects of the derived
classes without knowing it
Barbara Liskov in 1988
• The idea here is that the subtypes must be
replaceable for the super type references
without affecting the program execution

Liskov Substitution principle (LSP)

9
1/16/2017

Interface types

• Defines a type without an implementation


• Much more flexible than class types
– An interface can extend one or more others
– A class can implement multiple interfaces
interface Comparable {
/**
* Returns a negative number, 0, or a positive number as this
* object is less than, equal to, or greater than other.
*/
int compareTo(Comparable other);
}

Enum types

• Java has object-oriented enums


• In simple form, they look just like C enums:
public enum WeekDay { MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
• But they have many advantages!
– Compile-time type safety
– Multiple enum types can share value names
– Can add or reorder without breaking existing uses
– High-quality Object methods are provided
– Screaming fast collections (EnumSet, EnumMap)
– Can iterate over all constants of an enum

10
1/16/2017

Enum types

package Myjavaenum;

public class CompareEnumDemo {

public static void main(String[] args) {

WeekDay today = WeekDay.SUNDAY;

// Sử dụng toán tử == để so sánh 2 phần tử của Enum.


if (today == WeekDay.SUNDAY) {
System.out.println("Today is Sunday");
}
}
}

Boxed primitives

• Containers for primitive types


Boolean, Integer, Short, Long, Character, Float,
Double
• Lets you “use” primitives in contexts requiring
objects
• Don't use boxed primitives unless you have to!
• Language does autoboxing and auto-unboxing

11
1/16/2017

Autoboxing and Unboxing

• Autoboxing is the automatic conversion that


the Java compiler makes between the primitive
types and their corresponding object wrapper
classes.
Character ch = 'a';

List<Integer> li = new ArrayList<>();


for (int i = 1; i < 50; i += 2)
li.add(i); Run time code

List<Integer> li = new ArrayList<>();


for (int i = 1; i < 50; i += 2)
li.add(Integer.valueOf(i));

Autoboxing and Unboxing

• Converting an object of a wrapper type


(Integer) to its corresponding primitive
(int) value is called unboxing
Integer i = new Integer(-8);

// 1. Unboxing through method invocation


int absVal = absoluteValue(i);
System.out.println("absolute value of " + i + " = " + absVal);

List<Double> ld = new ArrayList<>();


ld.add(3.1416); // Π is autoboxed through method invocation.

// 2. Unboxing through assignment


double pi = ld.get(0);
System.out.println("pi = " + pi);

12
1/16/2017

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

Output

• Unformatted
System.out.println("Hello World");
System.out.println("Radius: " + r);
System.out.println(r * Math.cos(theta));
System.out.println();
System.out.print("*");
• Formatted
System.out.printf("%d * %d = %d%n", a, b, a * b);

13
1/16/2017

Command line input example

class Echo {
public static void main(String[] args) {
for (String arg : args) {
System.out.print(arg + " ");
}
}
}

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various

Command line input with parsing

class InputParse{
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
….
}
}

14
1/16/2017

Scanner input

• A Scanner breaks its input into tokens using a delimiter


pattern, which by default matches whitespace. The
resulting tokens may then be converted into values of
different types using the various nextmethods.
• Read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
• Read a number from file:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}

Scanner input

• Counts the words on standard input


class Wc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long result = 0;
while (sc.hasNext()) {
sc.next(); // Swallow token
result++;
}
System.out.println(result);
}
}
$ java Wc < Wc.java
32

15
1/16/2017

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

Primary collection interfaces

A Collection represents a group of objects known as its elements.

A Map is an object that


maps keys to values.

A Queue is a collection
Lists may contain for holding elements
duplicate prior to processing
A Set is elements
a Collection that
cannot contain A deque is a double-ended-queue, it is a
duplicate elements. linear collection of elements that supports
the insertion and removal of elements at
both end points

16
1/16/2017

Primary collection interfaces

Primary collection interfaces

17
1/16/2017

Set example

• Squeeze duplicate words out of command line


public class Squeeze {
public static void main(String[] args) {
Set<String> s = new LinkedHashSet<>();
for (String word : args)
s.add(word);
System.out.println(s);
}
}
$ java Squeeze I came I saw I conquered

[I, came, saw, conquered]

Print unique words in lexicographic


order

public class Lexicon {


public static void main(String[] args) {
Set<String> s = new TreeSet<>();
for (String word : args)
s.add(word);
System.out.println(s);
}
}
$ java Lexicon I came I saw I conquered
[I, came, conquered, saw]

18
1/16/2017

Map Example

• Print index of first occurrence of each word


class Index {
public static void main(String[] args) {
Map<String, Integer> index = new TreeMap<>();
// Iterate backwards so first occurrence wins
for (int i = args.length - 1; i >= 0; i--) {
index.put(args[i], i);
}
System.out.println(index);
}
}
$ java java Index if it is to be it is up to me to do it
{be=4, do=11, if=0, is=2, it=1, me=9, to=3, up=7}

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

19
1/16/2017

Methods common to all objects

• How do collections know how to test objects for


equality?
• How do they know how to hash and print them?
• The relevant methods are all present on Object
– equals - returns true if the two objects are “equal”
– hashCode - returns an int that must be equal for
equal objects
– toString - returns a printable string representation

Object implementations

• equals(Object o) - returns true if o refers to this


object
• hashCode() - returns a near-random int that
never changes over the object lifetime
• toString() - returns a nasty looking string
consisting of the type and hash code
For example: java.lang.Object@659e0bfd

20
1/16/2017

Overriding Object implementations

• No need to override equals and hashCode if


you want identity semantics
– When in doubt, don't override them
– It's easy to get it wrong
• Nearly always override toString
– println invokes it automatically

Overriding toString

final class PhoneNumber {


private final short areaCode;
private final short prefix;
private final short lineNumber;
...
@Override public String toString() {
return String.format("(%03d) %03d-%04d",
areaCode, prefix, lineNumber);
}
}
PhoneNumber Tom = ...;
System.out.println(Tom);
Prints: (071) 383-5309

21
1/16/2017

Overriding equals

• Overriding equals is tricky – here’s the contract


• The equals method implements an equivalence relation. It is:
– Reflexive: For any non-null reference value x, x.equals(x) must
return true.
– Symmetric: For any non-null reference values x and y,
x.equals(y) must return true if and only if y.equals(x) returns true.
– Transitive: For any non-null reference values x, y, z, if
x.equals(y) returns true and y.equals(z) returns true, then
x.equals(z) must return true.
– Consistent: For any non-null reference values x and y, multiple
invocations of x.equals(y) consistently return true or consistently
return false, provided no information used in equals comparisons
on the objects is modified.
– For any non-null reference value x, x.equals(null) must return
false.

Overriding hashCode

• Overriding hashCode also tricky – here’s contract


– Whenever it is invoked on the same object more than once during an
execution of an application, the hashCode method must consistently
return the same integer, provided no information used in equals
comparisons on the object is modified. This integer need not remain
consistent from one execution of an application to another execution
of the same application.
• If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
• It is not required that if two objects are unequal according to the
equals(Object) method, then calling the hashCode method on each of
the two objects must produce distinct integer results. However, the
programmer should be aware that producing distinct integer results for
unequal objects may improve the performance of hash tables.

22
1/16/2017

Contents

• Introduction to Java
– Hello World!
– The type system
– Quick ‘n’ dirty I/O
– Collections
– Methods common to all Objects
• Object-Oriented Programming in Java
• Specification and Testing

23
1/16/2017

24

You might also like