BIT205-HO1-Basic Concepts of JAVA Programming
BIT205-HO1-Basic Concepts of JAVA Programming
BIT205-HO1-Basic Concepts of JAVA 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.
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.
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!
• System.out.println();
Prints a blank line of output.
8
Names and identifiers
• You must give your program a name.
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 }
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."
\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
16
Comments example
/* Suzy Student, CS 101, Fall 2019
This program prints lyrics about ... something. */
// 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
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
20
Expressions
• expression: A value or operation that computes a value.
• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
42
21
Arithmetic operators
• operator: Combines multiple values or expressions.
–+ addition
–- subtraction (or negation)
–* multiplication
–/ division
–% modulus (a.k.a. remainder)
22
Real numbers (type double)
• Examples: 6.022 , -42.0 , 2.143e17
– Placing .0 or . after an integer makes it a double.
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);
}
}
• Syntax:
type name;
• The name is an identifier.
x
– int x;
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;
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;
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;
31
Text Processing
32
Type char
• char : A primitive type representing single characters.
index 0 1 2 3 4 5
String s = "Ali G.";
value 'A' 'l' 'i' ' ' 'G' '.'
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"
– This code will compile, but it will not print the song.
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!");
}
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
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.
• 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;
}
}
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 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");
51
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}
52
Increment and decrement
shortcuts to increase or decrease a variable's value by 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
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"
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:
**********
**********
**********
**********
**********
• Output:
*
**
***
****
*****
59
Pseudo-code
60
Pseudo-code
• pseudo-code: An English description of an algorithm.
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 {
67
Cumulative sum loop
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum = sum + i;
}
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
• Example:
public static void sayPassword(int code) {
System.out.println("The password is: " + code);
}
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