0% found this document useful (0 votes)
28 views

CS Notes

The document provides an introduction to computer programming and Java programming. It discusses what a program is, the need for programming languages, and how programs are executed by computers. It also covers Java programming concepts like data types, variables, methods, classes, input/output and Java integrated development environments.

Uploaded by

Selina LI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

CS Notes

The document provides an introduction to computer programming and Java programming. It discusses what a program is, the need for programming languages, and how programs are executed by computers. It also covers Java programming concepts like data types, variables, methods, classes, input/output and Java integrated development environments.

Uploaded by

Selina LI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Introduction to Computer Programming

A program is an organized list of instructions that when executed, caused the


computer to behave in a predetermined manner.

 Without programs, computers are useless


 Analogy: a program is like a recipe. It contains a list of ingredients (called
variables) and a list of directions (called statements) that tell the computer
what to do with the variables. The variables are data, such as numbers, text,
and graphical images

Human

High Level Language


• Machine independent
• Closer to human language
• e.g. a = 5
• Java, Turing, C++
Compiler High level Low level

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

 When you buy a software, you normally buy an executable version of a


program. This means that the program is already in machine language -- it
has already been compiled and assembled and is ready to execute.
IDE (integrated development environment) make it easier for programmer to
create program. Most IDE contains
• Code editor: entering and changing code
• Compiler
• Debugger: locate and fix errors
 A debugger allows a programmer to stop a program at any point and
examine and change the values of variables.

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

To create a simple Java Program to print out “Hello”

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”

• Print multiple lines


Screen Output
Output: information produced by a program.

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.

The print and println Methods


The two “commands” to produce output in Java are System.out.print and
System.out.println. Here is the explanation of the “commands”: the
System class contains a static field called out which is of type PrintStream.
print and println are two methods of the PrintStream class. Therefore to
find out the exact usage of these two methods, one should check the API
specifications of the PrintStream class.

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 Signatures for the print and println methods

void print (double d)


void print (String s)
void println (char c)
void println (String s)

Displaying Literal Strings


Literal string is a series of characters in quotes

Examples:
(Note that ‘^’ represents a space on the screen)

Code Output Notes


System.out.print(”Hellothere^bobby2 literal duplication
51!”); Hellothere^bobby
251!
System.out.print(“The^answer^is:^^” non letters ie “:”
); The^answer^is:^
^
System.out.print(”\tThe^answer\nis: ^^^^^^^The^answer control
”); is: characters (\)
eg. \n, \t, \\, …
System.out.print(“abc”); abcdef print vs println
System.out.println(“def”);
System.out.println(“abc”); abc print vs println
System.out.println(“def”); def

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”);

Special Control Characters

Special control characters in a regular expression specify characters that are


difficult to type.

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:

Code Output Notes


System.out.println (5); 5 integers
System.out.println (25); 25 integers
System.out.println 34.789 real
(34.789);
System.out.println 12 evaluates expression and prints answer
(4*3);
c.println (8+2-3); 7 evaluates expression and prints answer

notice:
• a number is evaluated not duplicated

Exercise:
What will the output be for the following code?

Code Output Notes


System.out.println (55.6);
System.out.println (39.2);
System.out.println (85 * 3);
System.out.println (8+6+9-2);

Displaying a combination of information


To print several pieces of data in one print statement, use the + operator to
concatenate (join) the characters. Note that the + sign between two
numbers with act as addition.

examples:

Code Output Notes


System.out.println (5 + "85" + 24.2 + 58524.2
"\n5*2"); 5*2

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

• If a program is receiving input, the information has to be stored somewhere;


we need a container for the information.

• Information (data) is stored in variables.

• Variables are named memory locations that can vary in value throughout the
program.

• Therefore we declare a variable for each piece of information in a program.

Syntax for variable declaration %recall that info in square brackets is optional

datatype ^ identifier [=expression];

% you can initialize a variables at declaration

Examples

int num;
int a = 5;
float answer;

Input

Input: information (data) read in by the program.

For user keyboard input, the Scanner can be used. Note that the Scanner is not
available before Java SE 1.5.0.

To read an input from standard input (keyboard), a scanner object needs to be


created, and before you can do that, you must import the package java.util:

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.__________( );

read method eg. nextInt

A read statement does the following:


1. wait user for input
2. store the input from the user to the variable

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.

Keyword Description Size Min Val Max Val


(integers …-3,-2,-1,0,1,2,3…)
byte Byte-length integer 1 byte -128 +127
15
2 -2
short Short integer +215-1
bytes
4 -231
int Integer +231-1
bytes
8 -263
long Long integer +263-1
bytes
(real numbers; eg. 5.4, 6.7, 8, -200.678)
4 32-bit IEEE 754
float Single-precision floating point
bytes floating-point numbers
8 64-bit IEEE 754
double Double-precision floating point
bytes floating-point numbers
(other types)
2 0
char A single character (eg. ‘a’, ‘&’, ‘8’, ‘%’ 216-1
bytes
boolean A boolean value (true or false) 1 bit true and false

Examples of Literal Values and Their Data Types


Literal Data Type
Notes:
178 int
• a series of digits with no decimal point is by default
8864L long considered an integer.
37.266 double • You can specify a long integer by putting an 'L' or
37.266D double 'l' after the number. 'L' is preferred as it cannot be
87.363F float confused with the digit '1'.
• A series of digits with a decimal point is by default
26.77e3 double
considered type double.
'c' char
• You can specify a float by putting an 'f' or 'F'
true boolean after the number.
false boolean • A literal character value is any single Unicode
character between single quote marks.
• The two boolean literals are simply true and
false.
Valid Variable Names
There are naming conventions for variable strings

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>;

It is a good programming practice to use constants in program where possible.


Using constants makes maintenance of the program much easier. If the
information is changed, instead of changing all the values within the program,
only the constant has to be changed.
Casting
To Cast: To convert the datatype of an expression ie cast it into another
datatype.

Automatic Type Conversion: This is when the compiler automatically converts


one data type to another.

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

Explicit Type Conversion: This is when the programmer forces a conversion.

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.

Mixed Types in an Expression


If an expression holds a mix of types, the lower precision or narrower value
operand is converted to a higher precision or wider type. This result then must be
cast if it goes to a lower precision type:

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.

if.. else if Syntax:


Remember: the first condition found true is the only body executed; only one
body can be executed.
Example:
float mark;
if (condition) System.out.print(“Enter your mark: “);
{ mark = sc.nextFloat();
//body of if clause
} if (mark >= 90)
else if (condition) {
{ System.out.println(“grade = A+”);
//body of 1st else if clause }
} else if (mark >= 80)
else if (condition) {
{ System.out c.println(“grade = A”);
//body of 2nd else if clause }
} else if (mark >= 70)
else {
{ System.out.println(“grade = B”);
//body of else clause }
} else if (mark >= 60)
{
System.out.println(“grade = C”);
}
else if (mark >= 50)
{
System.out.println(“grade = D”);
}
else
{
System.out.println(“grade
Please note that there is no semicolon after the if-statement, else-if-statement = F
(failure)”);
and else statement. The { and } is used to specify the block of code that fall
}
under the each condition.

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

Try to evaluate the following Boolean Expressions

Expression Value
9<3
8!= 64 % 8
‘a’ = = ‘A’
‘a’ > ‘A’

Boolean Operators

&& and (true only if both values are true)


|| or (true if ether Boolean value is true
! not (switches the value of a Boolean expression from true to false or
vice versa)

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;]

case ordinal value: [case ordinal value:]


//body of 1st case(s)
[break;]
[
default:
//body of default executed if not previous match

]
}

Example:

// The "Switch" class.

public class Switch


{
static Console c; // The output console

public static void main (String [] args)


{
final int ADD = 1;
final int SUBTRACT = 2;

Scanner sc = new Scanner(System.in);

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

Additional information on the switch statement found at:


http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html
Repetition – while Loops
Repetition: repeats a sequence of instructions until a specified condition is
satisfied.

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;

while (i < 4) while (i < 4)


{ {
System.out.println (i);
} System.out.println(i);
i = i + 1;
}
OUTPUT MEMORY OUTPUT MEMORY
1 i 1 I
1 1 2 1
1 3 2
1 3
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.

Comparison between while and do… while loop


The For Loop
In this section, we focus on the for loop, which is also called the for
statement.

For solutions that repeat instructions, the for loop makes...


♦ it easier to code the initial solution.
♦ it easier to modify the solution.
♦ the solution more flexible.
♦ the solution shorter.

The for loop is called a counted loop because it repeats a set of


instructions a specific number of times.
Syntax of the for Statement

for (initialization; condition; update)


{
//body statements
}
Syntax Details:
initialization: an assignment statement which gives the counter
variable an initial value; this sets the loop's lower
bound
condition: a boolean expression that states the condition for
repeating the loop
update: an assignment statement which changes the value of the counter after each

iteration of the loop; this sets the loop's upper bound

Examining a Trivial Example

The following example illustrates the execution of a simple for


statement.

(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

In the following example the counter is decreasing from 5 down to 1


by 1 each iteration.

(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 ();

System.out.println ("\nFridays in " + month);


for (int i = first ; i <= days ; i = i + 7)
{
System.out.println (month + " " + i);
}

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

Changing (Variable) Boundary Conditions

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.

(file: Squares) Write a program that


displays the squares of all integer Trace Output
numbers within a given range. The
range is entered by the user.
lowe
upper Enter your first
int lower, upper; r number: 5
5 11 Enter your last
System.out.print ("Enter your i number: 11
first number: ");
lower = sc.nextInt ();
5
6 Number Square
System.out.print ("Enter your 5 25
last number: "); 7
upper = sc.nextInt (); 8 6 36
9 7 49
System.out.println("\nNumber 10 8 64
Square"); 11 9 72
10 100
for (int cur = lower; cur <= 11 121
upper; cur++)
{
Sysetm.out.print (cur, 4);
System.out.println (cur *
cur,11);
}
Additional Examples

This section illustrates a variety of different problems that are best


solved using a for loop.

(file : Leap2) Write a program that


displays all leap years within a given Trace Output
range of years. The user chooses
the range.
year1 year2 Enter the initial y
boolean leap;
int year1, year2, cur; 1954 1965 1954
cur leap Enter the final ye
System.out.print ("Enter initial 1954 false 1965
year: "); Leap years:
year1 = sc.nextInt ();
1955 false
1956 true 1956
System.out.print ("\nEnter final
year: "); 1957 false 1960
year2 = sc.nextInt (); 1964
1958 false
System.out.print ("\nLeap years
\n"); 1959 false
1960 true
for (cur = year1 ; cur <= year2 ; 1961 false
cur++)
{ 1962 false
leap = (cur % 4 == 0) && ((cur 1963 false
% 400 == 0) || (cur % 100 != 0)); 1964 true
if (leap)
System.out.println( cur );
1965 false
}
Tips & Tricks

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 --)

2) for (int pos = 0; true; pos +=2)

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.

// constant for capacity


final int MAXSTUDS = 10;

//1. declare a variable of the array class to store integers


int[ ] marks;

//2. instantiate an instance of the class specifying a capacity of 10


elements
marks = new int[MAXSTUDS];

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]

Terminology & Details:


• marks is an array of type integer
• marks[0] = marks at index/subscript 0 = the first element of the array
• marks[9] = marks at subscript 9 = the last element of the array
• arrays in Java (and C++) are always indexed from 0 to (capacity – 1)
• Initial values are automatically assigned to arrays in Java. Elements of
numeric arrays are all set to zero. Boolean arrays are set to false. Arrays of
objects, such as strings are set to null.
• All arrays know their own length. The Array class has a public data field
called length
• so c.println (marks.length); would print the capacity of marks array (10 in the
case above)
Continue from the declaration above:

// Read input from the user and store in an array.


for (int j = 0; j < MAXSTUDS; j++) {
System.out.print(“Enter mark for student ” + (j+1));
mark[j] = sc.nextInt();
}

// print out the list of marks


for (int j = 0; j < MAXSTUDS; j++) {
System.out.println(“mark” + (j+1) + “:” + mark[j]);
}

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.

// constant for capacity


final int MAXROWS = 3;
final int MAXCOLS = 2

//1. declare a variable of the array class to store integers


int[][] table;

//2. instantiate an instance of the class specifying a capacity of 3


elements in a row, and 2 elements in a column
table = new int[MAXROWS][MAXCOLS];

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)

Abstractly, the above arrays can be visualize as the following:

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

// constant for capacity


final int MAXSTUDS = 4;
final int MAXTESTS = 5;

//1. declare a variable of the array class to store double


double[][] marks;

//2. instantiate an instance of the class specifying a capacity of 4


// rows, and 5 columns
marks = new double[MAXSTUDS][MAXTESTS];

// ask user for the mark


for (int j = 0; j < MAXSTUDS; j++) {
System.out.println(“Marks of student ” + j);
for (int k = 0; k < MAXTESTS; k++) {
System.out.print(“Test # ” + k);
marks[j][k] = sc.nextDouble();
}
}

A 2D array can be initialized with values, just like a 1D array:

String cartoons [][]=


{
{ "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
{ "Rubbles", "Barney", "Betty", "Bam Bam" },
{ "Jetsons", "George", "Jane", "Elroy", "Judy"},
{ "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" }
};

The above code automatically creates an array with 4 rows and 5


columns and fill in the content accordingly. If you want to print
out the content of the array, try the following code:

for (int i = 0 ; i < cartoons.length ; i++)


{
for (int j = 0 ; j < cartoons [i].length ; j++)
{
System.out.print (cartoons [i] [j] + " ");
}
System.out.println ();
}
Using Classes
A class is a blueprint or prototype that defines the variables and the methods
common to all objects of a certain kind. It is Java’s basic unit of encapsulation.
All java code is within a class. There are many pre-defined classes in Java.

A class contains two main components: fields and methods. Fields are variables
that store data and methods are codes that perform actions.

Fields and methods are either static or non-static.

Steps for using static fields and methods


1. import the class file
2. using the fields or methods by the format <class name>.<field name> or
<class name>.<method name>
If the fields and methods are in the same class as the caller, no class name is
needed.

Steps for using non static fields and methods


1. import the class file
2. declare class variable
3. construct an instance (object) of the class (by calling new)
4. Using the fields or methods by the format <variable name>.<field name> or
<variable name>.<method name>

Example on using non static fields and methods

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”

In Java, Strings are implemented as objects.

String Object:

String str1 = new String(“abc”);


String str2 = new String(data); //note the compatibility of an
//array of char and String

Declaring a String object comes with the benefit of predefined String methods.

Language help see: java.lang.String

Here are some more examples of how strings can be used:


System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

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.

Assume the following declarations:


String str1 = new String("abc");
String str2 = new String("def");
String Length: every string has a length equal to the number of characters
stored.
Method: public int length()
Example:
System.out.println(str1.length()); // outputs 3

String Concatenation: the joining of two strings

Using the + operator:

str2 = str1 + str2; /*string concatenation;


overloaded + operator */
System.out.println(str2); // outputs abcdef

Using the concat function:

method: public String concat(String str) //function signature

System.out.println(str1.concat(str2)); //outputs abcdef

CharAt: return character with specified index


method: public char charAt(int index)

System.out.println(str1.charAt(0)); // outputs ‘a’


System.out.println(str1.charAt(2)); // outputs ‘c’
System.out.println(str1.charAt(str1.length())); // error!

Substrings: subset of a string (substrings of “the” are: the, t, h, e, th, he)

method: public String substring(int beginIndex, int endIndex)


Returns a new string that is a substring of this string. The substring begins
at the specified beginIndex and extends to the character at index endIndex -
1.

Example:
System.out.println("abcdefgh".substring(3,4)); //outputs d
System.out.println(str1.substring(1, str1.length( ) - 2)
// outputs ____?

Comparing Strings: Compares two strings lexicographically.

method: public int compareTo(String anotherString)

Example:
if (“abc”.compareTo(“ABC”) < 0 )
System.out.println(“less than”); //output _____?
else
System.out.println(”greater than”);
Converting String to int

Converting int to String

ICS3M Lesson: Methods

1.0 What is a method?

• 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.

2.0 Method Declaration vs Call

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.

Example Method Declaration

public static int mystery (double a, double b) {


int value = 0;
if (a < b) {
value = -1; 2 parameters
} else if (a > b) {
value = 1;
}
return value;
}

Example Method Calls


int n = mystery (23.43, 23); //using literal values for
parameters

final double SIZE = 4.3;


final float WIDTH = 12;
int j;
j = mystery (SIZE, WIDTH); //using literals and
variables for parameters

3.0 Method Signature (header) Syntax:


[access_level] [static] [return type] identifier ([formal parameters])

Example Method Signatures


1) public static void printText(String text)

2) void printText(String text)

3) public int getPoints()

4) public float calcPerimeter(float length, float width)

4.0 Method Call Syntax for void methods


A return value of void means no value is returned.

methodname( [actual parameters]);

5.0 Method Call Syntax for non-void methods


When a method returns a value like int, float, String etc, we most likely want to
utilize the returned value (returning that value is usually the purpose of the call).
What we do with the value is context dependent eg. we could print it, store it, use it
another call.... and so on.

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.

Method Signature: public int getPoints( )

Example calls

System.out.println(getPoints( ) ); //printing returned


points

int pts = getPoints( ) ; //storing returned


points

int pts = 5 * getPoints( ); //using the returned value in


an equation
displayPoints(getPoints( ) ); //using the returned
value as a //parameter
to another call

Example Signatures and Calls (for void and non-void)


Signature Call
public static void printText(“abc”);
printText(String text)
void printText(String text) printText(“abc”);
public int getPoints() c.println(getPoints( ));
public float calcPerimeter(float int length = 5;
length, float width) float perimeter =
calcPerimeter(length, 10);

6.0 Another Example Method Declaration and Call

//declaration
public static boolean checkPrime (int n)
{
double sqrtr = Math.sqrt(n);
int factor = 2;

while (factor <= sqrtr && n % factor !=0)


{
factor++;
}
return factor > sqrtr;
}

//////////////////////////////////////////////////////////////////////////////////
//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

Actual Parameters: those in the call; the actual values

8.0 Pass-by-value vs Pass-by-reference Parameters


Actual Parameters are either pass-by-value or pass-by-reference.

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

Pass-by-Reference (Pass-by-variable): the memory address of the actual variable is


given to the method. These are used as both input and output. Partner formal and
actual parameters share the same location in memory ie. reference the same location

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.

You might also like