JAVA Notes.docx
JAVA Notes.docx
TABLE OF CONTENTS
CHAPTER 1: FLOWCHART CONSTRUCTION.............................................................................4
1.1 Introduction........................................................................................................................4
1.2 Significance of the Shapes................................................................................................. 4
1.3 Converting Scenarios into Flowcharts............................................................................... 4
1.4 Worksheet...........................................................................................................................7
CHAPTER 2: VARIABLES AND DATATYPES................................................................................ 8
2.1 Variables.............................................................................................................................8
2.2 Variable Naming Convention.............................................................................................8
2.3 Reserved Keywords in Java............................................................................................... 8
2.4 Datatypes............................................................................................................................8
2.5 Primitive vs Non-Primitive................................................................................................ 9
2.6 Declaration, Assignment and Initialization........................................................................9
2.7 Datatype Conversion Basics............................................................................................ 10
2.8 Numeric-to-Numeric Conversion.....................................................................................11
2.9 Numeric-to-Non-Numeric and Vise-Versa Conversion................................................... 12
2.10 Worksheet.......................................................................................................................12
CHAPTER 3: OPERATORS.............................................................................................................. 15
3.1 What are Operators?.........................................................................................................15
3.2 Arithmetic Operators........................................................................................................15
3.3 Assignment operators.......................................................................................................15
3.4 Relational Operators........................................................................................................ 16
3.5 Logical Operators.............................................................................................................16
3.6 Bitwise Operators.............................................................................................................16
3.7 Unary Operators...............................................................................................................16
3.8 Operator Precedence........................................................................................................ 17
3.9 Points to note: How to handle modulus of negative numbers..........................................18
3.10 Worksheet.......................................................................................................................19
CHAPTER 4: INTRODUCTION TO JAVA CODING.................................................................... 20
4.1 Essentials..........................................................................................................................20
4.2 Scopes.............................................................................................................................. 20
4.3 Printing.............................................................................................................................21
4.4 Comments........................................................................................................................ 22
4.5 Worksheet.........................................................................................................................23
CHAPTER 5: USER INPUT...............................................................................................................24
5.1 Creating a Scanner.............................................................................................................. 24
5.2 Inputting Different Datatypes............................................................................................. 24
5.3 Code Examples................................................................................................................... 24
5.4 Worksheet............................................................................................................................26
CHAPTER 6: UNDERSTANDING ERRORS.................................................................................. 27
6.1 Preamble...........................................................................................................................27
6.2 Syntax Errors....................................................................................................................27
6.3 Logical Errors.................................................................................................................. 27
Page | 2
1.1 INTRODUCTION
What is a flowchart?
A flowchart is a pictorial way of visualizing each step of a program/code using distinct shapes to represent
different functionalities of the code.
Parallelogram Used for inputs (prompt messages and user inputs) and outputs
(print statements)
✔ Scenario 1: Let’s design a flowchart of a program that will display the message “Hello There.” and observe
the steps carefully below.
Page | 5
For displaying anything, we use the PRINT statement. Simple, isn’t it? Now can you design a flowchart of a
program that displays your name? Try it by yourself.
✔ Scenario 2: Now, let’s talk about some numbers. Suppose, we want to display the summation of two
numbers. You need to take these two numbers as user input and store them somewhere. Let's see the
flowchart below:
To take user inputs, we need PROMPT and READ. PROMPT is used for displaying a prompt message to the
user and READ is used for storing the value from a variable (we will learn all the details about variables in
Chapter 2). In this scenario, after taking two number inputs, we can access those values from variables num1
and num2 respectively. We can then store the summation of these two numbers in another variable called sum
and display it.
Now, hopefully you can design flowcharts of adding, subtracting, multiplying two or more numbers and many
more.
✔ Scenario 3: Let’s calculate the area of a circle now. You know the formula of calculating its area. Your task
is to take the value of the circle radius from the user and then calculate the area. For simplicity, assume the
value of pi will be 3.1416 for this problem. Let’s design the flowchart:
Page | 6
Similarly, you will be able to calculate the circumference of the circle. Additionally, you can design flowcharts
by calculating the area of squares, triangles, rectangles and so on.
✔ Scenario 4: Suppose, you are a loyal employee of a renowned company. You need to calculate the bonus
you will receive during the upcoming festive season. The bonus will be 5% of your monthly salary. Let’s
design a simple flowchart for that.
Now, let’s assume, at the end of each month, you have to pay 2.5% of your monthly salary as income tax. So,
your festival bonus is now calculated using 5% of your monthly salary after deducting the income tax. Think
what steps need to be modified and re-design the above flowchart.
Page | 7
1.4 WORKSHEET
A. Write a short description and draw a flowchart to make a cup of tea or coffee. The steps could vary person
to person.
B. Draw a flowchart to find the result of addition of two numbers given by a user. Also, find their average.
C. Draw a flowchart to take temperature in Fahrenheit and convert it to Celsius and print it.
D. Draw a flowchart which takes a number from the user and then multiply it with 10, then add 2050 to the
result and divide the number by 5 and show the final result as output.
E. Write a flowchart that finds the number of hours, minutes, and seconds in a given number of seconds. For
example, how many hours, minutes, and seconds are there in 10,000 seconds?
F. Write a flowchart to print the area of a triangle taking base and height input from the user.
G. Write a flowchart that reads the values for the three sides x, y, and z of a triangle, and then calculates its
area. The area is calculated as follows:
Area = s (s − x) (s − y) (s − z), where s is (x + y + z)/2
H. Assume there are two variables x and y. Take Values of these variables from the user. For example, the user
gave the following two values.
x = 46;
y = 27;
Now exchange / swap values in such a way so that printing the variable x gives 27 and y gives 46.
I. Take the value of a, b, c from the user. Then swap the values and print in such a way that:
Value of a goes to b
Value of b goes to c
Value of c goes to a
J. Suppose a government employee has to pay 3000 taka plus 2.5% tax of his yearly salary. Now take the
salary input from a user and print his tax.
Page | 8
2.1 VARIABLES
What are variables?
Variables are identifiers that are used to store data values. They are used to reserve a storage space, so that data
can be accessed and modified.
● Must begin with either letters (A-Z or a-z), dollar sign ($) or underscore (_).
● They are case sensitive, i.e.- “name” and “Name” are two separate variables.
● Cannot have any white spaces.
● Can have numbers (0-9).
● Cannot begin with a number or any special signs.
● Can use camel casing (yourFirstName) or snake casing (your_first_name) for multiple words in a variable.
● Cannot be a reserved keyword (table given below).
● Should be meaningful.
● Should not be a single character.
Valid Invalid
a123bc abc123 123Abc ab cd
first_name firstName first name Ab.cd
Int $ami #number if
_ami class_1 class int
Always try to keep your variable names meaningful and close to the context. Otherwise, the code will not be
readable by you or anyone else.
2.4 DATATYPES
Every variable in Java must be of a specific datatype. Datatypes can be categorized as follows:
● Primitive Data Types: Holds a value, represents the size and type of a variable
● Non-Primitive Data Types: Holds a reference to an object or location
Page | 9
Double and double, Integer and int, Float and float all exist in Java. However, Double, Integer, and Float etc are
non-primitive datatypes (classes) where double, int and float are primitive. We shall learn more about classes
and interfaces later on.
Primitive Non-Primitive
Predefined, no need to create before using Must be created (except for String) before using
Contains a value Contains a reference
Cannot be null Can be null
The size of a primitive type depends on the data type All non-primitive types have the same size.
<datatype> <variable name> = <value> < format specifiers >; // format specifiers are only for double and float
Examples:
byte b1 = 51;
short s1 = 513;
int i1 = 5456;
long l1= 12345788;
float f1= 5.0f;
double d1= 123.4558428743d;
boolean b1 = true;
char c1 = 'A';
String s1 = "Hello";
int [] a= {10, 20, 100};
If you paid attention, you should have noticed that for float and double there are an f and d respectively after the
values. These are format specifiers for float and double literals. You do not need format specifiers for any other
datatype. Values of char datatype are enclosed in single quotation (') and values of String datatype are enclosed
in double quotation (''). Length of a String can be 1 or more but char can have only one character.
~ Self-Study ~
Refer to the table above and experiment to understand why some of the lines were invalid. You shall learn more
about lossy conversion in 2.7 Datatype Conversion (Type Casting).
● Widening/Implicit Casting
● Narrowing/Explicit Casting
Page | 11
Widening/Implicit Casting:
Converting a lower data type to a higher data type (from right to left in the following diagram) is known as
widening typecasting. As a result, there is no data loss. Since Java does this type of casting automatically and
without any explicit coding, it is often referred to as automatic type casting. To implement widening type
casting, we do not need to create any new code or modify any of the ones we already have. Example:
int num = 10;
double data = num;
Narrowing/Explicit Casting:
Narrowing type casting is the process of converting higher data types into lower data types (from left to right in
the following diagram). As we convert larger size data types into smaller ones, data loss occurs. Because of this,
the conversion has been made manual rather than automatic. This type conversion is also known as Explicit type
conversion. Example:
double num = 10.99;
int data = (int)num;
int to float Widening/ int num = 10; Assigning the int type variable named num to a
and double Implicit double data = num; //10.0 double type variable named data. Here, Java first
float data2= num; //10.0 converts the int type data into the double type.
And then assigns it to the double variable.
double and Narrowing double num = 10.99d;
Assigning the double type variable named num to
float to int / float num2 = 10.25f; an int type variable named data. Here, the int
Explicit int data = (int)num; //10
keyword inside the parentheses indicates that the
int data2= (int)num2 //10 num variable is converted into the int data type.
Page | 12
float to Widening/ float num = 127.45f; Assigning the float type variable named num to a
double Implicit double d = (double) num; double type variable named d. Here, Java first
System.out.println(d); converts the float type data into the double type.
// 127.44999694824219 And then assigns it to the double variable.
double to Narrowing double num=1.123456789d; Assigning the double type variable named num to
float / float f= (float)num; a float type variable named f. Here, the float
Explicit System.out.println(f); keyword inside the parentheses indicates that the
// 1.1234568 num variable is converted into the float data type.
int to byte Narrowing int num = 127; This will only work for int values between -128 to
/ byte b = (byte) num; 127. Otherwise, it will give an error because byte
Explicit System.out.println(b); can only store numbers from -128 to 127.
//127
int to char int a=65; The ASCII character of the given value is stored as the
char c=(char)a; character.
System.out.println(c); //A
char to int char a='Z'; The ASCII value of the given character is stored as the
int c=(int)a; integer.
System.out.println(c); //90
You will learn how to convert char to String and vise-versa later on in this course in Chapter 9: Strings. You are
also not familiar with how methods work. For now, just keep in mind that methods may take a certain value,
perform certain operations, and may return a different value.
~ Self-Study ~
Experiment on every possible kind of datatype conversion. Look up lossy conversion on the internet.
2.10 WORKSHEET
A. Trace the following code and write the outputs.
Page | 13
Code Output
class B {
public static void main(String[] args) {
int a= 15; //Value of a is 5
int b= 4; //Value of b is 7
System.out.println(a+b);
float a1= a;
float b1= b;
String a2= Integer.toString(a);
String b2= Integer.toString(b);
System.out.println(a1+b1);
System.out.println(a1 == a);
System.out.println(a2+b2);
System.out.println(a2+"Hi"+b2);
System.out.println("Hi"+Integer.toString(b+1));
}
}
B. Imagine you have the following lines of codes. Your task is to complete the code so that the desired
output is generated.
Code Output
class A { 12
public static void main(String[] args) { 12.0
int x= 5; //Value of x is 5
57
int y= 7; //Value of y is 7
System.out.println(x+y);
//Your code here
System.out.println(x1+y1);
System.out.println(x2+y2);
}
}
D. What is the difference between declaring, assigning and initializing a variable? Can we declare,
assign or initialize the same variable multiple times in Java?
CHAPTER 3: OPERATORS
While dividing an int with another int, the whole part is taken. On the other hand, while dividing a float/double
with a float/double, the decimal part is also taken into account. Therefore, float/double datatypes provide more
accurate results in some arithmetic operations. For example, 5/2 is 2 whereas 5.0/2.0 is 2.5.
Moreover, the bitwise operator checks both the operands regardless of the value of the first operand. On the
other hand, logical AND (&&) does not check the value of the second operand if the first operand is false.
Logical OR (||) does not check the value of the second operand if the first operand is true. Bitwise Exclusive OR
provides true if one of the operands is true and the other one is false, otherwise, it provides false. Bitwise
Complement only works for Boolean and is also a unary operator as it needs only one operand.
Now, let us find the output of the following Java code lines:
System.out.println(5*(5+5/5%(5*5))); //Output: 30; Here 5*5 was executed first, then 5/5.
System.out.println(5+1==(5+5/5%(5*5))); //Output: true.
System.out.println(-(-5-1)==(5+5/5%(5*5))); //Output: true; Here -5-1 and 5*5 were executed first.
System.out.println(5!=5 && 5%1!=1 || 1==(5/2)); //Output: true.
From the above lines of codes, we can see that if operators with same precedence are placed adjacently such as:
5/5*5, we must calculate from left to right. Which means performing the division first and then the
multiplication.
Page | 18
3.10 WORKSHEET
A. Trace the following lines of codes and write the outputs.
Code Output
class A {
public static void main(String[] args) {
int x= 5; //Value of x is 5
int y= 7; //Value of y is 7
System.out.println(x); //Print current value of x
System.out.println(y); //Print current value of y
x-=1;
y+=1;
System.out.println(x);
System.out.println(y);
x= ++y;
y= x--;
System.out.println(x);
System.out.println(y);
System.out.println(x==y);
System.out.println(x%y==4*2);
System.out.println(x&y);
System.out.println(x|y);
x= -x;
System.out.println(x);
x= ~x;
System.out.println(x);
y*=x;
System.out.println(y);
System.out.println(x%2==1 && y%2!=0);
}
}
4.1 ESSENTIALS
In order to start writing code in java, it is essential to understand the meaning and use of certain keywords that
are the building blocks of any java code.
4.2 SCOPES
In java, a block of code is the code inside the curly braces, {}. The scope of a variable represents the space or
block of code in which the variable can be accessed and modified. Usually, the scope of a variable is the block
of code in which it is created, for example- (1) A variable declared inside the curly braces of a loop is only valid
(can be accessed and modified) within the scope of the loop, (2) A variable declared inside the curly braces of a
method is only valid within the scope of the method.
int z=x+y; 39
while (x>5){ Sum of x+y = 35
int m=3; //m initialized inside loop.
int n=m+x; //n initialized inside loop.
System.out.println(m+" "+n); //m & n accessible only inside loop.
x--;
}
4.3 PRINTING
In order to show an output of a program, we use the print statement, System.out.println(“Text to be
printed.”). The System.out command basically invokes the System class to generate an output. The println() is
a built-in public method used to show an output. It prints the text inside the method parameter, as well as a new
line. To avoid adding the new line at the end, print() can be used instead as System.out.print().
x--;
}
}
}
public class Example1 { 109876
public static void main(String args[]) {
int x=10;
while (x>5){
System.out.print(x); //No new line is added at the end.
x--;
}
}
}
4.4 COMMENTS
In a program, comments are lines which are not executed but are there to help someone who is not familiar with
the code to understand how the code works. The compiler ignores these lines while compiling. Writing
comments can also help to debug code easily.
1. Single-line comments: These are comments written in a single line and are usually short. The
comment is initiated using two forward slashes, //. Anything written after the second slash in the same
line will be considered as a comment.
2. Multi-line comments: These are comments written when descriptions need to be written for methods
or loops in multiple lines. Writing multi-line comments using // is possible, but it becomes tedious
when there are several lines, and // needs to be written before each line. In order to make writing
multi-line comments easier, use a forward slash, /, followed by an asterisk, *, then write the comment,
and end using an asterisk, and a forward slash.
3. Documentation comments: It is often referred to as doc comment. It is usually used when writing
code for a software or package to generate a documentation page for reference. It follows the same
convention as a multi-line comment, only an exception of an additional asterisk at the beginning of
every new line.
4.5 WORKSHEET
A. Take two integer numbers from the user and print the summation and average.
B. Take the values of x, y and z and solve the result of the following equation:
result= x+(x%2+y*z^ (4/2))
C. Take the first name and last name from the user and print the outputs accordingly.
D. Take the first name, middle name and last name from the user and print the outputs accordingly. Keep
in mind that a user may or may not have a middle name. If the user does not have one, they must enter
an empty string as the middle name.
Tanvir
Page | 24
Now, inside the class we have to create an object of the Scanner class, so that we can use all its properties. You
will not understand the process of creating an object or its purposes now, as it is a concept of Object-Oriented
Programming. For now, just assume that the following line is necessary for taking user input. Using the variable
sc we can now take different types of user inputs. The System
Method Datatype
nextBoolean() Boolean
nextByte() Byte
nextShort() Short
nextLong() Long
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLine() String
Take the name (String), the import java.util.Scanner; Sami Enter name,
age (int) and the salary 23 age and
(double) from the user and class Main { 1200.5 salary:
print these. public static void main(String[] args) { Name: Sami
Scanner sc = new Scanner(System.in);
Age: 23
System.out.println("Enter name, age and salary:"); Salary: 1200.5
String name = sc.nextLine();
int age = sc.nextInt();
double salary = sc.nextDouble();
5.4 WORKSHEET
A. Write a program that takes input of the user's last name. Then prints it back as shown in the examples
below.
B. Write a Java program that reads two integers from the user and prints the sum, difference, product and
the average.
Sample Input Sample Output
10 Sum: 22
12 Difference: 2
Product: 120.0
Average: 11.0
5 Sum: 3
-2 Difference: 7
Product: -10.0
Average: 1.5
C. Write a Java program that reads the radius of a circle and prints the area and circumference of the circle
as shown in the examples below.
D. Write a program that takes a floating number as an input and prints the square of the number.
E. Write a program that reads two strings from the user and then prints their sum.
6.1 PREAMBLE
By this point you should have some Java coding experience and must have come across a lot of errors. Some are
easy to figure out, some are difficult. In this chapter we shall learn about some common errors and how to
prevent these. After completing this chapter, you will no longer have to spend hours trying to figure out what
error occurred. Errors in Java can be categorized as follows:
● Syntax Errors
● Logical Errors
● Runtime Errors or Exceptions
There is no hard and fast rule for preventing logical errors. You have to crosscheck all the logics if the output
does not match.
Page | 28
6.5 WORKSHEET
A. Check the following code carefully and find all the possible errors and then rewrite it correctly. The
output of this code should be:
false
15
Given Code Lines Error Present or Not (If Rewritten Code
present specify which error)
class A {
public static void man(String[]
args) {
int x= 5/0;
int y= 7
x-==1;
1y+=1;
System.out.println(y%2!=0;
int m = Integer.valueOf("Hi");
System.out.println(m);
}
Page | 29
Here, we can see that an “if” block is executed only when the if condition holds true.
True
block
}
}
}
Here, we can see that the keyword “if” is followed by a “condition” and a pair of curly braces { }. In the next
line, we can see leading whitespaces followed by a block of code. A block/scope of code is a collection of lines
of codes. For example, the “True block” inside the curly braces may contain multiple lines of codes which will
only be executed when the “if condition” is True. The leading whitespaces are called indentation which
separates a block/scope of code from the rest of the lines of code. Maintaining indentation is crucial in many
programming languages.
Let’s see another example. Here we want to print “num1 is greater” if the first number is greater.
Flowchart Code
int num1 = 9;
Page | 30
int num2 = 4;
System.out.println("num1 is greater");
Output: Explanation:
num1 is greater num1 variable holds the value 9 and num2 variable holds the value 4 so in the if condition
we are checking if num1 (9) is greater than num2 (4) or not, since 9 is greater than 4, the
condition yields True and the if scope is executed. Therefore, “num1 is greater” is printed.
Note that if num1 was any value smaller than num2 then the if scope would not be executed
and nothing would be printed.
Here, we can see that an “if” block is executed only when the if condition holds true and the “else” block is
executed only when the if condition holds false.
True block
}
else {
False block
}
}
Here, we can see the keyword “else” followed by a pair of curly braces { } which indicate the scope of the else
block separated by an indentation. The else block of code is only executed when the if condition yields false.
Notice that we do not need to write any conditional statement beside the “else” keyword.
Let’s see the previous example again. Now, we want to print “num1 is greater” if the first number is more than
the second number or print “num2 is greater” otherwise.
Flowchart Code
Output: Explanation:
num2 is greater num1 variable holds the value 7 and num2 variable holds the value 11 so in the if condition
we are checking if num1 (7) is greater than num2 (11) or not, since 7 is NOT greater than
11, the condition yields False and the else scope is executed. Therefore, “num2 is greater”
is printed. Note that if num1 was any value larger than num2 then only the if scope would
be executed and “num1 is greater” would be printed.
We can use Logical Operators within if conditions as well whenever there are multiple conditions that need to be
checked at a time.
Page | 32
Let’s see an example where we need to take an integer input from the user and determine if the number is a
positive even number or not.
Flowchart Code
import java.util.Scanner;
public class Sample5{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int num= sc.nextInt();
if (num>=0 && num%2==0){
System.out.println("positive even number");
}
else{
System.out.println("not");
}
}
}
Code
Flowchart
public class Sample6{
public static void main(String [] args){
if (condition) {
if True
block
}
else if (condition) {
else if True
block
}
else if (condition) {
else if True
block
Page | 33
}
else {
else
block
}
}
}
In the sample code it can be seen that conditional statements are placed after “else if” keywords. The else block
will only be executed if none of the above if or else if conditions yield True.
Remember that, a single “if” block can exist on its own without the help of any “else if” block or “else” block.
Also, an “if” block followed by one or multiple “else if” blocks can also exist without the help of any “else”
block. But, only “else” blocks or “else if” blocks cannot stand along without any initial “if” block.
Let’s see an example. We will take the salary and work experience of an employee as an input and calculate the
bonus based on their experience. If the work experience is over 8 years, then 15% bonus is awarded, if the work
experience is 5 years - 8 years then 10% bonus is awarded, if the work experience is 2 years - 4 years then 5%
bonus is awarded and work experience below 2 years will be awarded with 2.5% bonus.
Flowchart Code
import java.util.Scanner;
public class Sample7 {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int salary = sc.nextInt();
int experience = sc.nextInt();
if(experience > 8){
System.out.println(salary*0.15);
}
else if(experience >= 5){
System.out.println(salary*0.1);
}
else if(experience >= 2){
System.out.println(salary*0.05);
}
else{
System.out.println(salary*0.025);
}
}
}
30000 1500.0
Code
Flowchart
public class Sample8{
public static void main (String [] args){
if (condition) {
if (condition) {
nested True
block
}
else {
nested False
block
}
}
else {
if (condition) {
nested True
block
}
else {
nested False
block
}
}
}
}
In the sample code, it can be seen that the nested if/else blocks follow their own indentation. Remember, the
nested blocks also follow the same convention as any basic if…else if…else block that we learned in the above
sections.
Let’s see an example. We want to print “even multiple of 3” if a number is an even number and a multiple of 3,
“odd multiple of 3” if the number is an odd number and a multiple of 3 and “invalid” otherwise. [Note: this
problem can also be solved using “and” logical operator and “if…else if…else” blocks. Try it out on your
own.]
Page | 35
Flowchart Code
import java.util.Scanner;
public class Sample9 {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num % 2 == 0){
if(num % 3 ==0){
System.out.println(“even multiple of 3”);
}
else{
System.out.println(“invalid”);
}
}
else{
if (num % 3 ==0){
System.out.println(“odd multiple of 3”);
}
else{
System.out.println(“invalid”);
}
}
}
}
Input: Output:
33 odd multiple of 3
Explanation:
The input is 33 for which 33%2 is not equal to 0 so it
goes to the else block and then inside the else block 33
is again checked for which 33%3 is equal to 0 and so
“odd multiple of 3” is printed.
Syntax • There can be one or multiple case values for a switch expression. The
switch(expression){ expression is evaluated once and compared with the values of each case.
case value1 : • The case values must be of switch expression type only; variables are not
// Code Statements allowed. Also, the case values need to be unique. In case of duplicate
break; // optional values, it renders an error.
case value2 : • If there is a match, the associated block of code is executed. For example,
// Code Statements if expression matches with value1, the code of case value1 is executed.
break; // optional Similarly, the code of case value2 is executed, if expression matches with
. value2 and so on.
. • The optional break statement is used inside the cases to terminate a
. statement sequence. If it is omitted, execution will continue on into the
case valueN : next case.
// Code Statements • If there is no match, the code of the optional default case is executed. It
break; // optional can appear anywhere inside the switch block. In case, if it is not at the end,
default: // optional then a break statement must be kept after the default statement to omit the
// Default Code Statements execution of the next case statement.
}
Page | 36
In summary, the switch statement evaluates an expression and compares it to case values of the same type.
When a match is found, the associated block of code is executed. The break statement is used to exit the switch
block, and the default statement is executed if there is no match.
7.6 FLOWCHARTS
Now, let’s look at some relevant examples through flowcharts.
✔ Scenario 1: Let’s design a flowchart of a program that will take a number as user input and determine
whether the number is even or odd. [Hint: If you try to divide any even number in this universe by 2, you
will always end up with a remainder value 0 (zero).]
✔ Scenario 2: Let’s consider three numbers A, B and C. We need to find out which number is the largest
among these three and draw a flowchart for that. Let’s assume, for this problem all the values of A, B & C
are unique; that means there will be no duplicate values.
Before going to design the flowchart, let’s break down the problem and formulate the necessary conditions
first.
● If A is greater than B and A is greater than C, then definitely A will be the largest.
● If A is not greater than B (which means B is greater than A) and B is greater than C, then B will be the
largest.
● If the above two conditions are not fulfilled, then obviously C will be the largest.
✔ Scenario 3: Let’s calculate some taxes again. Suppose, you need to calculate the tax amount an employee
needs to be paid based on his/her salary. Here are the requirements:
7.7 WORKSHEET
A. Consider the following code. Suppose, the desired output should be: "A is greater than 100". What is
the problem in this code? How can you overcome this problem? [There can be multiple ways to solve
the issues.]
class SimpleCode {
public static void main(String[] args) {
int a = 120;
if (a > 10) {
System.out.println("A is greater than 10");
}
else if (a > 100){
System.out.println("A is greater than 100");
}
else {
System.out.println("A is less than 10");
}
}
}
B. Suppose, you are dealing with 3 conditions. You are trying to implement these conditions using if →
else if → else if blocks. So, clearly the “else” block is missing. But the code will not give any errors.
So, what do you think of omitting this “else” block? In which cases you can apply this technique?
if [condition]
System.out.println("Hello");
if [condition]
System.out.println("Hello");
else
System.out.println("Hello");
if [condition]
System.out.println("Hello");
else if [condition]
System.out.println("Hello");
else
System.out.println("Hello");
if [condition]
System.out.println("Hello");
D. Suppose, there are two boolean variables a and b. The value of a is set to true and the value of b is set
to false. What will be the result of the following expression? Briefly explain.
E. Design the flowchart and also write the Java code for the following problems.
a. Take a number from the user and find out if the number is positive or negative or zero.
b. Take a number as user input and calculate the absolute value of the number. [For example,
absolute value of 5 is 5 and absolute value of -5 is 5.]
c. Find out the largest number among four numbers taken from the user.
d. Find out the second largest number / second smallest number among three numbers taken from the
user. [You are not allowed to use a loop.]
F. Suppose, on normal days, a worker usually works a maximum of 8 hours daily. On some special days,
after 8 hours of work, overtime is counted. Suppose,
a. For the first 8 hours, the worker gets 200 taka hourly.
Page | 40
b. For the next 2 hours of overtime, the worker will receive 250 taka hourly.
c. For another 2 hours of overtime, the worker will receive 300 taka hourly.
Your first task is to write a Java program that takes the daily work hour of that worker as input. Then
calculate the amount the worker will receive based on the criteria mentioned above. If the daily work
hour is zero or negative or greater than 12, then display "Invalid".
80 - 100 A Excellent
70 - 79 B Good
60 - 69 C Satisfactory
50 - 59 D Okay
0 - 50 F Fail
Your task is to write a Java code where you need to take a student’s obtained marks as user input. Then
based on the above criteria, display the grade the student got and also display the corresponding
comment from the table. If the user enters a number that is outside the valid range 0-100, then display
the line "Invalid Input".
H. Write a Java program that takes an integer number as user input and print "Yes" if the number is
divisible by: (For each subproblem, there will be separate codes)
a. either 3 or 5
b. 3 and 5 both
c. 3 but not 5
d. 5 but not 3
e. 3 or 5 but not both
f. neither 3 nor 5
CHAPTER 8: REPETITIONS
It is not necessary for the expression initialization to be inside the for loop. It can be done before the loop starts.
Similarly, the expression update can also be done inside the body of the for loop.
While and for loops are entry control loops because before entering the loop the text expression always checked.
Therefore, cases might also occur where we cannot enter the loop at all.
For for (int i =1; i>0; i++){ for (int i =1; i>0;){ for ( ; ; ){
System.out.println(5); } System.out.println(5); System.out.println(5);
} }
Infinite loops can be used to solve problems that require indefinite number of iterations. You will learn more on
these in Chapter 8.7.
int count=1; for (int i=1; i<5; i++){ for (int i=1; i<10; i++){
while(count<5){ if (i==3){ if (i==3){
System.out.println(count); continue; continue;
count++; } }
if (count==3){ System.out.println(i); if (i>3){
break; } break;
} }
} System.out.println(i);
}
Output: Output: Output:
1 1 1
2 2 2
4
Here, after the second iteration, Here, the third iteration is Here, the third iteration is skipped and
the loop breaks. skipped. the loop breaks in the fourth iteration.
Remember that in case of nested loops (a loop inside another loop), the break or continue keywords will only
apply on the loop these keywords are directly in, not on the outer loops.
Page | 44
Print the number of divisors of all the numbers ranging from 1 to 10.
Now, let us understand how break and continue keywords work in a nested loop.
class A { Output:
public static void main(String[] args) { 1
for (int x=1; x<=5; x++){ 2
for (int i=1; i<=x; i++){ 1
if (x==1){ 2
continue; 3
} 1
if (x==4){ 2
break; 3
} 4
System.out.println(i); 5
}
}
}
}
Here, if you notice closely, having the break or continue keywords in the inner loop affected the inner loop and
not the outer loop.
For example, suppose you have to keep on taking inputs from the user until they enter 0. Now, there is no
guarantee when the user will enter 0. The user could enter 0 in the very first iteration, or even in the 100th
Page | 45
iteration. So, you have to run your loop indefinitely and break it when the condition is fulfilled. Here are a few
examples to help you understand when to use definite and indefinite loops.
Definite Indefinite
Print all the even numbers Print the first five numbers Keep taking user inputs until the user
within 1 to 10. divisible by 3 within 1 to 25. enters an even positive number. Then
print that number.
for (int i=1; i<=10; i++){ int num=0; Scanner sc= new Scanner(System.in);
if (i%2==0){ for (int i=1; i<=25; i++){ while(true){
System.out.println(i); if (i%3==0){ int num= sc.nextInt();
} System.out.println(i); if (num%2==0 && num>0){
} num++; } System.out.println(num);
if (num==5){ break;
break;} }
} }
Output: Output: Input: Output:
2 3 5 6
4 6 0
6 9 -4
8 12 6
10 15
8.8 FLOWCHARTS
The following flowchart is what a flowchart of a loop looks like. After encountering a while loop, the condition
is checked. If the condition satisfies, we enter the loop. We keep on iterating and executing the statements inside
the loop as long as the condition satisfies. We break out of the loop as soon as the condition is dissatisfied.
Now we shall look at a few problem examples and their corresponding flowcharts.
Page | 46
8.9 WORKSHEET
Flowchart Problems
A. Draw the flowchart of a program that calculates the sum of all the numbers from 1 to 100 using a while
loop.
B. Draw the flowchart of a program that prompts the user to enter a password. Keep asking for the password
until the user enters the correct password "abc123". Once the correct password is entered, display a message
"Access granted!".
C. Draw the flowchart of a program that prompts the user to enter a positive integer and then prints all the even
numbers from 2 up to and including that number.
D. Draw the flowchart of a program that prompts the user to enter a series of numbers. Continue reading
numbers until the user enters a negative number. Then, calculate and display the average of all the positive
numbers entered.
Coding problems
A. Write a program that asks the user to enter a series of numbers and calculates their average. Display the
average to the user.
B. Write a program that prompts the user to enter a positive integer and prints the factorial of that number.
C. Write a program that prints the multiplication table for a given number from 1 to 10.
D. Write a program that prints the ASCII values and characters for all uppercase letters (A-Z) using a loop.
E. Write a program that prompts the user to enter a positive integer and checks if it is a prime number. Display
an appropriate message indicating whether the number is prime or not.
F. Write a program that prompts the user to enter a positive integer and checks if it is a perfect number.
Display an appropriate message indicating whether the number is perfect or not.
G. Write a program that prompts the user to enter a positive integer and checks if it is a palindrome number. A
number is a palindrome if it reads the same forwards and backwards. Display an appropriate message
indicating whether the number is a palindrome or not.
Page | 47
CHAPTER 9: STRINGS
1. Using string literal - A new string object is created by using double quotation marks like
Using a string literal to create a string is more memory efficient for Java since it checks the string constant pool
after a string object is created. If the string is already present in the string constant pool, then only the reference
to the string is returned and if the string does not exist only then a new string object is created. You can consider
the string constant pool as a special memory location.
2. Using the new keyword, i.e., using the String class constructor - A new string object is created by using the
String class constructors. There are 13 constructors in the String class which can be used to create a string
object. The most common ones are
Using the new keyword creates a new String object each time in the heap memory.
Let’s write these 4 lines of code and see how the string objects are stored in the diagram below.
When s1 is created, there is no String literal “Java is fun” in the string constant pool and so it is added there.
When s2 is created, the string “Java is fun” is already present in the pool and hence its reference is only returned
to s2, and that is why s1 and s2 both point at the same String object. But s3 and s4 are created using the String
constructor and so both created new String objects which reside in the heap and both have separate locations.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String user_input = sc.nextLine();
System.out.println(user_input);
}
}
Notice that we used sc.nextLine() to take a string input because nextLine() takes the input until a new line is
encountered i.e. a \n is encountered.
The output of the above code is “I love ‘Java’ very much. Try the above code by replacing the single quotations
with double quotes.
The output of the above code is 11 since there are 11 characters in str5 including the spaces.
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
P r o g r a m m i n g i s f u n
It can be seen that the first element can be found in index=0 and the last element can be found in index=
length-1.
In order to access a particular element from the string, we can use the method charAt(). This method takes an
index number as an argument and returns the particular element in that position. Let’s extract the characters ‘P’
at index=0, ‘n’ at index=17 and ‘g’ at index 10.
System.out.println(last_character);
System.out.println(random);
The output of the above code is: I love Java programming very much. The output is a new string which is stored
in s3. Let’s see another example:
String s1 = “CSE”;
int num = 110;
String output = s1 + num
System.out.println(output);
Here, notice that we are concatenating an integer to a string using the + operator. In this case the output is a
string CSE110. This means that, wherever an operand of the + operator will be a string, the Java compiler will
automatically convert the other operand to a string representation and then contact it to create a new string.
Here, the output is: Fall2023. Note how operator precedence causes the concatenation of the string “Fall” to the
integer 20 at first which creates the string “Fall20” and then this string is concatenated to the integer 23 which
creates the output string “Fall2023”.
Had we written: String output = y1 + 23 + semester, then the operator precedence would cause the integer in
y1 and the integer 23 to be added using the + operator to produce an integer 43 and then this integer would be
concatenated to the string “Fall” to produce a string “43Fall”. Try this out yourself.
Page | 50
Here, the output of the first print statement is false since the elements of s1 and s2 are identical and the output of
the second print statement is true since the elements of s1 and s3 are identical.
Note: equals() method is case sensitive and so the strings “Let us code” and “Let us Code” will yield false.
However, another method equalsIgnoreCase() will ignore the case differences and will yield true.
● == operator - The == operator in Java checks whether two string objects have the same
reference/location or not. Let us see an example:
Here, the output of the first print statement is true since the elements of s1 and s2 are identical and the output of
the second print statement is false since s1 and s2 refer to different string objects stored in different memory
locations (Refer to the heap memory where string objects are stored when created using the new keyword).
● compareTo() - This method compares two strings lexicographically. It returns 0 if both strings are
equal with identical characters in the same positions. It returns a positive integer if the first string is
lexicographically greater than the second string and it returns a negative integer if the first string is
lexicographically smaller than the second string. Let’s see a few examples.
String s1 = “Java”;
String s2 = “Java”;
String s3 = “Jada”;
String s4 = “Lava”;
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
The first output is 0 since both s1 and s2 are identical. The second output is 18 since “v” is 18 more than “d”
lexicographically. The third output is -2 since “J” is 2 less than “L” lexicographically.
● indexOf() - This method takes a character/substring as an argument and finds the position of the first
occurrence of the character/substring in the string.
● lastIndexOf() - This method takes a character/substring as an argument and finds the position of the
last occurrence of the character/substring in the string.
The output of the first print statement is 2 since the first occurance of the character ‘n’ is in index=2 and the
output of the second print statement is 11 since the last occurance of the character ‘n’ is in index=11. The 3rd
output is 9 since the substring “ring” is found from index=9.
String s1 = “marathon”;
String new_s1 = s1.replace(“a”, “e”);
String new_s2 = s1.replace(“mara”, “py”);
System.out.println(new_s1);
System.out.println(new_s2);
The output of the first print statement is merethon. We can see that all the occurrences of “a” have been replaced
by “e”. The output of the second print statement is python. We can see that the substring “mara” has been
replaced by the substring “py”.
● split() - This method converts a string to a string array on the basis of a given parameter as delimiter. Let’s
see an example :
Page | 52
String s2 = "Java,is,,fun";
String [] s2_array = s2.split(“,”);
● toLowerCase() - This method converts all uppercase letters to lowercase in a string and returns a new
modified string.
The output of the above code is java programming is fun where all characters are presented in lowercase.
● toUpperCase() - This method converts all lowercase letters to uppercase in a string and returns a new
modified string.
String s1 = String.valueOf(digit);
System.out.println(s1);
String s2 = String.valueOf(decimal);
System.out.println(s2);
String s3 = String.valueOf(letter);
System.out.println(s3);
The variable s1 will contain a string representation of 85 (“85”), the variable s2 will contain a string
representation of 54.643 (“54.643”) and the variable s3 will contain a string representation of ‘A’ (“A”).
Sometimes we need to work with ASCII values of strings or characters. In that case we need to convert an
element in a string into its corresponding Unicode value. We can use the codePointAt() method which takes an
index of a string as a parameter and returns the Unicode value of the element in the given index.
Page | 53
We can also use these Unicode values to convert uppercase letters to lowercase and vice versa. Visit the link
above and check the Unicode value of uppercase “A”. You’ll see that it's 65. Now, check the Unicode value of
lowercase “a”. You’ll see that it’s 97. The difference between the two values is 32. That means if we add 32 to
the Unicode value of “A” we will get the Unicode value of “a” and if we subtract 32 from the Unicode value of
“a” we will get the unique value of “A”. If we cast the Unicode value using (char) then we will get the
corresponding character. This will follow for all alphabets from “A” to “Z” and from “a” to “z”. Let’s see an
example:
The output of the first three prints are true since “Java”, “love Java “ and “p” all these substrings exist in s1 but
the output of the last print is false since “java” with lowercase “j” does not exist in s1.
Page | 54
9.18 WORKSHEET
A. Write a Java program that takes a string as input and reverses it.
Sample input 1:
Programming
Sample output 1:
gnimmargorP
B. Write a Java program that takes a string as input and counts the number of vowels (a, e, i, o, u) present
in the string.
Sample input 1:
Programming
Sample output 1:
3
C. Write a Java program that takes a string as input and checks if it is a palindrome. A palindrome is a
word, phrase, number, or other sequence of characters that reads the same backward as forward. The
program should output "Palindrome" if the string is a palindrome and "Not a Palindrome" otherwise.
Sample input 1:
ABCDCBA
Sample output 1:
Palindrome
Sample input 2:
Nepal
Sample output 2:
Not a Palindrome
D. Write a program which takes a string as input and returns the number of characters in the string.
Sample input 1:
Programming
Sample output 1:
11
F. Your task is to input a word into a String. Then print code for each character in the String using the 2nd
method discussed above.
Sample input 1:
Pro
Sample output 1:
P : 80
r : 114
o : 111
Page | 55
G. Print the statistics of occurrence of each character on a line by itself. Assume that user will only give
CAPITAL letters. So, you will have to count values of CAPITAL letters only.
Sample input 1:
BALL
Sample output 1:
A which is 65 was found 1 time(s)
B which is 66 was found 1 time(s)
L which is 76 was found 2 time(s)
10.1 PROPERTIES
Information storage is an important task for programmers to perform in today's technologically advanced world.
For later use, each and every item of information must be stored in the memory location. We already know what
a variable is and how it stores data. The same way, data is stored using an array. However, Arrays are used to
store multiple values in a single variable, instead of declaring separate variables for each value. It is a data
storage where we store a fixed set of similar elements. For example, if we want to store the names of 40 students
then we can create an array of the string type that can store 40 names.
Any data type, including primitive types like integer, double, and Boolean as well as object types like String,
can be stored in a Java array. Arrays can also be multi-dimensional, meaning that they can have multiple rows
and columns. An array's length is assigned when it initially gets constructed. After creation, its length is fixed
and cannot be changed. Arrays in Java are index-based, the first element of the array is stored at the 0th index,
the 2nd element is stored on the 1st index and so on.
To create an array, an array variable of the desired data type must be declared first. The following is the general
form for declaring an array:
Here, the data type determines what type of elements will be stored in the array. For example:
int quiz_marks [ ] ;
In the above declaration quiz_marks is the name of the array. And this array will store only the integer types of
elements. Although this declaration establishes the fact that quiz_marks is an array variable, no array actually
exists.
To link quiz_marks with an actual, physical array of integers, we must allocate one actual array using the “new”
keyword and assign it to quiz_marks. “new “ is a special operator that allocates memory for arrays.
Now, we have finally created the actual array. Here, 5 defines the length of the array. That means this array can
store five elements.
Page | 57
This was the descriptive process for declaration and creation of an array. There is another short way for
declaring and creating an array. Instead of using two separate lines of codes we can simply use one line for
declaration and creation of an array.
Here, we have created an integer array, which can store 5 elements. Initially when we create an integer array, all
the elements of the array remain 0.
Stack is a temporary memory. after using new, now the array will be inserted into an actual data storage memory
called heap. Also, the name of the array only refers to the address where the actual array is stored.
Initial elements of the array change according to the data type. According to different data type array initial
elements:
Object null
Array declaration and creation examples with different data types:
To sum up, there are two steps involved in constructing an array. First, you must create a variable with the
specified data type. Second, you must use the “new” keyword to allocate the memory required to store the array
and then assign that memory to the array variable. After that default elements will be assigned automatically to
the array according to the data type.
Now, we need to store our actual elements. There are multiple ways to assign values into an empty array. The
general code for inserting any element into any specific index of an array is:
Here, at first, we declared the array with length 4. We declared the data type integer that is why the initial array
is loaded with all 0’s. After that we initiated the for loop, where we stated i=0. Because the first index of an
array is 0. The loop will stop when we reach the last index of the array. For that reason we have to know the
length of the array. In Java, the array length is the number of elements that an array can hold. There is no
predefined method to obtain the length of an array. We can find the array length in Java by using the array
attribute length. We use this attribute with the array name. In the above example if we write:
System.out.println(arr.length);
Our program will give us 4 as an output. So, the last index of an array is array.length-1.
In the above diagram, the value of “i” becomes: 0,1,2,3.
So, the first index is 0 and the last index is 3 which is the length - 1. Inside the loop we are taking inputs from
the user and inserting that input into the array index.
arr[i] = sc.nextInt();
In this line, arr is the name of the array, i is the index number. sc.nextInt() is taking inputs from the user. Here,
nextInt only takes the integer inputs
Page | 60
In this way we can take inputs from the user and create an array. There are various ways to initialize the array
values. Some of them are given below:
Created array:
At the time of We can also insert the elements at the time of int a[] = { 1, 2, 3, 4, 5 };
declaration array creation. here at first we declared the data
type which is int, then a is the name of the array.
And then on the right side of the equal sign inside Created array:
curly braces we write the elements we want to
insert.
Using loop Using for or while loop we can also insert values int a [] = new int [5];
into an array. Here, the loop starts from 0, and it for (int i = 0; i < a.length; i++) {
will continue until it doesn't reach the last index a[i] = i + 1;
of the array. The length of the array is 5. the }
value of i will be 0,1,2,3,4. Created array:
Taking User We can insert elements into an array by taking import java.util.Scanner;
Input user inputs. Scanner sc= new
a[i] = sc.nextInt(); Scanner(System.in);
In this line, a is the name of the array, i is the int a[] = new int [5];
index number. sc.nextInt() is taking inputs from for (int i = 0; i < 5 ; i++) {
the user. Here, nextInt only takes the integer a[i] = sc.nextInt();
inputs. }
Random value Java has a special class called Random. First we import java.util.Random;
generator need to import that class. After that we create an Random rd = new Random();
object of that class just like a scanner. int a[] = new int [5];
rd.nextInt(10). Here, rd is the object name, for (int i = 0; i < 5 ; i++) {
nextInt will generate only integer values and 10 a[i] = rd.nextInt(10);
defines the range. Any random numbers between }
0 to 10 will be inserted into the array.
In this way, we can declare, create and initialize an array in java. For better efficiency practice different
approaches with different data types for array initialization.
comes the iteration part where we need to access the elements from the array. Iterating over an array means
accessing each element of the array one by one.
System.out.println(name[0]);
Index 0 contains the highest scorer. So inside the print statement if we write the array name with index 0. then
the output will show the highest scorer's name. Here, we just printed the name. We can also store elements as
separate variables from the array.
Here, we created a new variable called top_scorer and copied an element from the array inside the new variable.
The element will remain the same in the array, we just copied it and stored that copy inside a new variable.
Sometimes, we need to iterate the whole array instead of a specific index. There are multiple ways to iterate
over a whole array. Mostly we use a loop for that process. The first index of an array is 0 so we initialize for
loop variable i = 0. Then i will continue incrementing by 1 value until it doesn't reach the last index which is
array length - 1. Inside the loop we write the print statement for printing the array.
We can iterate an array using not only for loop but also while loop and do while loops. As per our convenience
and requirements we can use any of the iteration processes.
For loop starts from 0, runs until it reaches the last index which is int a [ ] = {5,6,9,8,6};
Loop array length-1. i increments by 1. iterate over the whole array.
Page | 62
inside the loop, print statement prints the elements. for (int i = 0; i < a.length;
i++) {
System.out.println(a[i]);
}
While loop starts from 0, runs until it reaches the last index which is int a [ ] = {5,6,9,8,6};
Loop array length-1. int i = 0;
inside the loop, print statement prints the elements and i while (i < a.length) {
increments by 1. Iterate over the whole array. System.out.println(a[i]);
i++;
}
Do The initial variable i starts from 0. inside the do block we write int a [] = {5,6,9,8,6};
While the statements to be executed which is printing elements of the int i = 0;
Loop array. Then we increment i by 1. Then using while we set the do {
value to stop the loop. System.out.println(a[i]);
i++;
} while (i < a.length);
Traverse Traversing through all the elements in for (int i = 0; i < arr.length; i++) { 55
the array one by one. Can be used to System.out.println(arr[i]); 66
perform tasks that require visiting all } 7
the elements such as printing all the -2
elements. 9
Insertion Adds an element at the given index. int x [] = new int [5]; 0
x [1] = 10; 10
System.out.println(x[1]); 0
for (int i = 0; i < x.length; i++) { 0
System.out.println(x[i]); 0
}
Copying an Create another array with the same int arr2 [] = new int [arr.length]; 55
array length and datatype, and copy all the for (int i = 0; i < arr.length; i++){ 0
elements to the new array one by one. arr2[i]= arr[i]; 7
} -2
The memory addresses of both arrays for (int i = 0; i < arr2.length; i++) { 9
are different and changing one array System.out.println(arr2[i]);
does not affect the another. }
For example:
To access or modify values of a multidimensional array, we can use array indexing, just like previous examples,
but instead of just one index, we use multiple indexes to point to the location of a certain value. For example
numbers[1][2] represents 7, as [1] means the index of the outer array, and [2] is the index of the inner array.
10.6 WORKSHEET
B. Given an array of integers, write a program to find the maximum element in the array.
Given Array 1
{5, 2, 8, 3, 9}
Sample Output 2
9
C. Write a function that takes an array of integers as input and returns the sum of all the elements.
Given Array 1
{5, 2, 8, 3, 9}
Sample Output 1
27
D. Write a program that takes an array and a target element as input and prints the index of the target
element in the array. If not found in the array, print “Not Found”.
Given Array 1
{5, 2, 8, 3, 9}
8
Sample Output 1
Target element is at index: 2
Given Array 2
{5, 2, 8, 3, 9}
18
Sample Output 2
Not Found
E. Given an array of integers, write a program that prints the occurrence of each element in the array.
Given Array 1
{5, 3, 5}
Sample Output 1
5 is repeated 2 time(s)
3 is repeated 1 time(s)
Page | 65
F. Given two arrays, write a program that prints an array containing the common elements in both arrays.
Given Arrays
{5, 2, 8, 3, 9}
{6, 3, 5, 11, 10}
Sample Output 1
{3, 5}
G. Given an array with duplicate elements, write a program that removes the duplicates and prints a new
array with unique elements only.
Given Array 1
{5, 2, 8, 3, 2}
Sample Output 1
{5, 2, 8, 3}
H. Write a program that takes an array as input and returns a new array with the elements reversed.
Given Array 1
{1, 2, 3, 4, 5}
Sample Output 1
{5, 4, 3, 2, 1}
Page | 66
● Ascending (or increasing) order: arranged from the smallest to the largest element.
● Descending (or decreasing/non-increasing) order: arranged from the largest to the smallest element.
Java has a built-in Arrays.sort() method for sorting arrays. Let’s see that first.
Code Output
import java.util.Arrays; // importing Arrays class -5
public class BuiltInSortAscending{ 7
10
public static void main(String[] args){ 27
int[] arr = { 10, -5, 7, 45, 27 }; 45
The above code uses the Java built-in method to sort an array in ascending order. Now, if you just add another
step and reverse the sorted array, you will get the sorted array in descending order.
But this is pretty straight forward. As a Computer Science student, you need to know the underlying concepts
behind array sorting. You need to understand and visualize different sorting techniques. There are a lot of sorting
algorithms used in several domains. In this course, we will learn three such common sorting algorithms.
At each iteration, the array is partitioned into two sections. The left section is sorted and the right section is
being processed. Each iteration, we move the partition one step to the right, until the entire array elements have
been processed.
element 40 2 27 -7 14
index 0 1 2 3 4
Now, let’s visualize how Selection Sort works. We will sort the array in ascending order.
Iteration 1: At first, we will consider the element in index 0 as the minimum value which is 40 in this example.
Then, we will search from index 1 to index (length-1) to find an element less than 40.
Page | 67
element 40 2 27 -7 14
index 0 1 2 3 4
Here, we have found the lowest possible value less than 40 in index 3 which is -7. We will swap the values of
these two indexes.
element -7 2 27 40 14
index 0 1 2 3 4
Iteration 2: Here, we will consider the element in index 1 as the minimum value which is 2. Then, we will
search from index 2 to index (length-1) to find an element less than 2.
element -7 2 27 40 14
index 0 1 2 3 4
But there are no values which are less than 2 from index 2 to 4; which means 2 is already in the correct sorted
position. So, no swapping will be needed here.
element -7 2 27 40 14
index 0 1 2 3 4
Iteration 3: You guessed it right. Now, we will look for the value smaller than 27 from index 3 to 4.
element -7 2 27 40 14
index 0 1 2 3 4
The value less than 27 is 14 which is in index 4. So, we will swap the values of index 2 and 4.
element -7 2 14 40 27
index 0 1 2 3 4
Iteration 4: Similarly, the value of index 3 and 4 will be swapped since 27 is less than 40.
element -7 2 14 27 40
index 0 1 2 3 4
Iteration 5: This step is kind of useless and unnecessary. Because all the remaining elements are sorted from
left to right. So, the element in the last index of the array will definitely be in the correct sorted position. So, the
position of 40 will be unchanged.
element -7 2 14 27 40
index 0 1 2 3 4
You can see our array is now successfully sorted in the ascending order using Selection Sort. For descending
order sort, just find the maximum value instead of the minimum value on each iteration.
Page | 68
Here, for each iteration, we only consider the right section of the partition for finding the minimum value as the
left side is already sorted. Lastly, in the last step, only one element remains which is the minimum. So sorting is
unnecessary in that case. So, for Selection Sort, (length-1) times iteration is needed.
Code Output
public class SelectionSortAscending{ -7
2
public static void main(String[] args){ 14
int[] arr = { 40, 2, 27, -7, 14 }; 27
40
// implementing Selection Sort on the created array
element 40 2 27 -7 14
index 0 1 2 3 4
Let’s visualize how this algorithm works. Here, we will sort the array in ascending order too.
Iteration 1: We will compare between two adjacent index elements here. If the first element is greater than the
second element, then we will swap between two index values. For example, we will compare the index 0 value
with index 1 value, which means we will compare between 40 and 2. Since, 2 is less than 40, so these two
values will be swapped. Now, 40 is in index 1. We will compare 40 with the index 2 element which is 27. Again,
these two values will be swapped and 40 will move to index 3. Similarly, we need to do the same process for the
entire array in this iteration.
Page | 69
element 40 2 27 -7 14 40 > 2
swap places
index 0 1 2 3 4
element 2 40 27 -7 14 40 > 27
swap places
index 0 1 2 3 4
element 2 27 40 -7 14 40 > -7
swap places
index 0 1 2 3 4
element 2 27 -7 40 14 40 > 14
swap places
index 0 1 2 3 4
element 2 27 -7 14 40
index 0 1 2 3 4
You can see after iteration 1, the largest element 40 moved to the last index position. So, 40 is now in the sorted
position and we do not need to check for 40 again in the upcoming iterations.
Iteration 2: We will follow the similar procedure for the remaining unsorted array elements.
element 2 27 -7 14 40 2 < 27
no swap
index 0 1 2 3 4
element 2 27 -7 14 40 27 > -7
swap places
index 0 1 2 3 4
element 2 -7 27 14 40 27 > 14
swap places
index 0 1 2 3 4
element 2 -7 14 27 40
index 0 1 2 3 4
Iteration 3: You get the idea now. We will now perform 2 comparisons.
element 2 -7 14 27 40 2 > -7
swap places
index 0 1 2 3 4
Page | 70
element -7 2 14 27 40 2 < 14
no swap
index 0 1 2 3 4
element -7 2 14 27 40
index 0 1 2 3 4
We can see the array is already sorted. But the algorithm will run for another iteration.
Iteration 4: The algorithm will compare between -7 and 2. But there will be no swap because -7 is less than 2.
element -7 2 14 27 40 2 < 14
no swap
index 0 1 2 3 4
So, -7 and 2 are in the correct sorted position. So, after the 4th iteration, we get the sorted array.
element -7 2 14 27 40
index 0 1 2 3 4
Similar to Selection Sort, for Bubble Sort, (length-1) times iteration is needed. Another thing to notice is that
here in each iteration, the number of comparisons is reduced by one. For example, in our example, in the 1st
iteration, there were 4 comparisons. In the 2nd iteration, there were 3 comparisons and so on.
For the descending order sort, we just need to compare the two adjacent index values and if the later element is
greater than its immediate previous element, then the two array elements will be swapped.
Code Output
public class BubbleSortAscending{ -7
2
public static void main(String[] args){ 14
int[] arr = { 40, 2, 27, -7, 14 }; 27
40
// implementing Bubble Sort on the created array
Let’s visualize the working procedures of this technique using the same array used before.
element 40 2 27 -7 14
index 0 1 2 3 4
Initially we assume that the first index element is already sorted. So, as mentioned earlier, the array can be split
into two parts like below:
sorted unsorted
element 40 2 27 -7 14
index 0 1 2 3 4
Iteration 1: We consider the value of index 1 as key. So, key = 2 in this case. Here, key means the value of the
current array element which will be inserted in the correct position in the sorted section. Here, the value of index
0 is 40, which is greater than the key value 2. So, 40 will be moved to index 1 and the value of key will be
inserted to index 0.
key = 2
After inserting the key in index 0, the array now looks like this.
sorted unsorted
element 2 40 27 -7 14
index 0 1 2 3 4
Iteration 2: The value of key will be the value of index 2 now. So, key = 27. We need to follow the same
procedure as before.
key = 27
After inserting the key in index 1, the array looks like below:
sorted unsorted
element 2 27 40 -7 14
index 0 1 2 3 4
Iteration 3: The value of the key will be -7 now. So, key = -7.
key = -7
key = -7
Page | 73
key = -7
After inserting the key, the array will look like this:
sorted unsorted
element -7 2 27 40 14
index 0 1 2 3 4
Iteration 4: We now have to insert 14 in the correct position in this step. Here, key = 14.
key = 14
key = 14
After inserting the key in index 2, we now have the full array sorted.
sorted
element -7 2 14 27 40
index 0 1 2 3 4
That’s how the Insertion sort algorithm works. Here, we initially assume the index 0 value is already in the
sorted position. So, we look from index 1 to the last index of the array. So, (length-1) times iteration is needed
here too. We consider each index value as the key and insert that key into the appropriate position in the sorted
part of the array.
For the descending order sort, we will shift the current index value if it is less than the key and insert the key in
the appropriate position in each step afterwards.
Code Output
public class InsertionSortAscending{ -7
2
public static void main(String[] args){ 14
int[] arr = { 40, 2, 27, -7, 14 }; 27
40
// implementing Insertion Sort on the created array
11.4 WORKSHEET
A. Using Java built-in Arrays.sort() method, sort an array in descending order. You cannot use any other
built-in method to complete this task. [Hint: Modify the ascending order sort code and add another step
using a loop.]
B. Implement the descending order sort for the following sorting techniques:
1. Selection Sort,
2. Bubble Sort,
3. Insertion Sort.
A. We have learnt that Bubble sort needs (length - 1) times iteration. But sometimes even before
completing all the iterations, the array might get sorted and the code runs for some extra redundant
iterations. In that case, modify your ascending/descending order Bubble sort code so that it can handle
this issue and stop immediately without running for these redundant iterations. [Hint: Utilize the
concept of Flag variable.]
B. Let’s say you have an array of n elements. You only need the first k sorted elements (where k < n) of
the array. Which sorting algorithm will be efficient in this case? Share your opinion briefly.
C. Suppose, you have an array whose elements are nearly sorted (for example, 90% of the elements are
already in the correct sorting position). To sort the remaining values faster, which sorting technique will
you use? Explain shortly.
D. We have seen in both Selection Sort and Bubble Sort; we need to perform swapping. If we want to
minimize the overall swap operations, which sorting technique would be better? Explain briefly.
E. Write a Java program that takes a number T as user input where T denotes the total number of students.
Then the user needs to take the name and corresponding marks of T students as input. Display the
names of the students based on their marks from highest to lowest.
● Access Modifier (public/private/protected/default): Used to set access permission of the method. For
the time being, we shall only focus on the public methods. A public method can be accessed from
anywhere inside or outside the class.
● static Keyword: the keyword static indicates that a method is static. A static method belongs to the
class and not to the instance of a class. As it belongs to the class, it can be called without creating any
object. We use the keyword “static” to define a method as static. We can call a static method from
inside any other static method.
● Return Type: Indicates the data type of the returned entity. If the method contains a return statement,
the return type must match the data type of the returned entity. If a method does not have a return
statement, or if we do not explicitly return any data or variable from the method it returns Null and the
return type is written “void”.
● Method Name: Every method has a name that should signify its purpose.
● Parameter Type: In order to achieve its purpose, a method may take none, one or more parameters.
Datatype of every parameter must be specified.
● Parameter Name: Every parameter should be given a variable name, and the scope of these variables
is within the method. Which means, these variables are not accessible outside that method.
● Method Body: Each method is designed for a unique purpose, and that purpose is fulfilled inside the
method body. The method body varies for every method. Any variable declared inside the scope of a
method is not accessible from outside including the parameter variables.
● Return Statement(s): A method may require one or more return statements depending on its method
call. Return statements are the final lines of a method. No other line in the method is read after reaching
one of the return statements and then we go back to the point where that method was called from.
Note that all of the above are not mandatory while writing a method. Depending on the situation, you may or
may not include some of these fields. For example, a method may or may not have return statements,
parameters, etc.
Now let us look at some of the examples of different return types in action:
Here in case 1: subtract(2,3), the values 2 and 3 will be received as int a = 2 and int b = 3. Therefore, the
difference is (2-3) = -1.
In these two cases if your method does not explicitly return anything, a Null type is returned by default and the
results may be catastrophic.
In the following example, the method did not require any return statement, therefore the return type was void
and no return statements were written.
Page | 79
In the following example, the method call is initialized inside a variable. Therefore, return statements were
required.
The example above also shows that your method can have more than one return statement inside the if-elif-else
blocks. In this case, only one of the possibilities can happen and only one return statement will be executed at a
time.
The red marked lines are called method overloading and in CSE111, we shall explore this in detail.
12.9. WORKSHEET
A. Specify when the following are needed and not needed:
a. Parameter Type
b. return Type
c. Return Statements
B. Write a method named evenPositive to find even and positive numbers from an array of numbers.
C. Now, can you print a triangular palindrome like the following using a method called show_triangle()?
Note that you have to take the help of show_spaces() and show_palindrome() methods.
1
121
12321
1234321
123454321
Loop Recursion
Not much difference in terms of use. Both can be used to solve repetitive problems.
Constructs like for, while used. Method calls itself and consists of a base case and a
recursive case.
Loop condition given to stop loop execution at a Stop executing when the base case is reached.
point.
May not be easy to write about some complex May be easier to write complex problems and have
problems. more clarity.
Is more memory efficient. Possibility of using more memory and resources due
to stack overflow error.
Can you tell what could be the issue if there was no base case? Look at the following example and try to
understand.
Page | 83
Here in the first method call of recursive_method, 4 was passed down as the parameter. After that a few
successive recursive calls were made by the recursive_method and finally when the base case was satisfied
(when num==0), the recursive_method ended and the final result was returned to the main method where it was
printed.
In the example shown in 13.4 the stack would look like this:
Page | 84
13.7. WORKSHEET
Output:
-3
B. Write a recursive method for finding the sum of the first n numbers in a Fibonacci series.
Output:
6
C. Write a recursive method that returns the sum of all the elements of an array.
Output:
5
Page | 86
1. import java.io.FileReader;
2. import java.io.BufferedReader;
3. import java.io.IOException;
4.
5. class ReadingFile{
6. public static void main(String[] args) throws IOException{
7. String location = "C:\\users\\bracu\\Hello.txt";
8. FileReader fr = new FileReader(location);
9. BufferedReader br = new BufferedReader(fr);
10. String first_line = br.readLine();
11. String second_line = br.readLine();
12. String third_line = br.readLine();
13. System.out.println(first_line);
14. System.out.println(second_line);
15. System.out.println(third_line);
16. br.close();
17. fr.close();
18. }
19. }
Output:
This is the first sentence.
This is the second sentence.
This is the third sentence.
Page | 87
What if the number of lines in the file is unknown to us? We must resort to using loops in this situation. Let us
suppose we have a file called names.txt that contains an unknown amount of separate lines. Our job is to read
these lines and print them.
1. import java.io.FileReader;
2. import java.io.BufferedReader;
3. import java.io.IOException;
4. class ReadingFile_Loop{
5. public static void main(String[] args) throws IOException{
6. String location = "C:\\users\\bracu\\names.txt";
7. FileReader fr = new FileReader(location);
8. BufferedReader br = new BufferedReader(fr);
9. String line = br.readLine();
10. int i = 1;
11. while(line!=null){
12. System.out.println("Name#"+i+": "+line);
13. i++;
14. line = br.readLine();
15. }
16. br.close();
17. fr.close();
18. }
19. }
Output:
Name#1: Hayayo Miyazaki
Name#2: Daenerys Targaryen
Name#3: Chester Bennington
Name#4: Hideo Kojima
Name#5: Amy Lee
Name#6: Rustin Cohle
Name#7: Walter White
Name#8: Luke Skywalker
Name#9: Alan Moore
Name#10: Terry Davis
1. import java.io.FileWriter;
2. import java.io.BufferedWriter;
3. import java.io.IOException;
4. class WritingFile{
5. public static void main(String[] args) throws IOException{
6. String location = "C:\\users\\bracu\\test.txt";
Page | 88
1. import java.io.FileReader;
2. import java.io.BufferedReader;
3. import java.io.IOException;
4.
5. class WritingFile_Loop{
6. public static void main(String[] args) throws IOException{
7. String[] words = {"Hi","Hey","Hello","Yes","No"};
8. String location = "C:\\users\\bracu\\names.txt";
9. FileWriter fw = new FileWriter(location);
10. BufferedWriter bw = new BufferedWriter(fw);
11. for(int i=0; i<words.length; i++) {
12. bw.writeline( "Name"+(i+1)+words[i]+"\n" );
13. }
14. br.close();
15. fr.close();
16. }
17. }
18. /*after execution a words.txt file
19. will be created with the words written.*/
14.5. WORKSHEET
A. Suppose you have a file called names.txt that contains an unknown amount of separate lines. Your job
is to print the first 5 lines of that file.
B. Create a file called names.txt and write the numbers from 51 to 100 in separate lines using a loop.