Cc103 Midterm
Cc103 Midterm
1 MODULE 6
“Java Decision Making”
Java Decision Making
There are two types of decision making statements in Java. They are:
if statements
switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace) will
be executed.
X =30and Y =10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called
a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch(expression){
casevalue :
//Statements
break;//optional
casevalue :
//Statements
break;//optional
//You can have any number of case statements.
default://Optional
//Statements
}
The following rules apply to a switch statement:
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
throught o subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Example:
Compile and run above program using various command line arguments. This would produce the
following result:
$ javaTest
Welldone
Your grade is a C
$
SELF-CHECK MD-1.1-1
A. Fill in the blanks with the correct answer.
There may be a situation when we need to execute a block of code several number of times, and is often
referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example:
Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Example:
Syntax:
The syntax of a for loop is:
for(initialization;Boolean_expression; update)
{
//Statements
}
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the elements
of the array you are accessing. The variable will be available within the for block and its value
would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be an
array variable or method call that returns an array.
Example:
Syntax:
The syntax of a break is a single statement inside any loop:
break; Example:
This would produce the following result:
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
Example:
if (i == 4) {
break;
System.out.println(i);
Result:
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
Continue Example
int i = 0;
while (i< 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
Result:
0
1
2
3
5
6
7
8
9
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
To declare an array, define the variable type with square brackets:
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
cars[0]="Opel";
System.out.println(cars[0]);
}
}
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length property:
Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
System.out.println(cars.length);
}
}
// Outputs 4
Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array. This example accesses the third element (2) in the second array (1) of
myNumbers:
Example
public class MyClass{
public static void main(String[]args){
int[][]myNumbers={{1,2,3,4},{5,6,7}};
int x =myNumbers[1][2];
System.out.println(x);
}
}
Result: 7
We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we
still have to point to the two indexes):
Example
public class MyClass{
public static void main(String[]args){
int[][]myNumbers={{1,2,3,4},{5,6,7}};
for(inti=0;i<myNumbers.length;++i){
for(int j =0; j <myNumbers[i].length;++j){
System.out.println(myNumbers[i][j]);
}
}
}
}
Result:
1
2
3
4
5
6
7
A.
B.
A method must be declared within a class. It is defined with the name of the method, followed
by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can
also create your own methods to perform certain actions:
Example
// code to be executed
Example Explained:
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
Results:
I just got executed!
I just got executed!
I just got executed!
Information can be passed to methods as parameter. Parameters act as variables inside the
method.
Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the method is
called, we pass along a first name, which is used inside the method to print the full name:
Example
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}
Multiple Parameters
Example:
public class MyClass {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
Note that when you are working with multiple parameters, the method call must have the same number
of arguments as there are parameters, and the arguments must be passed in the same order.
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value. If
you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead
of void, and use the return keyword inside the method:
Example:
public class MyClass {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
Results:
Outputs 8 (5 + 3)
Example:
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
}
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
}
Example
public class MyClass {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
Method Overloading
With method overloading, multiple methods can have the same name with different parameters:
Example:
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which have two methods that add numbers of different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Result:
int: 13
double: 10.559999999999999
Instead of defining two methods that should do the same thing, it is better to overload one.
In the example below, we overload the plusMethod method to work for both int and double:
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Result:
int: 13
double: 10.559999999999999
Note: Multiple methods can have the same name as long as the number and/or type of parameters are
different.
2.
A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into
two categories:
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much much
more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contain all the classes that belong to
the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:
Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method, which is
used to read a complete line:
Example
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the java.util package. This package also contains date and time facilities, random-number
generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the java.util package:
Example:
import java.util.Scanner;
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store
them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java
“Java Files”
The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
Example
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
The File class has many useful methods for creating and getting information about files. For example:
getAbsolutePath(
String Returns the absolute pathname of the file
)
Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already exists. Note that the
method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error
occurs (if the file cannot be created for some reason):
Example
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
To create a file in a specific directory (requires permission), specify the path of the file and use double
backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path,
like: /Users/name/filename.txt
Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some
text to the file we created in the example above. Note that when you are done writing to the file, you
should close it with the close() method:
Example
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors