[Go to site: main page, start]

0% found this document useful (0 votes)
4 views309 pages

Java Programming Basics Explained

The document provides an introduction to computer science, programming, and Java, outlining key concepts such as algorithms, variables, and the structure of Java programs. It explains the programming process, including thinking of solutions, coding, and debugging, and introduces basic Java syntax through the 'Hello World' program. Additionally, it covers variable declaration, initialization, and assignment rules in Java programming.

Uploaded by

aamandaruiz20
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)
4 views309 pages

Java Programming Basics Explained

The document provides an introduction to computer science, programming, and Java, outlining key concepts such as algorithms, variables, and the structure of Java programs. It explains the programming process, including thinking of solutions, coding, and debugging, and introduces basic Java syntax through the 'Hello World' program. Additionally, it covers variable declaration, initialization, and assignment rules in Java programming.

Uploaded by

aamandaruiz20
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

CCCS 300 Programming Techniques 1

Slide 1:Introduction to Computers, Programs, and


Java

1
What is computer science?
• Computer science is the study of computing concepts.

• It requires thinking both in abstract terms and in concrete terms.

• Computer science can be seen as a science of problem solving. A


computer scientist
– must be able to model and analyze problems
– design solutions, and
– verify that they are correct.

2
What is Programming?

Programming can be thought as a 3 step process:


1. Think of a solution

2. Translate it into a sequence of instructions that specifies how


to perform a computation (i.e., a program). (coding)

3. Check to see if it is correct (testing) and fix any problems


(debugging).

3
What are algorithms?

• An algorithm is a sequence of steps that specifies how to solve


a problem.

• Using the terminology we have just learned, we can say that


computer science is the science of algorithms.

4
Examples

• A recipe to cook your favourite pie.


• The list of instructions you need to follow to install a game.
• The moves to solve a maze.
• The procedure we follow to build a house.

5
How does a computer work?
• Computers are made of wires. Current (electricity) can either pass through each
wire, or not.

• It is a huge amount of light switches that can be turned on and off.


• To do so, we use the ‘base 2’ system – called binary
– Off = 0
– On = 1

6
Recall decimal: base 10
When we refer to a decimal (base 10) number, like 5764, we are
referring to the value obtained by carrying out the following
addition:

5000 + 700 + 60 + 4
That is, we add together:
• Ones: 4
• Tens: 6
• Hundreds: 7
• Thousands: 5

7
From Decimal to Decimal
Compute 576410 in decimal notation (base 10)?

5764
= 576 𝑅 𝟒
10
576
= 57 𝑅 𝟔
10
57
=5𝑅𝟕
10
5
=0𝑅𝟓
10
Note that taking the remainders from bottom to top gives us the
answer.
8
From Decimal to Binary
What is 1310 in binary?

13
=6𝑅𝟏
2
6
=3𝑅𝟎
2
3
=1𝑅𝟏
2
1
=0𝑅𝟏
2

Now, the base 2 representation comes from reading off the remainders from
bottom to top!
1310 = 𝟏𝟏𝟎𝟏𝟐

9
Binary to Decimal

• Convert 𝟏𝟏𝟎𝟏𝟎𝟏𝟎𝟏𝟐 to a decimal number.


Position/ 7 6 5 4 3 2 1 0
Exponent

Powers of 2 128
Se 64 32 16 8 4 2 1

Digits 1 1 0 1 0 1 0 1

Output: 128 + 64 + 16 + 4 + 1 = 𝟐𝟏𝟑

10
Binary represent anything

11
What is programming language

• It’s a language (Like English or French).


• So the program can be written as a series of human
understandable computer instructions that can be read by a
compiler and translated into machine code that the computer
understand and run it.

12
Our very first program
The first program we learn in programming is the Hello World
program.
Here’s the code written in Java:

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

What does it do?


➢ It simply displays “Hello, World!” on your screen.

13
Curly Braces

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• Java uses curly braces to group things together.


• They denote a block of code.
• They help us keep track of what parts of the code are related.
• If one of them is missing or there’s an extra one → syntax
error
14
Statements

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• A statement is a line of code that performs a basic operation.


• All statements in Java end in a semi-colon.
• The statement in this program is a print statement: it displays a
message on your screen.

15
Printing to the console

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• You can print a phrase on your screen using the


[Link]() command. The phrase you
would like to see should be put inside the round parentheses.
• NOTE, Java is case-sensitive: System ≠ system ≠ SYSTEM

16
Strings

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• Phrases that appear in quotation marks are called Strings.

• Strings literals must start and end with double quotes.

17
Methods and Classes

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• Almost every line of code you will write in Java will be inside a
method.
• Every method you will ever write will be part of a class.
• In this program: HelloWorld is a class, main is a method.

18
Methods

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• A method is named sequence of statements


• These open and close curly brackets tell the computer where
the main method (named block of code) starts and ends.

19
Methods

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• This program defines a method called main, which is public,


static, and void (but don’t worry about this for now)
• The main method is a special one:
– The execution of a program always starts from the first statement in
the main method and ends when it finishes the last statement.

20
Classes

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello, World!”);
}
}

• This program must be saved as a file named [Link]


• Convention: names of classes starts with capital letter.
• A class is a collection of methods.
• This program defines a class called HelloWorld which is:
– public (we’ll see more about this later)
– defined by what is in between the curly brackets.

21
Comments
public class HelloWorld {
// This line is ignored
public static void main (String[] args) {
/* As well as this one
and this one
and this last one */
[Link](“Hello, World!”);
}
}

• A single line comment in Java starts with // and ends when you press
enter.
• A multi-line comment starts with /* and ends with */.
• All comments are ignored by the computer.

22
Demo

• Write the HelloWorld program and add some comments.

23
Code structure

• All of your methods must be inside a class.

• (Almost) all of your statements will be inside of a method.

24
Good Practice
• In Java most spaces are optional.
– But, you cannot write

publicstaticvoidmain (String[] args) {

– But it is ok to write our program as:

public class HelloWorld { public static void main


(String[] args) { [Link](“Hello, World!”);}}

– Tabs and newlines are optional, but without them the program becomes hard to
read!

25
When to press enter

In general, when writing your code, you should go to a new line


each time:
• You type an open curly bracket
• You type a close curly bracket
• You finished typing a statement ending in a semi-colon.
public class HelloWorld {
public static void main(String[] args) {
[Link](“Hello world!”);
}
}

26
Indentation

• Whenever we start a new “block” of instructions (i.e., we have


an open curly bracket) we indent (press tab) the subsequent
lines of code in.
• Whenever we end the block (i.e. we type a close curly bracket),
we un-indent the subsequent lines of code.
public class HelloWorld {
public static void main(String[] args) {
[Link](“Hello ”);
[Link](“world!”);
}
}

27
Statements

• A method in Java can have as many statements as you want.


• The computer will execute the statements (inside a method)
from top to bottom.
public class Help {
public static void main(String[] args) {
[Link](“Help! I need somebody.”);
[Link](“Help! ”);
[Link](“Not just anybody”);
}
}

28
print() vs println()
• println() appends to whatever is it displaying a special character called
newline.
• If you don’t want a newline at the end you can use print.
• What would the following program display?
public class Help {
public static void main (String[] args) {
[Link](“Help! ”);
[Link](“I need somebody.”);
}
}

➢ Help! I need somebody.

29
Escape Sequences
• Escape sequence: a sequence of characters that represents a special character.
• Examples:
– \n represents the character newline
– \” represents quotation marks (which otherwise would indicate a string)
– \t represents a tab.

public class Help {


public static void main (String[] args) {
[Link](“Help! I need somebody.\n”);
[Link](“Help! Not just anybody.”);
}
}

30
Displaying numbers
• We can also print numbers using the same methods.
• Note that in this example, we don’t need to have the double
quotes.
public class Test {
public static void main (String[] args) {
[Link](53);
}
}

➢ What happens if we try to display a String without the quotes?

31
Evaluation
[Link]()

Whatever is between the () gets evaluated before it is printed to the


screen.
public class HelloWorld {
public static void main (String[] args) {
[Link](“Hello” + “World!”);
}
}

What prints? HelloWorld!

32
Evaluation

We can combine two Strings together in Java using the ‘+’


operator.
public class HelloWorld {
public static void main (String[] args) {
[Link](“Hello ” + “World!”);
}
}

What prints? Hello World!

33
The + Operator

In java, the + operator can do two different things:


[Link] it is between two Strings, it concatenates them together:
“Apple” + “Banana” → “AppleBanana”

[Link] it is between two numbers, it adds them together:


2 + 3 → 5

NOTE that you cannot perform mathematical operations on


Strings (even if they look like numbers!).

34
Difference

public class Mistery {


public static void main(String[] args)
{
[Link](4 + 5);
}
} What is the
difference between
public class Mistery {
the two programs?
public static void main(String[] args)
{
[Link](“4” + “5”);
}
}

35
Exercises

• What is 1101110102 in decimal?


• What is 197410 in binary?

• Write a program called MySong. This program should output


the title of your favourite song on one line, followed by the
band/singer that performs it on the next line. For example,
your program might print something like this:
Behind Blue Eyes
by The Who

36
CCCS 300 Programming Techniques 1
Slide 2:Elementary Programming

37
Announcements

• Assignment 1
– Available on myCourses
– Due on: ??

38
What are we going to do today?

• Variables
• Primitive Data Types
• Mathematical Operators and String
• Expressions
• Command Line Arguments
• Random numbers

39
VARIABLES

40
Variables Recorded

• A variable is a named location that stores a value.


• By location we mean a place in the memory of the computer.
• Values can be numbers, text, booleans, and other type of data.

Thus,
• Variables have a name and a type
– We use the name to identify the location, and
– The type to keep track of which kind of value we store, and thus how
much space in memory is needed.

41
The Life of Variables Recorded

1. Declaration

2. Initialization

3. Manipulation

42
Declarations Recorded

• To store a value we first need to declare a variable.

• The following statements declare variables of different types:

String today;
int hour, minute;
boolean isSnowing;

• When you declare a variable, you give it a name and a type

43
Declarations (1) Recorded

int aNumber;

• The type of this variable is int


• int is a keyword (reserved word) in Java. It is short for integer.

44
Declarations (2) Recorded

int aNumber;
Blue

• The name of this variable is aNumber


• This is not a keyword in Java.
• aNumber is the name of the place in memory with enough space to
store an integer.

45
Declarations (3) Recorded

Back to the examples we have seen before:

NOTE 1: Some type start


String today; with capital letters,
int hour, minute; others don’t.
boolean isSnowing;

NOTE 2: You can declare


multiple variables of the
same type on one line.

46
Assignment – Rules Recorded

Assignment operator: =
It assigns the value from the right to the variable on the left. E.g. int a = 6
We can store values inside a variable with an assignment statement.

• When we make an assignment we update the variable’s value.

• The variable need to have the same type as the value we assign to it.
• Variables must be initialized (assigned for the first time) before they can
be used.

47
Assignment-Examples Recorded

Examples:
String today; // the variable today is
declared
today = “Monday”; // today gets initialized

/* the variable hour is declared and initialized on


the same line */
int hour = 10;
int date = “Wednesday”; // NOT LEGAL!

48
Assignment-Examples Recorded

• Note, we can use complicated expressions to assign a value to


a variable.
• In such case, the expression will first be evaluated and then the
variable will be assigned to such value.

int hour = 12;


int inFiveHours = hour + 5;

49
= is not equality! Recorded

• = is an operation assigning the value from the right to the


variable on the Left.
• It is NOT a statement of equality!

Which of the following can be legal?


x = 7;
7 = x;
3 = y + x;
Not legal!
y = x+3;

50
= is not equality! Recorded

A statement of equality is true all the time. If 𝑎 = 𝑏 now, then 𝑎


is always equal to 𝑏.

It is not the case for assignment statements!

int a = 3; a 3

a 3 b 3
int b = a;
a 5 b 3
a = 5;

51
Variables

• Declaration:

int a;

52
Variables (1)

• Declaration:

int a;

• Assignment: a 3
a = 3;

53
Variables (2)
• Declaration:

int a;

• Assignment:
a 5
a = 3;

• New assignment:

a = 5;

54
Manipulation Recorded

After we declare and initialize a variable, we can do things with


it:
int aNumber = 45;
[Link](aNumber);

➢ What prints?

55
Example Recorded

public class Mistery {


public static void main(String[] args)
{
int aNumber = 45;
[Link](aNumber);
}
What is the
}
difference between
public class Mistery { the two programs?
public static void main(String[] args)
{
int aNumber = 45;
[Link](“aNumber”);
}
}

56
Variable Naming Conventions Recorded

• If the variable is one word, all letters should be lowercase. Eg:


hour, day.

• If the variable is more than one word, the first word should be
all lowercase, and each subsequent word should have the first
letter capitalized. This is called lowerCamelCase. Eg:
isSnowing, catName.

57
Variable names Recorded

• Short, but not too short


• Descriptive and unique
• camelCase

Good variable names Bad variable names


hour asfdstow
isRaining dateoftoday
numberOfBooks urstupid
classCode CaPiTAlsANyWHErE

58
Accessing data from a variable Recorded

What happens when we put a variable on the right hand side of the ‘=’ operator?

int x = 5;
x = x + 1;

• What is the value of x?


➢ First the expression on the right hand side of ‘=’ gets evaluated. Then, that value (6) is
assigned to the variable x.

59
Multiple variables Recorded

What happens when we put a variable on the right hand side of the ‘=’ operator?

int x = 5;
int y = 8;
x = y;

• What is the value of y?


• What is the value of x?
➢ Again, the expression on the right is evaluated, and the value (8) is assigned to the variable
on the left.

60
Multiple variables Recorded

What happens when we put a variable on the right hand side of the ‘=’ operator?

int x = 5;
int y = 8;
x = y;
y = y + 1;

• What is the value of y?


• What is the value of x?
➢ On the third line, x is assigned to the value of y (8).
➢ Then, on the fourth line, y is assigned the value of y + 1 (9). Here x does not change.

61
PRIMITIVE
DATA TYPE

62
Primitive Recorded

A primitive type is
• predefined by the language, and
• named by a reserved keyword

Java supports 8 primitive data types.

63
The 8 Types supported Recorded

byte Integer values


short
int
long
float Real Numbers
double
Boolean True or False
char One character

64
Why different types? Recorded

It turns out that the difference between the types storing integer values
and real numbers is the number of bits reserved for those values.

Type Keyword Size Values


Very Small Integer byte 8-bits [−128, 127]
Small Integer short 16-bits [−215 , 215 −1]
Integer int 32-bits [−231 , 231 − 1]
Big Integer long 64-bits [−263 , 263 − 1]
Low Precision Reals float 32-bits -
High Precision Reals double 64-bits -
True/False boolean 1-bit [true, false]
One character char 16-bits -

65
Strings Recorded

• In addition to the 8 data types, java supports character strings


via [Link] class.

• Strings are sequences of characters.

• Not a primitive data type

66
Ascii Recorded

Char
• A character set is an ordered list of character, where each
character corresponds to a unique number.

• Unicode is an international character set.

• A char stores a single character from the Unicode


character set.
char type values must start and end with single quotes (‘).
char size;
size = ‘S’;

67
Boolean
A variable of type boolean can store either true or false.

boolean isSnowing;
isSnowing = false;

68
OPERATORS

69
Standard Integer Operations Recorded

• Addition ‘+’, Subtraction ‘-’

• Multiplication ‘*’
• Division ‘/’
– The output of the division between two integers is an integer. Java only computes
the quotient between two numbers.
• Modulo (remainder) “%”
– It performs integer division and outputs the remainder.

70
Order of Operations Recorded

As in math, certain operations have priority over others.

From left to right:

1. Parenthesis

2. Multiplication/Division/Modulo

3. Addition/Subtraction

71
Examples
• Whats the following instructions output?

int half = 1/2;


int + half;
[Link](one);

• What about the next one?

int quotient = 32/3;


int remainder = 32%3;
[Link](quotient*3 + remainder);

72
Expressions

• The following is an expression:

quotient * 3 + remainder

• It represents a single value that needs to be computed.

• When the program runs each variables is replaced by its value,


the operators are applied, and the value of the expression is
computed!

73
Overflow and Underflow
• Variables of type int store values between 231 − 1 and −231 .
– 231 − 1 = 2147483647 (Integer.MAX_VALUE)
– −231 = −2147483648 (Integer.MIN_VALUE)

• What happens if:

int x = 2147483647; int y = -2147483648;


[Link](x+1); [Link](y-1);

Output:-2147483648 Output 2147483647

74
Floating Point Recorded

• In java the default floating point type is double.


• All standard arithmetic operations can be done on floating
point.
• NOTE: Java distinguishes between 1 and 1.0.
If you write .0 after an integer, it will be considered to be a
double.
int x = 3.0;
int x = 3;
double x = 3.0;

75
Be Careful! Recorded

• Java automatically converts one type to the other (e.g. int to double)

double x = 1; // legal, but bad style!

int x = 1.0/2; // compiler error!


double y = 1/4; // no compiler error, but is it correct?

76
Typecasting Recorded

• We can convert back and forth between variables of type int and
double using typecasting. (or casting, for short)

int x = 3;
double y = 4.56;
int n = (int) y;
double m = (double) x;

• What are the values of x, y, n, and m?


➢ x = 3, y = 4.56, n = 4, m = 3.0

77
Casting
• When going from int to double, an explicit cast is NOT necessary.

• When going from double to int, you will get a compile-time error if
you don’t have an explicit cast.

• double 64 bits int 32 bits

78
Mathematical Operators
& String

79
The Math Library
• Java has a math library that provides us with many methods that we can use without
having to define our own!!
– [Link](x) – absolute value of x
– [Link](x) – square root of x
– [Link](x,y) – x to the power of y
– [Link](x) – sine of x, where x is in radians

• It also contains useful constants such as 𝒆 and 𝝅 which you can access using: Math.E,
and [Link]

How to learn about all these methods and what they do?
[Link]

[Link]

80
Strings
In addition to variable types for numbers, we also have a variable
type called String for phrases.

String type values must start and end with double quotes (").

We have seen that we can declare a String variable in the


same way as other variables:

String s = “This is a String”;


String phrase = “This is another String”;

81
Converting types with Strings Recorded

You cannot use a cast when converting from a String.


➢ To convert from int/double to a String, just concatenate the number with the
empty String (“”).
String s = “” + 4;
➢ To convert from a String to an int, use:
int x = [Link](“54”);
String s = “5”;
int y = [Link](s);

➢ To convert from a String to a double, use:

double z = [Link](“5.4”);

82
The ‘+’ Operator

• If used between numbers, it will add the numbers together

• If used between strings, it will concatenate those strings.

• What happens in the following example?

[Link]( 2 + 3 + “5”);
[Link](“5” + 2 + 3);

The two expressions are evaluated from left to right!

83
EXPRESSIONS

84
Expression
➢ An expression is a construct made up of variables, operators, and
method invocations, that evaluates to a single value.
E.g.
int result = 1+ 2;
String x = “hi” + “ben”;

➢ That value has a specific type! The data type of the value returned by an
expression depends on the elements used in the expression.

85
Expressions and Types
What value is assigned to x?

int x = 1/2 + 1/2;

86
Expressions and Types
What value is assigned to x?

int x = 0.5 + 0.5;

87
Expressions and Types (1)
What value is assigned to x?

double x = 0.5 + 0.5;

88
Expressions and Types (2)
What value is assigned to x?

double x = (double) 1/2 + 1/2;

89
COMMAND LINE
ARGUMENTS

90
Input Arguments
• Remember the main method?

public static void main (String[] args) {

• String[] args is often called command line arguments or input arguments.

• It allows for the person running the program to set values of variables.

• args is a variable of type String[] (a list of Strings)


– Don’t worry if you don’t fully understand how this works. We’ll get back to this
kind of data type in a couple of weeks.

91
Try it!
1. Write a program called Echo. The program should:
– Take a string as input,
– Store it in a variable you declare
– Display Your word is X, where X is the String passed as input.

Example:

> run Echo Hello


Your word is Hello

92
Try it!

• Write a program that takes three integer numbers as input,


adds them all together, and prints the result.

93
RANDOM NUMBERS

94
Random numbers

• In java, we can generate (pseudo)-random numbers

• One way, to do this is using the [Link]() method


– It takes no inputs
– It returns a random double value between 0 (inclusive) and 1
(exclusive)

95
Try it! (1)
• Write a program that displays a random number of type double
between 0 (inclusive) and 10 (exclusive).

• Modify it so that it displays a random integer between 0 and 10.

• Modify it again so that it displays a random integer between 0 and


max, where max is chosen by the user via args[0].

• Finally, make it display a random integer between min and max,


where the values for min and max are taken as inputs.

96
Exercises
1. Write a program that takes the radius of a circle as input. The
program should then convert that value to a double and
store it in a new variable. At this point, it can use it to
compute and display the area of the circle. Note that 𝐴 = 𝜋 ⋅
𝑟 2 . Use [Link] to access the value of 𝜋, and use
[Link]() to get the value of 𝑟 2 .

2. Write a program that get the largest value from the user’s
input via args[0], args[1], args[2].

97
Observations

1. The Strings we provide as inputs cannot have any spaces in it.

– Every word will be its own String

2. The only type of inputs we can provide are Strings!


– To use them as numbers you need to convert their type.

98
CCCS 300 Programming Techniques 1
Slide 3:Boolean expression and If-else

99
Review – type conversion
• We use typecasting to convert int into doubles and vice-versa.
– From int to doubles → not necessary: java does it automatically
– From doubles to int → necessary: compile-time error otherwise!
• From int/doubles to String: concatenate with empty String (“”).

int x = 5;
String s = “”+ x;

• From String to int/doubles: use built-in methods

String s = “54”; String s = “3.2”;


int x = [Link](s); double x = [Link](s);

100
What are we going to do today?

▪ Relational & Logical Operators

▪ Conditional Statements

101
RELATIONAL
OPERATORS

102
Relational Operators Recorded

• Used to check conditions and make comparisons.

– Is chicken cheaper than beef?


• The result is either true or false, that is the result is a boolean value.
• Expressions containing relational operators are called boolean
expressions.
• We can use a boolean variable to store a boolean value.

• E.g. boolean b = true;

103
Relational Operators Recorded

x == y Is x equal to y?
x != y Is x not equal to y?
x > y Is x greater than y?
x < y Is x less than y?
x >= y Is x greater than or equal to y?
x <= y Is x less than or equal to y?

Examples
• 5 > 2 is true.
• 7 < 1 is false

104
Order of Operations Recorded

Which operator has higher priority?


1. Relational: <, >, <=, >=

2. Equality: ==, !=
e.g. 10 >= 11 == 3 <5 The result will be false

You can always use parenthesis to raise priority.

105
Display Boolean values Recorded

As with other types of variable, you can display the value of a


boolean variable using a print statement.

double priceChicken = 7.71;


double priceBeef = 16.92;
boolean isChickenCheaper = priceChicken < priceBeef;
[Link](“Chicken costs ” + priceChicken + “ dollars per kg.”);
[Link](“Chicken is cheaper than beef: ” + isChickenCheaper);

Chicken costs 7.71 dollars per kg.


Chicken is cheaper than beef: true.

106
Be careful! Recorded

• Common error: use a single = instead of a double ==.


– The single = is the assignment operator.
– The double == is the equality operator.

• There no such thing as ≠, ≥, =<, or =>.

• The two sides of the relational operator need to be comparable.


2 == 2.0 is true.
2 == “2” does not compile.

107
Try it!
• Write a program isEven that take an integer as input and
displays on your screen whether it is true or false that such
integer is even.

An example of what you could see given a user input is:

> run isEven 5


5 is an even number: false

108
Logical Operators Recorded

• Logical operators take boolean expressions (i.e. expressions that


evaluate to a boolean value) as inputs and produce a result of type
Boolean

• Java has 3 logical operators:


– NOT !
– AND &&
– OR ||

109
! operator Recorded

Truth table…
Let b be a variable of type boolean:

b !b
true false
false true

!b evaluates to the opposite value of b.

110
! operator – Examples Recorded

• !(2<3)
➢ !true
➢ false

• !(1.0 == 2.0)
➢ !false
➢ true

111
&& Operator Recorded

Let a and b be two variables of type boolean,

a b a && b
true true true
true false false
false true false
false false false

a && b evaluates to true if and only if both a and b are


true.
112
&& Operator – Examples Recorded

• (1<2) && true


➢ true && true
➢ true

• (2 == 2) && !(3<5)
➢ true && ! true
➢ true && false
➢ false

113
|| Operator Recorded

Let a and b be two variables of type boolean,


a b a || b
true true true
true false true
false true true
false false false

a || b evaluates to false if and only if both a and b are


false.
114
|| Operator – Examples Recorded

• (1>2) || true
➢ false || true
➢ true

• (2 == 1) || ! (1<2)
➢ false || ! true
➢ false || false
➢ false

115
Order of Operations Recorded

From left to right:


1.!
2.&& Priority order
3.||

As usual, you can use parenthesis in order to change the priority.

116
Examples of Boolean Expressions Recorded

What does b && !a || b evaluate to if a = false and b = true?

➢ true && !false || true

➢ true && true || true

➢ true || true

➢ true

117
Examples of Boolean Expressions Recorded

What does a && !(a || b) evaluate to if a = true and b = false?

➢ true && !(true || false)

➢ true && !true

➢ true && false

➢ false

118
Short circuit evaluation
Meaning Short circuit?
&& and yes
& and no
|| or yes
| or no

A short circuit operator is one that doesn't necessarily evaluate all of its operands.
Example:
2<1 && !(x >= 1 || y == 3)
Java will return false immediately when the left operand is evaluated to false.
If the left operand of || is true, then the whole expression is true. Therefore, Java
will not evaluate the operand on the right.
Example:
1==1 || (x < 5)
is true no matter what x < 5 evaluates to.

119
Short circuit evaluation
It might seem like a small detail, but it is actually important.
Why is it useful?
• It can save time!
• It can avoid unnecessary errors.

Example:
(x != 0) & ( 5/x < 1)
If we try to evaluate the right operand when the left is false we will
get a runtime error (you cannot divide by 0). Therefore, exploiting
short circuit evaluation we can write conditions that will ensure us to
not get a runtime error.

120
Order of Operations Recorded

From left to right:


1. Parenthesis
2. !
3. Typecasting
4. Arithmetic
i. *, /, %
ii. +, -
5. Comparison
i. Relational: <, >, <=, >=
ii. Equality: ==, !=
6. Boolean: &&, ||

121
Examples Mixed Expressions Recorded

What does false || 1 / (int) 2.0 < 3.5 evaluate to?


1. Parenthesis
➢ false || 1 / 2 < 3.5 2. !
3. Typecasting
➢ false || 0 < 3.5
4. Arithmetic
i. *, /, %
➢ false || true
ii. +, -
➢ true 5. Comparison
i. Relational: <, >, <=, >=
You don’t need to memorize all this, use ii. Equality: ==, !=
parenthesis when in doubt!
6. Boolean: &&, ||

122
CONDITIONAL
STATEMENTS

123
How can we use Booleans? Recorded

To write useful programs, we almost always need to check conditions.

– We might want to execute certain statements only in specific


situations.

– Conditional statement give us this ability

124
Example Recorded

• For example,
• 1) if the temperature is over 27, the program will turn on a AC.
If the temperature is below 10, then turn on a heat.

• 2) If I have money at least $500, I will buy PS5, then I cry.

• If something happen, then do something..

125
If statement syntax Recorded

Make sure it is surrounded by parentheses


if(condition){
//do something (If block)
}else{
//do something (Else block)
}

The condition must be a boolean expression.

126
If statement Recorded

The simplest conditional statement is the if statement.

if (x > 0) {
[Link](“x is positive”);
}

The expression in parentheses is called the condition.


It must be a boolean expression.

127
If statement Recorded

The simplest conditional statement is the if statement.

if (x > 0) {
[Link](“x is positive”);
}

The block of code gets executed only if the condition evaluates to true.
Otherwise, the block of code is skipped.

128
If-Else Statements Recorded

If-else statements have two blocks of code:


• one gets executed if the condition evaluates to true
• the other gets executed if the condition evaluates to false
• The blocks are also called branches
if (x > 0) {
[Link](“x is positive.”);
}else {
[Link](“x is not positive.”);
}

129
If-else statements – Example Recorded

If x > 0 evaluates to true, then the first block of code is executed


and the second one is skipped.

if (x > 0) {
[Link](“x is positive.”);
}else {
[Link](“x is not positive.”);
}

If x > 0 evaluates to false, then the first block of code is skipped


and the second one is executed.

130
Try it!
Let’s go back to the program isEven. Let X be the integer the
program takes as input. Then the program should either print:
The number X is even OR The number X is odd.

131
Two ifs vs if-else Recorded

What is the difference?

if (condition) { if (condition) {
// some instructions // some instructions
} }
if (not condition) { else {
// more instructions // more instructions
} }

• Both blocks on the left could execute if somehow at the end of the first
block, (not condition) becomes true.

132
Example Recorded

• Both branches execute:


int x = 3;
if (x > 0) {
[Link](“Positive. Resetting value.”);
x = 0;
}
if (x <= 0) {
[Link](“Not positive.”);
}

133
Example Recorded

• Only the first branch executes:

int x = 3;
if (x > 0) {
[Link](“Positive. Resetting value.”);
x = 0;
} else {
[Link](“Not positive.”);
}

134
If-Else If-else chaining Recorded

You might want to check related condition and choose one of several actions.
You can do so by chaining a series of if and else statements.

• Only one of these blocks will if (x > 0) {


get executed. Order matters! [Link](“Positive”);
• As soon as one block is executed,
} else if (x < 0) {
the remaining will be skipped
• You can have as many else ifs [Link](“Negative”);
as you want } else {
• The final else is not required. [Link](“Zero”);
}

135
Example (1) Recorded

• Is there anything wrong?

if (money > 0.0) {


[Link](“Positive balance”);
} else if (money > 1000.0) {
[Link](“You’re rich! Go celebrate!”);
} else {
[Link](“Uh-oh.”);
}

136
If-else if-else nesting Recorded

You can also nest one conditional


statement inside another. if (x > 0) {
[Link](“Positive”);
• The first conditional statement } else {
has two branches if (x < 0) {
• The first branch contains a [Link](“Negative”);
print statement
} else {
• The second branch contains
another conditional statement [Link](“Zero”);
with two branches of its own. }
}

137
Example (2)
What is the output?

boolean a = 1 >20;
boolean b = 26.0 == 26;

if (a && b) {
[Link]("A = B");
} else if (a) {
[Link]("A");
} else {
if (!a) {
[Link]("not A");
} else {
[Link]("Something else");
}
}

138
Be Careful!

• Nested or chained conditional statements are common,


but can become very confusing!

• Try not use too much of them for better readability

• An accurate use of the curly brackets is essential for the


program to work correctly.

139
A dangerous game! Recorded

• When a branch has only one statement, curly brackets are optional.
if (x > 0)
[Link](“Positive”);
else
[Link](“Non positive”);

• BUT, it is always better to use them in order to avoid mistakes like the
following where the second print statement gets executed no matter
how the condition evaluates.
if (x > 0)
[Link](“Positive”);
[Link](“and not zero”);

140
Example (3)

What is the output?

int marks = 85;


if( marks > 80 )
[Link]("outstanding");
if( marks > 60 )
[Link]("pass");
else
[Link]("fail");
[Link]("better luck next time");

141
Common mistake

if (x > 0) ;{
[Link](“Positive”);
} else {
[Link](“Non positive”);
}

• Compile-time error!

142
Switch statement
• evaluates an expression, selects a matching case or an optional
default to execute a list of statements and an optional break.
switch(<expression>) { all cases }

switch(color) { switch(color) {
case 0: // red case ‘R’: // red
case 1: // green case ‘G’: // green
[Link]("I like"); [Link]("I like");
case 2: // blue case ‘B’: // blue
[Link]("I will wear it!"); [Link](I will wear it!");
[Link]("I’m happy!"); [Link](“I’m happy!");
break; break;
default: // all other colors default: // all other colors
[Link]("I don’t like"); [Link]("I don’t like");
} }

• In the example, color can be int, char, or String, but not double.
143
CCCS 300 Programming Techniques 1
Slide 4: methods and Strings

144
Review

What prints?

145
Review

What prints?

146
Review (1)

What prints?

147
Review (2)

What prints?

[Link]((!(true && false) || false)&& true);

148
Review (3)

What prints?

double d = 2/5;
[Link](d+(double)5/2);

149
What are we going to do today?

▪ Void methods

▪ Value methods

▪ Chars and Strings

150
VOID METHODS

151
Void Methods Recorded

public static void newMethod()

When used as part of a method header, the keyword void tells the
computer that the method does not return anything.

152
Another simple Method Recorded

public static void helpIntro() {


[Link](“Help! I need somebody,”);
[Link](“Help! Not just anybody,”);
[Link](“Help! You know I need someone, help.”);
[Link](“Help!”);
}

It is a void method: it does display strings on your screen, but it does not
return any value.

153
A simple program Recorded

public class Song {

public static void main(String[] args) {


helpIntro();
}

public static void helpIntro() {


[Link](“Help! I need somebody,”);
[Link](“Help! Not just anybody,”);
[Link](“Help! You know I need someone, help.”);
[Link](“Help!”);
}
}

154
Method calls Recorded

• You can call a method more than once.

• You can call a method from other methods

155
Java Code Recorded

156
Why should we use methods? Recorded

• Using methods can help you eliminate repetitive code.

• Methods allow you to name a group of statements, which make code


easier to read, and to understand.

• To solve complex problems a common approach is to break it down into


sub-problems. Using methods you can focus on each sub-problem in
isolation.

157
What print? Flow of Execution Recorded

public class AboutBooleans {

public static void secondLine() {


[Link]("even if you are wrong, ");
[Link]("you are only off by a bit.");
}

public static void firstLine() {


[Link]("The best thing about a booleans is: ");
}

public static void main(String[] args) {


firstLine();
secondLine();
}
}

158
Java Code

159
Program Execution
• When a program runs only the main method executes.

• The program is NOT executed by reading methods from top to bottom.

• Other methods only execute if they are called from the main method
(or from a method that was called by the main method).

160
Methods that Take inputs Recorded

• The method defined below has 1 input parameter: an integer variable


named x.
• The variable x exists only inside this method
• This is a void method → it returns no value.
public static void newMethod(int x) {
// work in progress
}

• If you want to call this method, you MUST provide an argument of type
int.
A possible call could be:
newMethod(2);
161
When calling a method with inputs Recorded

• You must provide the method with an argument of the correct type.
• Arguments can be any kind of expression.
• The expression will be evaluated and its value will be assigned to the
parameter inside the method.
• Example: public static void newMethod(int x) {
[Link](x);
}
public static void main(String[] args) {
int y = 6;
newMethod(2*y + 3);
newMethod(“Hello Ben”); Error
}

162
More than one input Recorded

• Methods can have more than one input parameter


• The type of each parameter can be different.
Example:
public static void newMethod(int x, String s, boolean b) {
// work in progress
}

• This is a void method. A call might look like:


• newMethod(2, “Hello”, true);
• newMethod(“Hello”,2 , true); Error

• Note that the order of the arguments matters!

163
Examples Recorded

public static void newMethod2(int x, y) {


[Link](“You’re here!”);
}

▪ This format is legal only for variable declarations.

▪ In the parameter list you need to specify the type of each variable
separately.

164
Examples (1) Recorded

public static void newMethod(int x, String s, boolean b) {


[Link](“You’re here!”);
}

public static void main(String[] args) {


String day = “Monday”;
int x = 5;
newMethod(x, day, false);
}

165
Examples (2) Recorded

public static void newMethod(int x, String s, boolean b) {


[Link](“You’re here!”);
}

public static void main(String[] args) {


String day = “Monday”;
int x = 5;
newMethod(int x, String day, false);
}

166
Examples Recorded

public static void newMethod(int x, String s, boolean b) {


[Link](“You’re here!”);
}

public static void main(String[] args) {


String day = “Monday”;
int x = 5;
newMethod(true, x, day);
}

167
Example Recorded

168
VALUE METHODS

169
Return statement Recorded

• The return statement allows you to terminate the execution of a


method before all the instructions have been executed.
• Why would you want to do that?
– Maybe an error condition have been detected.

public static void squareRoot(double x) {


if (x < 0.0) {
[Link](“Error: x is a negative number.”);
return;
}
[Link](“The square root of x is: ” + [Link](x));
}

170
Value Methods Recorded

Compare to void methods, value methods differ in 2 ways:


• They declare the type of the return value
• They use at least one return statement to provide a return value.

public static double circleArea(double radius) {


double area = [Link] * [Link](radius, 2.0);
return area;
}

• A call to this method could be: double a = circleArea(2.5);

171
Return statements Recorded

• The expression provided to the return statement can be complex.

return [Link] * [Link](radius, 2.0);

Temporary variables like area, can make the code more readable and
easier to debug.
• The type of the expression MUST match the return type.

If you try to return an expression of the wrong type, then the compiler
generates an error.

172
Method calls Recorded

public static double adder(int x) {


x = x+1;
return x;
}

Which of the following are valid ways to call the above method?

1) double val = adder(4); 3) int y = 5;


[Link](adder(y));
2) int x = 4; 4) double x = 5;
double val = adder(int x); x = adder(x);

173
Dead Code Recorded

• Code that appear after a return statement, or somewhere where it can


never be executed, is called dead code.
• If your program contains dead code you will receive a compile-time
error: “Unreachable statement”.

public static double circleArea(double radius) {


double area = [Link] * [Link](radius, 2.0);
return area;
[Link](“It will never print”);
}

174
Return and conditional statements Recorded

• If you use return statements inside a conditional statement, you need to


make sure that every possible instance of your program will reach a
return statement.
• If that’s not the case, you will get a compile-time error (e.g., “missing
return statement”)
public static double absoluteValue(double x) {
if (x > 0) {
return x;
} else {
return –x;
}
}

175
Returning from methods
This is NOT a valid way to have multiple return statements. To fix it, add a
return statement after the second if block.

public static int abs (int x) {


if(x > 0) {
return x;
}
if (x <= 0) {
return –x;
}
}

176
Method composition
• As void methods, value methods can be called from any other method.

• Moreover, you can use value methods as part of an expression.


Examples:
– double area = [Link] * [Link](3.0,2.0);

– String s = “The area of the circle is ” +


areaCircle(2.5);

– double x = [Link]([Link](25.0), 2.0);

177
Example – passing variables to methods Recorded

public static double adder (int x) {


x = x+1;
return x;
}

public static void main(String[] args) {


int x =1;
double y = adder(x) + adder(x) + adder(x);
[Link](y);
}

Does it compile? If so, what prints? Remember, we are passing a copy of


the value of x as input.

178
Example – passing variables to methods Recorded

public static double adder (int x) {


x = x+1;
return x;
}

public static void main(String[] args) {


int x =1;
double y = adder(adder(x) + adder(x) + adder(x));
[Link](y);
}

Does it compile? If so, what prints?

179
Example – passing variables to methods (1) Recorded

public static double adder (int x) {


x = x+1;
return x;
}

public static void main(String[] args) {


int x =1;
double y = adder((int) adder(x) + adder(x) + adder(x));
[Link](y);
}

Does it compile? If so, what prints?

180
Example – passing variables to methods (2) Recorded

public static double adder (int x) {


x = x+1;
return x;
}

public static void main(String[] args) {


int x =1;
double y = adder((int) (adder(x) + adder(x) + adder(x)));
[Link](y);
}

Does it compile? If so, what prints?

181
Overloading Recorded

• Having more than one method with the same name is called
overloading.

• It is legal as long as the methods have different parameters.

• Java will know, based on the inputs, which method has been called.

• Changing return type is not overloading.

182
Overloading example Recorded

• Method Overloading is a feature that allows a class to have more than


one method having the same name, if their argument lists are different.

You will get an error message because of You can use the same method name only if
using the same variable name as shown the parameters are different. The below
in the following: method are working without error.

public void method1(){} public void method1(){}


public void method1(){} public void method1(String s){}
public String method1(){ } public String method1(int i, char c){ }
//Even the return type is different

183
Recursion

• A “method calling itself” is recursion which can be elegant to compute.

public static long factorial(int n) {

if (n == 0)
return 1;
return n * factorial(n-1);

184
CHAR

185
char data type
• We have seen char as one of the primitive data types that we have in
Java.
• Recall that we can declare and initialize a variable of type char as
follows:

char letter = ‘a’;

• Character literals appears in single quotes


• Character literals can only contain a single character

186
Unicode
• Variables of type char have 16 bits reserved in the memory to store a
value.

• Java uses Unicode to represent characters.

• Each character is represented by an integer.


Note: not every integer represent a character!

187
Unicode for Characters

188
Character Arithmetic
• Since every character is practically an integer, we can perform
arithmetic operations on variables of type char.

char first = ‘a’;


char second = (char) (first + 1);

• What is the value of second?


– ‘b’
• Note the typecasting!
first is automatically converted into an integer, and
first + 1 evaluates to 98.
Then the typecasting converts the int into a char, and
stores ‘b’ in second.

189
Comparing Chars
What prints?

char letter = ‘z’;


if(letter == ‘a’) {
[Link](“first letter of the alphabet”);
} else if (letter == ‘z’) {
[Link](“Last letter of the alphabet”);
} else {
[Link](“None of the above”);
}

190
Comparing Chars
What prints?

char letter = ‘g’;


if(letter == ‘a’) {
[Link](“first letter of the alphabet”);
} else if (letter == ‘z’) {
[Link](“Last letter of the alphabet”);
} else {
[Link](“None of the above”);
}

191
Comparing Chars (1)
What prints?

char letter = ‘g’;


if(letter == ‘a’) {
[Link](“first letter of the alphabet”);
} else if (letter == ‘z’) {
[Link](“Last letter of the alphabet”);
} else if (letter > ‘a’ && letter < ‘z’) {
[Link](“Another letter of the alphabet”);
} else {
[Link](“Not a lower case letter of the alphabet”);
}

192
Comparing Chars (2)
What prints?

char letter = ‘!’;


if(letter == ‘a’) {
[Link](“first letter of the alphabet”);
} else if (letter == ‘z’) {
[Link](“Last letter of the alphabet”);
} else if (letter > ‘a’ && letter < ‘z’) {
[Link](“Another letter of the alphabet”);
} else {
[Link](“Not a lower case letter of the alphabet”);
}

193
STRINGS

194
String
• Recall that a String is sequence of characters.

• We introduced String with the primitive data types,


but technically String is a Class and a String is an
Object.
(more on classes and objects in the following weeks)

• We cannot use on Strings the same operators we use


on primitive data types.

• There’s a set of methods provided to manipulate


characters and they can be called on values of type
String.

195
Documentation
You can find it here:
[Link]
javase/7/docs/api/java/l
ang/[Link]

196
Comparing Strings
• To compare two strings you can use one of the following methods

equals is case sensitive, use equalsIgnoreCase if you don’t want to


distinguish between upper and lower case.

197
Examples (3)

String course = “COMP 202”;


String course2 = “comp 202”;
boolean a = [Link](course2);
boolean b = [Link](course2);

• The value of a is false


• The value of b is true

198
Be careful!

• If you try to use == or != on Strings you program will compile and run.
It is not doing what you think it’s doing though.

• Always use equals or equalsIgnoreCase if you want to compare


strings.

199
Useful string methods
[Link]() -> returns the number of characters in the String variable s.
String s = “Ben”; String s1 = “Ben Jimmy”;
[Link]([Link]()); // will print 3
[Link]([Link]()); // will print 9

[Link](i) -> returns the character in the String at index i. i must be an integer. The first character is at
position 0 in the String.
[Link]([Link](2)); // will print n
[Link]([Link](0)); // will print B
B e n J i m m y
0 1 2 3 4 5 6 7 8

If in the String s there’s no character with index i, then we will get a run-time error.
(StringIndexOutOfBoundsException)

200
Useful string methods
[Link]() and [Link]() -> returns a new String that is the same as the old one, but with
all lower case letters and all uppercase, respectively.
String s1 = “Ben Jimmy”;
[Link]([Link]()); // will print ben jimmy
[Link]([Link]()); // will print BEN JIMMY

[Link](s1) -> returns true if string s contains the specified substring s1.
String s = “Ben Jimmy”; String s1 = “mm”; String s2 = “jy”;
[Link]([Link](s1)); // will print true
[Link]([Link](s2)); // will print false

201
Example (4)
What prints?

String s = “Another string”;


[Link]([Link]());

202
Example (5)
What prints?

String s = “Another string”;


[Link]([Link](2)==‘n’);

203
Example (6)
What prints?

String s = “Another string”;


[Link]([Link](7)==‘ ’);

204
Example (7)
What prints?

String s = “Another string”;


[Link]([Link](0)==‘a’);

205
Example (8)
What can we do to get the last character of a given String s?

char lastChar = [Link]([Link]() -1);

206
Null Pointer

207
Review – methods from the string class
String s = “Review”;

Example – method call Input type Return type Return value


[Link](“review”) String boolean false
[Link](“review”) String boolean true
[Link]() none int 6
[Link](2) int char ‘v’
[Link]() none String review
[Link]() none String REVIEW

208
Exercises
1. Write a method that takes a String as input and prints true if the
String length is greater than 6 characters. The method should print
false otherwise.

2. Write a method that takes a String s and an int i as input. The


method should return true if the character at index i is a vowel,
false otherwise.

209
Exercises
1. Write a method reverseConcat that takes three input parameters of type String (s1,s2,s3). It
should return a value of type String equal to the three input Strings concatenated together in
reverse order. Call this from your main method and print the result.

2. Write a method chocolateBag that takes 3 integers as input. The first input indicated the number
of small (1 kg) chocolate bars you have, the second the number of big (5 kg) chocolate bars you have,
and the third the number of kg of chocolate you want in your bag.
The method returns the number of small bars to use to fill the bag, assuming we always use big bars
before small bars. It returns −1 if it can't be done.

– Example: chocolateBag(4, 1, 9) returns 4


chocolateBag(4,1,10) returns -1
chocolateBag(4, 1, 7) returns 2

210
CCCS 300 Programming Techniques 1
Slide 5: Loops

211
Review

212
Review

What prints?
public static void main(String[] args) {
int x = 5;
int y = 8;
myMethod(x,y);
[Link](x + “ ” + y);
}

public static void myMethod(int x, int y) {


x = y;
y = x;
}

213
Review (1)

What prints?
public static void main(String[] args) {
int x = 5;
int y = 8;
myMethod(x,y);
[Link](x + “ ” + y);
}

public static void myMethod(int x, int y) {


x = y;
y = x;
[Link](x + “ ” + y);
}

214
Review (2)

What prints?
public static void main(String[] args) {
int x = 5;
int y = 8;
myMethod(x,y);
[Link](x + “ ” + y);
}

public static int myMethod(int x, int y) {


x = y;
y = x;
return y;
}

215
Review (3)

What prints?
public static void main(String[] args) {
int x = 5;
int y = 8;
x = myMethod(x,y);
[Link](x + “ ” + y);
}

public static int myMethod(int x, int y) {


x = y;
y = x;
return y;
}

216
Review (4)
public static void main(String[] args){
What prints? String s = "Ben0205";
int x = 3;
if ([Link]() < 7) {
[Link]([Link](x));
x++;
}else{
s = secret(s);
x--;
}
[Link]([Link](x));
}

public static String secret(String s){


return "Cindy";
}

217
What are we going to do today?

▪ While Loops

▪ For Loops

▪ Scanner

218
MORE OPERATORS

219
Operation-assignment +=, -=, *=, /= Recorded

The following two blocks are equivalent

int x = 2; int x = 2;
x += 5; x = x + 5;

The same notation can be used for subtraction, multiplication,


and division.

220
Post Increment (Decrement) Recorded

• Post-increment: x++
• Post-decrement: x--

You can use these notations as statements as well as part of a more


complex expression.

• The following statements are equivalent:


x++; x = x + 1;

x--; x = x – 1;

221
Post Increment (Decrement) Recorded

When used as part of expressions, the increment happens after the


statement is executed.

The following blocks are equivalent:

int x = 5;
int x = 5;
int y = 2*x;
int y = 2*x++; x = x + 1;

222
Pre VS Post increment/decrement
• x++: the increment happens after the statement is executed.
• ++x: the increment happens before the statement is executed.

The following statements are the same The following statements are the same

int i = 2; int i = 2;
int i = 2; int i = 2;
←→ int j = 3 + i; ←→ i = i + 1;
int j = 3 + i++; int j = 3 + ++i;
i = i + 1; int j = 3 + i;

// j = 5 // j = 6

223
WHILE LOOPS

224
Loop Recorded

• The loop allows us to execute a code multiple times.

• Recall that the If statement only execute code once.

Example: Printing integer 1~10 on the console.


[Link](1);
[Link](2);
Solution 1: Copy and paste
[Link](3);
Problem:
[Link] annoying
[Link](10);
[Link] to make mistake
[Link] to read and maintain

225
Syntax – If Statement Recorded

Recall: if statement

if (condition) {
// some code
}

The block of code is executed once, only if the condition evaluates to true.

226
Syntax-while Recorded

while (condition) {
// some code
}

The block of code is repeatedly executed as long as the condition


evaluates to true.

227
While loop example Recorded

•The variable “count” keeps track of how many


An example of while loop: iteration the loop has run.
int count = 1;
•An iteration is a single execution of the code in
while (count <= 10){
the body of the loop.
[Link](count + “ ”);
count++; •The loop on the left has 10 iteration because
} the code inside the block runs 10 times.

//Print: 1 2 3 4 5 6 7 8 9 10 •The condition of a loop is checked per iteration


before the block of code is executed

228
Example Recorded

What prints?

int i = 0;
while (i < 100) {
if (i % 5 == 0) {
[Link](i);
}
i++;
}

229
Example Recorded

What prints?

int x = 0;
while (x < 4) {
[Link](x);
}

230
Infinite Loops

The previous code creates an infinite loop. The block of code will get
executed forever since the value of x is never changed, thus the condition
will never evaluate to true.

Be careful when writing a loop! It is important to make sure that it can


eventually terminate.

231
How many iterations? Recorded

int x = 4;
while (x > 4) {
# of iterations:
[Link](x); 0
x++;
}

232
How many iterations? Recorded

int x = 4;
while (x > 4) {
# of iterations:
[Link](x); 0
x++;
}

233
How many iterations? Recorded

int x = 6;
while (x > 4) {
# of iterations:
[Link](x); 2
x--;
}

234
How many iterations? (1) Recorded

int x = 6;
while (x > 4) {
# of iterations:
[Link](x); a lot! Is this what I
x++; want?
}

235
How many iterations? (2) Recorded

int x = 3;
while (x < 11) {
[Link](x); # of iterations:
4
x+=2;
}

236
How many iterations? (3) Recorded

int x = 3;
while (x != 10) {
[Link](x); # of iterations:
infinite!
x+=2;
}

237
Other examples

What prints?

int i = 0;
while ( ++i < 4){
[Link](i + “ ”);
i++;
}

238
More example

What prints?

int i = 27;
int j = 2;
while (i > 9 || j < 10){
i /= 3;
j *= 2;
[Link](i + “ ” + j);
}

239
FOR LOOPS

240
Common loop structure Recorded

Very often in loops, we will do


three things.
• Declare and initialize a variable
before the loop. int i = 0;
while (i < 5) {
• Check a condition before each [Link](i);
iteration.
i++;
}
• Perform some update step at the
end of each iteration.

241
For loop Syntax Recorded

The condition is checked at the beginning


The initializer is executed once, of each iteration. If it evaluates to false, the
before the loop starts. loop ends. Otherwise, the body is repeated.

for (int i = 1; i <= 10; i++) {


// some code
}

The update is executed at the end of each iteration.

242
For Loops
• A for loop is a while loop with a built-in counter

• The two loops are equivalent

• In general:
– use for loops when the condition depends on the value of an integer, and the
number of iterations is fixed or easily computable.
– use while loops when the number of iterations is indefinite.

243
General Structure

for (statement1; boolean expression; statement2) {


// loop body
}

• Any or all of the above statement/expression can be left out.


• The semicolons always need to be there.

244
To recap
1) The initializer is executed

2) The condition is checked. If true, the body is executed. Otherwise, the


loop ends.

3) The update is executed and we go back to step 2).

245
General Structure

for (statement1; boolean expression; statement2) {


// loop body
}

• Any or all of the above statement/expression can be left out.


• The semicolons always need to be there.

246
For vs While Recorded

Initialization of the counter

int i = 1;
while (i <= 10) { for (int i = 1; i <= 10; i++) {
[Link](i); [Link](i);
i++; }
}

247
For vs While (1)

Condition

int i = 1;
while (i <= 10) { for (int i = 1; i <= 10; i++) {
[Link](i); [Link](i);
i++; }
}

248
For vs While (2)

Counter increment

int i = 1;
while (i <= 10) { for (int i = 1; i <= 10; i++) {
[Link](i); [Link](i);
i++; }
}

249
For vs While (3) Recorded

NOTE: if you declare the variable in the initializer, it only exists inside
the for loop

int i = 1;
for (int i = 1; i <= 10; i++) {
while (i <= 10) {
[Link](i);
[Link](i);
}
i++;
[Link](i);
}
[Link](i);

250
For vs While (4)

NOTE: if you declare the variable in the initializer, it only exists inside
the for loop

int i = 1; int i;
while (i <= 10) { for (i = 1; i <= 10; i++) {
[Link](i); [Link](i);
i++; }
} [Link](i);
[Link](i);

251
Off-by-one errors
An off-by-one error is a common logic error that occurs when a loop
iterates one time too many or too few.
Example: you want your loop to iterate n times and you write the following

for (int i = 1; i < n; i++) { for (int i = 0; i <= n; i++) {


// loop body // loop body
} }

n-1 times! n+1 times!

252
Loop Commands Recorded

• A break statement will cause the program to exit the current


loop.

• A continue statement cause the program to skip to the next


iteration of the loop.

253
Break – Example Recorded

for (int i = 1; i <= 10; i++) {


if (i == 5) {
break;
}
[Link](i + “ ”);
}

What prints? 1 2 3 4

254
Continue – Example Recorded

for (int i = 1; i <= 10; i++) {


if (i == 5) {
continue;
}
[Link](i + “ ”);
}

What prints? 1 2 3 4 6 7 8 9 10

255
Break and Continue Recorded

• Even though, using break and continue gives you more control over the
loop execution, they make the code more difficult to read and debug.

• If you find yourself using them all the time, you are probably doing
something more complicated than it needs to be.

• Use them sparingly!

256
NESTED LOOPS

257
Nested loops Recorded

• You can have multiple levels of loops.

• This is useful when we are dealing with data with multiple


dimensions.

• Let’s look at the example of the multiplication table.

258
Multiplication table Recorded

Each row is a list of multiples of one


number:
• Row 1 contains multiples of 1
• Row 2 contains multiples of 2
• …
• Row 𝑖 contains multiples of 𝑖

259
One row Recorded

• Suppose the row number is fixed (let it be 5) and the number of


columns is stored in the variable cols.
• Then, the following code will print the fifth row of a multiplication table
with cols number of columns.

for (int i = 1; i <= cols; i++) {


[Link](5*i + “\t”);
}
[Link]();

260
Multiple rows Recorded

Now, if we want to print as many rows as the value stored in a variable


rows, we can generalize the previous code by adding an extra for loop.

for (int j = 1; j <= rows; j++) {


for (int i = 1; i <= cols; i++) {
[Link](j*i + “\t”);
} The variable j
[Link](); replaces the
} number 5 to
generalize the
statement.
For each iteration of the outer loop, a new
variable i is declared and initialized.

261
Java code Recorded

262
Squares Recorded

drawSquare(4);
public static void drawSquare(int size) {
for (int i = 0; i < size ; i++) {
for(int j=0; j < size; j++) {
[Link]("+"); ++++
} Each iteration of ++++
[Link](); the outer loop
} prints a line ++++
} ++++

Each iteration of the


inner loop prints a
character

263
Question: Squares Recorded

drawSquare(4);
public static void drawSquare(int size) {
for (int i = 0; i < size ; i++) {
for(int j=0; j < size; j++) {
[Link]("+"); In which
iteration of the ++++
}
two loops does ++++
[Link]();
this character ++++
} get printed?
} ++++

𝑖 = ?,𝑗 = ?

264
Question: Squares (1) Recorded

drawSquare(4);
public static void drawSquare(int size) {
for (int i = 0; i < size ; i++) {
for(int j=0; j < size; j++) {
[Link]("+"); ++++
} What about this
++++
[Link](); one?
} ++++
} ++++
𝑖 = ?,𝑗 = ?

265
Empty Square
public static void drawEmptySquare(int size) {
for (int i = 0; i < size ; i++) {
if (i == 0 || i == size -1) {
for(int j=0; j < size; j++) {
[Link]("+");
} +++++
} else { + +
for (int j=0; j < size; j++) {
if (j == 0 || j == size-1) { + +
[Link]("+"); + +
} else {
[Link](" ");
+++++
}
}
}
[Link]();
}
}

266
Exercises more
1. Write a method that takes two Strings as input and returns the String whose
first letter comes first in the alphabet. If the two Strings both begin with the
same letter, then the method should return the shortest between the two. If they
begin with the same letter and have the same length, then the method should
return either one of them.

2. Write a method called reverseString that takes one String as input and
returns a new String containing the same characters in reverse order.
For example, if the input is “bananagrams”, the method should return
“smargananab”.

267
CCCS 300 Programming Techniques 1
Slide 6: Scanner and review

268
Warmup

269
Warmup

What prints?

String s = "elephant";
for(int i = 0; i < [Link](); i += 2)
[Link]([Link](i));
}

270
Warmup (1)

What prints?

for (int i = 0, j = 5; i < j; i++, j--) {


[Link]("hello");
}

271
What are we going to do today?

▪ Scanner

▪ Variables Scope

▪ Midterm review

272
SCANNER

273
The Scanner class
• Scanner provides methods for inputting words, numbers, and other
data.

• Scanner is part of the [Link] package.

• Before using Scanner it is useful to import it.

274
The Import Statement
• The import statement for the Scanner class:

import [Link];

• This statement allows us to refer to Scanner in the program without


having to refer to the full package name ([Link]). It
makes sure that the compiler knows which class we are referring to.

• Import statements cannot be inside a class definition. All import


statements should be at the beginning of the file.

275
How to Use Scanner

▪ Once you have imported the Scanner class, you can create a Scanner

object using the following statement:

Scanner read = new Scanner([Link]);

Declaration of a variable Creation of a Scanner object.


named read of type Note the new keyword! Scanner
Scanner. is a reference type.

276
The Scanner class (1)
• The Scanner class provides multiple methods to parse
information.
– nextLine(): Reads one line and returns the input as a String
– nextInt(): Scans the next token of the input as an int
– nextDouble(): Scans the next token of the input as a double
– hasNextLine(): Returns true if there is another line in the input
– hasNextInt(): Returns true if the next token can be interpreted as an int value using the
nextInt method
– hasNextDouble(): Returns true if the next token can be interpreted as a double value
using the nextDouble method

• Find the full documentation here:


[Link]

277
Examples

import [Link];

public class NewFriends {


public static void main (String[] args) {

String name;
Scanner read = new Scanner([Link]);

[Link](“What’s your name? ”);


name = [Link]();
[Link](“Hello ” + name + “!”);
}
}

278
Examples
import [Link];

public class NewFriends {


public static void main (String[] args) {

String name;
int age;
Scanner read = new Scanner([Link]);

[Link]("What's your name? ");


name = [Link]();
[Link]("How old are you? ");
age = [Link]();

[Link](name + " is " + age + " years old.");


}
}

279
InputmismatchException

If Scanner tries to read an input of


a specific type, for instance an
integer, but instead reads
something else, it will throw an
InputMismatchException.

280
InputmismatchException (1)
• We can prevent an InputMismatchException by checking the
input before parsing it.
• We can do that using hasNextInt() or hasNextDouble()
int age;
Scanner read = new Scanner([Link]);

[Link]("How old are you? ");


if (! [Link]()) {
[Link](“You have not entered an integer”);
} else {
age = [Link]();
}

• [Link]

281
Buffer and Scanner
• When obtaining input via a Scanner, the values are stored in a
temporary location before being copied into your program. Such
temporary location we often refer it to buffer.

• In computer science, a data buffer (or just buffer) is a region of a


physical memory storage used to temporarily store data while it is being
moved from one place to another.

282
TRY IT
▪ Using Scanner to continuously ask for an integer. Your program should
sum up all the input integers. When the sum hits 100, the Scanner loop
is break.

283
THE SCOPE
OF A
VARIABLE

284
Scope of a Variable
• A variable only exists inside of the method in which it is declared.

• It does not exist in any other method.

• We call the scope of a variable the part of the code where it exists.

285
Example

286
Scope – Top down
When inside a method,

• a variable starts to exists when it is declared, and

• it ends to exists at the close curly bracket corresponding to the most


recent open curly bracket.

287
Scope of Variables

public static void newMethod() { public static void newMethod() {


int x = 5; int x = 5;
int y = 6; scope int z = x + y; scope
int z = x + y; int y = 6;
} }

public static void newMethod() { public static void newMethod() {


int x = 5; int x = 5;
{ {
int y = 6; int y = 6; scope
int z = x + y; scope }
} int z = x + y;
} }

288
Scope of Variables (1)
• As with methods, if we
declare a variable inside
a condition block, such
variable only exists public static void main (String[] args) {
inside that block. int x = 2;
int y = 3;
• However, if we declare if (x < y) {
a variable before the x = x + y; x and y both exists here
condition block, then int z = 5;
we can use the variable y = z*x; x, y, and z all exists here
inside (and after) the }
block. Any modification [Link](x + “ ” + y + “ ” + z);
to the value of the }
z does NOT exists here. This
variable will apply. line will give an error.

289
Scope of Variables (2)
• As with methods, if we
declare a variable inside
a condition block, such
variable only exists public static void main (String[] args) {
inside that block. int x = 2;
int y = 3;
• However, if we declare if (x < y) {
a variable before the x = x + y;
condition block, then int z = 5; This line will print:
we can use the variable y = z*x; 5 25
inside (and after) the }
block. Any modification [Link](x + “ ” + y);
to the value of the }
variable will apply.

290
Variable in nested block
• The variable name cannot be the same in the nested If of nested loop
statement.

if(condition){
int a = 0;
if (condition){
int a = 1; //Error, duplicate local variable “a”.
}
}

291
Variable in nested loop

for(int i =0; i< 6; i++){


[Link](j) //Error
for(int j =0; j< 6; j++){
int a = 1;
}
}

292
Scope of Variables (3)

public static void main(String[] args) {


int x = 5;
newMethod();
int y = 6;
[Link](x+y);
}
public static void newMethod() {
int x = 7;
int z = 10;
[Link](x+z);
}
• Does the above code compile? Is so, what prints?

293
Scope of Variables (4)

public static void main(String[] args) {


int x = 5;
newMethod();
}

public static void newMethod() {


x = x + 1;
[Link](x);
}

• Does the above code compile? Is so, what prints?

294
More Example
• List the names of all variables in scope on the line marked *****HERE*****.

public static void main(String[] args) {


int count = 5;
for(int i = 0; i < [Link]; i++) {
if(i<5) {
String s = “not enough”;
} else {
String t = “enough”;
****HERE****
}
}
}

295
More Example (1)
• List the names of all variables in scope on the line marked *****HERE*****.

public static void main(String[] args) {


int count = 5;
for(int i = 0; i < [Link]; i++) {
if(i<5) {
String s = “not enough”;
} else {
****HERE****
String t = “enough”;
}
}
}

296
More Example (2)
• List the names of all variables in scope on the line marked *****HERE*****.

public static void main(String[] args) {


int count = 5;
myMethod(count);
}

public static void myMethod(int x) {


int sum = 0;
for(int i=0; i<x; i++) {
sum += i;
}
*****HERE*****
[Link](sum);
}

297
MIDTERM INFO

298
Midterm – general info
• When: on ?, 18:05 to 20:55
• Where: Online under mycourse with lock down browser.
• Topic: Everything up to, and including this week’s classes.
• Format:
– Long Answer (Code Writing)

299
Midterm – how to study
• Study the slides and your notes
• Do the warm-up questions on the assignment
• Practice writing code by hand
• Practice reading code without compiling or running
• Test your knowledge of errors by making mistakes on purpose.

300
MIDTERM REVIEW

301
From Midterm Winter 2017

302
Type Conversion

int x = 5.4; // compile-time error!


int y = ‘a’; // automatic conversion
double z = ‘b’; // automatic conversion
double w = x; // automatic conversion
char a = 99.7; // compile-time error!
int n = [Link](53); // compile-time error!
double m = [Link](“53”); // automatic conversion
int n = [Link](“53”); // compile-time error!
int n = [Link](“cat”); // run-time error!

303
From Midterm Winter 2017

304
From Midterm Fall 2016

▪ How many *’s print?

int i=0;
int j=5;
while(i<j) {
[Link]('*');
for(int k =10; k > 0; k-=2) {
[Link]('*');
}
i++;
}

305
Long Answer
1. Write a method called reverseString that takes one String as
input and returns a new String containing the same characters in
reverse order.

For example, if the input is “bananagrams”, the method should return


“smargananab”.

306
Long Answer (1)
1. Write a method getSubstring() that takes as input a String s as
well as two integers i and j. The method returns the String composed by
the characters of s between index i and index j (both included).

307
Long Answer (2)
• A method countChar that takes as input a String and a char and returns
how many times that character is present in the String. Your method
must be case sensitive (for example, if you are counting the letter ‘a’, DO
NOT also include ‘A’ in your count)

308
Long Answer (3)
• Write the isAVowel method. This method takes a character as input and
returns true if the character is a vowel, false otherwise. You can assume
that the vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and all other characters are
consonants, including ‘y’

309

You might also like