In Collaboration
with
Midlands State University
DMIS 312: Java Programming
Lesson 3:
Java Control Structures, Arrays and Strings
Control Structures
These are statements that are used to define a specific way of execution of a
program
They control the execution of a program
The 2 structures to be covered are:
1. Selection / branching execution
2. Loop / iterative
Selection
Will cause a set or group of statements to be executed when a certain condition
is met
a) if
b) if….else
c) if….else if
d) Nested if
e) Switch
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is
true.
Syntax:
if(condition){
//code to be executed
}
Example: Java IF Statement
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
Java IF-else Statement
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example: Java IF-else Statement
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example: Java IF-else-if Statement
public static void main(String[] args) {
else if(marks>=70 && marks<80){
int marks=65;
System.out.println("B grade");
if(marks<50){ }
System.out.println("fail"); else if(marks>=80 && marks<90){
} System.out.println("A grade");
else if(marks>=50 && marks<60){ }else if(marks>=90 && marks<100){
System.out.println("D grade"); System.out.println("A+ grade");
} }else{
System.out.println("Invalid!");
else if(marks>=60 && marks<70){
}
System.out.println("C grade");
}
}
Example: if … else if statement
public class JavaApplication5 {
public static void main(String[] args) {
int num = 1;
if (num > 0) {
System.out.println("The number is positive");
} else if (num < 0) {
System.out.println("The number is negative");
} else {
System.out.println("The number is zero");
}
}
}
Nested if
This is a condition where you can have an if statement inside another if statement.
Example:
import java.util.*;
public class SelectionOperator {
public static void main(String[] args) {
int age=17, cash=200;
if (age>=18){
if (cash>=300){
System.out.println("You can go for a drink");
}
}
else {
System.out.println("Please stay home");
}
}
}
Switch case
public class JavaApplication5 {
public static void main(String[] args) {
int day = 1;
switch (day) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
// Other case statements
Default:
System.out.println(“Invalid Day");
}
}
}
Loops
Used to repeatedly execute a set of statements till a certain or defined
condition is met
1. for loop
2. while loop
3. do ….. while loop
For loop
The condition is set in the first line and should be met during the execution of
the statement
Example:
int i;
for(i=1; i<=5; i++){
System.out.println(i + " There we go again");
}
While loop
Example:
int x=1;
while(x<=5){
System.out.println(“ Welcome to Java Programming");
x++;
}
Do ….. While loop
Example:
int y=1;
do{
System.out.println("Do while loop will print 5 times");
y++;
} while(y<=5);
Java Break Statement
The Java break is used to break loop or switch statement. It breaks the current
flow of the program at specified condition. In case of inner loop, it breaks only
inner loop.
Example:
public static void main(String[] args) {
for(int i=1; i<=10; i++){
if(i==5){
break;
}
System.out.println(i);
}
}
Java Continue Statement
The Java continue statement is used to continue loop. It continues the current flow of
the program and skips the remaining code at specified condition.
In case of inner loop, it continues only inner loop.
Example:
public static void main(String[] args) {
for(int i=1; i<=10; i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
Practice Questions
1. Write a Java program to display all even numbers between 2 and 20
2. Write a Java program to display all multiples of 3 from 3 to 42
3. Write a java program to check if a number is prime number or not.
Even numbers between 2 and 20
public static void main(String[] args) {
int x;
for(x=1; x<=20; x++){
if(x%2==0){
System.out.println(x+"\n");
}
}
}
Multiples of 3 from 3 to 42
public static void main(String[] args) {
int x;
for(x=1; x<=42; x++){
if(x%3==0){
System.out.println(x+"\n");
}
}
}
Arrays
Arrays store multiple elements of the same data type. They are a set of
homogeneous data
Arrays are objects, so they’re considered reference types.
The conceptual view of an array is in a tabular form. It does have rows and
columns.
Arrays take two forms:
a) 1 Dimensional
b) 2 Dimensional
One dimensional array can be a data block with a single row and multiple
columns or a single column with multiple rows
Manipulating elements in an array
To manipulate an element in an array you need to use the array name and the index
or subscript
Subscripts are addresses to a particular element
An array data block can be referenced using a universal name called arrayName
Data items that can be stored in an array are called elements
Subscript / index is the address of a particular element in the array
Array declaration
To make an array exist in a program you must declare it
Syntax
dataType[] arrayName;
OR
dataType arrayName[];
Example
double[] myList;
or
double myList[];
Declaring and Creating Arrays
Array objects occupy space in memory.
Like other objects, arrays are created with keyword new.
To create an array object, you specify the type of the array elements and the number
of elements as part of an array-creation expression that uses keyword new.
Such an expression returns a reference that can be stored in an array variable.
Creating Arrays
You can create an array by using the new operator with the following
syntax −
arrayName = new dataType[arraySize];
The above statement does two things −
1. It creates an array using new dataType[arraySize].
2. It assigns the reference of the newly created array to the variable
arrayName
Creating Arrays
Declaring, creating and initializing an array can be combined in one statement:
dataType[] arrayName = new dataType[arraySize];
Example 1: int[] myList = new int [5];
Example 2: int myList[] = new int [5];
Alternatively you can create arrays as follows −
dataType[] arrayName = {value0, value1, ..., valuek};
Example 3: int[] myList = {20, 30, 50, 80, 120};
Example 4: int myList[] = {20, 30, 50, 80, 120};
The array elements are accessed through the index.
Array indices start from 0 to arrayRefVar.length-1.
Working with arrays
// Finding the largest element
public static void main(String[] args) {
double max = myList[0];
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
// Print all the array elements
}
for (int i = 0; i < myList.length; i++) {
System.out.println("Max is " + max);
System.out.println(myList[i] + " ");
}
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
Multi-dimensional Array
It is defined by multiple rows and columns
Syntax
dataType[][] arrayName;
OR
dataType arrayName[][];
Example
int myList[][] = {{60,80,90},{100,120,150}}
Java for-each Loop
In Java, the for-each loop is used to iterate through elements of
arrays and collections (like ArrayList). It is also known as the
enhanced for loop.
for-each Loop Syntax
The syntax of the Java for-each loop is:
for(dataType item : array) {
...
}
array - an array or a collection
item - each item of array/collection is assigned to this variable
dataType - the data type of the array/collection
Example 1: Print Array Elements
// print array elements
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
// for each loop
for (int number: numbers) {
System.out.println(number);
}
}
}
Example 2: Sum of Array Elements
// Calculate the sum of all elements of an array
class Main {
public static void main(String[] args) {
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
// iterating through each element of the array
for (int number: numbers) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}
class Main {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// iterating through an array using a for loop
for (int i = 0; i < vowels.length; ++ i) { for loop Vs for-each loop
System.out.println(vowels[i]);
}
}
}
class Main {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// iterating through an array using the for-each loop
for (char item: vowels) {
System.out.println(item);
}
}
}
Traversing the collection elements
import java.util.*;
class MyExample{
public static void main(String args[]){
//Creating a list of elements
ArrayList<String> list=new ArrayList<String>();
list.add(“Tadiwa");
list.add(“Lisa");
list.add(“Onias");
//traversing the list of elements using for-each loop
for(String s:list){
System.out.println(s);
}
}
}
Practice Question 1
Using an array mark[] write a program that accepts 5 student marks, display the
marks, determine and display the following:
a) Total marks
b) Lowest mark
c) Highest mark
d) Average mark
Practice Question 2
Write a program that accepts sales from 10 sales reps, determine and display the
following:
a) Average sales
b) Commission earned by each sales rep (given the rate as 0.22)
c) Total Commission
d) Average Commission
Practice Question 3
Design a program that enter 10 student marks between 0 and 100. The program
should distinguish the number of student who have failed and passed
0 to 49 fail
50 to 100 pass
Java - Strings Class
Strings are a sequence of characters.
In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in code, the compiler creates a String
object with its value in this case, "Hello world!'.
String objects
As with any other object, you can create String objects by using the new
keyword and a constructor
Example
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
Accessor Methods - String Length
Methods used to obtain information about an object are known as
accessor methods.
One accessor method that you can use with strings is the length()
method, which returns the number of characters contained in the string
object.
The following program is an example of length(), method String class.
Example
public static void main(String args[]) {
String myStmnt = “We are getting there";
int len = myStmnt.length();
System.out.println( "String Length is : " + len );
}
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
String Methods
Method Description
charAt() Returns the character at the specified index.
concat() Concatenates the specified string to the end of this string.
trim() Returns a copy of the string, with leading and trailing whitespace omitted.
length() Returns the length of this string.
toCharArray() Converts this string to a new character array
toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.
toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale
contains() Checks whether a string contains a sequence of characters
indexOf() Returns the position of the first found occurrence of specified characters in a string
substring() Returns a new string which is the substring of a specified string
The End!!!
Compiled by F. Zinyowera