CS Notes
CS Notes
Human
Assembly Language
• Symbolic representation of machine code
• e.g. MOVE 5 0X123
• Machine dependent
Assembler
Machine Language
• Sequence of binary digits
• e.g. 1001101
Computer Hardware
ReadyToProgram
• Java IDE
• No debugger
• Contains Java classes (HSA package) which make input / output easier
Dr Java
• Java IDE
• Has a debugger
• Has a interactive panel
Introduction to Java
Brief tour on Dr Java
• Menu: File, Tools, Project, Debugger, Language Level, Help
• Tools: Open Java API JavaDoc
• The editor
o Colour code
o Auto Indent (Tab)
• Compile & Run
File New
Comment:
• Starts with //
• Colour in green Class name:
• Ignored by the compiler • Start with capital letter
• Information regarding the • Source file is saved as
code for easy understanding // The "SayHello" class.
SayHello.java
import java.io.*;
• Class file is SayHello.class
Import packages:
public class SayHello main:
• classes in the packages can
{
be used within the program • Where the program starts
public static void main (String[] args)
running
{
/* The following line print a line of text to output */
System.out.println("Hello");
} // main method
Matching Brackets } // SayHello class
• Brackets defines a block of
System.out.println:
code
• No nesting • print the line “Hello”
Screen output
• displaying characters on the screen (numbers, letters, special characters,
spaces etc)
• formatting: controlling the way information is displayed eg. tabs, line breaks,
etc.
print: prints characters and leaves the cursor on the same line
println: prints characters and inserts a line break character; subsequent
print statements will start on the next line
Examples:
(Note that ‘^’ represents a space on the screen)
Note:
• the string is duplicated literally ie. 1 space = 1 space, no space = no space;
what you see is what you get.
• notice the quotes are not written to the screen
• notice that numbers and non-letters can be part of the string
• control characters eg \t, \n,\\ can be used for formatting
Exercise:
What will the output be for the following code?
Code Output
System.out.println(“yabba^^^dab Yabba^^^dabba
ba”);
System.out.println ( Yes
“yes\n\nmame”); >
mame
System.out.println \\\n2+3
(“\\\\\\n2+3”);
System.out.print(“big”); Bigapple
System.out.println(“apple”); =New York
System.out.println(“=New
York”);
Reference: http://java.sun.com/developer/technicalArticles/releases/1.4regex/
Examples:
\b backspace.
\e ASCII escape character.
\f form feed (new page).
\n newline.
\r carriage return.
\t horizontal tab.
\\ one slash
Displaying numbers
examples:
notice:
• a number is evaluated not duplicated
Exercise:
What will the output be for the following code?
examples:
System.out.println(“5” + “2”); 52
System.out.println(5 + 2); 7
System.out.println ("8*8=^" + 8 + 8); 8*8=^88
System.out.println(8 + 8 + “=8*8”); 16=8*8
User Input & Storage
• Variables are named memory locations that can vary in value throughout the
program.
Syntax for variable declaration %recall that info in square brackets is optional
Examples
int num;
int a = 5;
float answer;
Input
For user keyboard input, the Scanner can be used. Note that the Scanner is not
available before Java SE 1.5.0.
import java.util.*;
Scanner sc = new Scanner(System.in);
Then different methods can be used depending on the type of input. For
example, to read an integer input from the user:
int i = sc.nextInt();
The nextInt() method read the input from the user and place it into the
variable i.
Other methods to read value of different types from the user:
byte nextByte() //Returns the byte value (-128 to 127) read from the
keyboard.
short nextShort() //Returns the 2-byte integer (-32,768 to 32,767) read
from the keyboard.
int nextInt() //Returns the 4-byte integer (-2,147,483,648 to
2,147,483,647) read from the keyboard.
long nextLong() //Returns the 8-byte integer read from the keyboard.
float nextFloat() //Returns the 4-byte float read from the keyboard.
double nextDouble() //Returns the 8-byte double read from the keyboard.
boolean nextBoolean() //Returns the boolean value (either true or false,
case insensitive) read from the keyboard.
String nextLine() //Returns the entire line of input read from the
keyboard without the Return
Input Syntax
import java.util.*;
:
Scanner sc = new Scanner(System.in);
identifer = sc.__________( );
Outputting variables
To print the values of the variables, use print / println with no quotes around
the variable names.
Example
import java.util.*; Output
:
int num;
float a;
Memory
Scanner c = new Scanner (System.in); Enter first value: 30 30 num
System.out.print(“Enter first value: “); Enter second value: 50 a
num = sc.nextInt( );
System.out.print(“Enter second value: “);
50
First value = 30
Second value = 50
a = sc.nextFloat( );
System.out.println(“first value = “ + num);
Sysetm.out.println(“second value =” + a);
Datatypes
There are many primitive datatypes in any language. These differ in the type of
information that can be stored and in the size of the memory location (number of
bytes) allocated for the variable.
Guidelines
1) under 256 characters
2) only letters, digits and underscores (_)
3) can’t start with a digit
4) no spaces
5) no reserved/keywords
Constant
A constant is used to store factual information, e.g. pi, or information that does
not change within the program, e.g. number of students in a class
Syntax:
final <datatype> <identifier> = <value>;
Example:
char ch;
ch = 65; /* 65 (an integer) is automatically cast into the
character with Unicode value 65 */
System.out.println (ch); //prints A; A has the Unicode value 65
Automatic conversion will only take place when there is no loss of data. If a
conversion results in the loss of precision, as in an int value converted to a short,
then the compiler will issue an error message unless an explicit cast is made.
Expressions can promote (convert) to a wider type (one with more memory; more
bits) without an explicit cast. For example:
int i=12;
long j; // Literals are int types so require L suffix
j=i; // OK; automatically converts int to long
Syntax: To convert type1 data into type2 data, put the type1 keyword in brackets
in front of the type2 data.
For example, to convert floating point data to integer data:
int i ;
float f= 5.6F;
i = (int) f; // Cast float as int (truncates the decimals)
System.out.println(i); //prints 5
However, you can not assign a value to a more narrow type without an explicit
cast:
int i=12;
long j = 123L;
i=j; // Error in assigning long to int
i=(int)j; // OK; converts long to int
Summary:
So a data type with lower precision (fewer bits) can be converted to a type of
higher precision without explicit casting. To convert a higher precision type to a
lower precision, however, an explicit cast is required or the compiler will flag an
error.
Note that when you cast a value of a wider type down to a more narrow type,
such as an int value to a byte variable, the upper bytes will be truncated. That is,
the lowest order byte in the int value will be copied to the byte value. Data may
be lost.
Primitive Type Conversion Table
Below is a table that indicates to which of the other primitive types you can cast a
given primitive data type. The symbol E indicates that an explicit cast is required
since the precision is decreasing. The symbol A indicates that the precision is
increasing so an automatic cast occurs without the need for an explicit cast. N
indicates that the conversion is not allowed.
int long float double char short byte boolean
int - A A* A E E E N
long E - A* A* E E E N
float E E - A E E E N
double E E E - E E E N
char A A A A - E E N
byte A A A A E A - N
short A A A A E - E N
boolean N N N N N N N -
The * asterisk indicates that the least significant digits may be lost in the
conversion even though the target type allows for bigger numbers. For example,
a large value in an int type value that uses all 32 bits will lose some of the lower
bits when converted to float since the exponent uses 8 bits of the 32 provided for
float values.
float x,y=3;
int j,i=3;
x= i*y; // OK since i will be promoted to float
j= i*y; // Error since result is a float value
j= (int)(i*y) // OK
The process of converting a value to a wider or higher precision integer or
floating point type is called "numeric promotion". The following rules apply for
promotion in an expression of two operands, as in x+i:
• If either operand is of type double, the other is converted to double.
• Otherwise, if either operand is of type float, the other is converted to float.
• Otherwise, if either operand is of type long, the other is converted to long.
• Otherwise, both operands are converted to type int.
Note that char data can be cast to other integer values but may result in
unexpected values since it is unsigned while the other integer types are signed.
Selection – if - then - else Structure
Scenario:
Consider the following scenario where a person is logging into a system (like TEL
or hotmail). In this case, the program needs to react differently under different
conditions eg. If the login information is correct, they should enter the system and
if something is incorrect than they should not be permitted entry.
Selection constructs are used in programs that require different execution paths
in different situations. In selection, execution paths are dependent on the
evaluation of certain values. We use selection constructs like if, if...then...else &
switch (which you know as case in Turing) to do this in our programs.
if Syntax:
if (condition)
Example
int x;
{
//body of if clause
System.out.print(“Enter a number”);
}
x = sc.nextInt();
if (x > 100( ))
{
System.out.println(“Your number is greater than 100”);
}
if..else Syntax:
Example
if (condition) final int FREEZE = 0;
{
//body of if clause double temp;
}
else System.out.print(“Enter the temperature”);
{ temp = sc.nextDouble();
//body of else clause
} if (temp > FREEZE)
{
System.out.println(“the ice will melt”);
}
else
{
System.out.println(“the water will freeze”);
}
Nested if structure
Nested if structure is an efficient way to implement more than two possibilities
are necessary.
Another kind of nested if structure is to have one if..else structure within another
one. The following example determines the largest among three values x, y, z
and assigns this value to largest.
if (x >= y) {
// y eliminated – largest must be either x or z
if (x >= z) {
largest = x;
} else {
largest = z;
}
} else {
// x eliminated – largest must be either y or z
if (y >= z) {
largest = y;
} else {
largest = z;
}
}
Boolean Expressions
• expressions that evaluate to true or false
Examples:
Expression Value
6 > 9 false
‘a’ < ‘b’ true (compare the ASCII code)
7 + 2 != 9 false
Comparison Operators
== Equals (important to use two; one equal sign will be an assignment
statement)
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Expression Value
9<3
8!= 64 % 8
‘a’ = = ‘A’
‘a’ > ‘A’
Boolean Operators
Truth Tables
These tables illustrate the behavior of the Boolean Operators given the different
values for expressions A and B.
Expression Expression !(A) A || B A && B
A B
false false true false false
false true true true false
true false false true false
true true false true true
Trace Example
int n;
System.out c.println(“Enter an integer”);
n = sc.nextInt(); User inputs 4
if (i >= 3)
{ yep Memory
System.out.println ("yep"); 4 i(i)
}
else if ((i = = 0) || (i < 2))
{
System.out.println ("jump");
}
else if (i != 2)
{
System.out.println ("nobody");
} User inputs 2
else
{ dump Memory
System.out.println ("dump"); i(i)
}
Switch Syntax:
The switch statement can be used for numerous paths when choosing a path based on a
single value rather than a range.
like a case statement in Turing
start execution at body of 1st matching value and continue until the break statement.
switch (expression)
{
case ordinal value: [case ordinal value:]
//body of 1st case(s)
[break;]
]
}
Example:
int option;
int operand1, operand2;
int operation;
System.out.println ("Calculations\n");
System.out.println ("Enter two operands to manipulate");
System.out.print ("operand 1: ");
operand1 = sc.nextInt ();
System.out.print ("operand 2: ");
operand2 = sc.nextInt ();
System.out.println ("\nOperator Menu\n");
System.out.println (ADD + ": Addition");
System.out.println (SUBTRACT + ": Subtraction");
System.out.print ("What calculation do you want to perform: ");
operation = sc.nextInt ();
switch (operation)
{
case ADD:
System.out.println ("result = " + (operand1 +
operand2));
break;
case SUBTRACT:
System.out.println ("result = " + (operand1 -
operand2));
break;
default:
System.out.println ("Invalid option. Try again");
}
} // main method
} // Switch class
while loop
You use a while statement to continually execute a block of statements while a
condition remains true.
Syntax:
while (boolean expression)
{
// body statements
}
Execution Details
The while statement evaluates expression, which must return a boolean value. If
the expression returns true, then the while statement executes the statement(s)
associated with it. The while statement continues to test the expression and
execute its block until the expression returns false.
Examples
int i = 1; int i = 1;
Things to note:
1. The variable value must be initialized before the loop is entered for the first
time.
2. With the brace (curly) brackets, here can be more than one statement in body
of the loop.
3. There must be some actions within the loop that will eventually cause the
condition to become false.
4. If the boolean expression that controls the loop is false the first time that the
while statement is encountered, then the statements within the loop body
will never be performed.
5. If the expression that controls the loop is never changed to false, then
program will get stuck in the while (infinite loop).
6. Once a program enters the while loop, the entire sequence of statements in
the body of the loop is executed and only then is the boolean expression is
re-evaluated to see if the loop should be entered again.
7. Once the loop has been exited, the boolean expression that controls it must
be false.
Example: Ask user for a list of positive numbers. The program will print the
number the user just entered until a negative number is entered.
Example: Ask user for a list of positive numbers. The user will enter a negative
number to terminate. The program will print the sum of the numbers.
Repetition – do... while Loop
You use a do_while statement to continually execute a block of statements while
a condition remains true.
Syntax:
do
{
// body statements
}
while (boolean expression);
Execution Details: First, the do..while statement executes the body statements
and then tests/evaluates the boolean expression. If the expression returns true,
then the do..while statement repeats. The do..while statement continues
testing the expression and executing its block until the expression returns false.
Example:
//this code displays the numbers from 1 to 10
int i = 1;
do
{
System.out.println(i);
i = i + 1;
} while (i <= 5);
Important: Unlike the while loop, a do...while loop will always (under any
circumstance) execute at least once because it is post-tested. The while loop is
considered pre-tested.
(file: Count)
display the values from 1 to 6 Trace Output
k is the repeat while k increment k by k k <=6 1
counter and is less than or 1 each time;
1 true 2
starts at value equal to 6 same as k = k +
1 1 2 true 3
3 true 4
5
for (int k = 1; k <= 6; k++) 4 true
6
{ 5 true
Sysetm.out.println(k); } 6 true
7 false
Counting Backwards
Sometimes a problem requires the counter to decrease in value rather than increase. In this
case, make sure that:
♦ the update statement is decreasing the value of the counter
eg. counter = counter - 1
♦ the condition statement is suitably changed eg. using a >
sign rather than a < sign
(file: Countdown)
display the values from 5 to 0 and Trace Output
print “Action”
k is the repeat while k decrement k by k k >=0
counter and is greater than 1 each time;
5
starts at value or equal to 0 same as k = k - 5 true 4
4 true 3
3 true 2
1
for (int k = 5; k >= 0; k--) 2 true
0
{ 1 true Action!
System.out.println(k); } 0 true
c.println(“Action!”); -1 false
Counting by Intervals
Some problems require increasing or decreasing the counter by more than 1. In the
following example the counter is increased by 7 on each iteration.
(file: Fridays) Write a program that displays the dates of all Fridays in
the given month. The number of days in the given month and the date Trac
of the first Friday should be entered by the user.
firs
int first, days; t
String month; 1
System.out.print ("Enter the month (eg. April): "); m
month = sc.nextLine (); M
System.print ("Enter the number of days in the month
(eg. 30): ");
days = sc.nextInt ();
System.out.print ("Enter the day of the first Friday
(eg. 5): ");
first = sc.nextInt ();
Output
Enter the month (eg. April): March
Enter the number of days in the month (eg.
30): 31
Enter the day of the first Friday (eg. 5): 1
Fridays in March
March 1
March 8
March 15
March 22
March 29
More often than not, the for statement's upper and/or lower bounds differ each run
depending on the given input. In these cases, we need to use
variables to store the boundary values. In the following example, the
user defines the boundary conditions.
Here is a list of tips and tricks to help with problem solving and
debugging the for loop
In General:
Use the for loop in your solution when:
♦ the number of repetitions will be determined prior to beginning the loop.
♦ the counter will increase or decrease by the same amount each repetition.
♦ the condition needs to be tested prior to the first and subsequent repetitions of the
body statements. The for loop is a prefix loop because it tests the condition prior to
entry.
Java Specific:
♦ If you don’t use brackets {} to enclose the body, then by default only the first
statement following the for will be repeated. Example:
for (int k = 0; k <= 30; k+=3)
a = a + 1; a = a+ 1 is the only statement in the body of
b = b + 2; the for loop. Only a = a + 1 will be
♦ An infinite loop will occur if the condition is always true. Examples:
1) for (int k = 1; k <= 5; k --)
3) for (;;)
♦ Never put a semicolon (;) at the end of the for line; this will end the construct with no
body statements. Example:
for (int i = 1; i <= n; i++); don't put a semicolon
♦ It is not good practice to alter the value of the counter variable inside the loop.
Example:
for (int i=1; i != 10; i++)
{
System.out.println(i);
i += 3;
}
♦ It is not good practice to alter the value of the boundary conditions inside the loop.
Example:
int N = 10;
for (int i=1; i != N; i++)
{
System.out.println(i);
N = N + 1;
}
Arrays
An array is a structure that holds multiple values of the same type. It allows a block of
memory to be reserved in one declaration thus allowing reference through the same
variable name.
The length of an array is established when the array is created (at runtime). After
creation, an array is a fixed-length structure.
e.g.
1 3 marks
2
3 marks[0]
4 marks[1]
5 marks[2]
6 marks[3]
7 marks[4]
8 marks[5]
9 marks[6]
10 marks[7]
11 marks[8]
12 marks[9]
The size of the array can be read in when the program is executed. When this happens,
the array is dynamic (not pre-determined at compile time).
int numstuds;
int[ ] marks;
System.out.print(“How many students are there: “);
numstuds = sc.nextInt();
marks = new int [numstuds];
System.out.println(marks.length);
2D Array
If 1D arrays are thought of as list, then 2D arrays can be thought of as tables. In
Java, 2D arrays are implemented as an array of arrays.
e.g.
The 2D array created above has 3 rows and two columns. It is represented as
an array of 3 arrays of size 2. Therefore table.length will return 3 (number of
arrays), and table[0].length will return 2 (number of elements in the first
array)
table[0][0] table[0][1]
table[1][0] table[1][1]
table[2][0] table[2][1]
The index of each element has two components: [row number][column number].
Note that, same as 1D array, index starts with 0.
In memory, a 2D array is stored contiguously with one row follows the other:
1 3 table
2
3 table[0][0]
4 table[0][1]
5 table[1][0]
6 table[1][1]
7 table[2][0]
8 table[2][1]
Since each element has two indices, in order to loop through each row, and each
column, a two level nested loop is required.
e.g.
Using a 2D array to store a set of five test marks for each of 4 students. Ask the
user to enter each mark and store it in corresponding location.
You can think of the table as below:
Test
0 1 2 3 4
0
Students
1
2
3
A class contains two main components: fields and methods. Fields are variables
that store data and methods are codes that perform actions.
import hsa.Console;
Console window;
window = new Console();
window.println(“Hello World”);
Note that when an instance of the class is created using new, the constructor
with corresponding perimeters is called.
Lesson – Strings
String overview:
• Strings are a series of characters. Examples: “a”, “1”, “a!b cde”.
• Every string has a length equal to the number of characters stored.
• Each character within a string has an index – In Java, the first character is
considered to be at index 0 (to go along with arrays starting at 0).
• Some languages have a string terminator character that is stored after the
last character; when a string has a capacity beyond its actual length, this
character indicates the end of the valid characters.
• A string can be empty of characters by assigning it the “” string. This is still a
valid string value. The length in this case is 0.
Unicode:
Each character has a Unicode equivalent, which the character is translated to
before storage. Example ‘A’ has the Unicode 65 and ‘a’ is 97. Because there are
under 256 characters, any character value can be stored in a byte of storage
space and thus this is the standard capacity used to store characters.
When characters are compared, there Unicode values are compared therefore,
‘a’ > ‘A’ is a true statement.
When strings are compared, they are compared lexicographically; from right to
left, characters at the same position are compared until the characters at that
position are different and these become the deciding character. Example “ab” <
“ac” and “abs” > “ab” and “abcdefg” > “aa”
String Object:
Declaring a String object comes with the benefit of predefined String methods.
The class String includes methods for examining individual characters of the
sequence, for comparing strings, for searching strings, for extracting substrings,
and for creating a copy of a string with all characters translated to uppercase or
to lowercase.
Example:
System.out.println("abcdefgh".substring(3,4)); //outputs d
System.out.println(str1.substring(1, str1.length( ) - 2)
// outputs ____?
Example:
if (“abc”.compareTo(“ABC”) < 0 )
System.out.println(“less than”); //output _____?
else
System.out.println(”greater than”);
Converting String to int
• methods are mini programs (sub programs) that perform isolated re-usable tasks
eg. Scanner class has many methods: reading a line (nextLine), reading an integer
(nextInt), reading a double (nextDouble) etc
• parameters: parameters are information passed into the class to change the
outcome of the task eg. String’s charAt method has 1 piece of information that
represent the index of the character to be returned.
• return values: methods may return values to the call eg. String’s charAt returns
the character at the specified index.
Method Declaration: this is the signature and body of the method; the actual code
that performs the task.
Method Call: this is the code to execute (invoke) the method. Note: methods will
never run unless they are called.
Here’s an example of using a method that returns the points a user has. Notice there
are no parameters, but we still need to include brackets when we call it.
Example calls
//declaration
public static boolean checkPrime (int n)
{
double sqrtr = Math.sqrt(n);
int factor = 2;
//////////////////////////////////////////////////////////////////////////////////
//example call 1
checkPrime(5); /* useless, but won’t complain even if
you do nothing with the return type */
// example call 2
c.println(checkPrime(9)); // will print out the returned
result... false
// example call 3
int num = c.readInt();
if (checkPrime(num))
c.println(num + “is a prime number”);
else
c.println(num + “is not a prime number”);
7.0 Parameters
Parameters are either formal or actual.
Formal Parameters: those in the signature
Pass-by-Value: the value of the actual parameter is given to the method. Used as
input only. Partner formal and actual parameters have separate locations in memory
In Java methods, primitive arguments are passed by value. When invoked, the
method receives the value of the variable passed in. When the argument is of
primitive type, pass-by-value means that the method cannot change its value.
When the argument is of reference type, pass-by-value means that the method
cannot change the object reference, but can invoke the object's methods and
modify the accessible variables within the object.
Huh??? For now, this means that for all primitive types, if you change it in the
method, it doesn’t have an effect on the “actual parameter”. But for non-primitive
types like arrays, if you change it in the method, it will also change the value of
the actual parameter.