Download Document

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Big Java Chapter 4
Number types (chapter 4.1)
 So far, we have been using two types for numbers; int for integer
numbers, and double for decimal numbers
 These are two examples of so-called primitive types – types which
are not classes
 Variables of a primitive type are not references to objects, they are
represented “directly” in the variable
 In general, we have a total of eight primitive types in Java





Four primitive types for integer numbers:
byte: uses a single byte, range is -128 to 127 (28)
short: uses two bytes, range is -32768 to 32767 (216)
int: uses four bytes, range is (about) -2*109 to 2*109 (232)
long: uses eight bytes, range is (almost) -1019 to 1019 (264)
 Two types for decimal numbers:
 float: uses four bytes, range is 1038, 7 significant decimals
 double: uses eight bytes, range is 10308, 15 significant decimals
 char: For representing characters, uses 2 bytes
 boolean: Representing true or false, uses a single bit (in theory)
 Choice of correct type may matter in cases where very large – or
small – numbers are used for calculation
 In principle best to choose the smallest possible type, but unless we
use millions of numbers, hardly a problem (unless we work on a very
special platform)
Big Java Chapter 4
Number types (chapter 4.1)
 Overflow – when we try to put a value into a numeric variabke,
which is outside the range of the value.
 This is not reported!!
 Order of numeric operations may matter, watch out for successive
multiplications – divide when possible
 If we run into problems, we can switch to a long, or perhaps use
decimal numbers?
 Rounding errors may occur when using decimal types – it is
impossible to represent all fractional values precisely
 This is why we sometimes see results like 4.40000000001
 Printing of decimal numbers can be controlled by using formatting
strings, specifying the number of decimals
 Conversion between integer and decimal values is possible, by using
a cast operation
 Casting a decimal number to an integer will throw away some
information, namely the fractional part
 Cast syntax: (typeName)expression
 Example: int valueAsInt = (int)valueAsDouble;
 If this is not acceptable, use Math.round(value) instead
 For special purposes, we have two classes for handling big numbers
available: BigInteger and BigDecimal
 These types are classes, and we cannot apply normal arithmetic
operations to them
 Advantage: can handle almost infinitely large numbers with almost
infinite precision
 Drawback: Very slow, and cannot use standard arithmetic
Big Java Chapter 4
Constants (chapter 4.2)
 A constant is value which never changes!
 Why do we need constants in a Java program? To represent some
constant value once by a symbolic name, instead of writing that
value in various places in the code
 Easier to understand the code, and easier to change the value if
needed (only need to change the value one place)
 Avoid so-called “magic numbers” in your code!
 A constant is represented just like a variable, and can have the same
primitive types
 However, we use a slightly different syntax, in order to turn the
variable into a constant – the keyword final
 A variable declared as final cannot change its value. The compiler
will report an error if we try
 Very often, constanst are needed outside the classes in which they
are declared. Also, the constants should not belong to some specific
object. It seems a bit silly to create an object just to be able to use the
constants in the classs
 Both of these properties can be achieved by declaring the constants
to be public, and static
 The static keyword implies that this field is not an “instance field”,
it rather belongs to the class as such
 Note that non-constants can also be declared as static
 When we wish to refer to a (statically declared) constant, we use the
syntax ClassName.constantName
 A statically declared constant or variable will only occur once, no
matter how many objects we create! (“global variable”)
Big Java Chapter 4
Assignment, Increment and Decrement (chapter 4.3)
 Recall that in Java, the “=” symbol defines an action (assignment to a
variable), not a comparison.
 In an assignment, the expression on the right-hand side is evaluated
completely before assigning the resulting value to the variable on the
left-hand side
 The expression can be another variable, a method call, or some
expression involving the variable on the left-hand side
 It is perfectly legal to write count = count+ 5; This will just add
5 to the value in count, as we would expect
 For doing increment (increase the value by 1), and decrement
(decrease the value by 1), we have a special notation:
 Count++;
 Count--;
// Increment
// Decrement
 Why? These operations are so common, that a “shorthand” for these
operations is very useful, and even easier to read
 There is also a more general shorthand for updating the value of a
variable, which combines assignment and arithmetic
 balance += amount; means balance = balance + amount;
 balance -= amount; means balance = balance - amount;
 balance *= factor; means balance = balance * factor;
 balance /= factor; means balance = balance / factor;
 Some find this notation useful and easy to read, some find it
confusing. Choose the one you like best!
Big Java Chapter 4
Arithmetic Operation and Math Functions (chapter 4.4)
 We have already seen that division is symbolised by the “/” symbol.
 When we use decimal values, division behaves just as we would
expect, e.g. 7.0 / 4.0 = 1.75
 However, division of integer numbers may produce a surprising
result, e.g. 7 / 4 = 1 (??)
 If both numbers – or expressions – involved in the division are
integer, then the result becomes an integer, like above
 If just one of the numbers/expressions are a decimal number, the
result is a decimal number, e.g. 7 / 4.0 = 1.75
 To supplement integer division, the “%” symbol is used for
calculation of the remainder in a integer division, e.g. 7 % 4 = 3
 The “priority” of arithmetic operators is as usual, so multiplication
and division bind harder than addition and subtraction
 Example: 8 + 4 / 2 = 10 (not 6)
 Example: 8 – 4 * 2 = 0 (not 8)
 However, you are always allowed to use parentheses (brackets) in
order to make an expressions clearer
 The Java library also includes a Math class, which contains the most
common mathematical functions, such as rounding, trigonometry,
powers, exponentials and logarithm
 All functions in the Math class are static, so they are called using the
syntax Math.functionName(parameters);
 In general, any algebraic expression has to be “flattened” in order to
be transformed to Java code; this may be a bit complicated. Proper
use of parentheses may be a good help in this
 Using white space and parentheses does not make your code less
efficient, but probably more readable!
Big Java Chapter 4
Calling Static Methods (chapter 4.5)




So far, we have divided methods into accessors and mutators
Accessors return some value from the object on which it is called
Mutators may change some value in the object on which it is called
However, there are methods which are neither…
 Some methods simply perform an operation using the parameters to
the method, and return some value based on these parameters
 Example: Math.pow(3,3) = 27
 Such a method does not really need to be called on a specific object,
since they do not use or change the state of an object
 Still, we would like to give such methods a “home” to live in, like a
class definition
 The solution is to declare such methods as being static
 A static method is declared just a any other method in a class, but we
use the keyword static to indicate that we do not need to create an
object in order to call the method
 Syntax for call: ClassName.methodName(parameters);
 Since we do not create an object on which the method is called, it
follows that static methods can not use any instance fields or any
ordinary methods from that class
 How can we tell if a method is being called on a class or an object?
 Class names should always start with a capital letter
 Object – or rather, variables that are object references – should
always start with a small letter
 Following this convention makes it easy to see if a method is called
on a class or an object
Big Java Chapter 4
Strings (chapter 4.6)
 String is a very common, built-in type, but it is not a primitive
type! It is a class!
 Variables of type String are thus (references to) objects
 What are string actually? A sequence of characters
 Strings are enclosed in quatation marks, like “Hello”
 The length of a string is simply the number of characters in the
string, not counting the quotation marks
 Example: String myName = “Per Laursen”;
 myName.length(); will return 11
 We often need to put strings together (concatenation) – this is very
conveniently done using the “+” operator
 Also very useful, we can add for instance a string and a number
using “+”, this will convert the number to a string
 Example: “H” + 4 + “ck” + 3 + “r” will equal “H4ck3r”
 Very useful if you want to put together some result or user input with
some supplementary text, like “You typed “ + input;
 The return type of such an expression is a String, so we can use this
an input to a method call, like
 System.out.println(“Your balance is“ + balance);
 We often need to convert a string – e.g. from user input – to a
numeric type
 To integer: int value = Integer.parseInt(input);
 To double: double value = Double.parseDouble(input);
 Note that if the string does not match the expected format for the
numeric type, an error will occur
Big Java Chapter 4
Strings (chapter 4.6)







The substring method returns a subset of a given string
Example: myString.substring(2,5);
First parameter: starting character
Last parameter: one beyond end character
Note that the count of characters start at zero!
Example String myName = “Per Laursen”;
myName.substring(3,7); returns “r La”




What if we actually want to print out a quotation mark?
We cannot define a string like “””
Here we need to use a so-called escape sequence
We can print out a special character using the “\” to indicate, that this
character is to be printed, not used as a “control character”
 Example: System.out.println(“\”Hi!\””); prints “Hi!”
 So how do we print a “\”? Need to prefix this with a “\” as well!
 Example: System.out.println(“C:\\Temp\\Download”);
prints “C:\Temp\Download”




We can also use escape sequences for some formatting of output
“\n” define a newline
“\t” defines a tabulation
The lazy solution instead of writing multiple calls to
System.out.println();
Big Java Chapter 4
Reading Input (chapter 4.7)
 Instead of having to write and compile programs over and over, in
order to use and test them with different input data, it is much more
convenient to obtain data when the program is running.
 Since System.out is used for writing to the output window, it would
seem logical to use System.in for getting input; however, that is not
the case
 In order to read keyboard input, a class called Scanner must be used
 The Scanner class is created using System.in as input parameter,
and has a number of methods for reading data from the keyboard
 Example: Scanner in = new Scanner(System.in);





With a Scanner object, we can use the below methods:
nextInt(): Reads an integer from the keyboard
nextDouble(): Reads a double from the keyboard
nextLine(): Reads a string from the keyboard
next(): Reads an string from the keyboard, but only so far as the
first white space (space, new line or tab)
 Note that the method will not actually complete until you have hit the
Enter key, which indicates that you have finished your input
 The input for e.g a double must match the expected format, otherwise
an error will occur
 With regards to formatting output, the formatting of doubles may
often be a bit troublesome
 Unless we specify otherwise, doubles will usually have many
decimals like 450.000000001
 Using the printf method can help in producing a proper formatting
of doubles, with the format specifiers available
 Check the printf method, plus tables 3 and 4 on page 168
Big Java Chapter 4
Using Dialog Boxes for Input and Output (adv topic 4.7)
 In a real-life Java program, we would probably not communicate
with the user using an output window; we would use a graphical user
interface (GUI)
 Development of GUI applications is a large subject on its own – for
now, we just look at ways to easily get input and present output using
some simple dialogs
 The JOptionPane class contains methods for this purpose:
 Input: JOptionPane.showInputDialog(String prompt); (this
method returns a string)
 Output: JOptionPane.showMessageDialog(null, String
message);
 Since both of these methods use strings, we can use all of the string
formatting methods we have already learned
 Is generally more convenient to use dialogs for input and output
 A single line of code should be added to the main method in your
program: System.exit(0);
 This is needed for more technical reasons…
 If you want to know more about using dialogs, there are many more
ways to create JOptionPane dialogs, see the documentation!
Big Java Chapter 4
Exercises
Chapter 4.1
(15 min)
Self-Check:
Review:
Programming:
2
4.4, 4.6, 4.9
--
Chapter 4.2
(15 min)
Self-Check:
Review:
Programming:
4, 5
4.14, 4.15
--
Chapter 4.3
(5 min)
Self-Check:
Review:
Programming:
7
---
Chapter 4.4
(45 min)
Self-Check:
Review:
Programming:
-4.7, 4.8, 4.10
4.4, 4.10
Chapter 4.5
(5 min)
Self-Check:
Review:
Programming:
11, 12
---
Chapter 4.6
(25 min)
Self-Check:
Review:
Programming:
13, 14
-4.17
Chapter 4.7
(20 min)
Self-Check:
Review:
Programming:
16
-4.14
Adv Topic 4.7
(25 min)
Self-Check:
Review:
Programming:
--4.4, 4.8, 4.14 (but use dialogs!)