2 (1,2) Introduction To Java
2 (1,2) Introduction To Java
[CMP167
[CMP167-Unit
Lecture3-Introduction
1: IntroductiontotoJava]
Java] 3
2. Run Cycle Recap: Process
• Tool: • Tool:
• Tool: Editor Compiler None
• Produce: • Produce: • Produce:
Source Code Executable Result
Bytecode
Compilation Error
Runtime Error
Logic Error
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 4
2. Run Cycle Recap: Run Cycle for C Programs
vim welcome.c
◼ Writing/Editing Program
❑ Use an editor, e.g.: vim
❑ Source code must have a .c welcome.c
extension
◼ Executing Binary
❑ Type name of executable file [Link]
output
[CMP167
[CMP167-Unit
Lecture3-Introduction
1: Introduction
toto
Java]
Java] 5
2. Run Cycle Java: Compile Once, Run Anywhere?
◼ Normal executable files are directly dependent
on the OS/Hardware
❑ Hence, an executable file is usually not executable
on different platforms
❑ E.g: The [Link] 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
❑ The hardware environment is know as the Java
Virtual Machine (JVM)
❑ So, we only need a specific JVM for a particular
platform to execute all Java bytecodes without
recompilation
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 6
2. Run Cycle Run Cycle for Java Programs
vim [Link]
◼ Writing/Editing Program
❑ Use a text editor, e.g: vim
❑ Source code must have .java extension [Link]
◼ Compiling Program
❑ Use a Java compiler, e.g.: javac javac [Link]
❑ Compiled binary has .class extension
❑ The binary is also known as Java
[Link]
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 here compared to C
executable
[CMP167
[CMP167-Unit
Lecture3-Introduction
1: IntroductiontotoJava]
Java] 7
2. Run Cycle Java Execution Illustration
[Link] Normal executable (e.g.: C programs) are
tied to a specific platform (OS + Hardware)
This [Link] cannot work in a machine of
Windows 7 on Core 2 different architecture.
Windows 7 on Core 2
They are the same
[Link] portable file.
MacOS on PowerPC
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 8
3. Basic Java Program Structure
◼ Today: just the basic language components:
❑ Basic Program Structure
❑ Primitive data types and simple variables
❑ Control flow (selection and repetition statements)
❑ Input/output statements
◼ Purpose: ease you into the language
❑ You can attempt to “translate” some simple C
programs done in 501042 into Java
◼ We will gradually cover many other Java features over
the next few weeks
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 9
3. Basic Structure Hello World!
#include <stdio.h> C
int main(void) {
printf("Hello World!\n");
return 0;
} HelloWorld.c
[CMP167
[CMP167-Unit
Lecture3-Introduction
1: IntroductiontotoJava]
Java] 10
4.1 Arithmetic Expressions
4.1 Identifier, Variable, Constant (1/2)
◼ Identifier is a name that we associate with
some program entity (class name, variable name,
parameter name, etc.)
◼ Java Identifier Rule:
❑ May consist of letters (‘a’ – ‘z’, ‘A’ – ‘Z’), digit
characters (‘0’ – ‘9’), underscore (_) and dollar sign ($)
❑ Cannot begin with a digit character
◼ Variable is used to store data in a program
❑ A variable must be declared with a specific data type
❑ Eg: int countDays;
double priceOfItem;
[CMP167
[CMP167-Unit
Lecture
3-Introduction
1: Introduction
to to
Java]
Java] 12
4.1 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 how to name classes, variables,
and constants:
❑ 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
[CMP167
[CMP167-Unit
Lecture 3-Introduction
1: Introductionto
toJava]
Java] 13
4.1 Numeric Data Types
◼ Summary of numeric data types in Java:
Type Size Range
Name (#bytes)
byte 1 -27 to 27-1
Integer Data
short 2
Types
-215 to 215-1
int 4 -231 to 231-1
long 8 -263 to 263-1
float 4
Point Data
Types
Q: What is assigned to d?
The (int) d expression is
◼ Type casting: known as type casting
double d; Syntax:
int i;
(datatype) value
d = 3.14159;
i = (int) d; // i is assigned 3
Effect:
Q: What is assigned to i if d contains value is converted explicitly to
3.987 instead? the data type stated if possible.
◼ Notes:
❑ 5.0/9 is necessary to get the correct result (what will 5/9 give?)
❑ “+” 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, [Link](), which does
not include newline at the end of line (more in section 4.3)
boolean variable;
boolean isEven;
int input;
// code to read input from user omitted
if (input % 2 == 0)
Example
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 (XOR) (!isEven)
[Link]
[CMP167-Unit 3-Introduction to Java] 22
4.2 Comparison with C
◼ In ANSI C, there is no boolean type.
❑ Zero means ‘false’ and any other value means ‘true’
int x;
... // assume x is assigned a non-negative value
if (x%3)
printf("%d is not divisible by 3.\n", x);
else
printf("%d is divisible by 3.\n", x);
◼ 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, …
[CMP167-Unit 3-Introduction to Java] 25
4.2 Repetition Statements (2/2)
◼ In ANSI C, the loop variable must be declared before it is
used in a ‘for’ loop
int i;
for (i=0; i<10; i++) {
...
}
import [Link];
//Functionality provided
SYNTAX
}
}
[Link]
[CMP167-Unit
[CMP167 Lecture 3-Introduction
1: Introductionto
toJava]
Java] 32
4.3 Writing Output: The Standard Output
◼ [Link] is the predefined output device
❑ Refers to the monitor/screen of your computer
//Functionality provided
[Link]( output_string );
SYNTAX
[Link]( output_string );
Output:
[Link]("ABC"); ABCDEF
[Link]("DEF"); GHI
[Link]("GHI"); Very C-like 3.142
[CMP167-Unit
[CMP167 Lecture 3-Introduction
1: Introductionto
toJava]
Java] 33
4.3 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
[CMP167-Unit
[CMP167 Lecture 3-Introduction
1: Introductionto
toJava]
Java] 34
4.3 Problem: Approximating PI
◼ One way to calculate the PI () constant:
4 4 4 4 4
= − + − + − .........
1 3 5 7 9
◼ Write [Link] to:
1. Ask the user for the number of terms to use
for approximation
2. Calculate with the given number of terms
3. Output the approximation in 6 decimal
places
[CMP167-Unit
[CMP167 3-Introduction
Lecture 1: Introduction to Java] 38
4.4 API (2/2)
48
Java Exercises
◼ Write functions to calculate the below formulas
with n is provided by user (each formula is one
function):
49
Homework
◼ Setup the Java Environment (Java JDK,
environment variable), compile and run the Java
program by using command line.
◼ Setup IntelliJ IDEA Community Edition in your
computer
◼ Create Arrays
dataType[] arrayRefVar = new dataType[arraySize];
◼ Example:
double[] myList = new double[10];
58
Homework
◼ Write a Java program to calculate the average
value of array elements.
◼ Write a Java program to test if an array contains
a specific value.
◼ Write a Java program to find the index of an
array element.
◼ Write a Java program to find the second largest
element in an array.
◼ Write a Java program to convert an array to an
ArrayList.
59
6 String
Java String
◼ In Java, string is basically an object that
represents sequence of char values. An array of
characters works same as Java string. For
example:
- Arithmetic Expression
- Boolean Expression
Control Flow Statements:
- Selection Statements: if-else, switch-case
- Repetition Statements: while, do-while, for
Classes:
- Scanner
- Math
Array
StringBuffer - StringBuilder
[CMP167-Unit 3-Introduction to Java] 76
End of file