Introductory Java 1
Imperative programming languages Java Standard Library
Hello World
Structured Programming 1110/1140/6710
Copyright By PowCoder代写 加微信 powcoder
Introductory Java J1
Structured Programming 1110/1140/6710 32
Introductory Java J1
• Learnmultipleprogrammingparadigms
• Importantexampleof:
– Object-oriented programming
– Large scale programming
– Programming with a rich standard library
Structured Programming 1110/1140/6710 33
Introductory Java J1
Imperative Programming Languages
Declarative
languages describe the desired result without explicitly listing steps required to achieve that goal.
Pure functional
languages, like Haskell, only transform state using functions without side effects.
Programming Languages
Imperative
languages describe computation in terms of a series of statements that transform state.
Object-oriented
languages use structured (procedural) code, tightly coupling data with the code that transforms it.
Declarative
Imperative
Procedural
Object- Oriented
Functional
Logic Programming
Structured Programming 1110/1140/6710 34
Introductory Java J1
Imperative Programming Languages
• Sequence • Selection • Iteration
Object Oriented Programming Languages
• Structuredcode
• Code(behavior)tightlycoupledwithdata(state)thatitmanipulates
Structured Programming 1110/1140/6710 35
Introductory Java J1
The Waterloo Java Visualizer
A great resource. Type in simple Java programs and watch step-by-step execution. A great way to enhance your understanding of a new language.
Structured Programming 1110/1140/6710 36
Introductory Java J1
The Oracle Java Tutorials
This course follows the structure of the Oracle Java Tutorials for the basic introduction to Java.
The tutorials are subject to Oracle’s ‘Java Tutorial Copyright and License’ (Berkeley license).
We will move very fast for the first few weeks. You should use the tutorials to ensure that you rapidly become proficient in the basics of Java.
Structured Programming 1110/1140/6710 37
Introductory Java J1
The Java Standard Library
• The Java language is augmented with a large standard library (.NET does the same for C#)
– IO (accessing files, network, etc.) – Graphics
– Standard data structures
– Much more
• Usingandunderstandingthestandardlibraryispartoflearninga major language like Java or C#.
• Rich standard libraries are a key software engineering tool.
Structured Programming 1110/1140/6710 38
Introductory Java J1
Data types
The type of a unit of data determines the possible values that data may take on.
• Weak v strong
– Must all data be typed? Can types be coerced or converted?
• Static v dynamic
– Is checking done at compile-time or run-time?
Haskell: strong, static
Java: strong, static and dynamic
Structured Programming 1110/1140/6710 39
Introductory Java 2
Types Objects Classes Inheritance
Interfaces
Introduction to Software Systems 1110/1140/6710
Introductory Java J2
Objects combine state and behavior • State: fields (data types)
• Behavior: methods (imperative code)
Example: bicycle
• State: current speed, direction, cadence, & gear • Behavior: change cadence, change gear, brake
Introduction to Software Systems 1110/1140/6710
Introductory Java J2
Aristotle 384-322BC
‘Blood-bearing animals’:
1. Four-footedanimalswithliveyoung, 2. Birds,
3. Egg-layingfour-footedanimals,
4. Whales,
Introduction to Software Systems 1110/1140/6710
Introductory Java J2
A class is a blueprint or ‘type’ for an object
• Instance:oneinstantiationofaclass(akaobject) • Class: blueprint / definition for many instances
Example: bicycle
• Instance: your bike
• Class:KonaJakeTheSnake2012
Introduction to Software Systems 1110/1140/6710
Introductory Java J2
Inheritance
Classes may form a hierarchy
• sub-class:extendsasuper-class
Example: bicycle
• class:KonaJakeTheSnake2012 • super-class:CyclocrossBike • super-class:UprightBike
• super-class:Bike
• super-class:Object
Introduction to Software Systems 1110/1140/6710
Introductory Java J2
Java Interfaces
Methods define behavior
• Aninterfaceisagroupofmethodswithoutimplementations
Example: an interface MovableThing might include: • brake()
• speedup()
Any class that implements MovableThing must include definitions of these methods.
Introduction to Software Systems 1110/1140/6710
Introductory Java 3
Naming Literals Primitives
Structured Programming 1110/1140/6710
Introductory Java J3
Java Modules
• A module is a named group of packages and related resources • Strongencapsulation
• Explicitdependencies
module java.sql {
requires transitive java.logging; requires transitive java.transaction.xa; requires transitive java.xml;
exports java.sql; exports javax.sql;
uses java.sql.Driver; }
Structured Programming 1110/1140/6710
Introductory Java J3
Java Packages
Which Mary?
‘Queen of Scots’ provides a namespace within which ‘Mary’ is well defined. In Java a package provides a namespace.
Structured Programming 1110/1140/6710
Introductory Java J3
Java Variables
• Instance(non-staticfields,object-local)
– Each object has its own version (instance) of the field
• Class(staticfields,global)
– Exactly one version of the field exists
– Temporary state, limited to execution scope of code
• Parameters
– Temporary state, limited to execution scope, passed from one method to another
Structured Programming 1110/1140/6710
Introductory Java J3
Java Naming
• Java names are case-sensitive
– Whitespace not permitted
– $, _ to be avoided
– Java keywords and reserved words cannot be used
• Capitalizationconventions
– Class names start with capital letters (Bike)
– Variable names start with lower case, and use upper case for subsequent words (currentGear)
– Constant names use all caps and underscores (MAX_GEAR_RATIO)
Structured Programming 1110/1140/6710
Introductory Java J3
Java’s Primitive Data Types
In addition to objects, Java has 8 special, built-in ‘primitive’ data types.
Description
8-bit signed 2’s complement integer
-128 – 127
16-bit signed 2’s complement integer
-32768 – 32767
32-bit signed 2’s complement integer
-231 – 231-1
64-bit signed 2’s complement integer
-263 – 263-1
single precision 32-bit IEEE 754 floating point number
double precision 64-bit IEEE 754 floating point number
logically just a single bit: true or false
true, false
16-bit Unicode character
Structured Programming 1110/1140/6710
Introductory Java J3
Java Literals
• When a numerical value (e.g. ‘1’) appears, the compiler normally knows exactly what it means.
• Specialcases:
– An integer value is a long if it ends with ‘l’ or ‘L’
– The prefix 0x indicates hexadecimal, 0b is binary:
• 0x30 // 48 expressed in hex
• 0b110000 // 48 expressed in binary
– An ‘f’ indicates a float, while ‘d’ indicates double.
– Underscores may be used to break up numbers:
• long creditCardNumber = 1234_5678_9012_3456L;
Structured Programming 1110/1140/6710
Introductory Java 4
Arrays, Operators, Expressions Statements, Blocks, Random
Structured Programming COMP1110/6710
Introductory Java J4
Java Arrays
• Arrays hold a fixed number of values of a given type (or sub-type) that can be accessed by an index
• Declaring:
int[] values;
• Initializing:
values = new int[8]; // 8 element array
• Accessing:
int x = values[3]; // the 4th element
• Copying:
System.arraycopy(x, 0, y, 0, 8);
Structured Programming COMP1110/6710
Introductory Java J4
Java Operators
• Assignment
• Arithmetic
+ – ++ — !
• Equality,relational,conditionalandinstanceof == != > >= < <= && || instanceof
~ & ^ | << >> >>>
Structured Programming COMP1110/6710
Introductory Java J4
Expressions
• A construct that evaluates to a single value.
• Madeupof – variables
– operators
– method invocations
• Compoundexpressionsfollowprecedencerules – Use parentheses (clarity, disambiguation)
Structured Programming COMP1110/6710
Introductory Java J4
Statements
• A complete unit of execution.
• Expressionstatements(expressionsmadeintostatementsby terminating with ‘;’):
– Assignment expressions – Use of++or–
– Method invocations
– Object creation expressions
• Declaration statements • Control flow statements
Structured Programming COMP1110/6710
Introductory Java J4
• Zero or more statements between balanced braces (‘{’ and ‘}’)
• Can be used anywhere a single statement can
Structured Programming COMP1110/6710
The Random Class
The Random class provides a pseudo-random number generator:
Random rand = new Random();
You can optionally provide a seed (for determinism):
Random rand = new Random(12345);
You can then generate random numbers of different types:
int i = rand.nextInt(10); // number in 0-9
Structured Programming COMP1110/6710
Control Flow 1
Control flow if-then-else switch
Structured Programming 1110/1140/6710
Control Flow J5
Women workers (‘computers’) in a calculation “factory,” 1930s. Courtesy of the Library of Congress.
Structured Programming 1110/1140/6710
Control Flow J5
Calculating a trajectory could take up to 40 hours using a desk-top calculator. The same problem took 30 minutes or so on the Moore School’s differential analyzer. But the School had only one such machine, and since each firing table involved hundreds of trajectories it might still take the better part of a month to complete just one table. [Winegrad & Akera 1996]
Structured Programming 1110/1140/6710
Control Flow J5
Source: Ad Meskens, WikiMedia Commons
Structured Programming 1110/1140/6710
Control Flow J5
Structured Programming 1110/1140/6710
Control Flow J5
Control Flow
Control flow statements allow the execution of the program to deviate from a strictly sequential execution of statements (‘selection’).
Imperative programming: sequence, selection, iteration.
Structured Programming 1110/1140/6710
Control Flow J5
if-then & if-then-else statements
• The if-then construct conditionally executes a block of code.
• The if-then-else construct conditionally executes one of two blocks of code
Structured Programming 1110/1140/6710
Control Flow J5
The switch statement
• The switch statement selects one path among many.
• Execution jumps to the first matching case.
• Execution continues to the end of the switch unless a break statement is issued.
Structured Programming 1110/1140/6710
Control Flow J5
The switch expression
• Theswitchexpressionselectsonevalueamongmany.
• Execution jumps to the first matching case.
• The value of the expression is given by the yield operator in the matching case.
Structured Programming 1110/1140/6710
Control Flow 2
Control flow
while & do-while for
break, continue, return Structured Programming 1110/1140/6710
Control Flow J6
The while & do-while statements
• Thewhilestatementcontinuouslyexecutesablockwhilea
condition is true.
• Thedo-whileconstructevaluatestheconditionattheendofthe
block rather than at the start.
Imperative programming: sequence, selection, iteration.
Structured Programming 1110/1140/6710 16
Control Flow J6
The for statement
• A compact way to iterate over a set of values.
• The statement has three logical parts: – Initialization
– Termination condition
– Increment statement
• The‘enhanced’forstatementinferstheinitialization,termination and increment statements, given an array or collection
Structured Programming 1110/1140/6710 17
Control Flow J6
Branching statements
• Thebreakstatementterminatesaloopconstruct – Unlabeled terminates the loop in which it is called
– Labeled terminates the loop named by the label
• Thecontinuestatementskipsthecurrentiterationofaloop – Unlabeled skips the current iteration of the loop in which it is called – Labeled skips the current iteration of the loop named by the label
• Thereturnstatementexitsthecurrentmethod
Structured Programming 1110/1140/6710 18
Methods Parameters Return values
Structured Programming 1110/1140/6710
Methods J7
• Asubroutine
– Reusable code to perform a specific task – Modularity, encapsulation
• Maytakearguments(parameters) • May return a value
Structured Programming 1110/1140/6710 22
Methods J7
Method Declaration
Method declarations will have the following, in order: • Anymodifiers(public,private,etc.)
• return type
• methodname
• parameters,inparentheses
• Anyexceptionsthemethodmaythrow
• The method body (code)
class String {…
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {…}
Structured Programming 1110/1140/6710 23
Methods J7
Class and Instance methods
A method declared with the static modifier is a class method (otherwise it is an instance method)
• Class methods
– May operate on class fields only
• Instancemethods
– May operate on class and instance fields
Structured Programming 1110/1140/6710 24
Methods J7
Parameters (method arguments)
Parameters are the mechanism for passing information to a method or constructor.
• Primitive types passed by value
– Changes to parameter are not seen by caller
• Reference types passed by value
– Changes to the reference are not seen by caller – Changes to object referred to are seen by caller
• Your last parameter may in fact be more than one parameter (varargs), and treated as an array
Structured Programming 1110/1140/6710 25
Methods J7
Returning a Value from a Method
The return statement exits the current method Methods return to caller when:
• all statements in method executed, or
• areturnstatementisreached,or
• the method throws an exception (later) Methods declared void do not return a value.
All other methods must return a value of the declared type (or a subclass of the declared type, described later).
Structured Programming 1110/1140/6710 26
Nested Classes
Nested classes
Structured Programming 1110/1140/6710
Nested Classes J8
Nested Classes
A class may be defined within another class. Such a class is called a nested class. The main motivation for nested classes is to improve encapsulation and clarity.
• Static nested classes (use static keyword) behave as if declared elsewhere, but happen to be packaged together in a single file, cannot refer directly to instance fields of parent
• aninnerclass(non-static)hasdirectaccesstotheinstancefields and members of its enclosing class.
Structured Programming 1110/1140/6710 7
Lambda Expressions
Structured Programming 1110/1140/6710
Lambda Expressions J9
Lambda Expressions
From Java version 8, lambda expressions allow code to be passed as a parameter, just like data.
• Particularlyusefulforeventhandling;canpassbehaviorasan argument (‘do this when x happens’).
– Comma-separated formal parameters (x)
– Arrow (->)
– Body (either single expression or statement block, which may contain return)
x -> x > 100 or x -> { … return true; }
Structured Programming 1110/1140/6710
Lambda Expressions J9
Functional Interfaces
A lambda expression implements a functional interface: an interface which only defines a single method.
Commonly-used functional interfaces are defined in package
java.util.function, e.g.
public interface IntPredicate { boolean test(int value);
public interface DoubleSupplier { double getAsDouble();
Structured Programming 1110/1140/6710
Number, Autoboxing
Number, Integer, Short, Float, etc Autoboxing
Structured Programming 1110/1140/6710
Number J10
The Number Classes
Normally you will represent numbers with the primitive types int, short, float, etc. Java includes ‘boxed’ object analogues to each of these: Integer, Short, Float, etc.
• Number classes have methods (primitives don’t) – toString(), parseInt(), etc.
• Numberclasseshaveconstants
– Integer.MIN_VALUE, Short.MAX_VALUE, etc
• Number classes have a space overhead – They are instantiated as true objects
Structured Programming 1110/1140/6710
Autoboxing J10
Autoboxing
Classes such as Integer and Character are ‘boxed’ versions of the primitive types int and char (i.e. object versions of the primitives). Java offers automatic support for boxing and unboxing.
• Boxing:Integeri=5; • Unboxing: int j = i;
Structured Programming 1110/1140/6710
The Math class
The Math class contains methods and constants useful for basic mathematics:
• Constants:Math.PIandMath.E
• Trigonometry:sin(),cos(),etc.
• Rounding:abs(),ceil(),floor(),etc.
• Comparisonfunctions:max(),min()
• Exponentials and logs: exp(), log(), pow(), etc.
• Randomnumbergeneration:random()
Structured Programming 1110/1140/6710
Character and String
Character and String
Structured Programming 1110/1140/6710
Character and String J11
The Character Class
The Character class boxes char, just as Integer boxes int. It contains methods and constants useful for manipulating characters:
• Propertymethods:isLetter(),isDigit(),etc. • Conversion: toString() (a single character string!)
Escape sequences are used to represent characters that have a special meaning in Java syntax:
• \’,\”,\\,\n, etc.
Structured Programming 1110/1140/6710 11
Character and String J11
The String Class
The String class is provided by Java to store and manipulate strings
(by contrast, in C, a string is simply an array of characters). • Implicit creation from literal:
String x = “foo”; • Concatenation with “+”:
String y = x + “bar”; • StringBuilder class
Structured Programming 1110/1140/6710 12
Character and String J11
Operations on Strings
• Getlength(numberofcharacters):
if (x.length() > 3) … • GetacharacterwithcharAt()
• Getasubstringwithsubstring()
• Others: split(), trim(), toLowerCase(), etc. • Finding:indexOf(),contains(),etc.
• Replacing: replace(), replaceAll(), etc.
Structured Programming 1110/1140/6710 13
Structured Programming 1110/1140/6710
Generics J12
Sometimes it is useful to parameterize a class with a type, T.
Rather than IntContainer, LongContainer, etc. we can just write Container
We can also create generic methods that accept type parameters:
static
Prior to the introduction of Java generics, programmers often used Object as a work-around as it can refer to any non-primitive type.
Structured Programming 1110/1140/6710 17
Type Inference
Generic Type Inference Lambda Expressions Local Variables
Structured Programming 1110/1140/6710
Type Inference J13
Type Inference
The Java compiler can infer many types from context, cutting down on boilerplate code.
Instantiating generic classes:
LinkedList
public
Structured Programming 1110/1140/6710 22
Type Inference J13
Local Variables
With the var keyword, Java can infer the type of a local variable from its initialization expression.
The most specific type is inferred.
var theAnswer = 42;
var bike = new Bike();
var mystery; // invalid – no initializer
var nothing = null; // invalid – null has no type
Structured Programming 1110/1140/6710 23
Type Inference J13
Lambda Expressions
Types of parameters to lambda expressions: Predicate
However, can’t infer the type of a lambda expression:
var lambda = x -> x + 1; // invalid – what type is x?
var lambda = (int x) -> x + 1; // invalid – what is lambda? IntFunction lambda = (int x) -> x + 1; // OK
Structured Programming 1110/1140/6710 24
Collections
The Collections Framework forEach
Ordering Collections
Structured Programming 1110/1140/6710
Collections J14
The Collections Framework
• Interfaces
– Implementation-agnostic
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com