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

Class 4

Uploaded by

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

Class 4

Uploaded by

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

Some Maths

with
Primitive
data types
Assignment might need:
Java 2D Graphics and Imaging
https://docs.oracle.com/javase/8/docs/technotes/gu
ides/2d/index.html
Let us do some Maths: Java
Operators
• Operators are used to perform operations on variables and values.
• Java divides the operators into the following groups:
• Arithmetic operators
• Arithmetic operators are used to perform common mathematical operations.
• Assignment operators (see list in other slides)
• Assignment operators are used to assign values to variables. Assignment operator is (=).
• The addition assignment operator (+=) adds a value to a variable.
• Comparison operators
• Comparison operators are used to compare two values (or variables).
• The return value of a comparison is either true or false. These values are known as Boolean values.
• Logical operators
• You can also test for true or false values with logical operators.
• Logical operators are used to determine the logic between variables or values:
• Bitwise operators
Arithmetic Operators
A list of all
assignmen
t
operators:
Comparison Operators

• Open a BlueJ and create the following


class to illustrate comparison operators:

public class Main {


public static void main(String[] args) {
int x = 15;
int y = 20;
System.out.println (“Is student 1 older
than student 2?”);
System.out.println(x!= y); // returns true,
because 15 is not equal to 20
}
}
Logical Operators

• Open a BlueJ and create the following class to illustrate logical operators:
public class Main {
public static void main(String[] args) {
int x = 9;
System.out.println(x > 5 && x < 10); // 3<x<10 returns true because 5 is greater than 3 AND 5 is less
than 10
}
}
//Display the marks
DIY System.out.println();
System.out.println("James = "+w);
import java.util.*; System.out.println("Joyce = "+x);
public class someMaths System.out.println("Peter = "+y);
{ System.out.println("Petronella = "+z);
public static void main(String[] args) {
System.out.println("Total marks inserted = yours to determine
// input the values one after the other the formula");
System.out.println("Please insert the marks of James");
Scanner scn = new Scanner(System.in); //Example of arithmetic operator.
int w = scn.nextInt(); int sum = w+x+y+z; //addition
System.out.println("Please insert the marks of Joyce"); int Divide = sum/4; //division. sum divide by Total marks
Scanner scn2 = new Scanner(System.in); inserted
int x = scn2.nextInt(); System.out.println();
System.out.println("Please insert the marks of Peter"); System.out.println("Class Total = "+sum);
Scanner scn3 = new Scanner(System.in); System.out.println("The division of the values is:..."+Divide);
int y = scn3.nextInt(); //please practise by adding other arithmetic operators
System.out.println("Please insert the marks of System.out.println();
Petronella");
Scanner scn4 = new Scanner(System.in);
int z = scn4.nextInt();
DIY (cont.)
//Example of Comparison Operators
System.out.println("Are Joyce's marks greater than those of
James?"+"="+(y>x));
System.out.println("Are the marks of James less than or
equals to those of Joyce?"+""+(x>=y));
//please practise by adding more comparison operatos
System.out.println();
//Example of logical operators
System.out.println("Are Peter's marks between 50 and 60?"+
(y < 50 && y < 60));
System.out.println("Are Petronella's at least greater than 50%
but at most 60%? marks between 50 and 60"+(z > 50 && z <=
60));
//System.out.println(x < 5 && x < 10); //logical operator
//System.out.println(y > 3 && y < 10); //logical operator
}
}
Typecasting
• Type casting is when you assign a value of one primitive data type to another type.
• The cast operator lets you manually convert a value, even if it means that a narrowing
conversion will take place.
• Cast operators are unary operators that appear as a data type name enclosed in a set of
parentheses.
• The operator precedes the value being converted.
• In Java, there are two types of casting:
• Widening Casting (automatically) - converting a smaller type to a larger type size
• byte -> short -> char -> int -> long -> float -> double
• Narrowing Casting (manually) - converting a larger type to a smaller size type
• double -> float -> long -> int -> char -> short -> byte
Typecasting
DIY: Typecasting
Widening Narrowing
public class Simple{ public class Simple{
public static void main(String[] a
public static void main(String[]
rgs)
args)
{
{
float f=10.5f;
int a=10;
int a=(int)f;
float f=a;
System.out.println(f);
System.out.println(a); System.out.println(a);
System.out.println(f); }
} }
}
DIY: Typecasting
Overflow Adding Lower Type
Class Simple{
class Simple{ public static void main(String[] args)
public static void main(String[] {
args) byte a=10;
{ //Overflow byte b=10;
//byte c=a+b;//
int a=130; Compile Time Error: because a+b=2
byte b=(byte)a; 0 will be int
System.out.println(a); byte c=(byte)(a+b);
System.out.println(c);
System.out.println(b); }
} }
}
DIY: Recap reading a
character from Keyboard
• The Java Math class has many methods that
allows you to perform mathematical tasks on
numbers.
• Math.max(x,y)
• The Math.max(x,y) method can be used to find
Math the highest value of x and y
class • Math.min(x,y)
• The Math.min(x,y) method can be used to find the
lowest value of x and y
• Math.sqrt(x)
NB: All Math • The Math.sqrt(x) method returns the square root
methods are of x:
static • Math.abs(x)
• The Math.abs(x) method returns the absolute
(positive) value of x:
• Random Numbers
• Math.random() returns a random number between
0.0 (inclusive), and 1.0 (exclusive)
• Math.PI() for return pi (π)
• Math.pow(value,exponent) for creating exponents or power.
Control
Statements
Flow of Control
• So far, all the programs we have written executed all the statements they contained
• Suppose we want to write a program which asks the user to enter two numbers and
then displays only the larger of the two. This involves executing certain statements
in some circumstances, and different statements in other circumstances.
• By default, the order of statement execution through a method is linear
• one statement after the other is executed, in textual order (top of page, downwards to end of
page).
• Some programming statements modify that order, allowing us to:
• decide whether or not to execute a particular statement
• perform a statement over and over repetitively (while)
• The order of statement execution is called the flow of control.
Flow Control Statement
• Java provides three types of control flow statements.
1.Decision Making/Selection/Conditional statements
• if statements
• switch statement
2.Loop/Iteration statements
• do while loop
• while loop
• for loop
• for-each loop
3.Jump statements
• break statement
• continue statement
Decision Making statements: If statement

• The if statement has the following syntax:

• Simple If statement is the most basic statement among


all control flow statements in Java.
• It evaluates a Boolean expression and enables the
program to enter a block of code if the expression
evaluates to true.
DIY: Simple If statement
• Program 2
• Program 1 import java.util.Scanner;
public class Student { public class BusRide {
public static void main(String[] args) { public static void main (String[] args)
int x = 10; {
int y = 12; final int CAPACITY = 56;
if(x+y > 20) int passengers;
Scanner keyboard = new Scanner(System.in);
{
System.out.print("Enter the number of
System.out.println("x + y is greater than
people that want to get on the bus: ");
20"); passengers = keyboard.nextInt();
}
// Add your code here see instruction below
}
}
}
}
DIY: Simple If statement: Program 2 BusRide
Class

• Complete the main() method of the BusRide class


• By adding code to check whether the number of passengers is
greater than the capacity of the bus
• If it is, then you should display a message asking for x
(where x is the number of passengers in excess of the
capacity of the bus) volunteers to travel in "economy class":
on the roof
• Regardless of whether the number of passengers exceeds
the capacity of the bus, you should display "Let's go!"
after you have displayed whether or not volunteers are
needed for "economy class"
Decision Making statements: If-else statement

• The if-else statement is an extension to the


if-statement, which uses another block of
code, i.e., else block.
• The else block is executed if the condition of
the if-block is evaluated as false.
• An else clause can be added to an if
statement to make it an if-else
statement:
if (condition)
statement1;
else
statement2;
• If the condition is true, statement1 is
executed;
• if the condition is false, statement2 is
executed
• One or the other will be executed, but not
both
DIY: If-else statement
• Program 4
import java.util.Scanner;
• Program 3 public static void main (String[] args)
public class Student {
{
public static void main(String[] args) final double RATE = 8.25; // regular pay rate
{ final int STANDARD = 40; // standard hours / week
int x = 10; double pay = 0.0;
int y = 12; int hours;

if(x+y < 10) { Scanner keyboard = new Scanner(System.in);


System.out.print("Enter number of hours worked:");
System.out.println("x + y is less than 10");
} hours = keyboard.nextInt();
else {
System.out.println("x + y is greater than 20"); // Add your code here
}
} System.out.println(“Your pay is: “ + pay);
}
DIY: If-else statement: Program 4 Wages Class

• Complete the main() method of the Wages class by adding code to


compute the gross earnings of an employee
• If the employee has worked more than 40 hours during his/her work week, he/she
should be paid 1.5 times his/her hourly wage for all hours worked in excess of 40.
• Can you rewrite your code using only a regular if-statement (that is, one that
does not have an else clause)?
Decision Making statements: If-else-if statement

• Syntax of if-else-if statement


if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
DIY: If-else statement
• Program 6
import java.util.Scanner;
• Program 5 public static void main (String[] args)
public class Student {
{
public static void main(String[] args) final double RATE = 8.25; // regular pay rate
{ final int STANDARD = 40; // standard hours / week
int x = 10; double pay = 0.0;
int y = 12; int hours;

if(x+y < 10) { Scanner keyboard = new Scanner(System.in);


System.out.print("Enter number of hours worked:");
System.out.println("x + y is less than 10");
} hours = keyboard.nextInt();
else {
System.out.println("x + y is greater than 20"); // Add your code here
}
} System.out.println(“Your pay is: “ + pay);
}
Nested If statement
• The statement executed as a result of an if • One can write nested if-else
statement or else clause could be another if statements like this:
statement if (condition1)
• These are called nested if statements if (condition2)
• Indentation does not determine which if and statement1;
else matches with. It is determined by syntax else
(i.e. by the order of the clauses or {}) statement2;
• An else clause matches with the nearest if else
• Note: Dr.Java does not automatically perform if (condition3)
proper indentation for nested statements statement3;
• Solution: use {} else
statement4;
Nested If statement
DIY: Nested If statement

• Program 7 • Program 8
public class Student { import java.util.Scanner;
public static void main(String[] args) { public static void main(String[] args)
String city = “Vanderbijlpark";
if(city == “Verreening") {
{
System.out.println("city is Verreening"); int num1, num2, num3, min = 0;
} else if (city == “Meyerton") {
Scanner scan = new Scanner(System.in);
System.out.println("Enter three integers: ");
System.out.println("city is Meyerton");
num1 = scan.nextInt();
}else if(city == “Three River") {
num2 = scan.nextInt();
System.out.println("city is Three River"); num3 = scan.nextInt();
}else { // add code here
System.out.println(city); System.out.println("Minimum value: " + min);
} }
}
}
• Example 9
DIY: Nested If statement public class Main
{
public static void main(String args[])
{
• Example 8 int s = 18;
• Complete the main() method of if (s > 10)
{
the MinOfThree class by adding if (s%2==0)
code which determines which of the System.out.println("s is an even number
three numbers entered by the user is and greater than 10!");
the smallest number, and displays else
System.out.println("s is a odd number
that number and greater than 10!");
• Can you write this code both with }
else
and without using block statements? {
System.out.println("s is less than 10");
}
System.out.println("Hello World!");
}
}
DIY: Block Statement

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Block Statement

• Several statements can be grouped


together into a block statement
• A block is delimited by braces ( {...}
)
• Is public class a block statement?
• A block statement can be used wherever
a statement is called for in the Java
syntax
• For example, in an if-else statement,
the if portion, or the else portion, or
both, could be block statements
DIY: Block Statement
import java.util.Scanner;
import java.util.Random;
public class GuessGame
{
public static void main(String[] args) {
final int UPPER_BOUND = 10;
Scanner keyboard = new Scanner(System.in);
Random randomSource = new Random();
double money;
double betAmount;
int myNumber;
int yourNumber;
System.out.print("How much money to you have? ");
money = keyboard.nextDouble();
betAmount = keyboard.nextDouble();
myNumber = randomSource.nextInt(UPPER_BOUND) + 1;
System.out.print("I've chosen a number between 1” + “ and " + UPPER_BOUND + ". Try to guess it: ");
yourNumber = keyboard.nextInt();
// Add your code here
}
DIY: Block Statement
• Complete the main()method of the GuessGame class by adding code to
determine whether the user won or not
• The player wins if he / she is able to guess the number that the program chose at
random
• If the player wins, you should display a message stating that he/she has won, and
the amount of money he/she has won
• If the player loses, you should display a message stating that he/she has lost,
what the number chosen by the program was, and the amount the player has lost
• Whether the player wins or loses, you should display the amount of money
he/she has after playing the game
Conditional statement/Selection statements

• A conditional statement lets us choose which • Equality (==) and inequality (!=)
statement will be executed next. operators apply to values that have any
• Therefore, they are sometimes called Selection
Statements.
type
• Conditional statements give us the power to make • The other comparison operators (<, <=, >,
basic decisions >=) only apply to values which have a
• Java's conditional statements are the if statement, numeric type (byte, short, int, long, float,
the if-else statement, and the switch statement double) or that have type char
• A condition often uses one of Java's equality operators • They do not apply to values that have
or relational operators, which all return boolean type Boolean
results:
== equal to • Even though the operands of a
!= not equal to comparison operator may have various
<! less than
> greater than types, the type of the result of the
<= less than or equal to comparison is always the same:
>= greater than or equal to
• Boolean (This implies that the result of a
• Note the difference between the equality operator (==) comparison is always true or false)
and the assignment operator (=)
Conditional statement/Selection statements
Branchi • Branching statements in java are
ng used to jump from a statement to
another statement, thereby the
Statem transferring the flow of execution.

ents
Switch Statement
• A switch statement in java is used to execute a single statement from multiple conditions.
• The switch statement can be used with short, byte, int, long, enum types, etc.
• Certain points must be noted while using the switch statement:
• One or N number of case values can be specified for a switch expression.
• Case values that are duplicate are not permissible. A compile-time error is generated by the compiler if unique
values are not used.
• The case value must be literal or constant. Variables are not permissible.
• Usage of break statement is made to terminate the statement sequence. It is optional to use this statement. If
this statement is not specified, the next case is executed.
• The switch statement provides another means to decide which statement to execute next
• The switch statement evaluates an expression, then attempts to match the result to one of several
possible cases
• Each case contains a value and a list of statements
• The flow of control transfers to the case associated with the first value that it matches with (first
come,
first serve)
DIY: Switch and Break Statement
case 5:
public class Music {
musicInstrument = "Ukelele";
public static void main(String[] args)
break;
{
case 6:
int instrument = 4;
musicInstrument = "Violin";
String musicInstrument;
break;
// switch statement with int data type
case 7:
switch (instrument) {
musicInstrument = "Trumpet";
case 1:
break;
musicInstrument = "Guitar";
default:
break;
musicInstrument = "Invalid";
case 2:
break;
musicInstrument = "Piano";
}
break;
System.out.println(musicInstrument);
case 3:
}
musicInstrument = "Drums";
}
break;
case 4:
musicInstrument = "Flute";
break;
Break Statement
• Often a break statement is used as the last statement in each case's statement
list
• break is also a reserved word in Java
• A break statement causes control to transfer to the end of the switch statement
• If a break statement is not used, the flow of control will continue into the next case,
regardless of whether the value of the expression in the switch matches that case
• Sometimes this can be helpful, but usually we only want to execute the statements
associated with one case
Break Statement
• DIY: Break statement example
• Known as the most common loop, the
while loop evaluates a certain condition. public class Test
{
• If the condition is true, the code is
public static void main(String args[])
executed. {
• This process is continued until the for (int i = 5; i < 10; i++)
specified condition turns out to be false. {
if (i == 8)
• The condition to be specified in the while break;
loop must be a Boolean expression. An System.out.println(i);
error will be generated if the type used is }
int or a string. }
}

• What is the output?


Continue Statement • DIY: Continue example…
public class Main
{
• To jump to the next iteration of the
public static void main(String args[])
loop, we make use of the continue {
statement. for (int k = 5; k < 15; k++)
• This statement continues the current {
flow of the program and skips a part // Odd numbers are skipped
of the code at the specified if (k%2 != 0)
condition. continue;
// Even numbers are printed
System.out.print(k + " ");
}
}
}
• What is the output?
Statements that execute a block of
code repeatedly until a specified
condition is met are known as
Loops
looping statements. Java provides
the user with three types of loops:
(i) While,
Statements
(ii) Do-While, and
(iii) For loops
While Loop
• DIY: While example
• Known as the most common loop, the while
public class whileTest
loop evaluates a certain condition. {
• If the condition is true, the code is executed. public static void main(String args[])
This process is continued until the specified {
condition turns out to be false. int i = 5;
• The condition to be specified in the while while (i <= 15)
loop must be a Boolean expression. An error {
will be generated if the type used is int or a System.out.println(i);
string. i = i+2;
• Syntax: }
while (condition) }
{ }
statementOne;
• What is the output?
}
Do-while Loop
• The do-while loop is similar to the while loop, • DIY: Do-while example
the only difference being that the condition in public class Main
{
the do-while loop is evaluated after the public static void main(String args[])
execution of the loop body. {
• This guarantees that the loop is executed at int i = 20;
least once. do
{
• Syntax: System.out.println(i);
do { i = i+1;
//code to be executed } while (i <= 20);
} while(condition); }
}

• What is the output?


For Loop Statement

• The for loop in java is used to iterate and evaluate a • DIY: For loop example
code multiple times. public class forLoop
{
• When the number of iterations is known by the user, public static void
it is recommended to use the for loop. main(String args[])
• Syntax: {
for (initialization; condition; for (int i = 1; i <= 10; i++)
increment/decrement) System.out.println(i);
{ }
statement; }
}
• What is the output?
For-Each Statement

• The traversal of elements in an array can • DIY: For-Each loop example


be done by the for-each loop. public class foreachLoop
• The elements present in the array are {
returned one by one. public static void main(String args[])
• It must be noted that the user does not {
int s[] = {18,25,28,29,30};
have to increment the value in the for-
for (int i : s) {
each loop. System.out.println(i);
}
}
}
Boolean Expression Practice
• Write boolean expressions that evaluates to true if and only if the given
condition is true
• The absolute value of variable a (of type int) is greater than 100
• The values of variables a, b, and c are all different
• The character stored in either variable c1, or variable c2 (both of type
char), or both, is a digit
• Write boolean expressions that evaluates to true if and only
if the given condition is true
• The value stored in exactly one of the two variables a and b
(both of type int) is equal to 0
Java Helpful Characters
Escape Sequences in Java
public class NewLineExample
• Both \n and \t are called escape {
sequences in java. public static void main(String
• What does \n mean in Java? args[])
• This means to insert a new line at this {
specific point in the text. In the below String str1 = "Hello";
example, "\n" is used inside the print String str2 = "world";
statement, which indicates that the System.out.print(str1 + "\n" +
control is passed to the next line. str2);
• As a result, the text following "\n" will }
be printed on the next line. }
Escape Sequences in Java
• What does \t mean in Java? public class NewTabExample
• This means to insert a new tab at this {
specific point in the text. public static void main(String args[])
• In the below example, "\t" is used {
inside the println statement. It is String str1 = "Hello";
similar to pressing the tab on our String str2 = "world";
keyboard. System.out.println(str1 + "\t" +
str2);
}
}
Operator “?” mean in Java: Ternary

• What does ? mean in Java


• It is either a:
• Ternary operator
• Wildcard in generics
• Ternary Operator
• According to Oracle docs, ?: is a conditional operator which can be thought of as
shorthand for an if-then-else statement.
• This conditional operator is also known as the ternary operator in Java because it uses
three operands.
• Syntax:
• The ternary operator can be read as if someCondition is true, assign the value of
value1 to result. Else, assign the value of value2 to the result.
DIY: Ternary
• Program 2:
public class TernaryOperatorExample
{
• Program 1: public static void main(String args[])
public class TernaryOperatorExample2 {
{ int a = 5; int b = 10; int result; // Below code
using if-else
public static void main(String args[])
if(a > b)
{
result = a;
int x = 100;
else
int y = 1000;
result = b; // The above if-else block
String result = (x > y) ? "x is greater
becomes
than y" : " x is less than y"; result = (a > b) ? a : b;
System.out.println(result); System.out.println(result);
} }
} }
Operator “?” mean in Java: Wildcard

• What does ? mean in Java


• Wildcard in generics
• According to Oracle docs, ? is called Wildcard as part of Java generics.
• It represents an unknown type.
• It can be used in a variety of situations:
• as the type of a field, local variable, or parameter; sometimes as a return type.
• Never use the wildcard as a type argument for a generic method invocation, a generic
class instance creation, or a supertype.
• Syntax:
• The ternary operator can be read as if someCondition is true, assign the value of
value1 to result. Else, assign the value of value2 to the result.
DIY: Wildcard
import java.util.*;
public class WildCardExample
{
public static void main(String args[])
{ //Below code using a list of Integer objects, prints sum = 18.0
List<Integer> list1 = Arrays.asList(3, 4, 5, 6);
System.out.println("sum of integer values: "+ sumOfList(list1));
/* A list of Double objects using the same sumOfList() method , prints sum = 19.0 */
List<Double> list2 = Arrays.asList(3.2, 4.2, 5.3, 6.3);
System.out.println("sum of double values: " + sumOfList(list2));
}
public static double sumOfList(List<? extends Number> list)
{
double var = 0.0;
for( Number num : list)
var = var + num.doubleValue();
return var;
}
}
Modulus operator (%)
• For positive numbers, modulus operator(%) means
percent sign in the java programming language. • DIY Modulus:
public class PercentSignJava
• The modulus operator in java returns the remainder
{
from division.
• For example: public static void main(String args[])
1. int remainder = 14 % 3 {
2. int quotient = 14 / 3 System.out.println("Modulus
• The first operator modulus results in 2 whereas the operator examples:");
second operator division(/) results in 4. int a=20, b=7; int z = a%b;
• In other words, x = A%B means that x will contain the System.out.println("integer example:
value of the remainder when dividing A by B. 20%7 = " + z);
• The modulus operator can be used in the following ways: float c= 5.5f, d=2.5f;
1. You can check whether one number is divisible by float y = c%d;
another, for example, if a % b is zero then a is divisible by
b. System.out.println("float example: 5.5%2.5 = "
2. You can extract the rightmost digit or digits from a + y);
number. }
• for example, a % 10 returns the rightmost digit of a (in base 10).
}
• Similarly, a % 100 returns the last two digits.
Unary operators (!)
• According to Oracle Java docs, ! is a unary
operator. • DIY Unary operator:
public class UnaryNotOperator
• It is called a 'NOT' operator. {
public static void main(String args[])
• It can be used to convert false to true or {
vice versa. // initializing variables
int a = 100, b = 10;
• By using this operator, the logical state of boolean visible = true;
an operand is reversed. // Printing variable values
System.out.println("Is visible: " + visible);
• In simple words, it inverts the value of a System.out.println("a: "+ a + " b: " + b);
boolean. // Using unary operator !
• Unary operators are those operators System.out.println("Is visible: "+ !visible);
System.out.println(" !(a > b) : " + !(a > b));
which require a single operand. System.out.println(" !(a < b) : " + !(a < b));
• Syntax }
}
!(operand)
Unary operators (!)

1. When the above code will be executed,


the static variable x will set to zero when
the class is first loaded in the memory by
JVM before any counter instances are
created.
• When a counter instance is created, the
counter constructor executes and increments
the static variable by 1 and result is 1.
2. When the second object is created,
counter constructor again executes and
increments the static variable by 1. Now,
result is 2.
3. Similarly, when the third object is created,
the result will be 3.
Try this example out
• What is an instance?
output
Thank you

You might also like