Sie sind auf Seite 1von 28

Java Programming 2

Lecture #2
Mary Ellen Foster
MaryEllen.Foster@glasgow.ac.uk
25 September 2019

Image: “Juice Fruit Juice Green Juice”


From http://all-free-download.com/ Public domain
Schedule for Weeks 1—3
Wednesday 25 September (Today): Lecture
Thursday 26 September: Lab 1 distributed (by end of day)
Friday 27 September: Lecture in tutorial time slot (Friday 1pm)
Monday 30 September: Lecture
Monday 30 September/Tuesday 1 October: Lab 1 in scheduled lab session
Wednesday 2 October: Lecture
Thursday 3 October: Lab 1 due; Lab 2 distributed
Friday 4 October: Tutorial
Week 3 (7—11 October): Plans to be confirmed
Outline for today
Lab logistics
Java primitive types
Java identifiers
Identifier scope
Simple for and while loops in Java
Details of lab exercises (revisited)
Weekly – beginning in Week 2, based on previous week’s lectures
Each exercise is worth 4% of your final grade – mark will be based on best 5 exercises (of 8)
Schedule:
Lab distributed through Moodle on or before Thursday evening in week N-1
Lab is due (through Moodle) on Thursday 5pm in week N
Solutions discussed in Friday tutorial in week N
You may submit work that is incorrect or incomplete
In order to stretch the stronger members of the class, some of the laboratory exercises are
quite challenging …
… so don’t worry if you can’t complete all of them.
You should spend around 3 hours per week on programming exercises
Lab marking
Marking will be on a 5-point scale (“Excellent *****” … “Very poor *”)
We expect most students to get **** or *** most of the time
***** is reserved for flawless submissions (code correctness, formatting,
comments, …)
If you get a ** or *, please seek help ASAP (from me and/or lab tutor)
Tutors will also give general feedback on submissions – if you want more details,
please ask
We will give feedback on each submitted lab within 1-2 weeks
Avoiding excessive collaboration*
Every resource you use (except JP2 slides/sample code) must be noted in comments
Visits to StackOverflow, conversations with friends in same lab, conversations with a
tutor, …
You may ask help from a peer, but you should not look at each others’ code, and the
person being asked for help should not outline their own solution
You should not include any code into your lab that you don't fully understand.
Labs are meant to be learning experiences, and you must complete the lab exam by
yourself at the end of the course!
We will run similarity checking software on all of your submitted code
(… and then use our judgement to determine whether similarity is problematic)
* Adapted from https://cseducators.stackexchange.com/a/4285
Lab computer details
Computers in the labs are running Windows 10
For this course, you will be using OpenJDK 12 and Eclipse 2018-12
https://jdk.java.net/13/ (Java 13 is identical to Java 12 for our purposes)
https://www.eclipse.org/downloads/eclipse-packages/ (latest version is fine)
… however
We will not use Eclipse until after we have introduced objects
For now, we use JShell + your favourite text editor to work on Java
Lab sheet will explain how to launch and use JShell
(If you want to use Eclipse already, you can …)
IGNORE EVERYTHING I SAID IN LECTURE
ABOUT LAB LOCATIONS
All labs are in the Library – either Jura or Islay (check your timetable)
Exception: Labs 13 and 14 are in Boyd Orr 715
Back to our regularly
scheduled programming
Producing output in Java
System.out.println()
Prints the string and moves to the next line
System.out.print()
Prints the string and does not move to next line
Combining multiple arguments: use +
System.out.println("Hello" + " " + "world");
int i = 3;
System.out.println("The number is " + i);
Primitive types in Java
“Primitive?”
Built into the language
Cannot be decomposed into simpler
components
Not a class
(technical) Variables of this type hold
the value, not a reference
See also:
http://programmers.stackexchange.com
/questions/139747/what-is-meant-by-a-
primitive-data-type
Image of a horse from the Lascaux caves.
https://commons.wikimedia.org/wiki/File:Lascaux2.jpg
List of Java primitive types
Type Description Min value Max value Default
value
byte 8-bit signed integer value -128 127 0
short 16-bit signed integer value -32,768 32,767 0
int 32-bit signed integer value -231 231 - 1 0
long 64-bit signed integer value -263 263 - 1 0L
float 32-bit single precision IEEE 754 floating point value 2-149 (2-2-23)·2127 +0.0F
double 64-bit double precision IEEE 754 floating point value 2-1074 (2-2-52)·21023 +0.0
boolean Boolean value (true/false) n/a n/a false
char 16-bit Unicode character value \u0000 (0) \uffff (65,535) \u0000
(use single quotes – e.g., ’c’)
What about strings?
Technically, Java strings are of type java.lang.String which is an object (not
primitive)
However, the Java language has special support for strings
E.g., you can create a new one by using double quotes
String s = “This is a string”;
Also, they are immutable (will be explained later in the course)
So you will probably often tend to think of them as primitive – just don’t forget that
they are not!
Declaring a variable
Java is statically typed Variable can be declared and initialised in
one statement, or separately
So types of all variables must be int i;
declared i = 5;
Local variables: int j = 4, k = 6, m;
int i;
Class fields:
Variable must have a value before it is
class C { boolean b; }
used
boolean b;
Method parameter and return values System.out.println (”Value of b: ” + b);
public float getValue (long
l) { … }
Error! (OK
in jshell
though)
A note on integers
An integer literal value can be expressed in
Decimal (default) – base 10 15
Octal (leading 0) – base 8 017 All the same number
Hexadecimal (leading 0x) – base 16 0xF
They can be printed in these different bases using System.out.printf() with
the %d, %o, and %x format specifiers
Primitive wrapper classes
Every primitive type has an associated wrapper class
So you can treat them as objects if necessary (relevant later)
Primitive Wrapper
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Useful operators for primitive types
Assignment = (single equals sign)
int i = 5;
Equality comparison == (two equals signs), != (not equal to)
if (i == 5) { … }
if (j != 5) { … }
Relational operators <, >, <=, >=
Boolean combinations && (and), || (or)
Special considerations for String:
use .equals() instead of ==
relational operators are not relevant
Identifiers
Identifiers in Java
An identifier is the label for a named Java entity
Class, field, method, parameter, local variable, …
There are both rules and conventions for identifiers
Rules: follow them or the compiler will be unhappy
Conventions: follow them or your tutors and fellow programmers will be unhappy
Identifier rules
Must begin with a letter or an underscore (“_”)
Must be at least one character long
Other characters may be letters, numbers, or underscores
Since Java supports Unicode, “letters” are not restricted to a-z and A-Z

Please do not do this!

http://rosettacode.org/wiki/Unicode_variable_names#Java
Identifier conventions
Standards and guidelines can differ on the details
Near-universal conventions
Classes start with a capital letter
Other identifiers start with a lower-case letter
Multi-word identifiers use “CamelCase”
ArrayIndexOutOfBoundsException
Constant values are written in ALL CAPS
Math.PI, Double.POSITIVE_INFINITY
Identifier scope
Block of statements is enclosed in System.out.print("2+1=");
curly braces { } int two = 2, three = two + 1;
Usually all statements in a block System.out.println(three);
have same indentation level
Unlike Python, this is not mandatory – ➢ 2+1=3
but strongly recommended!
A variable is in scope (accessible) …
From the point of declaration …
To the end of the enclosing block

Java Language Specification, Java SE Edition


Sharing the same name
No two local variables or method class a {
parameters can have the same a a(a a) {
name in a given scope a:
Local variables can have the same name for(;;) {
as method parameters (watch out!)
if (a.a(a) == a)
Variables can have the same name break a;
as a package, type, method, field, }
or statement label return a;
}
} Please do not do this either!
Java Language Specification, 2nd edition, p. 113
Methods
(OO term for what Python calls “functions”)
Details of Java methods
A method declaration has six components (in order):
1. Access modifier(s) (zero or more – details later)
2. Return type (void if it does not return a value)
3. Method name (conventionally beginning with a verb)
Method
4. Parameter list in parentheses – comma delimited list of input parameters, signature
preceded by data type, enclosed in parens. No parameters – empty parens.
5. An exception list (more on this in a few lectures)
6. The method body, enclosed in braces { }
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) {
//do the calculation here
}
More on methods
To return from a method, use return statement
Multiple return statements are possible!
But be sure to return the correct type
It is possible to have two methods with the same name as long as they have different
parameter lists (this is called overloading)
double doSomething(int a, int b) {
if (a > b) { double doSomething(double a) {
return a;
} else { return 0 – a;
return b; }
}
}
Next time (Friday!)
Loops in Java
Switch statements
Advanced loop control
Type conversions
Constant values
Integer division
Writing good comments

Das könnte Ihnen auch gefallen