OOP U3 BasicJava2 2024s1
OOP U3 BasicJava2 2024s1
*Remark: This unit provides a very condensed introduction of starting Java programming, and can much be treated as a revision
for learners already with basic programming background. 2
Numerical Types and Operations
Low
Precision Data Type Default value* Size Range (Minimum ~ Maximum)
byte 0 8-bit -27 ~ 27-1 (-128 ~ 127)
* Remark: Default values are applied to fields of objects, not local variables. 3
Arithmetic Operators
Unary Operators
+ Unary plus operator; indicates positive value ( +expr )
- Unary minus operator; negates an expression (-expr )
++ Increment operator; increments a value by 1 ( expr++ )
-- Decrement operator; decrements a value by 1 ( expr-- )
! Logical complement operator; inverts the value of a boolean
Logical Operators
&& Conditional-AND
|| Conditional-OR
! Logical complement operator; inverts the value of a boolean
6
Summary of Operators
7
Order of Evaluations
(of Arithmetic Expression)
• Given an arithmetic expression with more than one operators, how
does the expression get evaluated? Example: x + 3 * y
– Answer: First 3*y, then with + the x is added later
• This + operator can also be applied to two Strings e.g. a="12.3" and
b= "21", and the result becomes a new string ("12.321"), appending
one to another (concatenation)
9
Precedence Rules
Operators Precedence (From highest at top, to bottom)
postfix expr++ expr--
unary (and prefix) ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
** When operators of equal Precedence appear in the same expression, Associativity rules govern
which is evaluated first. All binary operators except for the assignment operators are evaluated
from left to right; assignment operators and unary operators are evaluated right to left. 10
Data Type Compatibility and Conversion
• If the value of one data type could be converted to that of another data
type, these two data types are compatible.
12
Implicit Type Conversion / Casting
• Example 2:
double x = 3+5;
13
Explicit Type Conversion / Casting
14
The Math Class
(in the package of java.lang)
• Very often, we may need to solve more complicated mathematical
problems
Reference: https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/lang/Math.html 15
Commonly Used Constant and Class Methods in Math
Constant Description
static double E The double value that is closer than any other to e, the base of
the natural logarithms.
static double PI The double value that is closer than any other to pi, the ratio of
the circumference of a circle to its diameter.
Method Description
exp(a) Natural number e raised to the power of a
log(a) Natural logarithm (base e) of a
floor(a) The largest double value less than or equal to a
max(a,b) The greater of a and b
pow(a,b) The number a raised to the power of b
sqrt(a) The square root of a
random() Returns a double value with a positive sign, greater than
or equal to 0.0 and less than 1.0
* Similar to for statement, the brace pair {} (curly brackets) is optional if the
loop-body block has only one single simple statement line
Boolean
int sum = 0, number = 1; Expression
20
Example: Control Flow of do-while
do {
Statement (loop-body):
sum += number; These statements are
executed as long as sum is
number++; less than or equal to 1000
} while ( sum <= 1000 );
Boolean Expression
sum += number;
number++;
true
sum <= 1000 ?
The flow chart false
21
Loop-and-a-Half Repetition Control
22
Example: Loop-and-a-Half Control
String name;
while (true){ // true all time, when check condition HERE
name = JOptionPane.showInputDialog(null, "Your name");
if (name.length() > 0)
break; // HERE break the while loop
JOptionPane.showMessageDialog(null, "Invalid Entry." +
"You must enter at least one character.");
}
23
The for Statement
24
Example: Control Flow of Statement for
<boolean expression> <updating>
<initialization> (Condition) (Increment)
i < 20 ?
false
true
number = . . . ;
sum += number;
i++;
25
More for Loop Examples
i = 0, 5, 10, … , 95
j = 2, 4, 8, 16, 32
26
break and continue
28
Initializing and Accessing Individual Elements
Index Number 0 1 2 3 4 5 6 7 8 9 10 11
2.3 8.9 2.3 5.1 8.2 1.1 0.1 9.9 2.1 2.2 8.9 2.2
29
Converting Array to String
Rainfall is [2.3, 8.9, 2.3, 5.1, 8.2, 1.1, 0.1, 9.9, 2.1, 2.2, 8.9, 2.2]
30
Example of Accessing Array with for Statement
• The for statement has another form designed for iteration through arrays
• E.g. consider the array rainfall in the last example, and how the
enhanced-for loop is used:
double[] rainfall = new double[12];
double sum = 0.0;
// ...
for (double rf : rainfall ) //enhanced-for loop
sum += rf;
34
Multiple Methods
(Modularizing Programs)
• The basic syntax of declaring a method:
<modifier(s)> <return type> <method name> (<parameter(s)>) {
<method body>
} A parameter has the same
value of the passed argument,
in the method declaration
• E.g.
public static int calSum(int a, int b, int c){
int retSum = a + b + c;
return retSum; // return value must match return type
}
* Remark: At the moment, we focus on static methods, which can be called without the
need for an object of the class to exist. Details will be given in later units.
37
Multiple Methods
(Sample Program for Numerical Calculation)
public class NumCal{ // declare a class
RUN, on console
finished operation. "Total Sum is " + sum
+ "; Average is " + avg); C:\>java NumCal
Total Sum is 45; Average is 5.0
}
}
38
Working with Multiple Java Source Files
• It is common to have more than one Java source files (*.java) for
one program, even for simple programs
– This approach with multiple Java files involves multiple Java classes,
often one class in one java source file
– For an executable program, it is common to separate a class module
which mainly (if not only) includes the main() method where the
program starts execution, and such class is often called the “Main” class
• Essentially the program starts with the main class, and within its
main() method it would then call other classes to do works.
COMPILE ALL Java Files
File Main.java
COMPILE ALL Java Files 1 File A.java
Main Class: A Class:
C:\>javac *.java
Program starts main() {
2 MethodONE() {
A.MethodONE();
RUN, on console
...
RUN, on console ... }
... MethodTWO() {
C:\>java Main
B.MethodONE();
...
3 ...
File B.java
}
Program Ends B Class:
}
MethodONE {
...
}
Remarks: More details of this approach will be discussed in later units. 39
Multiple Methods in Two Java Files
(Sample Program for Numerical Calculation – Two-Files Version)
// File NumCal.java, class supporting numerical calculation
public class NumCal{ // declare a class
// method to calculate total sum:
public static int calSum(int [] nums){
int retSum = 0;
for (int i=0; i<nums.length; i++)
retSum += nums[i]; COMPILE ALL Java Files
RUN, on console
return (float)calSum(nums)/nums.length;
} C:\>java MainNumCal
} Total Sum is 495; Average is 55.0
java MainNumCal
pause
* Remark: Batch file script line starts with "REM" is a comment. 41
Working with Multiple Methods in a Given Class
• Apart from defining our own classes which implement a set of multiple
methods, we can also make use of methods from given external
classes if we are given enough information about these classes, e.g.
– Methods and their descriptions: what they do & how to access them
• This is much related to the idea of Abstract Data Type (ADT) we have
learnt in other courses:
– External users may still use the given classes and their methods, without
knowing how they are actually implemented.
calSum(int[]):int Calculate and return sum of integers, Java method header below:
public static int calSum(int [] nums)
calAvg(int[]):floa Calculate and return average of integers, Java method header below:
t public static float calAvg(int [] nums)
.. And more .. .. And more ..
44
Class: JOptionPane
(In javax.swing package)
• JOptionPane is a class in the javax.swing package, for standard
dialog boxes that prompt users for a value or informs them of something
https://docs.oracle.com/en/java/javase/22/docs/api/java.desktop/javax/swing/JOptionPane.html 45
Class: JOptionPane
Method: showMessageDialog()
• Use showMessageDialog of the JOptionPane class is a simple
way to display a result of a computation to the user
– May display multiple lines of text by separating lines with a new line
marker '\n'
Reference:
public static void showMessageDialog(Component parentComponent, Object message)
46
Class: JOptionPane
Method: showConfirmDialog()
• Use showConfirmDialog of the JOptionPane class to bring up a
dialog with the options (e.g. Yes, No and Cancel), with the title, e.g.
int ans = JOptionPane.showConfirmDialog( null,
"Do you love OOP?", "An OOP Title",
JOptionPane.YES_NO_OPTION);
if (ans==JOptionPane.YES_OPTION) //... Do Yes thing
JOptionPane.showMessageDialog(null, "Great!");
if (ans==JOptionPane.NO_OPTION) //... Do No thing
JOptionPane.showMessageDialog(null, "No Good!");
Ref: public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) 47
Class: JOptionPane
Method: showMessageDialog()
• May create complex showMessageDialog display with more options,
including image
JOptionPane.showMessageDialog(null,
"Our Mesg", "Our Title",
JOptionPane.INFORMATION_MESSAGE,
new javax.swing.ImageIcon("cc.jpg"));
Reference:
public static void showMessageDialog(Component parentComponent, Object message, String title,
int messageType, Icon icon)
48
Class: JOptionPane
Method: showInputDialog()
• Use showInputDialog of the JOptionPane class is a simple way to
let user input a string
String name = JOptionPane.showInputDialog
(null, "What is your name?");
Click Cancel
OK to return
to return
a string
null string.
typed.
SelectCancel
Click OK
thetodesired
return
to return
aoption
string
null string
(Object)
(Object)
(Object).
selected.
Ref: public static Object showInputDialog(Component parentComponent, Object message, String title,
int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue) 50
Icons used by JOptionPane
51
Common Problems in Java Programming
52
References
• Part of this slide set is referenced, extracted, and/or modified from the
followings:
– Deitel, P. and Deitel H. (2015) “Java How To Program”, 10ed, Pearson.
– Liang, Y.D. (2015) “Introduction to Java Programming”, Comprehensive
Version, 10ed, Prentice Hall.
– Wu, C.T. (2010) “An Introduction to Object-Oriented Programming with
Java”, 5ed, McGraw Hill.
– Oracle Corporation, “Java Language and Virtual Machine Specifications”
https://docs.oracle.com/javase/specs/
53