Class 4
Class 4
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 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
• 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
• 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. }
}
• 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