java programming part 1mcsc.sc.mahidol.ac.th/courses/cps/slides/java.pdf · 3 cpu executes...
TRANSCRIPT
Chaiwoot Boonyasiriwat
January 22, 2020
Computer Programmingusing Java
2
▪ Problem definition: determine what the problem really is, set the goals
▪ Analysis: determine inputs, outputs, and relevant factors
▪ Design: describe methods used, provide detail of all steps required to turn input into output
▪ Implementation: write a code corresponding to the designed algorithm
▪ Testing: validate program using test cases▪ Redo analysis/design/implementation if
program fails the validation test
Problem Solving using Computer
3
Flowchart: Average
4
Flowchart: Greeting
5
Java Programming Cycle
Suchato (2011, p. 23)
Text editor or IDE JDK: javac.exe JRE: java.exe
IDE = integrated development environment
6
Running Java Program
Suchato (2011, p. 22)
Write Once, Run Anywhere (with JRE installed)
JVM = Java Virtual Machine
JRE = Java Runtime Environment
7
▪ A Hello World program is conventionally the first program anyone should learn to develop when starting to learn a new programming language.
▪ The Hello World program can be written in Java as follows.
File: Hello.java
class Hello {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Hello World Program
8
▪ Java source code:• File name must be exactly the same as the
class name (case sensitive)• File extension must be .java
▪ Compilation: javac [file name of source code]
• Example: javac Hello.java
▪ Execution: java [class name]• Example: java Hello
Compiling and Running Java Program
9
"Command line or console or terminal is a text-based interface that forwards commands from the user to the operating system."Commands for PowerShell or Terminal:▪ ls list the files and directories (folders) in
the current directory▪ cd change the current directory to
another directory▪ mkdir make a new directory▪ cp copy files or directories
Command Line/Terminal
https://www.ionos.com/digitalguide/server/know-how/windows-cmd-commands/
10
▪ pwd present working directory▪ mv move files or directories▪ rm remove files or directories
Command Prompt (cmd.exe) Commands▪ dir list the files and directories (folders) in
the current directory▪ cd change the current directory▪ mkdir make a new directory▪ copy copy files or directories▪ move move files or directories
Terminal Commands
11
> cd change the current directory to home directory of the user
> cd java change the current directory to directory java which is a sub-directory in the current directory
> cd .. change the current directory to one level up
If you are in /home/user/java, "cd .." will move you to /home/user.
Examples: cd
12
▪ A Java program must contain• a class definition using the keyword class• the main method defined within the class
▪ Definition of a class named Hello:class Hello
{
... main(...)
{
...
}
}
Basic Structure of a Java Program
keyword
class name
block of class
block of method
method main
13
// import java.lang.System;
class Hello
{
public static void
main(String[] args)
{
System.out.print("Hello");
}
}
Hello World Program Revisited
keyword
methodclass variable literal
14
KeywordsKeywords cannot be used as identifier
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
15
Identifiers"Identifiers are the names of variables, methods, classes, interfaces"
Naming Rules for Identifier
If these rules are violated, a compilation error will occur.
http://www.cafeaulait.org/course/week2/08.html
Suchato (2011, p. 39)
16
If these conventions are violated, a compilation error will NOT occur.
Naming Conventions for Identifiers
17
Literals"Literal is notation for representing a fixed value in source code."
Examples:▪ 0, 100, -2 int literals▪ 1L, 50L, 321l long literals▪ 3.14F, 1.0f, 2.0E4F float literals▪ 3.14, 1D, 2d, 2.0E2 double literals▪ true, false boolean literals▪ 'a', '4', '$', '\n' char literals▪ "Hello","1","//","/* */" String literals
https://en.wikipedia.org/wiki/Literal_(computer_programming)
18
Type Value/Range Sizeboolean true, false 1 bytechar 'a', 'd', '\n' 2 bytesbyte [-128, 127] 1 byteshort [-32768, 32767] ~ 3.2104 2 bytesint [-2147483648, 2147483647] 4 bytes
~ 2.1109
long [-263, 263-1] ~ 9.21018 8 bytesfloat 4 bytesdouble 8 bytes
Primitive Data Types
19
▪ Since data in computers are represented as binary numbers, computers need to know how to convert binary numbers to characters.
▪ This is done by character encoding called Unicode (universal coded character set)
Character Encoding
20
Escape Characters
Example: Escape.java
class Escape {
public static void main(String[] args) {
System.out.println("Hello\nWorld\tHello");
}
}
21
Examples: declare one variable per statementbyte a;
short b;
int c;
long d;
char e;
Examples: declare multiple variables per statementfloat a, b, c;
double pi, r, area;
boolean yes, no;
Variable Declaration
22
Examples: declare variables and assign the value in the same statementint a = 1;
long b1 = 1L, _b = 20l;
boolean yes = true;
float c = 12.3F, _c = 1.0e2f;
double pi = 3.14, r = 1.0;
double value = 1.234E10;
String name = "Jack";
Declaration and Assignment
23
▪ Final variables are variables that can be assigned a value only once.
▪ Final variables are declared using the keyword final in front of the type and variable name.
▪ Conventionally, final variables are named using all uppercase letters and words are separated by underscore _.
▪ Examples:final double PI = 3.14159;
final double YOUNG_MODULUS;
Final Variables
24
▪ Variables that have been declared but have not been assigned a value cannot be used.
▪ Using an un-initialized variable will result in a compilation error.
▪ Example:int a = 1;
int b, c;
c = a + b;
Un-initialized Variables
25
▪ Values can be manipulated using built-in operators including• arithmetic operators: +, -, *, /, %• logical operators: &&, ||, !• comparison operators: ==, !=, >, <, >=, <=• grouping operators: parentheses ( )
▪ "Binary operators are operators that required 2 operands." Examples: +, -, *, /, %, &&, ||, ==, !=, >, <, >=, <=
▪ "Unary operators are operators that required only 1 operand." Examples: !
Operators
26
Addition a + b
Subtraction a – b
Multiplication a * b
Division a / b
Modulo a % b
(modulo = remainder after division)
Arithmetic Operators
27
a==1 && b ==2 AND operatora==1 || b ==2 OR operator!b NOT b
Logical Operators
28
a == b Is a equal to b?a != b Is a not equal to b?a > b Is a greater than b?a < b Is a less than b?a >= b Is a greater than or equal to b?a <= b Is a less than or equal to b?
Comparison Operators
29
a += 1; a = a+1
a -= 1; a = a-1
a *= 1; a = a*1
a /= 2; a = a/2
a %= 3; a = a%3
Java Language Specification:E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)) where E1 and E1 are expressions, T is the type of E1, op is arithmetic operator (+, -, *, /, %)
Compound Assignment Operators
30
a = (1<3) ? 2 : 4; a = 2
a = (1>3) ? 2 : 4; a = 4
Conditional Operator
Deitel and Deitel (2010, p. 109)
31
++a Increment a by 1, then use the newvalue of a
a++ Use the current value of a, then increase a by 1
--a Decrement a by 1, then use the newvalue of a
a-- Use the current value of a, then decrease a by 1
Increment/Decrement Operators
Deitel and Deitel (2010, p. 110)
32
▪ Expressions only contain identifiers, literals, operators (arithmetic or logical operators), method call (e.g., print())
▪ Expressions can be evaluated to a value.▪ "A statement is a complete sentence that
causes an action to occur."▪ Statements must end with semicolon ;▪ Examples of statements:int a; a = 10;
System.out.print(a);
Expression and Statement
33
▪ Order of execution of operators in an expression is exactly determined by the precedence and association rules.
▪ "Each operator is assigned a precedence level."
▪ "Operators with higher precedence levels are executed before ones with lower precedence levels."
Precedence Rules
Suchato (2011, p. 71)
34
▪ Order of execution of operators with the same precedence level are determined by the association rules of the operators.
▪ "The association rule indicates whether operators to the left or to the right are to be executed first."
Association Rules
Suchato (2011, p. 71)
35
Precedence/Association
Suchato (2011, p. 71)
36
Precedence/Association
https://introcs.cs.princeton.edu/java/11precedence/
37https://introcs.cs.princeton.edu/java/11precedence/
38
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
39
▪ 1+2*3 = 1+(2*3) = 1+6 = 7
▪ 1*2-6/2 = (1*2)-(6/2) = 2-3 = -1
▪ 1+2>2+3 = (1+2)>(2+3) = 3>5 = false
▪ 1+(-2)*3 = 1 + (-2*3) = 1 – 6 = -5
Example 1: Precedence
40
Example 2: Precedence
Suchato (2011, p. 74)
41
Example 3: Precedence
Suchato (2011, p. 74)
42
▪ Various universal constants and mathematical functions can be used via the class Math.
▪ These functions include abs, round, ceil, floor, exp, max, min, pow, sqrt, sin, cos, tan, asin, acos, atan etc.
▪ Examples:double a = Math.PI * Math.sin(1);
a = exp(-10);
double b = Math.min( -1, 10);
For a complete list of methods of class Math, see https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
Mathematical Methods
43
Distance d between 2 points in 3D space and can be computed from
Distance in 3D Space
Suchato (2011, p. 75)
44
File: Distance2d.java
Distance in 3D Space
Suchato (2011, p. 75)
45
There are 2 types of type conversion▪ implicit/automatic type conversion
• no loss of magnitude of numeric value• Example: long a = 100;
▪ explicit type conversion• magnitude of numeric value may be lost• a cast operator is required for conversion• Example: short a = (short) 123;
Type Conversion
Suchato (2011, p. 75)
46
Type Value/Range Sizeboolean true, false 1 bytechar 'a', 'd', '\n' 2 bytesbyte [-128, 127] 1 byteshort [-32768, 32767] ~ 3.2104 2 bytesint [-2147483648, 2147483647] 4 bytes
~ 2.1109
long [-263, 263-1] ~ 9.21018 8 bytesfloat 4 bytesdouble 8 bytes
Primitive Data Types
47
▪ "Widening primitive conversion does not lose information about the overall magnitude of a numeric value but may result in loss of precision."
Widening Primitive Conversion
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
48
▪ "Narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range."
Narrowing Primitive Conversion
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
49
A = automatic type conversionC = cast operator is requiredX = type conversion is not allowed
* loss of precision might occur from conversion
Type Conversion Table
Suchato (2011, p. 83)
50
Rules governing the evaluation of expressions with multiple data types are as follows.
Expression with Multiple Data Types
Suchato (2011, p. 85)
51
Examples
Expression with Multiple Data Types
Suchato (2011, p. 85)
52
Although integer literals are treated by default as int, in some cases integer literals are treated by the compilers as byte or short.
An integer literal in the range [-128,127] is treated as byte when it is assigned to a variable of type byte.
byte a = 127; // OK
byte b = 128; // Wrong: 128 = int
Assignment Statement
53
An integer literal in the range [-32768,32767] is treated as short when it is assigned to a variable of type short.
short a = 32767; // OK
short b = 32768; // Wrong
// 32768 = int
Assignment Statement (con.)
54
An integer literal in the range [0, 65535] is treated as char when it is assigned to a variable of type char. (size of char is 2 bytes or 16 bits)
char a = 65535; // OK
char b = 65536; // Wrong
// 65536 = int
Assignment Statement (con.)
Floating-Point Numbers
55
IEEE Standard for Floating-Point Arithmetic (IEEE 754) defines▪ arithmetic formats: sets of binary and decimal floating-
point data, which consist of• normal numbers, signed zeros and subnormal numbers• signed infinities, and "not a number" (NaN)
▪ interchange formats: encodings (bit strings) used to exchange floating-point data
▪ rounding rules: properties to be satisfied when rounding numbers during arithmetic and conversions
▪ operations: operations on arithmetic formats▪ exception handling: indications of exceptional conditions
(such as division by zero, overflow, etc.)
https://en.wikipedia.org/wiki/IEEE_754
IEEE 754 Format
56Reference: http://en.wikipedia.org/wiki/IEEE_floating_point
IEEE 754-1985
57
Precision: The number of decimal digits precision is calculated via number_of_mantissa_bits * . Thus ~7.2 and ~15.9 for single and double precision respectively.
Reference: http://en.wikipedia.org/wiki/IEEE_754-1985
Single precision
Double precision
Single-Precision Floating-Point Format
58
▪ minimum positive normal number▪ minimum positive subnormal number ▪ precision =
https://en.wikipedia.org/wiki/Single-precision_floating-point_format
Example: Normal Numbers
59https://en.wikipedia.org/wiki/Single-precision_floating-point_format
Example: Subnormal Numbers
60https://en.wikipedia.org/wiki/Single-precision_floating-point_format
Example: Zeros, Infinities, NaNs
61https://en.wikipedia.org/wiki/Single-precision_floating-point_format
62
▪ Decimal number system cannot exactly represent some fractions, e.g. 1/3, 1/11, 1/13
▪ These fractions become repeating decimals, e.g., 1/3 = 0.33333...
▪ Binary number system cannot also exactly represent some fractions, e.g., 1/5, 1/10
▪ To convert a decimal fraction into a binary fraction, simply multiply only the fraction by 2 repeatedly and record the whole number
Limitation on Floating Point
63
2 x 0.1 0.2 x 0.2 02 x 0.4 02 x 0.8 02 x 1.6 12 x 1.2 12 x 0.4 02 x 0.8 02 x 1.6 12 x 1.2 1
0.4 0
Decimal to Binary Fraction
Therefore, 0.1 cannot be exactly represented using single-precision floating-point format (float) or double-precision floating-point format (double).
64
▪ Since some real numbers cannot be exactly represent using float or double, comparing two floating-point numbers is something that should be avoided.
▪ Instead, use the absolute of the difference to compare two numbers instead.
▪ Example: d = |a-b|if d < then a is equal to botherwise a is not equal to b
Comparing Floating-Point Numbers
65
class CompareFloat {
public static void main(String[] args) {
float a = .1f+.1f+.1f+.1f+.1f+.1f+.1f;
float b = .1f*7;
boolean c = a==b;
float d = Math.abs(a-b);
boolean e = d < 1.0e-7f;
System.out.println(c);
System.out.println(e);
}
}
Example: Floating-Point Operations
66
▪ Each numeric data type has a corresponding valid range of numerical values.
▪ When a value larger than the largest value of a data type is assigned to a variable, an overflow occurs.
▪ When overflow occurs for integer types (byte, short, int, long), a wrap-around of value occurs.
▪ For float and double, overflow will result in the special value of POSITIVE_INFINITY or NEGATIVE_INFINITY
Overflow
67
class ByteOverflow {
public static void main(String[] args) {
byte a = 127;
a++;
System.out.println(a);
a = -128;
a--;
System.out.println(a);
}
}
Example: Byte Overflow
68
class ShortOverflow {
public static void main(String[] args) {
byte a = 32767;
a++;
System.out.println(a);
a = -32768;
a--;
System.out.println(a);
}
}
Example: Short Overflow
69
class FloatOverflow {
public static void main(String[] args) {
float a = 3.4e38f;
System.out.println(a);
a *= 10;
System.out.println(a);
a = -3.4e38f;
System.out.println(a);
a *= 10;
System.out.println(a);
}
}
Example: Float Overflow
70
▪ The smallest positive subnormal number for float is about 1.4 x 10-45
▪ The smallest positive subnormal number for double is about 4.9 x 10-324
▪ When a value smaller than these numbers is assigned to a variable, an underflow occurs and the value 0 is assigned to the variable instead.
Underflow
71
class FloatUnderflow {
public static void main(String[] args) {
float a = 1.4e-45f;
System.out.println(a);
a /= 10;
System.out.println(a);
float b = -1.4e-45f;
System.out.println(b);
b /= 10;
System.out.println(b);
}
}
Example: Float Underflow
72
class DoubleUnderflow {
public static void main(String[] args) {
double a = 4.9e-324;
System.out.println(a);
a /= 10;
System.out.println(a);
double b = -4.9e-324;
System.out.println(b);
b /= 10;
System.out.println(b);
}
}
Example: Double Underflow
73
▪ For integer types, division by zero will lead to runtime error of type divide-by-zero arithmetic exception.
▪ For floating-point types, division by zero will lead to signed infinities.
Division By Zero
74
class IntegerDivideByZero {
public static void main(String[] args) {
int a = 1/0;
}
}
int: Division by Zero
75
class FloatDivideByZero {
public static void main(String[] args) {
float a = 1.0f/0.0f;
System.out.println(a);
a = -1.0f/0.0f;
System.out.println(a);
}
}
float: Division by Zero
76
▪ In mathematics, indeterminate forms include 0/0, /, 0, 1, - , 00, 0
▪ For integer types, indeterminate form 0/0 will results in a runtime error of type divide-by-zero arithmetic exception.
▪ For floating-point types, indeterminate forms will result in a special Not-a-Number (NaN).
Indeterminate Form
77
class FloatIndeterminate {
public static void main(String[] args) {
float a = 0.0f/0.0f;
System.out.println(a);
a = -0.0f/0.0f;
System.out.println(a);
float b = 1.0f/0.0f;
a = b/b;
System.out.println(a);
a = b * 0.0f;
System.out.println(a);
}
}
float: Not-a-Number
78
▪ Real-world objects (e.g., cars, TV) have both attributes (data) and functionalities (methods).
▪ These objects can be classified as classes of objects.
▪ An object is an instance of a class.▪ In Java, a class is a non-primitive data type that
can be created using the class keyword.▪ A class can contain both data (variables) and
methods. This is called encapsulation which is one of the fundamental concept of object-oriented programming (OOP).
Class and Object
79
▪ Constructors: special methods used to initialize objects
▪ Variables• instance variables: belong to an instance• static variables: shared among all instances
▪ Methods• instance methods: called via an instance• static variables: called via class name
Member variables and methods must be accessed using the . operator.
Members of a Class
80
class Point {
public double x, y;
public static Point o = new Point(0,0);
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double distance(Point p) {
double dx = x – p.x;
double dy = y – p.y;
return Math.sqrt(dx*dx+dy*dy);
}
}
Point: Class Definition
81
Point: UML Class Diagram
Point
+x: double
+y: double
+o: Point
+Point(x: double, y: double)
+distance(p:Point): double
UML (Unified Modeling Language) class diagram contains 3 parts: (1) class name, (2) variables, (3) methods. (+ = public, underline = static)
82
class UsingPoint {
public static void main(String[] a) {
Point p1 = new Point(1, 2);
Point p2 = new Point(4, 3);
double d = p1.distance(p2);
System.out.println(d);
d = p1.distance(Point.o);
System.out.println(d);
}
}
Point: Usage
83
▪ When a class is used to declare a variable, that variable is called object which is an instance of the class. That class is said to be instantiated.
▪ Example:Point p = new Point(1,2);
An Instance of a Class
class object
- keyword- operator for creating object
constructor: special methodused for creating object
84
▪ Data members or variables of a class can be classified as• instance variables: can be accessed only via
an instance of the class, i.e., an objectExample: Point p = new Point(1,2);
double x = p.x;
• class or static variables: can be accessed only via the class name and are shared among all instances of the classExample: Point p = Point.o;
Data Members of a Class
85
“All programs could be written in terms of only three control structures:”▪ Sequence structure▪ Selection structure
• if, if-else statements• switch statement
▪ Repetition structure• for statement• while statement• do-while statement
Control Structures
Remark: if, else, switch, for, do, while are keywords
86
Statements are executed one after another.
Sequence Structure
Deitel and Deitel (2010, p. 89)
a = 1
b = 2
c = a + b
a = 1;
b = 2;
c = a + b;
Process 1
Process 2
Process 3
Flo
wch
art
Terminator
Terminator
Begin
End
Flow line
87
Selection Structure: if
Deitel and Deitel (2010, p. 90)
b = 1
false
if (a > 0) {
b = 1;
}
Decision a > 0
Connector
true
if (a > 0)
b = 1;or
Flow line
88
Selection Structure: if…else
Deitel and Deitel (2010, p. 92)
b = 1false
a > 0true
if (a > 0)
b = 1;
else
b = 2;
b = 2
if (a > 0) {
b = 1;
} else {
b = 2;
}
89
Nested if
Suchato (2011, p. 145)
90
Example: Nested if
if (a > 0) {
if (b > 1) {
c = 1;
}
}
if (a > 0 && b > 1) {
c = 1;
}
is equivalent to
91
if-else-if
Suchato (2011, p. 148)
is equivalent to
92
if-else-if Flowchart
action1
F
expr1T
action2expr2
expr3
F
93
Flowchart: Absolute Value
94
switch: syntax
switch (expression) {
case constant expression:
// do something
break;
case constant expression:
// do something
break;
default:
// do something
break;
}
95
switch: Example
switch(a){
case 1:
System.out.println("a = 1");
break;
case 2:
System.out.println("a = 2");
break;
default:
System.out.println("a is not 1,2");
break;
}
96
switch: Flowchart
https://chortle.ccsu.edu/java5/Notes/chap43/ch43_8.html
97
Repetition Structure: while
Deitel and Deitel (2010, p. 96)
a++
false
a < 10true
a = 0;
while (a < 10) {
a++;
}
98
Repetition Structure: do…while
Deitel and Deitel (2010, p. 146)
a++
false
a < 10true
a = 0;
do {
a++;
} while (a < 10);
a = 0;
99
Repetition Structure: for
Deitel and Deitel (2010, p. 136)
sum = 0;i = 0;
false
i 10true
sum = 0;
for (i = 1; i<=10; i++) {
sum += i;
}
sum+=i i++
100
char charAt(int index)
returns the char value at the specified indexint compareTo(String str)
compares two strings lexicographicallyint compareToIgnoreCase(String str)
compares two strings lexicographically, ignoring case differences
String concat(String str)
concatenates the specified string to the end of this string
Methods of String Class
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
101
boolean startsWith(String prefix)
tests if this string starts with the specified prefixboolean endsWith(String suffix)
tests if this string ends with the specified suffixint indexOf(int ch)
returns the index within this string of the first occurrence of the specified character
int indexOf(String str)
returns the index within this string of the first occurrence of the specified substring
Methods of String Class
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
102
int lastIndexOf(int ch)
returns the index within this string of the last occurrence of the specified character
int lastIndexOf(String str)
returns the index within this string of the last occurrence of the specified substring
int length()
returns the length of this stringString substring(int begin, int end)
returns a string that is a substring of this string
Methods of String Class
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
103
String toLowerCase()
converts all characters to lower caseString toUpperCase()
converts all characters to upper caseString trim()
returns this string without leading and trailing whitespace
Methods of String Class
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
104
String valueOf(boolean b)
String valueOf(char c)
String valueOf(int i)
String valueOf(long l)
String valueOf(float f)
String valueOf(double d)
converts the input to a string representation
Static Methods of String
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
105
Static Data:int MAX_VALUE
the maximum value an int can have, 231-1int MIN_VALUE
the minimum value an int can have, -231
Constructor:Integer(int value)
Integer(String s)
constructs a newly allocated Integer object
Integer Class
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
106
int parseInt(String s)
parses the string argument as an intString toBinaryString(int i)
returns string representation of the integer argument as an unsigned integer in base 2
String toHexString(int i)
returns string representation of the integer argument as an unsigned integer in base 16
String toOctalString(int i)
returns string representation of the integer argument as an unsigned integer in base 8
Static Methods of Integer
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
107
String toString(int i)
returns a String object representing the specified integer
Static Methods of Integer
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
108
double MAX_VALUE
the largest positive finite value of type double(2-2-52)x21023
double MIN_VALUE
the smallest positive nonzero value of type double, 2-1074
double NaN
Not-a-Number (NaN) value of type doubledouble NEGATIVE_INFINITY
negative infinity of type doubledouble POSITIVE_INFINITY
positive infinity of type double
Static Data of Double Class
https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html
109
boolean isInfinity(double v)
returns true if the specified number is infinitely large in magnitude, false otherwise
boolean isNaN(double v)
returns true if the specified number isNot-a-Number (NaN) value, false otherwise
double parseDouble(String s)
parses input String into a doubleString toString(double d)
returns a string representation of double argumentDouble valueOf(String s)
returns Double object from the input string
Static Methods of Double
https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html
110
▪ Primitive data types• integer data: use a==b, a!=b• floating-point data: use |a-b| < c where c is a small number, e.g. 10-6
▪ Non-primitive data types• (a == b) returns true only if a and b
contains the same reference to the same object in the heap memory
Equality Testing
111
▪ ==tests for reference equality▪ .equals() tests for value equality▪ Objects.equals() checks for null
before calling .equals()
Equality Testing for
Non-Primitive Data Type
https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
112
// These two have the same value
new String("test").equals("test") // true
// but they are not the same object
new String("test") == "test" // false
new String("test") == new String("test") // false
// String literals are interned by the compiler
// Unique String literals are in a String pool
"test" == "test" // true
// String literals are concatenated by the
// compiler and the results are interned.
"test" == "te" + "st" // true
// Compare String value using Objects.equals()
Objects.equals("test",new String("test")) // true
Objects.equals(null, "test") // false
Objects.equals(null, null) // true
Equality Testing for String
https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
▪ "A running program uses two regions of memory to store data: stack and heap."
▪ "Stack is a last-in, first-out (LIFO) data structure."
▪ "Data can be added to and deleted only from the top."
▪ Placing a data item at the top of stack is called pushing the item onto the stack.
▪ Deleting an item from the top of stack is called popping the item from the stack.
▪ Stack memory stores several types of data• value of certain type of variables, e.g., local
Stack and Heap
Stack
Solis and Schrotenboer (2018)
▪ "Data can be stored and removed from the heap in any order."
Heap
Solis and Schrotenboer (2018)
Garbage Collector (GC)
Solis and Schrotenboer (2018)
117
JavaIdentifiers:name of package, class, variable,method, label, interface, enum
Control FlowStatements
ModifiersAccess modifiers:public, private,protected, default
Non-access modifiers:static, final, abstract,synchronized, volatile
Types
Primitive/Value Types:boolean, char, byte, short, int, long,float, double
Non-primitive/Reference Types:array, enum, class, interface
Decision-Making:if-then, if-then-else, switch
Looping:while, do-while, for
Branching:break, continue, return
Operators
+,-,*,/,%,++,--
,!,~,=,+=,=,*=,/=,%=,
&=,^=,|=,<<=,>>=,>>>=,==,!=,>,<,>=,
<=,&&,||,?:,(),[],.,new,instanceof
Exception
Checked/Unchecked Exceptions
try, catch, finally, throw, throws
Precedence/AssociationRules
Object-orientedProgramming (OOP)
Encapsulation
Inheritance
Polymorphism
Java Virtual Machine (JVM)
Stack and Heap Memory
Garbage Collector
Class Loader
Method Overriding/Overloading
interface, abstract class, casting
118
▪ Suchato, A., 2011, Learning Computer Programming using Java with 101 Examples, Chulalongkorn University.
▪ D. Solis and C. Schrotenboer, 2018, Illustrated C# 7, 5th edition, Apress.
Reference