CSIT111 Lecture 3
CSIT111 Lecture 3
CSIT111 Lecture 3
1
Starting Point
• A Java program is comprised of classes
- How many classes should I define in my program?
- How to declare attributes and methods?
. . . There will be many other questions after these ones are answered
• Let's analyze a simplest possible program that has only
one class and this class has only one method main()
UML source file: Welcome.java
/* --- A simple Java program --- */
Welcome
class Welcome
+main()
{
public static void main(String[] args)
Even a simple {
program must have System.out.print("Welcome !");
at least one class
}
} // end of class Welcome
2
Class definition
Class declaration class Welcome
{
Class body
}
5
Comments
• Even a well written program may be hard to follow if it
implements complex data processing algorithms, or has a
complex architecture
• It is a common programming practice to insert comments
to improve readability of programs
• Comments in Java programs are indicated by special
combination of characters
1. /* these comments can span several lines */
/* A simple Java program
UOW , SCIT 2017 */
2. // these are one line comments
// calculation of the transform coefficient
3. /** these comments are processed by javadoc program */
• Comments are ignored by the compiler and have no
affect on the program execution
6
Program 2: add two numbers
• The major purpose of programs is to process data
• Let's implement a simple program that calculates a sum
of two numbers and displays the result
What should be
/* A simple program that calculates the sum */ a name of the
class SimpleAdder file to store this
{ source code?
public static void main(String[] args)
{
// calculate and print the result
System.out.print("The sum = ");
System.out.println( 3.5 + 4.5 );
} an expression
}
10
Declaration of variables
• Declaration of a variable is a non-executable statement and
therefore it must be terminated with ; (as all Java statements)
Data type Identifier (name) ;
int number;
int numberOfDays;
Examples:
int itemsInStock, code, frameRate;
char grade, inputCharacter;
double totalPrice;
11
Java reserved words
Words reserved in the Java programming language that are
forbidden for identifiers (class/method/variable names)
• Fixed values which you use in your source code are called literals
• Literals do not have any designated location in memory
• Literals can be specified using different notations, or numbering systems
double distance = 2.34e6; scientific notation for 2.34×106
Literals of invisible characters are
char code = '\n';
specified through escape sequences
\n – new line, direct output to the
variable literal next line of the command window
\t – horizontal tab
14
Arithmetic operators and expressions
• Once a variable has been declared and initialised, it can
be used for data storage and processing
• Java defines a set of arithmetic operators
+ addition left operand operator right operand
- subtraction
* multiplication
/ division speed * time
. . . .
expression
• Operators which require two operands are called binary operators
• A sequence of operands and operators that produces a value is
called an expression
Examples of 4.5 * newValue - oldValue
expressions: (number1 + number2)/2.0
3.14159 * radius * radius
15
Assignment operator
this keyword indicates a Name of the constant The actual value of the
constant Java notation - uppercase symbolic constant COEFF
17
Symbolic constants
• Define a symbolic constant when a fixed value is needed
• Use it everywhere in your program instead of literals
• If the actual value needs to be changed, the literal needs to
to be changed only in the constant declaration statement
public static void main(String[] args)
{
. . .
final double COEFF = 1.609; // conversion coefficient for English mile
final double PI = 3.1416; // a more accurate value may be needed
. . .
distInKilom = COEFF * distInMiles;
. . .
area1 = PI * radius1 * radius1;
. . .
area2 = PI * radius2 * radius2;
}
18
Quiz
Statement
Operands
Statement
terminator
Operators Expression
19 19
Quiz
class Example
{
public static void main(String[] args)
{
double num1= 0.5, num2, num3, result; // declare variables
num2 = 4.0; // assign a value to num2
result = (num1 + num2) * num3;
System.out.println( result ); // print the result
}
}
20
Math functions
• Java defines only a limited set of arithmetic operators
(there are some others to be discussed later) that may not be
enough to implement complex calculations
• Java is an extensible language. It has a library Math of
methods for performing the most common numeric
operations
21
Math functions
1] 1]
22
The import statement
• It may be a bit inconvenient to type Math every time you use a
method or a constant defined in this class
• If you simply omit the class name, the compiler will not be able to
find these methods and constants as they are defined inside the class
• Java provides an import statement that notifies the compiler where to
find the required methods, constant, or classes
class SignalProcessor
{
. . .
public double getPhase( double time, double f )
{ You don't need to specify Math
. . .
explicitly as it is specified implicitly
phase = sin( 2.0*PI*f*time ); through the import statement
. . .
}
23 }
Java packages
• The Java designers have proposed a flexible network based
environment where classes can be loaded if their directories are
accessible ( locally, or via networks )
• There are currently more than 4000 classes in Java API and all
visible identifiers must be unique (which is hard to achieve)
• To avoid collision of names, Java classes are grouped together into
separated namespaces which are called packages
• Actually, to use any Java component you need to specify its full
name including its package
Example: ph = java.lang.Math.cos(0.5);
25
A simple application scenario
• Programming is a problem solving activity that involves understanding
of the application area and analysis of the problem
Write a program that converts distance measured
in miles into kilometres
1. Analyze the problem (input data, output data, data processing algorithm)
Input: distance in miles
Output: distance in kilometres
Algorithm: kilometres = 1.609 * miles
2. Use UML to describe a class
3. Implement the program
Converter
Converter
-distInMiles:
-distInMiles:
What is wrong -distInKilom:
-distInKilom:
with this class? -COEFFICIENT
-COEFFICIENT == 1.609
1.609 {read
{read only}
only}
++ main()
main()
26
Java implementation
/* A program that converts miles into kilometres Converter.java
input: distance in miles -> output: distance in kilometres */
import java.util.Scanner; // import Scanner class
class Converter
{ // --- fields ---
private static double distInMiles;
private static double distInKilom;
private static final double COEFF = 1.609;
// --- definition of the method main() ---
public static void main(String[] args)
{
// Create a scanner that can read numbers, or words
Scanner input = new Scanner(System.in);
System.out.print("Enter distance in miles:");
distInMiles = input.nextDouble(); // input a number typed by a user
// calculate the distance
distInKilom = COEFF * distInMiles;
// output the result
System.out.println("Distance = " + distInKilom + " km");
}
} // end of class Converter
Distance = 160.9 km
27
Keyboard input
• Scanner methods nextInt(), nextFloat() and nextDouble()
do not read keyboard input directly ( Java cannot have direct access to
hardware )
• Everything what you type goes into the keyboard input buffer first
(processed by the operating system modules)
• Java uses Scanner to reads whatever has been placed into the buffer
Java program
Keyboard input buffer
Scanner 3 0 . 5 1 4 e 2 \t K 5 \cr
cannot be interpreted as a number
– Print date as 25
printf("%d", date);
– Print date as Today is 25th and direct output to the next line
printf("Today is %dth \n", date);
30
printf(…) method
format string print list
31
printf(…) method
• Formatting parameters
Grayed parameters are optional.
% flag width .prec type If they are used, they must appear in this order
type Interpretation
d Display as an integer
f Display as a floating point number
(with six decimal places by default)
e Display a floating-point number in exponential format
c Display a single character
32
printf(…) method
printf("Doubles:\n"); Doubles:
printf("%f %e\n", weight, weight); 12.978000 1.297800e+001
printf("%.2f %.2e\n", weight, weight); 12.98 1.30e+001
printf("%.0f %.0e\n", weight, weight); 13 1e+001
printf("%9.2f %9.2f\n", weight, temp); 12.98 -97.46
9 positions 9 positions
reserved reserved
33
Binary Numeral System
Source code Program memory
byte a = 5; 11111011
1011
1011 = 1*23 + 0*22 + 1*21 + 1*20
2 is a base
A weight of each symbol also depends on its position
The binary system and binary arithmetic was invented by Gottfried Leibniz
and published in 1701 in Paris.
The first computer utilising the binary system was built in 1946 at the
University of Pennsylvania.
37
Binary to Decimal conversion
• Binary number
101011 = 1*25 + 0*24 + 1*23 + 0*22 + 1*21 + 1*20
20 = 1
21 = 2
22 = 4
3
2 = 8
24 = 16
25 = 32
26 = 64
27 = 128
38
Quiz
• Convert to decimal
0000 = 0*8 + 0*4 + 0*2 + 0 = 0 20 = 1
21 = 2
22 = 4
1000 = 1*8 + 0*4 + 0*2 + 0 = 8
23 = 8
24 = 16
5
1111 = 1*8 + 1*4 + 1*2 + 1 = 15 2 = 32
6
2 = 64
27 = 128
39
Decimal to Binary conversion
• Conversion from binary to decimal:
repetitive multiplication and addition
• Conversion from decimal to binary:
repetitive division by 2 and subtraction
STOP
2. Convert to binary: 9
41
Terminology
• A bit: 0 or 1
• A byte: 1 0 0 0 1 0 1 1
42
Binary Addition
• Addition is carried out on individual bits
taking into account carry bits
Basic rules:
0 + 0 = 0 1 + 0 = 1 1 + 1 = 10
Example:
carry bit 1
1 0 1 0 10
+ 0 0 1 1 + 3
----------- ----
1 1 0 1 13
43
Signed Binary Numbers
• All Java variables are signed (they can store positive and
negative values)
• Signed binary numbers are represented in two's
complement format
unsigned format: 5 = 101
two's complement: 5 = 0101 an extra bit is required to
two's complement: -5 = 1011 represent a sign
0 0 0 0 0 0 0 0 -> 0
0 0 0 0 0 0 0 1 -> 1
0 1 1 1 1 1 1 1 -> 127
1 0 0 0 0 0 0 0 -> -128
1 1 1 1 1 1 1 1 -> -1
45
Suggested reading
46