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

04 MoreOnJava Part2

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)
18 views

04 MoreOnJava Part2

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

More on Java - Part 2

Object-Oriented Programming
Outline
■ Input/Output
■ Command-line parameters
■ Packages
■ Default and Static methods of Interfaces
■ final keyword
■ Lambda and Streams

Đại học Công nghệ - ĐHQG HN More on Java 2


Input / output

■ Details:
❑ Head First Java. Ch. 16

■ In this slide:
❑ standard input / output stream

❑ simple imput / output

❑ simple text file input / output

Đại học Công nghệ - ĐHQG HN More on Java 3


Standard I/O

■ Three stream objects automatically created when a Java


program begins executing:
❑ System.out : standard output stream object

■ normally enables a program to output data to the console


❑ System.err : standard error stream object
■ normally enables a program to output error messages to the
console
❑ System.in : standard input stream object
■ normally enables a program to input bytes from the keyboard

■ Redirect at command line (input and output stream only):


C:\> type input.dat | java AJavaProgram > output.dat

Đại học Công nghệ - ĐHQG HN More on Java 4


Standard output and error streams

■ System.out and System.err can be used directly


❑ System.out.println("Hello, world!");

❑ System.err.println("Invalid day of month!");

Đại học Công nghệ - ĐHQG HN More on Java 5


Standard input

■ System.in
❑ An InputStream object

❑ must be wrapped before use

■ Scanner: wrapper that supports input of primitive types and


character strings
❑ next(): get the next word separated by white spaces

❑ nextInt(), nextDouble(),…: get the next data item

❑ hasNext(), hasNextInt(), hasNextDouble(),…: check if there

are data left to be read

Đại học Công nghệ - ĐHQG HN More on Java 6


Standard input. Example
// import the wrapper class
import java.util.Scanner;
...
// create Scanner to get input from keyboard
Scanner input = new Scanner( System.in );

// read a word
String s = sc.next());

// read an integer
int i = sc.nextInt();

// read a series of big intergers


while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}

Đại học Công nghệ - ĐHQG HN More on Java 7


Import required
classes
Input from a text file. Example
import java.util.Scanner;
import java.io.FileInputStream; To deal with errors such
import java.io.IOException; as file-not-found
...
public static void main(String args[]) {
try {
// create Scanner to get input from a file stream
Scanner sc = new Scanner(new FileInputStream("test.dat"));

String s = sc.next()); // read a word


int i = sc.nextInt(); // read an integer
while (sc.hasNextLong()) { // read a series of big intergers
long aLong = sc.nextLong();
}
Open and close
the text file
sc.close();

} catch(IOException e) {
e.printStackTrace();
}
}
...
Đại học Công nghệ - ĐHQG HN More on Java 8
Write to a text file. Example
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
...
public static void main(String args[]) {
int i = 1; long l = 10;
try {
// create a printwriter to write output to a file stream
PrintWriter out = new PrintWriter(new FileWriter("test.data"));

// write to file
out.println("Hello " + i + " " + l);

out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
...

Đại học Công nghệ - ĐHQG HN More on Java 9


Command-line parameters

//CmdLineParas.java: read all command-line parameters


public class CmdLineParas {
public static void main(String[] args)
{
//display the parameter list
for (int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
}
C:\>java CmdLineParas hello world
hello
world

Đại học Công nghệ - ĐHQG HN More on Java 10


Package: Declaration
■ a package statement appears as the first
non-comment in the file

package declaration with package


name.
The rest of the file belongs to the same
// HelloMsg.java package
package hanv;

public class HelloMsg {


public void sayHello() {
System.out.println("Hello, world!");
}
}
Declared as public so that
they can be used outside package hanv

Đại học Công nghệ - ĐHQG HN More on Java (cont.) 11


Package: Usage
■ Two ways:
1. Use the import statement
//Hello.java to make the name(s) in the
package available, once for
import hanv.HelloMsg;
all

public class Hello {


public static void main(String[] args) {
HelloMsg msg = new HelloMsg();
msg.sayHello(); 2. Give the fully qualified
} name at every call
} //Hello.java
public class Hello {
public static void main(String[] args) {
hanv.HelloMsg msg = new hanv.HelloMsg();
msg.sayHello();
}
}
Đại học Công nghệ - ĐHQG HN More on Java (cont.) 12
Package – Compile and run
■ Compile
javac HelloMsg.java –d <class_root_dir>
javac Hello.java

■ Run
java Hello

Đại học Công nghệ - ĐHQG HN More on Java (cont.) 13


public

Package – make it simple


■ Where to put source files?
❑ C:\java root directory
❑ C:\java\hanv classes in hanv package

■ Compile: stay at the root!


❑ C:\java\> javac hanv\HelloMsg.java
❑ equivalent to javac hanv\HelloMsg.java –d .
❑ or javac hanv\HelloMsg.java –d c:\java

❑ C:\java\> javac Hello.java

■ Run
❑ C:\java\> java Hello
❑ C:\java\> java hanv.HelloMsg (if HelloMsg is a program)

Đại học Công nghệ - ĐHQG HN More on Java (cont.) 14


Interface - default methods
interface Vehicle {
String getBrand();
String speedUp();
String slowDown(); public static void main(String[] args) {
default String turnAlarmOn() { Vehicle car = new Car("BMW");
return "Alarm on."; System.out.println(car.getBrand());
System.out.println(car.speedUp());
}
System.out.println(car.slowDown());
default String turnAlarmOff() { System.out.println(car.turnAlarmOn());
return "Alarm off."; System.out.println(car.turnAlarmOff());
} }
}
public class Car implements Vehicle {
private String brand;

public String getBrand() {


return brand;
}
public String speedUp() {
return "The car is speeding up.";
}
public String slowDown() {
return "The car is slowing down.";
}
15
}
Interface - default methods
public class Addition
interface Expression {
implements BinaryExpression
double evaluate();
{
String convertToString();
private Expression left, right;
}
public Expression getLeft() {
return left;
interface BinaryExpression }
extends Expression
{ public Expression getRight() {
Expression getLeft(); return right;
Expression getRight(); }
default String convertToString() { public String getOperator() {
return getLeft() + return "+";
" " + getOperator() + " " + }
getRight() + " = " +
evaluate(); public double evaluate() {
} return left.evaluate() + righ
}
String getOperator(); ...
}
default methods can call instance methods
16
Default methods - multi-inheritance?

(interface) (interface)
BinaryExpression Foo

default default
convertToString() convertToString()

BinaryFoo

BinaryFoo binaryFoo = new BinaryFoo(); which version to use?


System.err.print(binaryFoo.convertToString());

17
Default methods - multi-inheritance?

(interface) (interface)
BinaryExpression Foo

default default
convertToString() convertToString()

BinaryFoo

convertToString()

have to
public String convertToString() { implement and specify
return BinaryExpression.super.convertToString() which version to use
+ Foo.super.convertToString();
}
18
Interface - static method

interface Vehicle {
...
static int getHorsePower(int rpm, int torque) {
return (rpm * torque) / 5252;
}
}

Vehicle.getHorsePower(2500, 480);

This function
- cannot access instance variables/method
- can be called from anywhere, just like a class’ static function

19
Abstract classes vs. Interfaces

Abstract classes can have constructors and states


Interfaces can’t

20
Immutable data types

String: immutable
should use for Key types in data structures
StringBuilder, StringPrinter: mutable

Immutables: Integer, Double, Character….

21
final instance variables

final variables cannot be modified once assigned.


■ to create immutable data types
■ to stop unintended changes of states
■ help improve security
■ must be initialized at declaration points or in a
constructor

public class Number {


final double value;
public Number(double v) {
value = v;
value = v + 1; //compile-error
}

22
final instance method

final instance method cannot be overriden


■ to prevent subclasses change a behavior
■ help improve security

public class Car {

private String brand;

public final String getBrand() {


return brand;
}
...
public class Taxi extends Car {
public String getBrand() {
return "Taxi";
}

23
final class

final class cannot have subclasses


■ for classes that are intended to be used as is and
should not be modified or extended
■ help improve security

final class Taxi extends Car {...}

public class TaxiSpecial extends Taxi {...}

24
Streams - motivation

loops
■ are used all over the place
■ tedious to write and error-prone
Common tasks on a collection of data:
- sort
- take only the top k items and ignore the rest
- ignore duplicated items
- ignore items that don’t match certain criteria
- map each item to something else to continue work on it
- sum
- grouping by certain key and make a map
- …

25
Stream API

26
Example

27
01 Source

Str
ea
m
Zero or more
intermediate operations
m
ea
Str

01 terminal operation

28
01 Source

Zero or more
intermediate operations

01 terminal operation

29
Stream pipeline
List<String> strings = Arrays.asList(
"I", "am", "a", "list", "of", "Strings", "Z");
List<String> result = strings.stream()
.sorted((s1, s2) -> s1.compareToIgnoreCase(s2))
.skip(2)
.limit(4)
.collect(Collectors.toList());
System.err.print("result = " + result);

("I", "am", "a", "list", "of", "Strings", "Z")


=> ("a", "am", "I", "list", "of", "Strings", "Z")
=> ("a", "am", "I", "list", "of", "Strings", "Z")
=> ("a", "am", "I", "list", "of", "Strings", "Z")
=> ["I", "list", "of", "Strings"]

30
Stream pipeline
List<String> strings = Arrays.asList(
"I", "am", "a", "list", "of", "Strings", "Z");
List<String> result = strings.stream()
.sorted((s1, s2) -> s1.compareToIgnoreCase(s2))
.skip(2)
.limit(4)
.collect(Collectors.toList());
System.err.print("result = " + result);

("I", "am", "a", "list", "of", "Strings", "Z")


=> ("a", "am", "I", "list", "of", "Strings", "Z")
=> ("a", "am", "I", "list", "of", "Strings", "Z")
=> ("a", "am", "I", "list", "of", "Strings", "Z")
=> ["I", "list", "of", "Strings"]

Nothing is done until the terminal operation!

31
forEach()
List<String> strings
= Arrays.asList("I", "am", "a", "list", "of", "Strings");

for (String string : strings) {


System.err.print(string);
}

strings.forEach(s -> System.err.print(s));

strings.stream()
.sorted((s1, s2) -> s1.compareToIgnoreCase(s2))
.skip(2)
.limit(4)
.forEach(s -> System.err.print(s));

32
Lambda Expression - Functional Interface

....forEach(s -> System.err.print(s));

33
Lambda Expression - Comparator Interface

34

You might also like