BIT205-HO1-Basic Concepts of JAVA Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 73

Object Oriented Programming

BIT205
Handout # 1
Basic Concepts of JAVA
programming
Chapters 1,2,3,4
Covers Course Learning Outcome(s):
1. Review structured programming concepts..

All handouts are available and accessible as soft copies at the following
address:
https://lms.ectmoodle.ae
What is programming?
• program: A set of instructions
to be carried out by a computer.

• program execution: The act of


carrying out the instructions
contained in a program.

• programming language: A systematic set of rules used to


describe computations in a format that is editable by humans.
– This textbook teaches programming in a language named Java.

2
Programming languages
• Some influential ones:

– FORTRAN
• science / engineering
– COBOL
• business data
– LISP
• logic and AI
– BASIC
• a simple language

3
Basic Java programs with
println statements
Compile/run a program
1. Write it.
– code or source code: The set of instructions in a program.

2. Compile it.
• compile: Translate a program from one language to another.
– byte code: The Java compiler converts your code into a format
named byte code that runs on many computer types.

3. Run (execute) it.


– output: The messages printed to the user by a program.
source code byte code output
compile run

5
A Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}
• Its output:
Hello, world!

This program produces


four lines of output

• console: Text box into which


the program's output is printed.
6
Structure of a Java program
public class name { class: a program
public static void main(String[] args) {
statement;
statement; method: a named group
... of statements
statement;
}
} statement: a command to be executed

• Every executable Java program consists of a class,


– that contains a method named main,
• that contains the statements (commands) to be executed.
7
System.out.println
• A statement that prints a line of output on the console.
– pronounced "print-linn"
– sometimes called a "println statement" for short

• Two ways to use System.out.println :


• System.out.println("text");
Prints the given message as output.

• System.out.println();
Prints a blank line of output.

8
Names and identifiers
• You must give your program a name.

public class GangstaRap {

– Naming convention: capitalize each word (e.g. MyClassName)


– Your program's file must match exactly (GangstaRap.java)
• includes capitalization (Java is "case-sensitive")

• identifier: A name given to an item in your program.


– must start with a letter or _ or $
– subsequent characters can be any of those or a number
• legal: _myName TheCure ANSWER_IS_42 $bling$
• illegal: me+u 49ers side-swipe Ph.D's
9
Keywords
• keyword: An identifier that you cannot use because it already
has a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized

10
Syntax
• syntax: The set of legal structures and commands that can be
used in a particular language.
– Every basic Java statement ends with a semicolon ;
– The contents of a class or method occur between { and }

• syntax error (compiler error): A problem in the structure of


a program that causes the compiler to fail.
– Missing semicolon
– Too many or too few { } braces
– Illegal identifier for class name
– Class and file names do not match
...

11
Syntax error example
1 public class Hello {
2 pooblic static void main(String[] args) {
3 System.owt.println("Hello, world!")_
4 }
5 }

• Compiler output:
Hello.java:2: <identifier> expected
pooblic static void main(String[] args) {
^
Hello.java:3: ';' expected
}
^
2 errors

– The compiler shows the line number where it found the error.
– The error messages can be tough to understand!

12
Strings
• string: A sequence of characters to be printed.
– Starts and ends with a " quote " character.
• The quotes do not appear in the output.

– Examples:
"hello"
"This is a string. It's very long!"

• Restrictions:
– May not span multiple lines.
"This is not
a legal String."

– May not contain a " character.


"This is not a "legal" String either."
13
Escape sequences
• escape sequence: A special sequence of characters used to
represent certain special characters in a string.

\t tab character
\n new line character
\" quotation mark character
\\ backslash character

– Example:
System.out.println("\\hello\nhow\tare \"you\"?\\\\");

– Output:
\hello
how are "you"?\\
14
Comments
• comment: A note written in source code by the programmer
to describe or clarify the code.
– Comments are not executed when your program runs.

• Syntax:
// comment text, on one line
or,
/* comment text; may span multiple lines */

• Examples:
// This is a one-line comment.
/* This is a very long
multi-line comment. */

15
Using comments
• Where to place comments:
– at the top of each file (a "comment header")
– at the start of every method (seen later)
– to explain complex pieces of code

• Comments are useful for:


– Understanding larger, more complex programs.
– Multiple programmers working together, who must understand
each other's code.

16
Comments example
/* Suzy Student, CS 101, Fall 2019
This program prints lyrics about ... something. */

public class BaWitDaBa {


public static void main(String[] args) {
// first verse
System.out.println("Bawitdaba");
System.out.println("da bang a dang diggy diggy");
System.out.println();

// second verse
System.out.println("diggy said the boogy");
System.out.println("said up jump the boogy");
}
}

17
Data Types
Data types
• type: A category or set of data values.
– Constrains the operations that can be performed on data
– Many languages ask the programmer to specify types

– Examples: integer, real number, string

• Internally, computers store everything as 1s and 0s


104  01101000
"hi"  01101000110101

19
Java's primitive types
• primitive types: 8 simple types for numbers, text, etc.
– Java also has object types, which we'll talk about later

Name Description Examples


– int integers (up to 231 - 1) 42, -3, 0, 926394
– double real numbers (up to 10308) 3.1, -0.25, 9.4e3
– char single text characters 'a', 'X', '?', '\n'
– boolean logical values true, false

• Why does Java distinguish integers vs. real numbers?

20
Expressions
• expression: A value or operation that computes a value.
• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
42

– The simplest expression is a literal value.


– A complex expression can use operators and parentheses.

21
Arithmetic operators
• operator: Combines multiple values or expressions.
–+ addition
–- subtraction (or negation)
–* multiplication
–/ division
–% modulus (a.k.a. remainder)

• As a program runs, its expressions are evaluated.


– 1 + 1 evaluates to 2
– System.out.println(3 * 4); prints 12
• How would we print the text 3 * 4 ?

22
Real numbers (type double)
• Examples: 6.022 , -42.0 , 2.143e17
– Placing .0 or . after an integer makes it a double.

• The operators + - * / % () all still work with double.


– / produces an exact answer: 15.0 / 2.0 is 7.5

– Precedence is the same: () before * / % before + -

23
Variables

24
Receipt example
What's bad about the following code?
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .08 +
(38 + 40 + 30) * .15);
}
}

– The subtotal expression (38 + 40 + 30) is repeated


– So many println statements
25
Variables
• variable: A piece of the computer's memory that is given a name
and type, and can store a value.
– Like preset stations on a car stereo, or cell phone speed dial:

– Steps for using a variable:


• Declare it - state its name and type
• Initialize it - store a value into it
• Use it - print it or use it as part of an expression
26
Declaration
• variable declaration: Sets aside memory for storing a value.
– Variables must be declared before they can be used.

• Syntax:
type name;
• The name is an identifier.

x
– int x;

– double myGPA; myGPA

27
Assignment
• assignment: Stores a value into a variable.
– The value can be an expression; the variable stores its result.

• Syntax:
name = expression;

x 3
– int x;
x = 3;

– double myGPA; myGPA 3.25


myGPA = 1.0 + 2.25;
28
Using variables
• Once given a value, a variable can be used in expressions:
int x;
x = 3;
System.out.println("x is " + x); // x is 3
System.out.println(5 * x - 1); // 5 * 3 - 1

• You can assign a value more than once:


x 3
11
int x;
x = 3;
System.out.println(x + " here"); // 3 here

x = 4 + 7;
System.out.println("now x is " + x); // now x is 11

29
Declaration/initialization
• A variable can be declared/initialized in one statement.

• Syntax:
type name = value;

myGPA 3.95
– double myGPA = 3.95;

– int x = (11 % 3) + 12; x 14

30
Receipt answer
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
int subtotal = 38 + 40 + 30;
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;

System.out.println("Subtotal: " + subtotal);


System.out.println("Tax: " + tax);
System.out.println("Tip: " + tip);
System.out.println("Total: " + total);
}
}

31
Text Processing

32
Type char
• char : A primitive type representing single characters.

– A String is stored internally as an array of char

index 0 1 2 3 4 5
String s = "Ali G.";
value 'A' 'l' 'i' ' ' 'G' '.'

– It is legal to have variables, parameters, returns of type char


• surrounded with apostrophes: 'a' or '4' or '\n' or '\''
char letter = 'P';
System.out.println(letter); // P
System.out.println(letter + " Diddy"); // P Diddy

33
Type String
• string: A sequence of text characters.
String name = "text";
String name = expression;

– Examples:
String name = "Marla Singer";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";

34
String concatenation
• string concatenation: Using + between a string and another
value to make a longer string.
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc" is "3abc"
"abc" + 9 * 3 is "abc27"
"1" + 1 is "11"
4 - 1 + "abc" is "3abc"

• Use + to print a string and an expression's value together.


– System.out.println("Grade: " + (95.1 + 71.9) / 2);

• Output: Grade: 83.5


35
Comparing strings
• Relational operators such as < and == fail on objects.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name == "Barney") {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}

– This code will compile, but it will not print the song.

– == compares objects by references (seen later), so it often gives


false even when two Strings have the same letters.

36
The equals method
• Objects are compared using a method named equals.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name.equals("Barney")) {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}

– Technically this is a method that returns a value of type boolean,


the type used in logical tests.

37
String test methods
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one

String name = console.next();


if (name.startsWith("Prof")) {
System.out.println("When are your office hours?");
} else if (name.equalsIgnoreCase("STUART")) {
System.out.println("Let's talk about meta!");
}

38
Conditional Execution
The if statement
Executes a block of statements only if a test is true

if (test) {
statement;
...
statement;
}

• Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Application accepted.");
}

40
The if/else statement
Executes one block if a test is true, another if false

if (test) {
statement(s);
} else {
statement(s);
}

• Example:
double gpa = console.nextDouble();
if (gpa >= 2.0) {
System.out.println("Welcome to Mars University!");
} else {
System.out.println("Application denied.");
}
41
Relational expressions
• if statements and for loops both use logical tests.
for (int i = 1; i <= 10; i++) { ...
if (i <= 10) { ...
– These are boolean expressions, seen in Ch. 5.

• Tests use relational operators:


Operator Meaning Example Value
== equals 1 + 1 == true
2
!= does not equal 3.2 != true
2.5
< less than 10 < 5 false
> greater than 10 > 5 true
<= less than or equal to 126 <= false 42
100
Nested if/else
Chooses between outcomes using many tests
if (test) {
statement(s);
} else if (test) {
statement(s);
} else {
statement(s);
}

• Example:
if (x > 0) {
System.out.println("Positive");
} else if (x < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
43
Logical operators
• Tests can be combined using logical operators:
Operator Description Example Result
&& and (2 == 3) && (-1 < false
5)
|| or (2 == 3) || (-1 < true
5)
! not !(2 == 3) true
• "Truth tables" for each, used with logical values p and q:
p q p && q p || q p !p
true true true true true false
true false false true false true
false true false true
false false false false

44
if/else with return
// Returns the larger of the two given integers.
public static int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}

• Methods can return different values using if/else


– Whichever path the code enters, it will return that value.
– Returning a value causes a method to immediately exit.
– All paths through the code must reach a return statement.

45
All paths must return
public static int max(int a, int b) {
if (a > b) {
return a;
}
// Error: not all paths return a value
}

• The following also does not compile:


public static int max(int a, int b) {
if (a > b) {
return a;
} else if (b >= a) {
return b;
}
}

– The compiler thinks if/else/if code might skip all paths, even
though mathematically it must choose one or the other.
46
if/else, return answer
public static int quadrant(double x, double y) {
if (x > 0 && y > 0) {
return 1;
} else if (x < 0 && y > 0) {
return 2;
} else if (x < 0 && y < 0) {
return 3;
} else if (x > 0 && y < 0) {
return 4;
} else { // at least one coordinate equals 0
return 0;
}
}

47
The for loop

48
Repetition with for loops
• So far, repeating a statement is redundant:
System.out.println("Homer says:");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("S-M-R-T... I mean S-M-A-R-T");

• Java's for loop statement performs a task many times.


System.out.println("Homer says:");
for (int i = 1; i <= 4; i++) { // repeat 4 times
System.out.println("I am so smart");
}
System.out.println("S-M-R-T... I mean S-M-A-R-T");
49
for loop syntax
for (initialization; test; update) { header
statement;
statement;
... body
statement;
}

– Perform initialization once.


– Repeat the following:
• Check if the test is true. If not, stop.
• Execute the statements.
• Perform the update.
50
Initialization
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

• Tells Java what variable to use in the loop


– Performed once as the loop begins

– The variable is called a loop counter


• can use any name, not just i
• can start at any value, not just 1

51
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

• Tests the loop counter variable against a limit


– Uses comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to

52
Increment and decrement
shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer version


variable++; variable = variable + 1;
variable--; variable = variable - 1;

int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5

53
Modify-and-assign
shortcuts to modify a variable's value

Shorthand Equivalent longer version


variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % value;

x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;
54
Repetition over a range
System.out.println("1 squared = " + 1 * 1);
System.out.println("2 squared = " + 2 * 2);
System.out.println("3 squared = " + 3 * 3);
System.out.println("4 squared = " + 4 * 4);
System.out.println("5 squared = " + 5 * 5);
System.out.println("6 squared = " + 6 * 6);
– Intuition: "I want to print a line for each number from 1 to 6"

• The for loop does exactly that!


for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared = " + (i * i));
}

– "For each integer i from 1 through 6, print ..."


55
Counting down
• The update can use -- to make the loop count down.
– The test must say > instead of <

System.out.print("T-minus ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + ", ");
}
System.out.println("blastoff!");
System.out.println("The end.");

– Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!
The end.

56
Nested for loops

57
Nested loops
• nested loop: A loop placed inside another loop.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println(); // to end the line
}

• Output:
**********
**********
**********
**********
**********

• The outer loop repeats 5 times; the inner one 10 times.


– "sets and reps" exercise analogy
58
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

• Output:
*
**
***
****
*****

59
Pseudo-code

60
Pseudo-code
• pseudo-code: An English description of an algorithm.

• Example: Drawing a 12 wide by 7 tall box of stars

print 12 stars.
for (each of 5 lines) { ************
print a star. * *
* *
print 10 spaces. * *
print a star. * *
* *
} ************
print 12 stars.

61
Class constants
• class constant: A fixed value visible to the whole program.
– value can be set only at declaration; cannot be reassigned

• Syntax:
public static final type name = value;
– name is usually in ALL_UPPER_CASE

– Examples:
public static final int DAYS_IN_WEEK = 7;
public static final double INTEREST_RATE = 3.5;
public static final int SSN = 658234569;

62
Constants and figures
• Consider the task of drawing the following scalable figure:

+/\/\/\/\/\/\/\/\/\/\+
| |
| |
| | Multiples of 5 occur many times
| |
| |
+/\/\/\/\/\/\/\/\/\/\+

+/\/\/\/\+
| |
| | The same figure at size 2
+/\/\/\/\+

63
Repetitive figure code
public class Sign {

public static void main(String[] args) {


drawLine();
drawBody();
drawLine();
}
public static void drawLine() {
System.out.print("+");
for (int i = 1; i <= 10; i++) {
System.out.print("/\\");
}
System.out.println("+");
}
public static void drawBody() {
for (int line = 1; line <= 5; line++) {
System.out.print("|");
for (int spaces = 1; spaces <= 20; spaces++) {
System.out.print(" ");
}
System.out.println("|");
}
}
}
64
Adding a constant
public class Sign {
public static final int HEIGHT = 5;
public static void main(String[] args) {
drawLine();
drawBody();
drawLine();
}
public static void drawLine() {
System.out.print("+");
for (int i = 1; i <= HEIGHT * 2; i++) {
System.out.print("/\\");
}
System.out.println("+");
}
public static void drawBody() {
for (int line = 1; line <= HEIGHT; line++) {
System.out.print("|");
for (int spaces = 1; spaces <= HEIGHT * 4; spaces++) {
System.out.print(" ");
}
System.out.println("|");
}
}
}
65
Cumulative algorithms
Adding many numbers
• How would you find the sum of all integers from 1-1000?

// This may require a lot of typing


int sum = 1 + 2 + 3 + 4 + ... ;
System.out.println("The sum is " + sum);

• What if we want the sum from 1 - 1,000,000?


Or the sum up to any maximum?
– How can we generalize the above code?

67
Cumulative sum loop
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum = sum + i;
}
System.out.println("The sum is " + sum);

• cumulative sum: A variable that keeps a sum in progress and


is updated repeatedly until summing is finished.

– The sum in the above code is an attempt at a cumulative sum.

– Cumulative sum variables must be declared outside the loops that


update them, so that they will still exist after the loop.
68
Scanner and cumul. sum
• We can do a cumulative sum of user input:

Scanner console = new Scanner(System.in);


int sum = 0;
for (int i = 1; i <= 100; i++) {
System.out.print("Type a number: ");
sum = sum + console.nextInt();
}
System.out.println("The sum is " + sum);

69
Parameters and Objects
Declaring a parameter
Stating that a method requires a parameter in order to run

public static void name ( type name ) {


statement(s);
}

• Example:
public static void sayPassword(int code) {
System.out.println("The password is: " + code);
}

– When sayPassword is called, the caller must specify


the integer code to print.

71
Passing a parameter
Calling a method and specifying values for its parameters

name (expression);

• Example:
public static void main(String[] args) {
sayPassword(42);
sayPassword(12345);
}
Output:
The password is 42
The password is 12345

72
Multiple parameters
• A method can accept multiple parameters. (separate by , )
– When calling it, you must pass values for each parameter.

• Declaration:
public static void name (type name, ..., type name) {
statement(s);
}

• Call:
methodName (value, value, ..., value);

73

You might also like