Java Programming Basics Explained
Java Programming Basics Explained
1
What is computer science?
• Computer science is the study of computing concepts.
2
What is Programming?
3
What are algorithms?
4
Examples
5
How does a computer work?
• Computers are made of wires. Current (electricity) can either pass through each
wire, or not.
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
Powers of 2 128
Se 64 32 16 8 4 2 1
Digits 1 1 0 1 0 1 0 1
10
Binary represent anything
11
What is programming language
12
Our very first program
The first program we learn in programming is the Hello World
program.
Here’s the code written in Java:
13
Curly Braces
15
Printing to the console
16
Strings
17
Methods and Classes
• 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
19
Methods
20
Classes
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
23
Code structure
24
Good Practice
• In Java most spaces are optional.
– But, you cannot write
– Tabs and newlines are optional, but without them the program becomes hard to
read!
25
When to press enter
26
Indentation
27
Statements
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.”);
}
}
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.
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);
}
}
31
Evaluation
[Link]()
32
Evaluation
33
The + Operator
34
Difference
35
Exercises
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
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
String today;
int hour, minute;
boolean isSnowing;
43
Declarations (1) Recorded
int aNumber;
44
Declarations (2) Recorded
int aNumber;
Blue
45
Declarations (3) Recorded
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.
• 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
48
Assignment-Examples Recorded
49
= is not equality! Recorded
50
= is not equality! Recorded
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
➢ What prints?
55
Example Recorded
56
Variable Naming Conventions Recorded
• 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
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;
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;
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;
61
PRIMITIVE
DATA TYPE
62
Primitive Recorded
A primitive type is
• predefined by the language, and
• named by a reserved keyword
63
The 8 Types supported Recorded
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.
65
Strings Recorded
66
Ascii Recorded
Char
• A character set is an ordered list of character, where each
character corresponds to a unique number.
67
Boolean
A variable of type boolean can store either true or false.
boolean isSnowing;
isSnowing = false;
68
OPERATORS
69
Standard Integer Operations Recorded
• 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
1. Parenthesis
2. Multiplication/Division/Modulo
3. Addition/Subtraction
71
Examples
• Whats the following instructions output?
72
Expressions
quotient * 3 + remainder
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)
74
Floating Point Recorded
75
Be Careful! Recorded
• Java automatically converts one type to the other (e.g. int to double)
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;
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.
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 (").
81
Converting types with Strings Recorded
double z = [Link](“5.4”);
82
The ‘+’ Operator
[Link]( 2 + 3 + “5”);
[Link](“5” + 2 + 3);
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?
86
Expressions and Types
What value is assigned to x?
87
Expressions and Types (1)
What value is assigned to x?
88
Expressions and Types (2)
What value is assigned to x?
89
COMMAND LINE
ARGUMENTS
90
Input Arguments
• Remember the main method?
• It allows for the person running the program to set values of variables.
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:
92
Try it!
93
RANDOM NUMBERS
94
Random numbers
95
Try it! (1)
• Write a program that displays a random number of type double
between 0 (inclusive) and 10 (exclusive).
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
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;
100
What are we going to do today?
▪ Conditional Statements
101
RELATIONAL
OPERATORS
102
Relational Operators Recorded
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
2. Equality: ==, !=
e.g. 10 >= 11 == 3 <5 The result will be false
105
Display Boolean values Recorded
106
Be careful! Recorded
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.
108
Logical Operators Recorded
109
! operator Recorded
Truth table…
Let b be a variable of type boolean:
b !b
true false
false true
110
! operator – Examples Recorded
• !(2<3)
➢ !true
➢ false
• !(1.0 == 2.0)
➢ !false
➢ true
111
&& Operator Recorded
a b a && b
true true true
true false false
false true false
false false false
• (2 == 2) && !(3<5)
➢ true && ! true
➢ true && false
➢ false
113
|| Operator Recorded
• (1>2) || true
➢ false || true
➢ true
• (2 == 1) || ! (1<2)
➢ false || ! true
➢ false || false
➢ false
115
Order of Operations Recorded
116
Examples of Boolean Expressions Recorded
➢ true || true
➢ true
117
Examples of Boolean Expressions Recorded
➢ 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
121
Examples Mixed Expressions Recorded
122
CONDITIONAL
STATEMENTS
123
How can we use Booleans? Recorded
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.
125
If statement syntax Recorded
126
If statement Recorded
if (x > 0) {
[Link](“x is positive”);
}
127
If statement Recorded
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
129
If-else statements – Example Recorded
if (x > 0) {
[Link](“x is positive.”);
}else {
[Link](“x is not positive.”);
}
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
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
133
Example Recorded
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.
135
Example (1) Recorded
136
If-else if-else nesting Recorded
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!
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)
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?
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
150
VOID METHODS
151
Void Methods Recorded
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
It is a void method: it does display strings on your screen, but it does not
return any value.
153
A simple program Recorded
154
Method calls Recorded
155
Java Code Recorded
156
Why should we use methods? Recorded
157
What print? Flow of Execution Recorded
158
Java Code
159
Program Execution
• When a program runs only the main method executes.
• 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
• 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
163
Examples Recorded
▪ In the parameter list you need to specify the type of each variable
separately.
164
Examples (1) Recorded
165
Examples (2) Recorded
166
Examples Recorded
167
Example Recorded
168
VALUE METHODS
169
Return statement Recorded
170
Value Methods Recorded
171
Return statements Recorded
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
Which of the following are valid ways to call the above method?
173
Dead Code Recorded
174
Return and conditional statements Recorded
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.
176
Method composition
• As void methods, value methods can be called from any other method.
177
Example – passing variables to methods Recorded
178
Example – passing variables to methods Recorded
179
Example – passing variables to methods (1) Recorded
180
Example – passing variables to methods (2) Recorded
181
Overloading Recorded
• Having more than one method with the same name is called
overloading.
• Java will know, based on the inputs, which method has been called.
182
Overloading example Recorded
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.
183
Recursion
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:
186
Unicode
• Variables of type char have 16 bits reserved in the memory to store a
value.
187
Unicode for Characters
188
Character Arithmetic
• Since every character is practically an integer, we can perform
arithmetic operations on variables of type char.
189
Comparing Chars
What prints?
190
Comparing Chars
What prints?
191
Comparing Chars (1)
What prints?
192
Comparing Chars (2)
What prints?
193
STRINGS
194
String
• Recall that a String is sequence of characters.
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
197
Examples (3)
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.
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?
202
Example (5)
What prints?
203
Example (6)
What prints?
204
Example (7)
What prints?
205
Example (8)
What can we do to get the last character of a given String s?
206
Null Pointer
207
Review – methods from the string class
String s = “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.
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.
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);
}
213
Review (1)
What prints?
public static void main(String[] args) {
int x = 5;
int y = 8;
myMethod(x,y);
[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);
}
215
Review (3)
What prints?
public static void main(String[] args) {
int x = 5;
int y = 8;
x = myMethod(x,y);
[Link](x + “ ” + 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));
}
217
What are we going to do today?
▪ While Loops
▪ For Loops
▪ Scanner
218
MORE OPERATORS
219
Operation-assignment +=, -=, *=, /= Recorded
int x = 2; int x = 2;
x += 5; x = x + 5;
220
Post Increment (Decrement) Recorded
• Post-increment: x++
• Post-decrement: x--
x--; x = x – 1;
221
Post Increment (Decrement) Recorded
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
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
}
227
While loop example Recorded
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.
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
241
For loop Syntax Recorded
242
For Loops
• A for loop is a while loop with a built-in counter
• 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
244
To recap
1) The initializer is executed
245
General Structure
246
For vs While Recorded
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
252
Loop Commands Recorded
253
Break – Example Recorded
What prints? 1 2 3 4
254
Continue – Example Recorded
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.
256
NESTED LOOPS
257
Nested loops Recorded
258
Multiplication table Recorded
259
One row Recorded
260
Multiple rows Recorded
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 ++++
} ++++
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?
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.
274
The Import Statement
• The import statement for the Scanner class:
import [Link];
275
How to Use Scanner
▪ Once you have imported the Scanner class, you can create a Scanner
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
277
Examples
import [Link];
String name;
Scanner read = new Scanner([Link]);
278
Examples
import [Link];
String name;
int age;
Scanner read = new Scanner([Link]);
279
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]
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.
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.
• 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,
287
Scope of Variables
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
292
Scope of Variables (3)
293
Scope of Variables (4)
294
More Example
• List the names of all variables in scope on the line marked *****HERE*****.
295
More Example (1)
• List the names of all variables in scope on the line marked *****HERE*****.
296
More Example (2)
• List the names of all variables in scope on the line marked *****HERE*****.
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
303
From Midterm Winter 2017
304
From Midterm Fall 2016
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.
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