Lecture1 Intro to Java
Lecture1 Intro to Java
Lecture Note #1
Introduction to Java
Outline
1. Java: Brief history
2. Run cycle
3. Basic program structure
4. Basic Java program elements
4.1 Primitive and Reference Types
4.2 Control Flow Statements and Logical Expressions
4.3 Basic Input (Scanner class) and Output
4.4 User defined method (class method)
4.5 Useful Java API classes – Scanner, Math, String
4.6 Essential OOP concepts for CS2040
2
1. Java: Brief History
James Gosling
1995, Sun Microsystems
3
Java: Compile Once, Run Anywhere?
Normal executable files are tied to OS/Hardware
An executable file is usually not executable on
different platforms
E.g: The a.out file compiled on sunfire is not
executable on your Windows computer
Java overcomes this by running the executable
on an uniform hardware environment simulated
by software
This is the Java Virtual Machine (JVM)
Only need a specific JVM for a particular platform to
execute all Java bytecodes without recompilation
4
2. Run Cycle Run Cycle for Java Programs
Writing/Editing Program vim HelloWorld.java
Compiling Program
Use a Java compiler, e.g.: javac javac HelloWorld.java
Compiled binary has .class extension
The binary is also known as
HelloWorld.class
Java Executable Bytecode
Executing Binary
Run on a Java Virtual Machine (JVM) java HelloWorld
e.g.: java HelloWorld
(leave out the .class extension)
output
Note the difference compared to C executable
5
3. Basic Structure Hello World!
6
3. Basic Structure Hello World! - Dissection (1/3)
import java.lang.*; // optional
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
HelloWorld.java
7
3. Basic Structure Hello World! - Dissection (2/3)
import java.lang.*; // optional
public class HelloWorld { Beginners’ common
mistake:
public static void main(String[] args) {
Public class name not
System.out.println("Hello World!"); identical to program’s
file name.
}
}
HelloWorld.java
8
3. Basic Structure Hello World! - Dissection (3/3)
import java.lang.*; // optional
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
HelloWorld.java
12
Identifier, Variable, Constant (2/2)
Constant is used to represent a fixed value
Eg: public static final int PASSING_MARK = 65;
Keyword final indicates that the value cannot change
Guidelines on naming
Class name: UpperCamelCase
Eg: Math, HelloWorld, ConvexGeometricShape
Variable name: LowerCamelCase
Eg: countDays, innerDiameter, numOfCoins
Constant: All uppercase with underscore
Eg: PI, CONVERSION_RATE, CM_PER_INCH
Reference from old module …
http://www.comp.nus.edu.sg/~cs1020/labs/styleguide/styleguide.html
13
Primitive and Reference Types
Data types in Java are categorized into 2 groups
Primitive types – byte, short, int, long, float, double,
char, boolean
Variable of primitive type “store” a value of the same type as the
variable in the stack (fast memory access)
Reference types – any class in Java
Variable of reference type do not store a value of the same type
as the reference but rather the “memory address” of a value
(more accurately an object) of the reference type in the heap
(slower memory access)
This memory address is also know as a reference/pointer
In order to create/instantiate an object of the reference type we
have to use the “new” keyword (will see this later)
14
Primitive Numeric Data Types
Summary of numeric data types (primitive types) in Java:
Type Size Range
Name (#bytes)
byte 1 -27 to 27-1
Integer Data
Types
Usually you will use int for integers and double for floating-point
numbers
char can be considered an integer data type as each character is
associated with an integer ASCII value
15
Numeric Operators
() Parentheses Grouping Left-to-right
++, -- Postfix incrementor/decrementor Right-to-left
Higher Precedence
16
Numeric Data Type Conversion
When operands of an operation have differing types:
1. If one of the operands is double, convert the other to double
2. Otherwise, if one of them is float, convert the other to float
3. Otherwise, if one of them is long, convert the other to long
4. Otherwise, convert both into int
17
Data Type Conversion
Conversion mistake:
double d;
int i; What’s the mistake? How
do you correct it?
i = 31415;
d = i / 10000;
19
Instantiating/creating an object
Since the wrapper classes are a reference type, after
declaring a variable of the wrapper class type we still have
to instantiate/create an object of the class to use it
20
Schematic view of primitive vs reference type in
memory
Eg int i = 7
i
7
21
Reference Types: Wrapper Classes (2/2)
We may convert a primitive type value to its corresponding
object. Example: between int and Integer:
int x = 9;
Integer y = new Integer(x);
System.out.println("Value in y = " + y.intValue());
23
Autoboxing/unboxing (2/2)
Converting an object of a wrapper type (e.g.:
Integer) to its corresponding primitive (e.g: int)
value is called unboxing.
The Java compiler applies unboxing when an object of
a wrapper class is:
Passed as a parameter to a method that expects a value of the
corresponding primitive type
Assigned to a variable of the corresponding primitive type
int i = new Integer(5); // unboxing
Integer intObj = 7; // autoboxing i = 5
System.out.println("i = " + i); intObj = 7
System.out.println("intObj = " + intObj);
24
Arrays in Java (1)
An array in Java is a reference type
You need to “new” an array instantiate an
array object
An array can store either primitive values or
objects (more precisely the references
pointing to them)
25
Arrays in Java (2)
Declaring an array is as follows
<type> [] identifier;
e.g float [] height;
declares an array of floating point values
26
Arrays in Java (3)
To instantiate a height array of size say 10 and a weight
array of size 10x10
height = new float[10];
weight = new float[10][10];
or simply
float [] height = new float[10];
float [] weight = new float[10][10];
28
Schematic view of array in memory (1)
E.g int [] height = {1,2,3}
height
1 2 3
3 4 5
30
Problem 1: Adding 2 fractions
Write a simple Java program FractionV1.Java:
𝑎𝑎 𝑐𝑐
Given 2 fractions +
𝑏𝑏 𝑑𝑑
31
P1: Adding 2 fractions
FractionV1.java
public class FractionV1 {
a = 1; Output:
b = 2; New Fraction = 10/8
c = 3;
d = 4;
newDenom = b*d;
newNum = a*d+c*b;
System.out.println("New Fraction = "+newNum+"/"+newDenom);
}
}
Notes:
10/8 is not the simplest form but it will suffice here
“+” in the printing statement
Concatenate operator, to combine strings into a single string
Variable values will be converted to string automatically
There is another printing statement, System.out.print(), which does not
include newline at the end of line
32
4.2 Control Statements
boolean variable;
boolean isEven;
int input;
// code to read input from user omitted
if (input % 2 == 0)
Example
34
Boolean Operators
Operators Description
< less than
Operands are variables /
> larger than values that can be
Operators
Relational
compared directly.
<= less than or equal
>= larger than or equal Examples:
== Equal X < Y
1 >= 4
!= not equal
&& and Operands are boolean
Operators
variables/expressions.
Logical
|| or
! Examples:
not
(X < Y) && (Y < Z)
^ exclusive-or (!isEven)
35
Selection Statements
if (a > b) { if-else statement
... else-part is optional
}
else {
Condition:
... Must be a boolean expression
} Unlike C, integer values are NOT valid
36
Repetition Statements
Valid conditions:
while (a > b) {
... //body Must be a boolean expression
} while : check condition before
executing body
do { do-while: execute body before
... //body condition checking
} while (a > b);
A: initialization (e.g. i = 0)
for (A; B; C) { B: condition (e.g. i < 10)
... //body C: update (e.g. i++)
}
Any of the above can be empty
Execution order:
A, B, body, C, B, body, C, …
37
4.3 Basic Input/Output
import java.util.Scanner;
//Functionality provided
scVar.nextInt(); Read an integer value from
SYNTAX
source System.in
39
P2: Reading Input for 2 Fractions
import java.util.*; // or import java.util.Scanner;
newDenom = b*d;
newNum = a*d+c*b;
System.out.println("New Fraction = "+newNum+"/"+newDenom);
}
}
FractionV2.java
40
P2: Reading Input - Key Points (1/3)
import java.util.*; // or import java.util.Scanner;
41
P2: Reading Input - Key Points (2/3)
import java.util.*; // or import java.util.Scanner;
43
Writing Output: The Standard Output
System.out is the predefined output device
Refers to the monitor/screen of your computer
//Functionality provided
System.out.print( output_string );
SYNTAX
System.out.println( output_string );
Output:
System.out.print("ABC"); ABCDEF
System.out.println("DEF"); GHI
System.out.println("GHI"); Very C-like 3.142
44
Writing Output: printf()
Java introduces printf() in Java 1.5
Very similar to the C version
The format string contains normal characters and a
number of specifiers
Specifier starts with a percent sign (%)
Value of the appropriate type must be supplied for each specifier
Common specifiers and modifiers:
%d for integer value
%f for double floating-point value %[-][W].[P]type
SYNTAX
%s for string
-: For left alignment
%b for boolean value W: For width
%c for character value P: For precision
45
P3: Add 2 fractions and output the new
fraction in simplest form
New requirement: Given the new fraction we
want to express it in it’s simplest form
e.g 1: Simplest form of 2/3 is 2/3 itself
e.g 2: Simpest form of 10/8 is 5/4
47
P3 Solution
import java.util.*; // using * in import statement
int rem,e,f;
e = newNum;
f = newDenom;
while (f > 0) {
rem = e%f;
e = f;
f = rem;
} // GCD is the value of e after while loop stops
newNum /= e;
newDenom /= e;
System.out.println("New Fraction = "+newNum+"/"+newDenom);
}
}
FractionV3.java
48
4.4 User defined method
(class method)
50
P4: Writing a class method for gcd
public class FractionV4 { FractionV4.java
52
4.5 Useful Java API classes –
Scanner, Math, String
API Specification
http://docs.oracle.com
/javase/8/docs/api/
54
Scanner Class: Reading Inputs
API documentation
http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
For reading input Note Java naming convention
Import java.util.Scanner Method names – lowerCamelCase
next()
nextDouble()
nextInt()
nextLine()
…
hasNext()
hasNextDouble()
hasNextInt()
hasNextLine()
…
55
String Class: Representation in Text
API documentation
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html
Import java.lang.String (optional)
Ubiquitous; Has a rich set of methods
charAt()
concat()
equals()
indexOf()
lastIndexOf()
length()
toLowerCase()
toUpperCase()
substring()
trim()
And many more…
56
String Class: Demo (1/2)
public class TestString { TestString.java
public static void main(String[] args) {
String text = new String("I'm studying CS2040.");
// or String text = "I'm studying CS2040.";
57
String Class: Demo (2/2)
Outputs Explanations
text: I'm studying CS2040.
length() returns the length (number of
text.length() = 20 characters) in text
charAt(5) returns the character at
text.charAt(5) = t position 5 in text
newText = newText.toUppercase()
converts characters in newText to uppercase.
The + operator is
newText: I'M STUDYING CS2040.HOW ABOUT YOU? string concatenation.
59
String Class: Immutable class
String objects once created are immutable, that is you
cannot change the content of the object
This is why you see that all operations which “changes”
the string actually returns a new string
Not taking this into consideration can result in
inefficient string processing
For mutable strings you can look up StringBuilder in
the Java API
There are other immutable classes in Java API
including all the primitive wrapper classes
60
Sequence and Subsequence
A sequence is any enumerated collection of
items in which repetition is allowed.
For example a sequence of integers <1,3,5,9,10>
A String can be considered a sequence of characters
2 class attributes
(constants):
E and PI
62
Math Class: Demo
Enter 3 values: 3.2 9.6 5.8
import java.util.*; pow(3.20,9.60) = 70703.317
public class TestMath2 { Largest = 9.6
public static void main(String[] args) {
Generating 5 random values:
Scanner sc = new Scanner(System.in);
0.874782725744965
System.out.print("Enter 3 values:0.948361014412348
");
double num1 = sc.nextDouble(); 0.8968816217113053
double num2 = sc.nextDouble(); 0.028525690859603103
double num3 = sc.nextDouble(); 0.5846509364262972
System.out.printf("pow(%.2f,%.2f) = %.3f\n",
num1, num2, Math.pow(num1,num2));
System.out.println("Largest = " +
Math.max(Math.max(num1,num2), num3));
System.out.println("Generating 5 random values:");
for (int i=0; i<5; i++)
System.out.println(Math.random());
}
}
TestMath.java
63
4.6 Essential OOP Concepts for
CS2040
65
Encapsulation in Java Class
Encapsulation
Bundling data and associated functionalities
Hide internal details and restricting access
66
Data in a java Class (1)
Data in a java Class is represented by
attributes/variables that you declare outside
of the methods but within the class
Instance Attribute Each created instance/object
of a class has it’s own copy of the instance
attribute
Class Attribute Associated with the class, and
is shared by all objects created from the class
Usually used to denote constants or in some rare cases
global variables (e.g keeping a count of the number of
objects created for a class)
67
Data in a java Class (2)
Declaring Attributes in Java
Instance Attribute Similar to declaring any
variable but it should be outside of any method in
the class, e.g class Circle {
public int radius;
…
}
…
}
71
Simple design guidelines (2)
Instance method Method which needs to
operate on the instance attributes in an object
72
Fraction class OOP design (1)
Make the Fraction class actually represent a
fraction (1)
Make the numerator, denominator as instance
attributes
Make instance methods to access/modify the
numerator/denominator (also know as
accessor/mutator methods)
Make gcd a class method (not really associated with a
specific fraction)
73
Fraction class OOP design (2)
Make the Fraction class actually represent a
fraction (2)
The addition operation can be made either a class or
instance method
Class method if you do not modify the attributes of the object
but merely return a new Fraction that is the result of the
addition (pass both fractions into add method)
Instance method if you modify the attributes of an object after
perform addition with another Fraction object we will
implement this one
74
FractionOOPV1 class (1)
class FractionOOPV1 {
public int num, denom; Instance attributes
76
Overloading methods
Methods in a class can be overloaded
Having multiple methods with the same name but
different parameters
The correct method will be called based on what
arguments are supplied for the parameters
//instance method add -> takes in another fraction add to this fraction
//and modify it
public void add(FractionOOPV1 iFrac) {
num = num*iFrac.getDenom()+denom*iFrac.getNum();
denom = denom*iFrac.getDenom();
int divisor = gcd(num,denom);
num /= divisor;
denom /= divisor;
}
}
FractionOOPV1.java
80
Fraction class OOP design (3)
FractionOOPV1 is now called a service class
(like the classes in the Java API)
It can be used by anyone who has access to
your Fraction class whenever they need to
represent fractions
Now in order to test out or make use of our
FractionOOPV1 class we have to create a
client class
This is the public class with the main method
81
TestFractionOOPV1 client class V1
A client class we can create is as follows
82
Overriding methods
All classes in Java “inherit” from the Object
class
One method inherited is the toString method
which returns a string representation of the
object for output/printing purposes
However in order to be useful you will have to
override the method (provide your own
implementation to format your object as a
string nicely)
83
Overriding the toString method
class FractionOOPV1 { FractionOOPV1.java
84
TestFractionOOPV1 client class V2
The client class can now be updated as follows
85
Finishing touches
Usually we don’t just perform 1 addition
operation
We can be given a list of addition operations
The input would be then be
First the number of addition operations N
Followed by N addition operations (given N number of
fraction pairs to add)
86
Finished TestFractionOOPV1
public class TestFractionOOPV1 {
88
Extra: “this” reference (2)
The “this” reference is used to solve the problem in
the preceding example where parameter name is
identical to attribute name
public void setNum(int num) {
}
num = num;
public void setDenom(int denom) {
denom = denom;
}
denom