Programming With Java ABhuiyan MAmiruzzaman 2025031201
Programming With Java ABhuiyan MAmiruzzaman 2025031201
With Java
Ashik Ahmed Bhuiyan, Ph.D. &
Md Amiruzzaman, Ph.D.
1
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License (CC
BY-NC 4.0) as a part of PA-ADOPT, except where otherwise noted
The contents of this eTextbook were developed under a grant from the Fund for the Improvement of
Postsecondary Education, (FIPSE), U.S. Department of Education. However, those contents do not
necessarily represent the policy of the Department of Education, and you should not assume endorsement
by the Federal Government.
The Verdana (© 2006 Microsoft Corporation) and Courier New (© 2006 The Monotype Corporation) fonts
have been used throughout this book, which is permitted by their licenses:
License: You may use this font as permitted by the EULA for the product in which this font is
included to display and print content. You may only (i) embed this font in content as permitted by
the embedding restrictions included in this font; and (ii) temporarily download this font to a printer
or other output device to help print content.
Embedding: Editable embedding. This font may be embedded in documents and temporarily
loaded on the remote system. Documents containing this font may be editable (Apple Inc. (2021).
Font Book (Version 10.0 (404)) [App].).
2
About PA-ADOPT
The Pennsylvania Alliance for Design of Open Textbooks (PA-ADOPT) is made up
of four participating institutions from Pennsylvania State System of Higher
Education (PASSHE) that are all regional and primarily undergraduate
institutions, situated in Southeastern Pennsylvania. The PA-ADOPT project
addresses gaps in the open eTextbook marketplace, improve student learning,
and mitigate rising student costs. PA-ADOPT was made possible by the US
Department of Education Open Textbook Pilot Program.
About OER
Open Educational Resources (OER) are instructional, learning and research
materials, digital or non, that open-source and in the public domain or that are
licensed so that users have free and perpetual permission to engage in the
following activities:
• Retain: the right to make, own, and control copies of the content
• Revise: the right to adapt, adjust, modify, or alter the content itself
• Remix: the right to combine the original or revised content with other open
content to create something new
3
About the Authors
Ashik Ahmed Bhuiyan
Ashik Ahmed Bhuiyan, Ph.D. is an assistant professor in
the Department of Computer Science at West Chester
University of Pennsylvania (WCUPA). He teaches various
undergraduate and graduate courses, including data
structures, algorithms, introduction to programming,
fundamentals of computer science, and research
seminars.
4
Md Amiruzzaman
Md Amiruzzaman, Ph.D., is an Assistant Professor in the
Department of Computer Science at West Chester
University. Before joining WCU, he worked as a software
developer for almost 10 years for several companies. He
has also held the position of Assistant Professor at Kent
State University. He has completed a Bachelor's Degree
in Computer Science from National University. Along
with that, he has completed four Master's degrees with
major in Computer Engineering in 2008 from Sejong
University, Computer Science in 2011 from Kent State
University (also, partly at Korea University), and
Technology in 2015, also from Kent State University, and Md Amiruzzaman
5
Table of Contents
About PA-ADOPT 3
About OER 3
About the Authors 4
Ashik Ahmed Bhuiyan 4
Md Amiruzzaman 5
Table of Contents 6
1 Introduction 10
1.1 What is a Computer? 10
1.2 What is Computer Programming? 10
1.3 What is Java? History of Java 10
1.4 A Sample Java Program 10
1.5 What is Source Code? 12
1.6 Variables and Constants 12
1.6.1 Keywords/Reserved Words 12
1.6.2 VariableS 12
1.6.3 Identifier 12
1.7 Rules for Variable Declaration 13
1.7.1 How to Declare a Variable 13
1.7.2 Types of Variables in Terms of the Value They Store 14
1.7.3 Type of Variables in Java Based on Where They are Declared 16
1.8 Constants 18
1.9 ASCII-Table 19
1.10 Widening and Narrowing 22
1.10.1 Widening 23
1.10.2 Narrowing 24
1.11 Exercise 25
2 Control Statements and Loops 26
2.1 What is a Control Statement? 26
2.2 If-Else Statement 28
2.2.1 If-Else Statements with Multiple Operations 29
2.2.2 If Without Else 31
2.2.3 Relational and Logical Operators 32
2.2.4 Nested If-Else Statement 37
6
2.2.5 The If-Else If-Else Statement 39
2.3 Switch-Case Statement 42
2.3.1 Program Flow 43
2.3.2 Advantage and Disadvantage of Using Switch-Case (Compared to If-
Else Statement) 46
2.4 Loops 46
2.4.1 Java Loops and Syntax 47
2.4.2 The While Loop 48
2.4.3 The For Loop 50
2.4.4 The Do-While Loop 52
2.4.5 Nested Loops 53
2.5 Exercise 55
3 String 58
3.1 What is String? 58
3.2 How to Declare String 58
3.3 String Input 58
3.4 Helpful String Methods 59
3.4.1 String length() Method 59
3.4.2 String toUpperCase() Method 60
3.4.3 String toLowerCase() Method 61
3.4.4 String charAt() Method 61
3.4.5 String substring() Method 62
3.4.6 String indexOf() Method 63
3.5 Chaining Method Call 63
3.6 String Operations 64
3.6.1 Concat 64
3.6.2 Compare String Variable 65
3.7 Exercise 68
4 Methods in Java 71
4.1 Why Write a Method 71
4.2 Java Methods 73
4.2.1 Defining a Method 74
4.2.2 Calling a Method 75
4.2.4 Different Types of Methods 78
4.2.5 Scope of Variables 82
7
4.2.6 Common Mistakes 84
4.3 Exercise 86
5 Arrays 90
5.1 Introduction to Arrays 90
5.2 Array Indexing and Array Length 92
5.2.1 Initialize and Access the Array Elements 92
5.2.2 Input and Output the Array Content 94
5.3 Array Manipulation 95
5.3.1 More Examples of Array Operations 95
5.3.2 Copying an Array 99
5.4 Array Algorithms 101
5.4.1 Sorting an Integer Array 102
5.4.2 Removing Duplicate Items from an Array 103
5.5 Multidimensional Arrays 105
5.5.1 Declaring, Initializing, and Accessing Elements in a 2D Array 105
5.5.2 Matrix Multiplication Using a 2D Array 108
5.6 Array Pitfalls and Best Practices 109
5.6.1 Array Index Out of Bounds 110
5.6.2 Uninitialized Array Elements 110
5.6.3 Incorrect Array Size 111
5.6.4 Mixing Array Types 112
5.6.5 Caution During Array Traversal 113
5.6.6 Pass Arrays as Parameters to Methods 114
5.7 Exercise 115
6 Introduction to Classes and Objects 118
6.1 Introduction to Class 118
6.1.1 General Form of a Class 118
6.2 Objects 120
6.3 Class Members and Scope 122
6.3.1 Member Variables (Properties) 122
6.3.2 Member Functions (Methods) 123
6.3.3 Access Modifiers 124
6.3.4 Scope of Class Members 126
6.4 Constructors 128
8
6.4.1 Introduction to Constructors 128
6.4.2 Default and Parameterized Constructors 129
6.4.3 Constructor Overloading 133
6.5 Passing Objects as Arguments 135
6.5.1 Passing Objects by Value vs. Reference 135
6.5.2 Examples and Use Cases 135
6.6 Conclusion 137
6.7 Exercises 137
7 File Handling 141
7.1 Introduction to File Handling 141
7.1.1 Significance of File Handling 142
7.1.2 Operations on Files 142
7.2 File Classes in Java 142
7.3 File Navigation and Manipulation 144
7.4 Reading and Writing Text Files 147
7.4.1 FileReader 147
7.4.2 BufferedReader 148
7.4.3 FileWriter 149
7.4.4 BufferedWriter 150
7.5 Exception Handling 151
7.6 Best Practices and Error Handling 152
7.7 Practical Examples and Exercises 153
7.7.1 Reading and Writing Data Line by Line, Character by Character, or in
Bulk. 153
7.8 Exercise 155
References 157
Chapters 1-5 157
Chapter 6 157
Chapter 7 158
9
1 Introduction
1.1 What Is a Computer?
A computer is an electronic and programmable device that allows users to store,
retrieve, and process information and data (see Figure 1.1). Computers can be
programmed to perform mathematical calculations or logical computations using
different types of computer programming languages such as Java, C, C++, C#,
and Python.
Java was first introduced in 1995 by Sun Microsystems. Since its introduction,
Java has evolved. Today, many computer applications are developed using Java
programming language.
10
“Hello Class!!” displayed on the screen. The “SampleClass” ends with the closing
curly brace (i.e., “}”) at line 6.
Example 1
Line Code
1 Public class SampleClass {
2 public static void main(String args[]) {
3 // print "Hello Class!!" on the screen when this program runs
4 System.out.println("Hello Class!!”);
5 }
6 }
Hello Class!!
The file name for the “SampleClass” will be “SampleClass.java,” which means
that the class name and the source code file are the same. Also, whatever you
place within the double quotes (i.e., “”) in the System.out.println(); will be
displayed in the screen as an output.
Also, note that anything you write using “//” will not be checked by the compiler.
So, programmers use “//” to write programming comments. If you want to add
multi-line comments in your program file or source code, then you can use “/* …
*/”, which is known as a block comment.
/*
example of
multiple line
comments
*/
11
1.5 What Is Source Code?
Programming statements are also known as source code. In other words, in Java,
programming source code means the .java file where programmers write and
save their programming statements. Compilers use source code to generate
object codes or output files. The Example 1 code above is an example of a Java
source code.
public
class
static
void
int
double
1.6.2 VariableS
In Java, there are multiple different ways variables can be declared. Different
ways of declaring variables depend on the data type or what type of data value
the variable will hold. Examples include integer, floating point, string, character,
and the like.
1.6.3 Identifier
The identifier helps to identify something uniquely. For example, within a
program, variable names can be identifiers that enable us to identify uniquely the
variables within the program. A class name is an identifier since it helps to
identify the class uniquely. On the other hand, a variable name is given to a
memory location that holds a value.
12
An identifier is often used to name variables, classes, packages, methods, and
functions. Variables are designed to hold a value within a memory location, and
that value can be changed while a program is running.
2. Variable names must begin with a letter (i.e., either upper-case or lower-
case alphabet), and not with a number or digit.
The example below shows an integer type of variable: “a” is declared, and
subsequently a value is assigned (Example 2). However, commenting on the
initialization indicates that the initialization is not required until the variable is
used. The second example in line 7 shows that both the declaration and
initialization can be done at the same time. Notice that “int” is short for integer
type. Variable declaration must end with a “;” as same as other statements must
do, too.
Since the variable “a” and “b” are the same type, one could declare them as,
13
Note that the above example did not require adding the keyword “int” two times,
since both variables are the same type and one use of “int” is enough. Multiple
declarations of the same type are separated by a comma in between them.
• char - stores single characters, such as ’a’ or ’B’. Unlike String values,
singles quotes are used to represent character values.
Example 2
This example shows how to declare and use ”int” type variables:
Sum of a + b = 11
14
Example 3
The following example shows how to declare and use ”string” type variables:
Hello Class!!
Example 4
The following example shows how to declare and use ”int” type variables:
Sum of a + b = 10.0
Example 5
The following example shows how to declare and use ”char” type variables:
15
public class ExampleCharacter{
public static void main(String []args){
// declare c1 as character variable and assign ’H’
char c1 = ’H’;
// declare c2 as character variable and assign ’i’
char c2 = ’i’;
// declare c3 as character variable and assign ’!’
char c3 = ’!’;
System.out.println("Output: " + (c1) +(c2) + (c3));
}
}
Output: Hi!
Example 6
This example shows how to declare and use ”boolean” type variables:
16
3. static variable—this type of variable is shared among instances of a class.
Example 7
Local value: 20
Static variable: 10
Instance variable: 15
17
So, it is allowed to update the value of variable a1 in a subsequent statement.
This was possible as a1 is a variable. Reassignment would not be possible if a1
was a constant. See more on this in discussion below.
1.8 Constants
Constants are a type of variable whose values do not change within the program.
Sometimes we declare a constant variable in a different class. In that event, the
value of the constant will remain unchanged. If we try to change the value of a
constant, then the compiler will show an error message.
Note that, programmers often use all upper case letters to define a constant
variable (see Example 8). This is an attempt to separate the constant variables
from the rest of the variables.
Example 8
The example below shows how to declare and use a constant variable:
18
1.9 ASCII-Table
The American Standard Code for Information Interchange (ASCII) is the most
widely used character encoding format in computer science. In ASCII encoding,
there are total 256 (i.e., 0 to 255) alphabetic, numeric and special characters
codes. Please see the ASCII character tables below.
19
Dec Hex Oct Character Dec Hex Oct Character
0 0x00 000 NUL 32 0x20 040 SP
1 0x01 001 SOH 33 0x21 041 !
2 0x02 002 STX 34 0x22 042 ”’
3 0x03 003 ETX 35 0x23 043 #
4 0x04 004 EOT 36 0x24 044 $
5 0x05 005 ENQ 37 0x25 045 %
6 0x06 006 ACK 38 0x26 046 &
7 0x07 007 BEL 39 0x27 047 ’
8 0x08 010 BS 40 0x28 050 (
9 0x09 011 TAB 41 0x29 051 )
10 0x0A 012 LF 42 0x2A 052 *
11 0x0B 013 VT 43 0x2B 053 +
12 0x0C 014 FF 44 0x2C 054 ,
13 0x0D 015 CR 45 0x2D 055 -
14 0x0E 016 SO 46 0x2E 056 .
15 0x0F 017 SI 47 0x2F 057 /
16 0x10 020 DLE 48 0x30 060 0
17 0x11 021 DC1 49 0x31 061 1
18 0x12 022 DC2 50 0x32 062 2
19 0x13 023 DC3 51 0x33 063 3
20 0x14 024 DC4 52 0x34 064 4
21 0x15 025 NAK 53 0x35 065 5
22 0x16 026 SYN 54 0x36 066 6
23 0x17 027 ETB 55 0x37 067 7
24 0x18 030 CAN 56 0x38 070 8
25 0x19 031 EM 57 0x39 071 9
26 0x1A 032 SUB 58 0x3A 072 :
27 0x1B 033 ESC 59 0x3B 073 ;
28 0x1C 034 FS 60 0x3C 074 ”¡
29 0x1D 035 GS 61 0x3D 075 =
30 0x1E 036 RS 62 0x3E 076 ”¿
31 0x1F 037 US 63 0x3F 077 ?
20
Dec Hex Oct Character Dec Hex Oct Character
64 0x40 100 @ 96 0x60 140 ‘
65 0x41 101 A 97 0x61 141 a
66 0x42 102 B 98 0x62 142 b
67 0x43 103 C 99 0x63 143 c
68 0x44 104 D 100 0x64 144 d
69 0x45 105 E 101 0x65 145 e
70 0x46 106 F 102 0x66 146 f
71 0x47 107 G 103 0x67 147 g
72 0x48 110 H 104 0x68 150 h
73 0x49 111 I 105 0x69 151 i
74 0x4A 112 J 106 0x6A 152 j
75 0x4B 113 K 107 0x6B 153 k
76 0x4C 114 L 108 0x6C 154 l
77 0x4D 115 M 109 0x6D 155 m
78 0x4E 116 N 110 0x6E 156 n
79 0x4F 117 O 111 0x6F 157 o
80 0x50 120 P 112 0x70 160 p
81 0x51 121 Q 113 0x71 161 q
82 0x52 122 R 114 0x72 162 r
83 0x53 123 S 115 0x73 163 s
84 0x54 124 T 116 0x74 164 t
85 0x55 125 U 117 0x75 165 u
86 0x56 126 V 118 0x76 166 v
87 0x57 127 W 119 0x77 167 w
88 0x58 130 X 120 0x78 170 x
89 0x59 131 Y 121 0x79 171 y
90 0x5A 132 Z 122 0x7A 172 z
91 0x5B 133 [ 123 0x7B 173 {
92 0x5C 134 \ 124 0x7C 174 |
93 0x5D 135 ] 125 0x7D 175 }
94 0x5E 136 ^ 126 0x7E 176 ”
95 0x5F 137 _ 127 0x7F 177 DEL
21
Example 9
This example shows how to declare and use ”char” type variables and ASCII
values:
Output: Hi!
In Java, not all primitive types are the same in size and range. The sizes of the
primitive types are as follows:
Example 10
short value : 10
int value : 10
23
long value : 10
float value : 10.0
double value : 10.0
1.10.2 Narrowing
Like the widening concept, narrowing in Java means downcasting or downgrading
a primitive type using an explicit conversion that is performed in the following
situations:
Example 11
24
The output of Example 11:
1.11 Exercise
1. What is computer programming? What is source code in Java?
int a = 10
a int = 10
int a = 10;
int; a = 10;
3. Write a Java program that has two double type variables and values that are
3.6, and 5.4. Also, display the sum of those variables.
5. What are the different types of variables in Java based on their locations?
8. Write a Java program that multiplies two double type variables’ values and
displays the result.
10. Write a Java program only using character variables to display ”Hello
Class!!”. Instead of using characters, use ASCII values. Hint: each character
variable will hold only one character, e.g., char c1 = 72;
25
2 Control Statements and Loops
2.1 What Is a Control Statement?
A control statement deals with one or more conditions to be evaluated by the
program, one of which must be true. Below, we represent a general form of a
typical control statement structure used in many programming languages.
Here, the condition will be evaluated as true or false. If the condition is true,
block-1 will be executed. If the condition is false, block-2 will be executed.
Example 1
Now, let us describe this concept by using a real-life example. John wakes up at
7.00 AM and has his breakfast. Now, he wants to go out to buy groceries.
However, he does not like rain, and he will first check if it is raining or not before
heading out. If it is raining, he will buy the groceries on a different day and clean
the house instead. Otherwise, he will buy groceries today. Whatever he does,
i.e., clean the house or buy groceries, he will have lunch after that. We can
depict this scenario as shown in Figure 1 above. Here,
Without the knowledge of the control statement, we may think that the codes (or
statements) are executed sequentially, i.e., in the order they appear. However, a
control statement allows us to control the program/code execution flow based on
the result of the conditional statement known during run time. Now, we will
describe two types of control statements supported by Java: if-else statements
and switch-case statements.
27
2.2 if-Else Statement
The if statement is used to route the program execution path in two (or multiple)
directions. Below, we present the primary form of the if statement:
if (Condition)
Statement-1;
else
Statement-2;
Example 2
Now, let us describe the example of John’s work schedule by the if statement
(shown below):
boolean isItRaining;
// Activity outside the condition
Wake up and have breakfast
Imagine a scenario like this. John wakes up and has his breakfast. He then goes
to the window and pulls back the curtain to see if it is raining (assuming he has
not checked the weather forecast yet). Initially, there was a question in his mind:
Is it raining outside? However, after pulling back the curtain, he got the answer.
The answer is either YES (true) or NO (false). Based on this answer, he will
decide on his next task.
Example 3
28
main() {
int var = 47;
// if the var is even
if (var % 2 == 0 ){
var = var/2;
}
This code initializes a variable var to 47 and checks whether it is even or odd
using the modulus operator (%). The modulus operator returns the remainder of
a division, so var % 2 == 0 checks if var is divisible by 2 (even). If it is even, var
is divided by 2. Otherwise, if the var is odd, it is updated to 3 * var + 1. Since 47
is odd, the program computes var = 3 * 47 + 1 = 142 and stops after this
calculation.
Practice Problem
• Write a Java program to find the maximum between two numbers using an
if-else statement. The code should take two numbers from the user as
input and find the maximum between them. Assume both these numbers
are unique. Hint: To take input from the user, you can use the Scanner
class in Java. For example:
29
Example 4
Reconsider Example 1 with some minor edits. Let’s say that John wakes up at
7.00 AM and has his breakfast. If it rains, he will buy groceries on a different day
and clean the house instead. In addition, he will call his mom. If it does not rain,
he will buy groceries today and meet a friend (who lives on the way to the
grocery store). Whatever he does—that is, clean the house and call his mom or
buy groceries and meet his friend—he will have lunch after that. We can depict
this scenario using the code below.
boolean isItRaining;
// Activity outside the condition
Wake up and have Breakfast;
Other than multiple actions, all other things are the same as depicted in Example
1. Notice the use of curly braces that enclosed the set of steps.
Example 5
main() {
int var = 47;
30
// if the var is odd
else {
system.out,println ("This is an odd value");
var = 3*var+1;
}
system.out.prinln("Updated value of var is " + var);
}
Notice that we are doing multiple operations here inside the if-else block. First,
we print a message (whether the number is even or odd). Second, we are
performing a mathematical operation. Finally, we are printing the value of var
irrespective of the conditions. Hence, we place the system.out.prinln(“Updated
value of var is ” + var) statement outside any block.
Example 6
This time, consider a slightly different example. Let’s say that John wakes up at
7.00 AM and has his breakfast. Now, he starts reading an article and plans to
read it until noon, and then he will have lunch. The only thing he will do before
lunch other than reading is drink water (if he is thirsty). We can depict this
scenario using the code below. Here ,
boolean isThirsty;
// Activity outside the condition
Wake up and have Breakfast;
31
if (isThirsty == TRUE){ // Block-1
Drink water.
}
// Activity outside the condition
Have lunch
Example 7
main() {
int var = -47;
32
true or false. If the overall condition is true, statement-1 will execute. Otherwise,
statement-2 will run.
Here, we see that two different boolean conditions are evaluated and joined via a
logical operator (i.e., OR operator) to form one final expression. If one of these
statements is true—that is, it is raining, or the outside temperature is below 55
degrees Fahrenheit—the overall expression will be evaluated as true. The reader
33
may ask why the general statement becomes true when only one statement is
true. We will explain the answer via the truth table (Table 3). A truth table is
used to check whether the compound expression is true or false, based on the
input values. Below we provide the truth table for the logical AND (&&), logical
OR (||), and the logical NOT (!) operator.
A B A&& B A||B !A !B
True True True True False False
True False False True False True
False True False True True False
False False False False True True
Concept Check
✓ It is raining outside.
Concept Check
34
What will happen if a person
Example 8
Now, let us describe this concept again with a real-life example. John wakes up
at 7.00 AM and has his breakfast. Now, he wants to go out to buy groceries.
However, he will check the weather before heading out. If it is raining or the
temperature is below 55F, he will not go for groceries and will instead clean the
house. Otherwise, he will buy groceries today. Whatever he does—clean the
house or buy groceries—he will have lunch afterwards. We can depict this
scenario by using the figure (Figure 3) presented below. Here,
• Condition 1 = Is it raining
35
We can describe the example of John’s work schedule using the following code
snippet.
We already have seen how the truth table works. In this example, a logical OR
statement joins two different boolean conditions. Hence, if any (or both) of these
conditions are true, the whole expression becomes true. That is, if it rains
outside, or it is sunny, but the temperature is below 55, or it is raining, and the
temperature is below 55, John will clean the house.
Example 9
Consider a 24-hour time format and let an office run from 9.00 (i.e., 9.00 AM) to
16.00 (i.e., 4.00 PM) on weekdays. The following code snippet shows a Java
program that takes hours and days as input (from the user) and determines
whether the office is open or closed. For the sake of simplicity, we take all input
as integers and represent a day with a number, i.e., Saturday = 0, Sunday =
1, . . . , Friday = 6).
We have used the onlinegdb compiler to execute this code snippet. It is a free
online compiler and debugger that supports multiple programming languages,
including but not limited to C, C++, Python, Java, etc. It offers an easy-to-use
interface where users can write, compile, and debug code directly in their
browser without installing additional software. It comes with features like code
execution, syntax highlighting, and debugging tools, and benefits students and
developers practicing coding online.
In Line 12, multiple boolean expressions are joined by the && operator. Each of
these expressions contains a relational operator. According to the truth table, the
overall expression will return true (and thus print “Office is Open”) if all these
expressions are true. Conversely, if one of the expressions is false, it will print
“Office is closed”.
36
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int currentDay, timeInHour;
Practice Problem
Write a Java program that determines if a person is a resident of the US for tax
purposes. A person is a resident for tax purposes if they meet one of the
following criteria:
• the person legally stayed in the US and paid taxes for at least five years
This program will ask the above questions and decide if this person is a resident
for tax purposes. Then, it will print, “You are a resident for tax purposes.”
Otherwise, it will print “You are not a resident yet.”
37
a weekday, we need to check the time (Line 15). Finally, we say that the office is
open if this time also falls during office hours (Line 16). Otherwise, the office is
closed (Line 19).
Line Code
1 import java.util.Scanner;
2 public class Main{
3 public static void main(string[] args) {
4 Scanner myObj = new Scanner(System.in);
5 int currentDay, timeInhour;
6
7 System.out.printIn(“Enter the Day: “);
8 currentDay = myObj.nextInt();
9 System.out.printIn(“Enter the Hour: “);
10 timeInhour = myObj.nextInt();
11
12 if((currentDay <= 6) && (currentDay > 1)){
13 if((timeInHour < 17) && (timeInHour > 8))
14 System.out.println("Office is Open");
15 else
16 System.out.printIn(“Office if Closed”);
17 }
18 else{
19 System.out.printIn(“Office is Closed”);
20 }
21 }
22 }
Example 10
38
user to enter the membership duration and then display the membership level.
We will use a nested if-else statement to solve this problem.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int mem_Duration;
System.out.println("Enter your membership duration:");
mem_Duration = myObj.nextInt();
Practice Problem
Write a Java program that will allow a user to enter a test score and then display
the grade for that score. Use a nested if-else statement to solve this problem.
39
if( boolean Expression 1){
Statement 1;
Statement 2, etc;
}
// requires an IF statement above
else if( boolean Expression 2){
Statement 1;
Statement 2, etc;
}
else if( boolean Expression 3){
Statement 1;
Statement 2, etc;
}
// insert more else-if statement if necessary
else {
Statement 1;
Statement 2, etc;
}
The boolean expressions inside if/else if blocks must be unique. The code starts
by evaluating boolean expression 1. If expression 1 is true, the program control
will immediately execute all the statements inside the if block. In contrast, it will
ignore the rest of the else if (and else) blocks. If expression 1 is false, the code
evaluates the next else-if block (i.e., expression 2). Again, if it is true, all the
statements inside the else-if block will be executed immediately, and the rest of
the blocks will be ignored. This process continues until one of the expressions is
true. If none of the expressions are true, by default, the ending else clause will
execute. Note that the end else clause is optional, but helpful in most cases.
Example 11
We will solve the same problem here as shown in Example 10. Refer to the
snapshot given below. In this code snippet, if the user enters something less
than two years, the if block will execute, and the code will be basic status. Also,
the code will skip the rest of the conditions (else-if, else statements). Suppose
the user provides something greater or equal to two but less than five. In this
case, the code will print ”silver status” and skip the remaining conditions. If the
user provides something so that all the conditions become false, the else
statement will execute by default.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
40
int mem_Duration;
if(mem_Duration < 2)
System.out.println("Basic Status");
else if((mem_Duration >= 2) && (mem_Duration < 5))
System.out.println("Silver Status");
else if((mem_Duration >= 5) && (mem_Duration < 10))
System.out.println("Gold Status");
else
System.out.println("Platinum Status");
}
}
Practice Problem
• Write a code that takes the lengths of a triangle’s three sides as input from
the user. Assume all these values are integers. Next, you need to check if
an input is valid or not (0 or negative value is invalid). Also, the sum of
any two sides must be greater than the third. Now, determine whether it is
an equilateral, isosceles, or scalene triangle. Note that an equilateral
triangle is a triangle in which all three sides are equal. A scalene triangle is
a triangle that has three unequal sides. Finally, an isosceles triangle is a
triangle with (at least) two equal sides.
• Write a Java program that takes a random string that may contain letters,
numbers, and alphanumeric characters. Then, write a Java program that
will count the number of letters, numbers, and alphanumeric characters in
the string. For example, if the user provides a string BN!X254@0%QK$#”,
the code will print the following:
• Write a Java program that does the following: (i) Take electricity
consumption in KWH as input (from the user) (ii) Calculate the total
electricity bill according to the following given conditions:
41
• For next 100 units, 23 cents/unit
Example 12
While writing code using the if/else statement, we need to pay attention to using
the = and == operators. The former is referred to as an assignment operator
and is used to assign a value to a variable. Meanwhile, the latter is a relational
operator used to find the equality between operands. Let us consider an example
where a program takes two integer variables (say firstVar and secVar) as input
from the user. If the firstVar is equal to the secVar, it will print that “both of them
are equal.” Otherwise, it will print that “they are not equal.” Consider the
following code snippet. We present it as an exercise to test the output and justify
the reason.
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int firstVar, secVar;
firstVar = myObj.nextInt();
secVar = myObj.nextInt();
if(firstVar = secVar)
System.out.println("They are Equal");
else
System.out.println("They are not Equal");
}
}
42
System.out.println("January");
else if (month == 2)
System.out.println("February");
...
else if (month == 12)
System.out.println(“December");
Now, we will write the same program using a switch statement. While writing a
switch-case statement, we need to consider some essential points. They are
mentioned below:
• Block of codes.
switch (month){
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
...
case 12:
System.out.println(“December");
break;
}
43
the break statement jumps control past the rest of the cases, i.e., the rest of the
cases are ignored. The switch-case statement is similar to if/else-if statements.
if (month.equals("January"))
//..... Do Something;
else if (month.equals("February"))
//..... Do Something;
....
else
// Invlid Month
switch (month)
{
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
...
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid Month");
break;
}
44
Example 13
Let’s say that we want to check if it is summer in your region. For example, the
following code snippet will print “Summer” if it is May, June, or July. For
simplicity, we denote each month numerically, i.e., January = 1, February = 2, ...
December = 12, and so on.
switch (month)
{
case 5:
case 6:
case 7:
System.out.println(“Summer");
break;
}
Example 14
The ”break” statement is essential for many reasons. See the code below. If the
user enters 1 (i.e., January), it will print January, February, March, and Invalid
Month.
switch (month)
{
case 1:
System.out.println("January");
case 2:
System.out.println("February"); ...
case 3:
System.out.println("March");
Default:
System.out.println("Invalid Month");
}
45
2.3.2 Advantage and Disadvantage of Using Switch-Case
(Compared to If-Else Statement)
A switch-case statement is more aesthetic when a logical OR joins several
conditions. Compare the following two code snippets.
switch (number)
{
case 1:
case 4:
case 7:
case 10:
case 15:
case 21:
System.out.println("Do Something");
}
Below is how the same code will look if we write them using an if-else construct.
2.4 Loops
Did you ever get punished for forgetting to do your homework in middle school?
For example, being asked to write “I will complete my homework on time” 100
times? Boring and tedious, isn’t it? Instead of your using pen and paper, if the
teacher asks you to write this sentence using Java programming, then the
statement below will do this job:
But how can we print the same statement 100 times or more? Obviously, using
tons of print statements is not useful and will not be feasible in many cases. Yet,
there are situations when we need to execute a statement or set of statements
several times. In general, running these statements is very complicated and
time-consuming. Hence, the Java programming language provides a feature to
46
handle such complex execution statements as loops. Loops allow a set of
statements, instructions, or code blocks to execute repeatedly until a particular
condition is met.
while(boolean expression){
Loop-body
}
Details on how the loop works have already been mentioned above. However,
this general syntax does not depict the whole scenario:—that is, it does not show
the role of the control variable. We present the following examples to
demonstrate how the while loop works.
Example 15
In this example, we write a Java program that prints all numbers from 1 till 500.
In this example, we initialize the control variable (i.e., count) to 1 and provide
the boolean expression in the while loop. Suppose the test expression or
condition is true. In that case, the program control enters the loop body, where
the control variable is also updated. Eventually, the boolean expression will
become false (when the count variable becomes 501). Then the loop will break,
and the program control passes next to the loop’s body.
Concept Check
What will happen if we do not update the control variable, i.e., skip the COUNT+
+ statement?
48
Example 16
Now, we will write a Java program that prints all the even numbers from 0 till
500.
This example is almost the same as Example 15, other than the change we make
in the control variable initialization and update. We want to print all the even
numbers from 0-500. Hence, we initialize the variable to 0 and increase it by two
at each iteration until the boolean expression becomes false.
Example 17
In this example, we write a Java program that prints the sum of all numbers
from 1 till 500.
Concept Check
3. We initialize the variable sum with a different value other than ZERO?
49
Scope of a Variable in a Loop. Let us declare a variable inside the loop. In this
case, the scope of this variable is within the loop body. Hence, if the loop is
terminated, we cannot access the variable outside the loop body.
Example 18
Unlike the while loop, the for loop allows for initialization and updating of the
control variable inside the parentheses. Let us explain by using the same
example that we used in the while loop.
50
Example 19
We repeat Example 15 and print all numbers from 1 to 500 using a for loop.
In this example, we both initialize and update the control variable (i.e., count)
inside the parenthesis. The initialization is executed only once at the beginning.
Then, the boolean expression is evaluated. If it is true, the program control
enters the loop body. Unlike the while loop, the program control goes back to the
parentheses, where the control variable is updated. The loop will break when the
boolean expression becomes false.
Example 20
Write a Java program that prints the sum of all numbers from 1 until 500, using
for loop.
Concept Check
What will happen if we execute this code? Can you justify the output?
51
int i, sum;
for( i = 1, sum = 0 ; i <= 10 ; sum +=i, ++i )
System.out.println(i);
In this code snippet, we write two initialization expressions (i.e., i = 1 and sum =
0) and two update expressions (i.e., sum += i and ++i). As usual, these
statements execute sequentially.
Empty Loop. In Java programming, we also can write an empty loop that
contains no statement in the loop body. Consider the following example of an
empty loop:
int counter;
// The following loop has nothing in the loop-body
for (counter = 2000; counter >=0; counter—)
do{
Loop-body;
} while(boolean expression);
It is very similar to the syntax of a while loop, other than the following
differences:
Like before, the loop body is repeated until the boolean expression evaluates as
false. However, contrary to the while loop and the for loop, the do-while loop will
execute at least once. In a do-while loop, first, the loop body is executed. Then,
it evaluates the boolean expression. Based on these characteristics, the while
loop and for loop are known as the pretest loops, and the do-while loop is a
posttest loop.
52
Example 21
Write a Java program using a do-while loop that prints all numbers from 1 until
500.
Unlike the while loop, the loop body will execute at least once. Then, it will
continuously evaluate the boolean expression, and the loop will break when the
expression becomes false (when the count variable becomes 501).
Concept Check
Can you write a Java program where a pretest (while, for) and posttest (do-
while) loop does not generate the same result?
// Nested Loop-1
while(boolean expression){
//body of the outer loop
while(boolean expression){
//body of the inner loop
}
}
// Nested Loop-2
for(initialization;boolean expression;update statement){
//body of the outer loop
for(initialization;boolean expression;update statement){
//body of the inner loop
}
}
// Nested Loop-3
for(initialization;boolean expression;update statement){
//body of the outer loop
while(boolean expression){
53
//body of the inner loop
}
}
A nested loop may seem tricky at the beginning. However, while writing a nested
loop, keep in mind:
• For each iteration of an outer loop, the inner loop goes through all of its
iterations.
• The inner loops must complete their iterations before the outer loop.
• Suppose we multiply the number of iterations of all the loops. In that case,
we will find the total number of iterations of a nested loop.
The following code snippet prints the value of variable j (from one to three) for
each value of variable i (from one to two).
Concept Check
• Consider the code snippet provided above. Can you generate the same
output, but using a nested while loop?
• Consider the following code snippet. What will be the output if we set the
value of numRows to 5?
54
for (int colNum = 1; colNum <= rowNum; colNum++)
System.out.print("*");
System.out.println();
}
2.5 Exercise
1. Let, x = 10, y = 8, z = 18. Determine the values (TRUE or FALSE) of the
following expressions:
2. Write a Java program that takes the length and width of a rectangle from the
user and checks if it is square or not.
3. Write a Java program that takes a character as input and check whether it is
a lowercase (a to z) or uppercase (A to Z) letter or a non-letter (e.g., 8, #,
*, etc.)
4. Write a Java program that takes the salary of 3 people as input from the
user. Now, determine the highest, lowest, and average salary. If all of them
have the same income, print “all of them have the same salary.”
5. Write a Java program that takes an input of an integer number and then
checks whether this number is divisible by 4, 6, and 10, or some of them or
none of them. If multiple of these numbers, divide your number; you must
mention all of them.
6. Professor Simeone adopts a policy in his CSC 141 course. He will not allow a
student to sit for the final exam if his/her attendance is below 80%. Write a
Java program that takes the number of classes held and the number of
classes attended by a particular student. Then, print the percentage of
classes attended by that student. Also, print if the student is allowed to sit
for the final exam or not.
a x 2 + bx + c = 0
55
Here, a, b, and c are the coefficients of the equation. Write a Java program
that takes the value of a, b, and c as input from the user and finds all roots
of a quadratic equation.
8. The dates for each season in the northern hemisphere are as follows:
Write a Java program that takes a date as input and outputs the date’s
season in the northern hemisphere. The input is a string representing the
month and an int representing the day. First, you must check if the string
and int are valid (an actual month and day). For example, July 23 is valid,
while March 53 or Covid 19 is invalid.
A. 0 - 50 units: 10 cents/unit
B. 51 - 150 units: 16 cents/unit
C. 151 - 250 units: 22 cents/unit
D. 251 unit or higher: 30 cents/unit
10. Write a Java program to create a simple calculator. This calculator will
perform the add, subtract, multiply, divide, modulus, and exponent
operations. The program should take two numbers and an operator as input
from the user. Then, it will operate according to the operator entered. The
input must be provided in the following format and any other format should
be considered as invalid.
11. Write an infinite loop using the while loop, the for loop, and the do-while
loop.
12. Write a Java program that takes a string as input and counts the frequency
of each character in this string.
56
13. Write a Java program that takes an integer as input from the user. Now it
should calculate the sum and product of all input digits. For example, if the
user inputs 5143, the sum of digits is (5 + 1 + 4 + 3 = 13) and the product of
digits is (5 × 1 × 4 × 3 = 60).
14. Write a Java program that takes an integer as input and reverses the input
digits. Let the input is 51430, then the output will be 3415.
17. The Least Common Multiple (LCM) of two or more numbers is the smallest
number that is divisible by all these numbers. For example, assume two
integers, “a” and “b.” Their LCM is denoted as LCM (a,b). If a = 12 and b =
8, LCM (12,8) = 24. Write a Java program that takes non-zero integers as
input and calculate their LCM.
18. Repeat the same problem as mentioned above in No. 17. This time, take
three non-zero integers as input and calculate their LCM.
19. In the Fibonacci series, each number (other than the first two) is the sum of
the previous two numbers. Here, the first two numbers are 0 and 1. So, the
series looks like the one below:
Write a Java program that takes an integer n as input and calculates the nth
Fibonacci number.
57
3 String
3.1 What Is String?
Simply put, a string is a sequence of characters. In Java programming the String
class represents the character strings, and all string literals are implemented as
an instance of the String class.
Example 1
The example shows how to declare a string variable and assign value to it.
Hello Class!!
58
Example 2
The example shows how to declare a string variable and assign value to it.
import java.util.Scanner;
public class KeyboardInput {
public static void main (String[] args) {
// create a scanner object
Scanner input = new Scanner(System.in);
// use the scanner object to read line from keyborad
String inputString = input.nextLine();
// print the input string
System.out.println(inputString);
}
}
Hello Class!!
• toUpperCase()
• toLowerCase()
• charAt(int index)
• indexOf(String str)
Example 3
The example shows how to use length() method to find the length of a string
variable.
59
public class LengthExample {
public static void main(String args[]) {
// declare a string variable s1 and assign "Hello Class!!"
String s1 = "Hello Class!!";
// print the length of s1 variable
System.out.println(s1.length());
}
}
13
When we create a string variable by using the String constructor. As shown in the
example above (see example 3).
Example 4
The example shows how to use toUpperCase() method to convert all characters
of a string variable to uppercase letters.
Hello
HELLO
60
3.4.3 String toLowerCase() Method
The toLowerCase() method helps to convert a string variable’s values to
lowercase letters.
Example 5
The example shows how to use the toLowerCase() method to convert all
characters of a string variable to lowercase letters.
Hello
hello
Example 6
The example shows how to use charAt() method to get a character from a string
variable using the index of the character.
61
char c1=s1.charAt(4);
System.out.println(c1);
o
H
and
Example 7
The example shows how to use substring() method to get a string from a string
variable using the index of the string.
62
class
Hello
Example 8
The example shows how to use indexOf() method to get the index of the
substring within a string variable.
6
0
63
Example 9
The example shows how to call multiple methods at the same time in Java. This
example utilizes concept of class, constructor, setter, and method which is
discussed in detail in chapter 4 and 6.
64
Example 10
The example shows how to use concat() method to join two string variables.
Hello Class!!
String equals() method In Java, uppercase letters and lowercase letters are
not the same. So, if a string variable value is ”S” and another is ”s”, then
comparing them will show that they are not the same. This means variables ”s1”
and ”s2” are not same or not equal (see Example 11),
String s1 = "S"
and
String s2 = "s"
Example 11
The example shows how to use ”equals” method to compare string variables.
65
public class TestStringComparison{
public static void main(String args[]){
// declare s1 string variable and assign value "S"
String s1 = "S";
// declare s2 string variable and assign value "s"
String s2 = "s";
// compare s1 and s2
System.out.println(s1.equals(s2));//false
}
}
false
Example 12
The example shows how to use ”equals” method to compare string variables.
true
true
false
Note that if a string variable is ”John” and another is ”john”, then equals()
method will return false since ”John” and ”john” contain characters in different
cases and therefore are different variables. However, if you want to ignore the
case, then you can use equalsIgnoreCase().
66
Example 13
true
false
true
Example 14
The example shows how to use ”compareTo” method to compare string variables.
67
System.out.println(s3.compareTo(s1));//3
}
}
0
-3
3
Example 15
-32
0
3.7 Exercise
1. What is a string in Java? Please provide an example.
3. Write a program to take two string inputs from keyboard and contact them;
display the result.
4. Write a program to find the length of the following string. Make sure to
ignore the white space when computing the length of the string.
68
Hello Class
Hello, My name is John!
7. Write a program to take user input as string and display the input values in
uppercase letters.
8. Write a program to take user input as string and display the input values in
lowercase letters.
9. Write a program that takes two string inputs from the keyboard and displays
TRUE if the second string value exists in the first input.
10. Write a program that takes two string inputs from the keyboard and displays
an index if the second string value exists in the first input.
11. Write a program that will take a string as inputs and print the most
frequently appearing character (in this string) and its frequency. For
example, if you enter ”AliBaba”, the output is ”A:3”.
12. Write a program that will take a string as input and switch the cases of the
letters (lowercase to uppercase and vice versa) without using built-in
methods. For example, if the user provides hgFh@gbBBT5e54& as input, the
method will convert this string to HGfH@GBbbt5E54&.
13. Write a program that will take a string as input. Now, check if the string is
valid as a password. A password is valid if it contains
You are not allowed to use any built-in methods provided in the String class.
69
14. Write a Java program that only takes a string formed only by letters (any
non-letter input is invalid). The length of the string must be between 7-16
characters. Now, do the following:
A. Replace all the vowels (in this string) with the immediate next
consonants from English alphabet list.
B. Replace all the consonants (in this string) with the immediate next
vowels from English alphabet list. If the consonants appears after ”U”
alphabetically, replace it with ”A” or ”a”. Consider the following input-
output for understanding:
You are not allowed to use any built-in methods provided in the
STRING class.
15. Write a program that will take a date as input in MM/DD/YYYY style. Now
display it this way: DD First 3 letters of Month, YYYY. For example, if the
user provides 08/24/2002, the program will print “24 Aug, 2002.” If the user
provides 18/24/2002 or 07/42/2001, the program will print ”Invalid Input”.
You are not allowed to use any built-in methods provided in the String class.
70
4 Methods in Java
A method is a system or a way of doing something. However, in Java, a method
is a collection of given instructions or statements that are grouped and perform a
specific task. In other words, a method in Java or Java is an assortment of
explanations that play out a particular assignment and return the outcome to the
guest.
This code is pretty simple. However, if we want to calculate the tax for one more
friend, we must repeat similar statements. In addition, if someone moves to a
different state, all these calculations must be rechecked and probably adjusted.
We can rewrite this code with a method, and it will look like the example below:
71
public static void main(){
String f1 = "John", f2 = "Chris", f3 = "Aby", f4 = "Mary";
int salary_f1 = 89600, salary_f2 = 106300, salary_f3 = 92000, salary_f4 =
86200;
double rate_MI = 4.25, rate_CO = 4.55, rate_PA = 3.07, rate_UT = 4.95;
calc_Tax(f1,salary_f1,rate_MI);
calc_Tax(f2,salary_f2,rate_CO);
calc_Tax(f3,salary_f3,rate_PA);
calc_Tax(f4,salary_f4,rate_UT);
}
static void calc_Tax(String name, int salary, double Rate){
double tax = salary * Rate/100.0;
System.out.println(name + "pays $" + tax + "per year.");
}
Example 1
Write a Java program that prints the sum of all numbers from 1 to 100, 1 to
1000, and 100 to 5000.
1Alternatively, think about a fruit juicer. We put in water and different types of fruits (consider them as input
parameters), and it produces the juice (i.e., output).
72
System.out.println("Sum of 1 to 100 is: " + sum_1);
System.out.println("Sum of 1 to 1000 is: " + sum_2);
System.out.println("Sum of 100 to 5000 is: " + sum_3);
}
Notice that all these for loops are doing almost the same job. They add all the
numbers that fall within a range. We can replace this code and write it using
methods, as shown below:
Needless to say, the code with the method is more manageable and organized.
73
• Depending on the return type, it can return an answer. A void method
returns nothing.
// Method signature
modifier(s) returnType methodName(parameter list){
// method body
}
• Return Type: A method could be a void method (we have covered some
examples on this type) or a value-returning method (we will provide
examples on this type). The return type specifies if a method will return a
value or not.
74
// Method signature
public static int returnMax(int var1, int var2){
// Method body: return the greater value
if(var1 >= var2)
return var1;
else
return var1;
}
Concept Check
1. take three integer numbers as input, calculate their average, and print the
average value. This method will not return anything.
2. take your first name as input and count the number of characters. This
method will return the character count.
calc_Sum(1,100);
75
Tip
Method modifiers and the return type are not mentioned while calling the
method.
Practice Problem
The method will take a test score as input (provided by the user) and then
display the grade for that score.
Concept Check
• Is it possible to call a method from another method (other than the main
method)?
calc_Sum(1,100);
This statement calls the calc_Sum(1,100) method and passes two integer values
as arguments. Now, let us examine the method definition, which is presented
below:
76
System.out.println("Sum of " + low + " to " + high + " is: " + sum);
}
Declaration of the integer variable appears inside the parentheses, i.e., (int low,
int high). This declaration enables the method to accept the values as an
argument. The statement calc_Sum(1,100) executes the method. The argument
(i.e., the integer values) inside the parentheses is copied into the method’s
parameters—i.e., low becomes 1, and high becomes 100. Figure 1 illustrates this
concept: It is also possible to pass a variable as an input argument. Consider the
following code snippet:
Example 2
In the code snippet shown above, we declared two integer variables and
initialized their values. When we call the method printMyInfo(myAge,
myWeight), the value of the myAge and myWeight variables are copied to the
input parameters (i.e., age and weight).
Tip
When passing parameters to a method, the number of parameters and their data
type must match.
Concept Check
Consider the following code snippet that calls and defines a method. This code
snippet contains errors. Modify and correct all the mistakes.
77
System.out.println(name + " lives in " + city);
}
public static void main(String[] args) {
String Name = "Fiona";
int age = 5;
myMethod(age, name);
}
Void Methods
A void method performs a task and terminates without returning anything to the
caller method. We have already discussed the process of creating a method
(refer to Subsection 4.2). We need to provide the method definition, consisting of
a header and a body. In the method header, we offer much important information
about the method. We presented the skeleton of a method in Subsection 4.2.
Now, we will change the skeleton slightly to represent a void method.
// Method signature
public static void methodName(parameter list){
// method body
}
Example 3
Let us present an example where we write a program using void methods with
and without input arguments (or parameters). In this program, a user will print a
generic text in the first line, e.g., ”Hi There”, ”Good afternoon”, or something
similar. Then, the user will declare his (or her) name and hometown in the
following line. Of course, we can write the same code without using any
methods. However, the purpose of this example is to explain writing a void
method.
78
public class Main{
static void welcomeMsg(){
System.out.println("Hi There! Good Morning");
}
static void presenter(String name, String city){
System.out.println("I am " + name + " from " + city + "welcome you");
}
Example 4
In the S.I. unit system, the units to measure distance and temperature are
kilometer (km) and degrees Celsius, respectively. However, in the U.S., they use
miles and degrees Fahrenheit as units of measurement. Therefore, we will write a
Java program that takes the distance and temperature in miles and degrees
Fahrenheit and converts it to the S.I. units. We present the complete code below:
import java.util.Scanner;
public class Main {
static void milesToKM(double miles) {
double km = 1.61 * miles;
System.out.println(miles + " miles is equivalent to " + km +
"Kilometers");
}
static void fahrenheitToCelsius(double fahrenheit) {
double celsius = (fahrenheit - 32) / 1.8;
System.out.println(fahrenheit + " F is equivalent to " + celsius +
“C");
}
public static void main(String[] args) {
double distanceInMiles, temperatureInF;
Scanner myObj = new Scanner(System.in);
79
distanceInMiles = myObj.nextDouble();
Value-Returning Methods
We already see that we can pass data or information into a method by using
parameter variables. Unlike a void method, it is possible to return a value to the
statement from where a method is called. When a method returns a value to the
caller, it is known as a value-returning method. Similar to the void methods, we
need to provide the method definition, consisting of a header and a body. We
provide the skeleton below that represents a value-returning method. We
consider that the method will return an integer value in this skeleton.
// Method signature
public static int methodName(parameter list){
return an int value;
}
Example 5
Let us consider that we want to calculate the sum of all numbers from 1 to 1000.
We have already solved such a problem in Example 1. We will rewrite this
example with the help of a value-returning method.
80
}
return temp;
}
Example 6
We will repeat the problem shown in Example 4. The only difference is that,
instead of void methods, we will solve this problem using value-returning
methods. This code will generate the same output as shown in Example 4.
import java.util.Scanner;
public class Main {
static double milesToKM(double miles) {
double km = 1.61 * miles;
return km;
}
static double fahrenheitToCelsius(double fahrenheit) {
double celsius = (fahrenheit - 32) / 1.8;
return celsius;
}
public static void main(String[] args) {
double km, celsius, distanceInMiles, temperatureInF;
Scanner myObj = new Scanner(System.in);
81
System.out.println(temperatureInF + " F is equivalent to " + celsius
+ " C");
} // end of main method
}
Concept Check
km = milesToKM(distanceInMiles);
• What will happen if we add a return statement inside the main() method?
Why?
Example 7
In the code snippet shown below, we provide a comparison between two major
cities in the US. We write two methods, each having three variables with the
same name. We initialize one of them (city) via a parameter passed to the
method, and we initialize the other two (population and area) by providing hard-
coded values. The same naming of these variables does not create any issues.
This is because these variables are written in different methods, and the program
can see only one of them at a specific time. The population and area of
82
Chicago_details() do not influence the population and area of
Atlanta_details().3
Example 8
3 We can visualize this concept differently. For example, say you write a question on a paper, create three
different copies, and give it to three other students. They receive the same question but will each write a
different answer, and the explanation written by one will not influence the others.
83
var = var * 2;
System.out.println("var inside changeVar(): "+ var);
}
Concept Check
Consider the following code snippet (slightly modified from Example 7).
• If it does not work, make the necessary changes inside the main() method
(do not write any additional methods) so that it works.
84
2. Do not use method modifiers and return types in method calls.
3. Write the empty parentheses while calling a method even if it does not
accept arguments.
// Method signature
public static void main(String[] args){ // no ;
String s1 = "Good Morning”;
String s2 = "John Doe";
85
// Need to mention the data type of input param
public static void demoMethodTwo(String str){ // no ;
System.out.println(str);
}
// Return statement needed for a value-returning method
public static String demoMethodThree(String name){ // no ;
String s1 = "I am ", s2 = " Welcome you all";
String temp = s1.concat(name);
temp = temp.concat(s2);
return temp;
}
/* Output: Hello World
Good Morning
I am John Doe Welcome you all */
4.3 Exercise
1. Write a Java program that takes an integer number (say num) as input
(from the user), which is between 100 to 9999999. Now, write a function
void revNum(int num), which reverses this number and prints the difference
between the original number and the reversed number. While printing the
difference, ignore whether the difference is positive or negative. For
example, you should publish as XYZ only if the difference is -XYZ.
A. int GCD(int num1, int num2); it will return the GCD of num1 and
num2.
B. int LCM(int num1, int num2); it will return the LCM of num1 and
num2.
For example, 11 is prime because while factorizing 11, its only factors are
itself and 1, i.e., 1 × 11 or 11 × 1. Now, write a method void primeCheck(int
n) that checks if n is a prime number and prints the decision.
86
4. Write a Java method void findPrimes(int lowLimit, int hiLimit), which
will print all the prime numbers between lowLimit and hiLimit (including
themselves). Here, 2 ≤ lowLimit < hiLimit ≤ 999999.
6. Write a method that will take a string as input and switch the cases of the
letters (lowercase to uppercase and vice versa) without using built-in
methods. For example, if the user provides hgFh@gbBBT5e54& as input, the
method will convert this string to HGfH@GBbbt5E54&.
8. Write a Java program that takes a string formed only by letters (any non-
letter input is invalid). The length of the string must be something between
7-16. Now, write a method:
87
it with ”A” or ”a”. Consider the following input-output for
understanding:
11. Write a program that will take a string as input. Now, write two methods,
findSpace(String input) and removeSpace(String input). The former
method will print the location of white spaces in the string, and the latter will
print the modified string after removing all the white spaces.
For example, if the user inputs ”Have a nice day!” It will invoke the
findSpace(String input) method and print: ”Whitespaces found at
positions 4, 6, and 11.” Then, it will invoke the removeSpace(String
input) method and print: ”Haveaniceday!”
12. Consider Problem 8 from Chapter 2. Solve this problem by writing a method
String session(String month, int day). Here, month and day are the
month and day provided by the user. This function will return the season (as
string).
13. In this problem, you will create a basic calculator to perform the following
binary operations ={+, −, ∗, /, %}. Then, write a program that will do the
following:
88
A. The user will provide the operator. Any input other than the operators
listed above is invalid. If an invalid input is provided, terminate the
program and print a message saying that the input is not valid.
89
5 Arrays
In this chapter, we introduce a data structure called an array—a collections of
related data items of the same type. An array is a static data structure—their
length remains the same length once they are created. First, we will discuss
declaring, creating, and initializing an array. Then, we will discuss how to
manipulate an array and observe some standard array algorithms. We will also
examine some common mistakes while using an array. We will present several
examples to demonstrate these topics.
dataType[] arrayName;
For example, consider the following statement that declares an array reference
variable. In this statement, numbers is an array reference variable. It can refer
to an array of `int` values.
int[] numbers;
It is important to note that declaring an array reference variable does not create
an array. The next step is to use the new keyword to create the array and assign
its memory address to the numbers variable. Here's a complete example:
This statement creates an array of integer values with a length of 10, using the
new keyword. The numbers variable then contains the memory address of the
newly created array. By following this approach, you can create and work with
arrays in Java, storing and manipulating groups of values efficiently.
Now, let us answer an important question, why use an array? Arrays provide a
convenient and efficient way to store and access multiple values of the same
type. The following examples highlight the motivation behind using arrays.
90
Example 1
Suppose we want to write a program that reads the temperatures of a city for
each day of the month and performs some calculations, such as finding the
maximum, minimum, and average temperature. Without using an array, we may
want to declare separate variables for each day of the month, making the code
cumbersome and challenging to manage:
Example 2
Let us consider another example demonstrating the need for a different data type
array, such as storing a collection of strings. Suppose we write a program that
manages a student roster for a class size of fifty. Each student has a name, and
we need to store these names. Without using an array, we face similar challenges
as in the previous example. For example,
String student1;
String student2;
String student3;
// ... declare 50 variables for 50 students
91
Like the last example, when the number of students increases, this approach
quickly becomes cumbersome and impractical. An array can efficiently store and
manage the names of multiple students:
In this case, we create an array called studentRecord that can store the names of
up to fifty students.
The above examples should motivate the use of an array. In both examples, one
piece of information still needs to be included, i.e., how to access a particular day
of the month or a particular student from all the students. We will discuss this
topic in the next section.
In the same way, in Example 2, we can assign individual names using the
indices:
studentRecord[0] = "Alice";
studentRecord[1] = "Bob";
// ... and so on
92
Tip
In Java, the index always starts at zero. The index of the last element in an array
is one less than the total number of elements. If an array has N elements, the
index for the last element is (N-1). See Example 3 for details.
Example 3
Array length: 10
Last index is 9, and the value at last index: 10
Concept Check
What will happen if we do not subtract one from length, i.e., assign lastIndex as
lastIndex = length?
Now, let us describe a bit more about the array memory management. We
declare an integer array as follow:
Here, memory space holds 10 int numbers, each with a different address.
Suppose, at the time, that their memory addresses start from 1000. The
93
memories unite each other and are separated by the same distance. If 4 bytes
represent the int storage, henceforth, the other memories will have 1004, 1008,
and 1012, and so on.
Figure 1: Array Memory Management. ©2025 Bindu sai Jammula. Used with permission.
Example 4
We will modify Example 1 so that a user can store the temperature of the last
seven days in an array. Then, we will print the temperature on each day. We
write the following code snippet for this purpose.
import java.util.Scanner;
94
System.out.println("Day " + (i + 1) + ": " + temperature[i]);
}
In this example, we utilize the Scanner class. Inside the main() method, we
create a scanner object named scanner to read user input. Next, we declare and
initialize an array called temperature with a size of seven. This array will store
the temperature for a specific week (i.e., decimal numbers entered by the user).
We prompt the user to enter seven decimal numbers using the
scanner.nextDouble() method. We use a for loop to iterate through the elements
of the temperature array and assign the user's input to each element. When a
user provides these values, we display the array's contents using another for
loop. We iterate through the elements of the array and print each value along
with its corresponding index.
95
Example 5
We use the code from Example 4 to take the user input, i.e., the last seven days'
temperature. Then we use this information to calculate the maximum, minimum,
and average temperature. Let us discuss how we calculated the average and the
maximum temperature and leave it as an exercise to understand how the
minimum temperature is calculated.
• We run a for loop to iterate over each element in the temperature array,
adding each element to the sum variable.
• When the loop terminates, we divide the sum variable by the length of the
`temperatures` array.
• We use a for loop starting from the second element to iterate over each
element and check if the current element is greater than the
maxTemperature. If Yes, it updates the value of maxTemperature to the
current element.
• When the loop terminates, the maxTemperature variable will hold the
maximum temperature.
96
}
97
Example 6
In this example, the program asks the user to enter the ages of 7 students. We
store the ages in an integer array called ages. The program then calculates the
total age and the average age (divide the total age by the number of students).
Finally, it counts the number of students above and below the average age. We
print the results using System.out.println() statements. We also calculate the
standard deviation using the formula sqrt((sumOfSquaredDifferences /
ages.length)), where sumOfSquaredDifferences is the sum of the squared
differences between each age and the average age, and ages.length is the
array's length.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int totalAge = 0, aboveAverageCount = 0, belowAverageCount = 0;
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
98
if (ages[i] < averageAge) {
belowAverageCount++;
}
}
99
// Copy the elements from sourceArray to destinationArray
for (int i = 0; i < sourceArray.length; i++) {
destinationArray[i] = sourceArray[i];
}
Source Array:
1 2 3 4 5 6 7 8 9 10
Destination Array:
1 2 3 4 5 6 7 8 9 10
100
}
101
5.4.1 Sorting an Integer Array
This section will consider a random unsorted array and sort it in ascending order.
We provide the Java code (below) that starts with an array of integers. We then
call the bubbleSort() method, which implements the bubble sort algorithm. The
algorithm compares adjacent elements in the array and swaps them if they are in
the wrong order. We repeat this process until the array is fully sorted. The
printArray() method displays the array's contents before and after sorting.
Example 7
102
}
Original Array:
19 5 20 9 3 29 8 21 13
Sorted Array:
3 5 8 9 13 19 20 21 29
Concept Check
2. The method first determines the array length (i.e., n). Suppose the input
array is empty or has only one element (i.e., n= 0 or 1). In that case, the
method returns the input array with no duplicates to remove.
4. The program then traverses arr, and for each element (index i), it checks
if that element is already present in the uniqueArr. To check for the
presence of an element, the program uses another loop (with index j) to
iterate over the elements in uniqueArr. Suppose the element at index-i of
“arr” matches any element in “uniqueArr". In that case, the inner loop is
terminated using the break statement (Refer to Section 2.3 for details
regarding break statement), indicating that the element is a duplicate.
103
5. The element is unique if the element is not present in uniqueArr (i.e., the
inner loop completes without finding a match). It is added to the
uniqueArr at index uniqueCount. After adding the element, the
“uniqueCount” is incremented.
6. The process repeats for all elements in arr. At the end of the loop,
uniqueArr contains only the unique elements from arr.
Example 8
104
uniqueArr = Arrays.copyOf(uniqueArr, uniqueCount);
return uniqueArr;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 20, 40, 10, 50};
Array before removing duplicates: [10, 20, 30, 20, 40, 10, 50]
Array after removing duplicates: [10, 20, 30, 40, 50]
Concept Check
In Example 8, when there is a duplicate, the program keeps the first occurrence
of that item. Modify the code to keep the last occurrence of any duplicate item.
Consider the same array from Example 8. The updated output will be:
Array before removing duplicates: [10, 20, 30, 20, 40, 10, 50]
Array after removing duplicates: [30, 20, 40, 10, 50]
105
Here, “data_type” specifies the type of elements the array will hold,
“array_name” is the array's name, “rows/columns” represents the number of
rows/columns in the 2D array. For example, to declare a 2D integer array named
“matrix” with 4 rows and 3 columns, you would use the following code:
The code snippet creates a 2D array with four rows and three columns, where all
elements are initialized to their default values for the int data type (which is 0 for
numeric types). Once we declare the 2D array, we can initialize it with specific
values using the following syntax:
Here, each set of curly braces “{}” represents a row in the 2D array, and the
elements inside the braces represent the values for each column in that row. The
number of elements in each row must be the same as the number of columns
specified during the declaration. For example, if you want to initialize a 2D
integer array named “matrix” with the following values:
1 2 3
5 6 7
9 10 11
In this example, the 2D array “matrix” has three rows, each containing four
elements corresponding to the values in the matrix.
Using 2D Arrays
Once the 2D array is declared and initialized, we can access its elements using
two indices, one for the row and another for the column. For example, to access
the element at the 2nd row and 3rd column of the “matrix" array, we would
write:
int element = matrix[1][2]; // The indices are 0-based, so the 2nd row is at
index 1, and the 3rd column is at index 2
106
2D arrays provide a powerful way to organize and manipulate data in a
structured manner. They are helpful when working with tabular data or
representing matrices in mathematics and graphics, such as matrix operations,
image processing, and game development. Now, we present a small example
where we declare, initialize, and access elements of a 2D array representing a
simple 3x3 matrix.
Example 9
}
}
In this example, we declare a 2D integer array (i.e., matrix) with three rows and
columns and initialize the array with some values. Finally, we use nested loops to
access and display the elements of the 2D array in row-major order. Recall that
107
the indices in a 2D array are zero-based, so the first row starts at index 0, the
second is at index 1, and so on. Similarly, the first column starts at index 0, the
second at index 1, etc.
Example 10
108
// Perform matrix multiplication
// To calculate the element at position (i, j) in the result matrix,
// we need to take the dot product of the i-th row of matrix1
//and j-th column of matrix2.
// The dot product is obtained by multiplying corresponding
//elements of the row and column and summing them up.
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
for (int k = 0; k < columns1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
Content of matrix1:
1 2
3 4
Content of matrix2:
5 6
7 8
Result of matrix multiplication:
19 22
43 50
In this example, we create two matrices, i.e., matrix1 and matrix2, and
calculate their product, using a third matrix result. The resulting matrix stores
the product of matrix1 and matrix2, which is displayed as the output.
109
they come with pitfalls and common mistakes, especially at the beginning. Being
mindful of these pitfalls will help prevent errors and ensure the correct and
efficient use of arrays in programming.
Example 11
Example 12
110
In the example mentioned above, we create an integer array named numbers
with a size of 5. Since arrays are objects in Java, they are initialized with default
values for their respective data types (which is 0 for integers). We do not
explicitly assign any values to the array elements, which remain in their default
state (0). When we attempt to access and print the elements using a loop, the
output will be as follows:
Element at index 0: 0
Element at index 1: 0
Element at index 2: 0
Element at index 3: 0
Element at index 4: 0
When one is creating arrays, it is good practice to initialize them with appropriate
default values. Doing so ensures that the array elements contain meaningful data
from the start.
Example 13
111
}
}
}
Scores of Students:
Student 1: 78
Student 2: 90
Student 3: 85
Student 4: 92
Student 5: 68
Student 6: 75
Student 7: 88
Student 8: 0
Student 9: 0
Student 10: 0
Example 14
112
int[] mixedArray = {1.5, 2, "Hello", 3.14, 4};
^
Main.java:5: error: incompatible types: possible lossy conversion from double
to int
int[] mixedArray = {1.5, 2, "Hello", 3.14, 4};
^
3 errors
Example 15
}
}
113
5.6.6 Pass Arrays as Parameters to Methods
Arrays allow us to store and manipulate collections of elements of the same data
type, making them robust data structures. Many programming scenarios expect
the passing of arrays as arguments to methods for various data processing tasks.
Writing efficient and maintainable code requires a crucial understanding of how
to pass arrays as parameters and how they are modified inside methods.
Example 16
114
In this example, we have a method, doubleElements, that takes an integer array
as a parameter and doubles the value of each element. When we call this method
with the numbers array, the elements in the original numbers array are modified
directly. After the method call, the changes made to the array elements persist in
the original array.
Note that the ability to modify array elements directly in a method is powerful
but may introduce potential side effects. Modifying arrays inside methods may
lead to unintended consequences, especially in large and complex programs.
Therefore, using arrays as method parameters makes it crucial to be mindful of
side effects.
Concept Check
Consider the following scenario. We will pass the original array to a method and
make some changes in the passed array. Now, propose an approach such that
the initial array remains unchanged.
5.7 Exercise
1. Write a Java program that takes an integer number (say num) between 20
to 100 as input (from the user). Now, declare an integer/double array with
total "num" items. Finally, reverse the array in place (without using extra
space).
2. Write a Java program to find the second smallest element in an array. For
example, if the initial array contains [23, 43, 18, 98, 11, 30, 29, 63, 18, 84,
11, 110, 37], the updated array will be [23, 43, 98, 11, 30, 29, 63, 84, 11,
110, 37].
3. Write a Java program to merge two sorted arrays into a new sorted array.
For example, if array A1 contains [23, 43, 58, 98, 111, 130] and array A2
contains [29, 63, 68, 84, 91, 110, 137], the merged array will contain [23,
29, 43, 58, 63, 68, 84, 91, 98, 110, 111, 130, 137].
115
5. Write a function that takes a character array as input and returns the count
of vowels and consonants in the array. For example:
Input: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
Output: Vowels: 3, Consonants: 7
6. Write a function that takes a character array as input and checks if it forms a
palindrome. For example:
Input: ['r', 'a', 'c', 'e', 'c', 'a ', 'r']
Output: It is a palindrome.
Input: ['r', 'a', 'c', 'e']
Output: It is not a palindrome.
7. Write a Java program that checks if two given character arrays are anagrams
of each other. For example:
Input: ['l', 'i', 's', 't', 'e', 'n'], ['s', 'i', 'l', 'e', 'n', ’t']
Output: true
Input: ['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', ‘d']
Output: false
8. Write a Java program that finds the common characters in two given
character arrays. You can show multiple occurrences of the same character
only once. For example:
Input: ['D', 'E', 'L', 'A', 'W', 'A', 'R', 'E'], ['F', 'L', 'O', 'R', 'I', 'D', ‘A'].
Output: [‘D', ‘L’, ‘A’, ‘R'] or [‘L', ‘R’, ‘D’, ‘A']
Input: ['h', 'e', 'l', 'l', 'o'], ['l', 'o', 'l', 'l', ‘y’, ‘p’, ‘o’, 'p']
Output: [‘l', ‘o’]
Input: A = [3 2
12
3 4]
Output: AT = [3 1 3
2 2 4]
10. Write a program that takes a 2D array as input and calculates the sum of its
diagonal. Assume the number of rows equals the number of columns.
116
Input: A = [ 3 2 1 4
1 2 8 7
3 4 9 2
7 4 5 1]
Output: 15
117
6 Introduction to Classes and Objects
Class is a fundamental concept of Java, serving as the foundation for object-
oriented programming (OOP). It defines the structure and behavior of objects,
encapsulating concepts within its blueprint. Classes in Java are robust,
establishing new data types that can be instantiated as objects. Therefore, a
class acts as a template for objects, with the terms "object" and "instance" often
used interchangeably in Java programming. This chapter will explore the
essential elements of classes, including methods, constructors, and the "this"
keyword.
Example 1
class classname {
type instanceVariable1;
type instanceVariable2;
// List all variables
type methodName1(parameter-list) {
// body of method
}
118
type methodName2(parameter-list) {
// body of method
}
// List all methods
}
Explanation:
• // List all variables: This comment reminds the programmer to list all
variables (i.e., instance variables) of the class.
• // List all methods: This comment reminds the programmer to list all
class methods.
Example 2
119
// Define a method to make the dog wag its tail
void wagTail() {
System.out.println("The dog wags its tail happily.");
}
6.2 Objects
In Java, you can touch or interact with a computer program using an object. An
object is created based on a blueprint called a class, which defines what the
object can do and what information it holds. Think of it this way: Imagine you
have a blueprint for building a toy robot. The blueprint tells you what parts the
robot has (e.g., arms, legs, and a head) and what it can do (like walk, talk, and
light up). When you build the robot following that blueprint, you create an object
based on that class. So, in Java, an object is like a real-life robot you build using
a blueprint. It has its unique characteristics (state) and can perform specific
actions (behavior) defined by the class blueprint. Let us describe an object using
the "Dog" class as a reference:
Example 3
120
}
}
In this example:
• The "Dog" class has a constructor that initializes these member variables
when a new "Dog" object is created. We do this by passing the required
values as arguments to the constructor. This keyword is used within the
constructor to distinguish between the class-level member variables and
the constructor's parameters, as both have the same names. This keyword
explicitly refers to the current object's variables, ensuring that the values
provided in the parameters are correctly assigned to the object's breed,
age, and color fields.
• The "displayDetails()" method within the "Dog" class displays the details of
the "Dog" object.
• In the "Main" class, we create an object in the "Dog" class named "myDog"
using the "new" keyword and passing specific values for breed, age, and
color to the constructor.
121
upcoming sections, we will discuss the private member variables (see Section
6.3) and constructors (see Section 6.4).
In the context of the "Dog" class example provided earlier, member variables
could include properties like breed, age, and color, which represent
characteristics specific to each dog object. These variables define attributes that
distinguish one dog from another. Let's illustrate this with an updated "Dog" class
example:
Example 4
// Define methods...
}
In this example, "breed," "age," and "color" are member variables of the "Dog"
class. Consider three dogs (Mojo, Vojo, and Dingo). Each of them is an instance
of the "Dog" class. Each dog object (Mojo, Vojo, and Dingo) will have values for
these variables, allowing us to differentiate between them (and other dogs)
based on their breed, age, and color.
122
6.3.2 Member Functions (Methods)
Member functions, aka methods, encapsulate the behavior or actions that objects
can perform. In object-oriented programming, methods enable objects to exhibit
specific behaviors or functionalities, allowing interaction with the object's data
and other objects in the system. Methods promote code reusability, modularity,
and maintainability by encapsulating related functionality within the class.
Methods are declared within the class and can manipulate the object's state by
accessing and modifying member variables. Let's expand on the "Dog" class
example provided earlier to include methods:
Example 5
In this example, we've added three methods: “bark(),” “wagTail()” and “play().”
The “bark()” method simulates the action of a dog barking, the “wagTail()”
method simulates the action of a dog wagging its tail, and the “play()” method
simulates a situation when a dog is playing. These methods encapsulate
behaviors associated with dogs and allow objects of the "Dog" class to exhibit
these behaviors.
123
6.3.3 Access Modifiers
Access modifiers in Java control the visibility and accessibility of class members
within the program. They determine which parts of the program can access and
modify class members. Java provides four access modifiers:
Example 6
class Dog {
// Declare private member variables
private String breed; // Represents the breed of the dog
private int age; // Represents the age of the dog
private String color; // Represents the color of the dog
124
In this updated example, we've modified the member variables of the "Dog" class
to be private. This means these variables are accessible only within the same
class and cannot be accessed or modified directly from outside the class. To
provide controlled access to these private variables, we've added public accessor
and mutator methods: getBreed() and setBreed(). These methods allow other
parts of the program to read and modify the "breed" variable indirectly while still
maintaining encapsulation and preventing direct access to it.
Example 7
125
}
In this example, we have a class named "Dog" with private member variables
(breed, age, and color). The "Main" class, which is outside the "Dog" class,
attempts to access and modify the private member variable "breed" directly
using the dot operator. Such an attempt violates the rules set by access
modifiers, as private member variables are only accessible within the class where
they are declared. Therefore, attempting to access or modify the "breed" variable
outside the "Dog" class results in compilation errors.
Example 8
In this example, the member variable breed and the method displayBreed()
are declared as public within the "Dog" class. As a result:
126
Let us expand the "Dog" class example to illustrate clearly the class members'
scope.
Example 9
Now, let's create another class called "Main" to demonstrate the scope of class
members. In this "Main" class, we create an instance of the "Dog" class named
"myDog" and initialize it with specific breed, age, and color values. We
demonstrate the scope of the private member variables by attempting to access
the breed variable directly from outside the "Dog" class. However, this results in
a compilation error because we attempted to access private members directly
from outside the class. Instead, we access the public method "displayDetails()" of
the "Dog" class, which internally accesses the private member variables to
display the dog's details.
Example 10
127
// Attempt to access private member variables
//directly (violating encapsulation)
// Compilation error: breed has private access in Dog class
// System.out.println("My dog's breed is: " + myDog.breed);
6.4 Constructors
In this section, we dive into constructors using the example of a "Dog" class.
Constructors are like instructions that tell a program how to create a new object:
They set up everything needed for the object to "exist" in the program. We start
by explaining what constructors are and why they're essential. Then, we will
show how you can have different types of constructors (default and ones where
you give specific details), which help create dogs with different details like name,
age, or breed right from the start.
We also discuss having multiple constructors in the same class, which provide
different options when creating a new object. Being able to pick the constructor
that fits your object's needs makes working with the program easier.
Example 11
Let us now discuss constructors through the "Dog" class. To prepare a Dog object
for use immediately after its creation, we can define a constructor that sets up its
initial state. For example, when we create a Dog object, we should specify its
breed, color, and age immediately. Here's how we might add a constructor to our
"Dog" class:
class Dog {
String breed;
String color;
int age;
128
// Constructor for Dog class
public Dog(String breed, String color, int age) {
this.breed = breed;
this.color = color;
this.age = age;
}
void run() {
System.out.println(breed + " is running...");
}
void play() {
System.out.println(breed + " is playing...");
}
}
When we want to create a new Dog object, we call the constructor and pass in
the specific values for the breed, color, and age of the dog:
In the example above, the Dog constructor takes three parameters (breed, color,
and age) and assigns them to the instance variables of the new "Dog" object
using the “this" keyword. The "this" keyword differentiates between instance
variables and parameters that share the same name.
This above statement creates a new Dog object named myDog, a 3-year-old
white poodle. The constructor ensures that myDog has all its essential attributes
set from the moment it's created, immediately making the object ready for use.
129
Default Constructors: A default constructor doesn't take any parameters. Java
automatically provides one if no other constructors are explicitly defined in the
class. The default constructor initializes the object with default values or
performs default initialization tasks. Let us illustrate using default constructors
with the "Dog" class:
Example 12
class Dog {
String breed;
String color;
int age;
void run() {
System.out.println(breed + " is running...");
}
void play() {
System.out.println(breed + " is playing...");
}
}
We've added a default constructor to the "Dog" class in this example. This
constructor initializes a Dog object with default values: "Unknown" for the breed
and color and 0 for the age.
Using the Constructors: Now, we describe how to create Dog objects using
both types of constructors:
130
// Creating a Dog object using the default constructor
Dog unknownDog = new Dog();
System.out.println("Unknown Dog:");
unknownDog.bark();
unknownDog.run();
unknownDog.play();
In this code snippet, we create two Dog objects: one using the default
constructor (which initializes an "Unknown" dog) and another using the
parameterized constructor (which initializes a "poodle" dog with a specified
breed, color, and age).
Example 13
131
void bark() {
System.out.println(breed + " barking...");
}
void run() {
System.out.println(breed + " is running...");
}
void play() {
System.out.println(breed + " is playing...");
}
}
Unknown Dog:
Unknown barking...
Unknown is running...
Unknown is playing...
Poodle:
Poodle barking...
Poodle is running...
Poodle is playing...
132
6.4.3 Constructor Overloading
Constructor overloading in Java is a technique where a class includes more than
one constructor with different parameter lists. It allows objects in that class to be
initialized in different ways. Overloaded constructors can take different numbers
of parameters or parameters of different types, providing flexibility and
improving code readability by allowing various ways of object instantiation based
on the user context.
Example 14
In this example, we will instantiate three objects in the “Dog" class, each using a
different constructor to demonstrate the versatility provided by constructor
overloading.
// Default constructor
public Dog() {
this.breed = "Unknown";
this.color = "Unknown";
this.age = 0;
}
// Parameterized constructor 1
public Dog(String breed, String color) {
this.breed = breed;
this.color = color;
}
void bark() {
System.out.println(breed + " barking...");
}
void run() {
System.out.println(breed + " is running...");
133
}
void play() {
System.out.println(breed + " is playing...");
}
@Override
public String toString() {
return "Breed: " + breed + ", Color: " + color + ", Age: " + age;
}
System.out.println(unknownDog);
unknownDog.bark();
System.out.println(goldenRetriever);
goldenRetriever.play();
System.out.println(poodle);
poodle.run();
}
}
134
Here is the code output:
The significance of this distinction becomes apparent when you modify the object
inside the method. Since the method references the same object, changes in the
method affect the original object. However, when you attempt to reassign the
object to a new object within the method, the original reference (outside the
method) remains unchanged. This behavior showcases how Java treats object
passing as passing the value of the reference.
Example 15
class Dog {
String name;
int age;
135
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
changeDog(myDog);
In this example, we have a "Dog" class and a "TestDog" class that contains the
main method and a changeDog method. The changeDog method illustrates the
effect of modifying an object passed as an argument.
• The attempt to reassign the dog to a new Dog object inside changeDog
does not change the original myDog object in the main method—the
method receives a copy of the object reference, not a direct link to the
original object.
136
The output will be as follows:
6.6 Conclusion
This chapter comprehensively explored classes and objects in Java. We began by
explaining the fundamental concepts of classes, emphasizing their role as
blueprints for creating objects. Through discussions on constructors, we learned
how to initialize objects, understand their different types, and leverage
constructor overloading for enhanced flexibility.
This chapter also deeply dove into passing objects as arguments in Java
methods, clarifying the differences between passing by value and reference.
Using the "Dog" class as an example, we illustrated how Java handles object
references when they're passed to methods, empowering you to understand how
objects are manipulated and reassigned. From basic class creation to exploring
constructor overloading and object passing, this chapter provided foundational
insights into Java's object-oriented programming principles.
6.7 Exercises
1. Define a "Car" class with properties for make, model, and year.
1.1. Include methods to display car information and update the year.
1.2. Test the class by creating instances and calling its methods. Sample
input/output:
2. Expand the "Dog" class to include a method that calculates and displays the
dog's age in dog years.
137
myDog.displayDogYears(); // Output: Dog Buddy's age in dog years: 35
4. Develop a "Student" class with properties like `name`, `age`, and `grade`.
4.1. Include methods to update the grade and display student information.
4.2. Test the class by creating multiple student instances and modifying their
grades.
5. Expand the "Student" class to include a method that checks if the student is
eligible for graduation (grade is above a certain threshold). Test this method
with different student grades.
6. Enhance the "Dog" class to include methods to check if the dog is a puppy
(age less than 1 year) or a senior dog (age more than 10 years).
138
7. Define a "BankAccount" class with properties like accountNumber, balance,
and accountHolder.
8.1. Develop methods to calculate and display the area and perimeter of the
triangle.
8.2. Test the class by creating instances and calling its methods.
9.2. Test the class with different book instances and transactions.
139
10. Consider the need for a balancing warning as an assigned problem in a
"BankAccount" class. Implement additional functionality to check if the
account balance falls below a certain threshold (say $1,000), triggering an
alert. Test the class with various transactions and alert scenarios.
myAccount.withdraw(600);
myAccount.displayInfo(); // Output: Account Number: 123456789,
Balance: 700, Account Holder: John Doe
myAccount.checkBalanceAlert(); // Output: Alert! Account balance is
below $1000.
140
7 File Handling
7.1 Introduction To File Handling
A file is a named location that can be used to store data and information. For
example, a data file may contain names of different people. Combining the name
with address can be turned into information and store in a file as well.
• The “java.io.file” library can help to create a file object. After importing the
library, the following statement can be used to create a file.
141
7.1.1 Significance of File Handling
Java is a popular programming language. Java allows file handling using its
libraries (e.g., java.io)—which means reading and writing from files. User inputs
can be passed to a java program using file handling. Similarly, a program’s
output can be saved to a file using file handling.
• Reading a file
To read a file, a file must exist otherwise the program trying to read from a file
will encounter a file not found exception. However, when writing into a file that
does not exist, the program will create a new file with the given name. Similarly,
the program should check if the file exists before trying to update (i.e., adding
new content to an existing file) or delete the file.
Example 1
The “File” class provides some built-in helpful methods as listed below in Table 1.
A programmer can use any of the above methods; however, the example below
shows the use of two built-in methods from the File class.
142
Table 1: Different methods, descriptions and their return type from File class
Example 2
import java.io.File;
143
The example above shows a file name is passed to the “File” constructor when
creating an object of File class. Then the object is used to an executable variable
with the help of a built-in function “canExecute()”. Later the “File” object is used
to get absolute path of the file using the “getAbsolutePath()” function.
Example 3
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException
{
String content = null;
File file = new File("my_test_file.txt");
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
System.out.println(content);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
reader.close();
}
}
}
}
The above code block shows how a File object can be used to read a file. Notice
that after creating a File object, it is passed to a FileReader object as a
parameter. Also, notice the reader close(); this is important to free up resources
being used by the file. Of course, the close() needs to be called after the tasks
are performed by the code.
144
location. The example below shows how a File object can be used to print the file
directory information.
Example 4
import java.io.File;
public class Main {
public static void main(String[] args) {
File f = null;
File[] paths;
try {
// create new file in the location /
f = new File("/");
// array of files and directory in the location /
paths = f.listFiles();
// for each file in the path array
for(File path:paths) {
// prints filename and directory name
System.out.println(path.getName());
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
The “isDirectory()" method returns true or false. It returns true if and only if the
file denoted by this abstract pathname or file location is a directory. Otherwise,
the method returns false. The example below shows how a File object can be
used to check if a file path is a directory.
Example 5
import java.io.File;
public class Main {
public static void main(String[] args) {
File f = null;
File f1 = null;
try {
// create new files
f = new File("test.txt");
// create new file in the system
f.createNewFile();
// create new file object from the absolute path
f1 = f.getAbsoluteFile();
145
// prints the file path if is directory
System.out.print("Is directory: "+ f1.isDirectory());
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
Example 6
the “isFile()” method returns true if and only if the file denoted by this abstract
pathname is a file; otherwise, the method returns false.
import java.io.File;
public class Main {
public static void main(String[] args) {
File f = null;
File f1 = null;
try {
// create new files
f = new File("test.txt");
// create new file in the system
f.createNewFile();
// create new file object from the absolute path
f1 = f.getAbsoluteFile();
// prints the file path if is file
System.out.print("Is file: "+ f1.isFile());
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
146
Example 7
import java.io.File;
public class Main {
public static void main(String[] args) {
File f = null;
File f1 = null;
try {
// create new files
f = new File("test.txt");
f.createNewFile();
//rename file
f = new File("test.txt");
f1 = new File("test1.txt");
boolean successr = f.renameTo(f1);
System.out.println("Rename successful: "+ successr);
//delete file
f1 = new File("test1.txt");
boolean successd = f1.delete();
System.out.println("Delete successful: "+ successd);
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
Example 8
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fileReader = new FileReader("my_test_file.txt");
int i;
147
while((i = fileReader.read()) != -1){
System.out.print((char)i);
}
fileReader.close();
}
}
The example code above first checks if the file has something to read. If the file
is empty or reaches to the end-of-file, then it will return -1, and the program will
stop. Otherwise, the program will read each position of characters and convert
and print them.
7.4.2 BufferedReader
The BufferedReader class from the java.io package can be used to read input
from files. It reads a character-input stream using the buffering concept. Thus, it
is efficient in reading characters, arrays, and lines from file input.
Example 9
An example of BufferedReader
First, we create a FileReader object and then pass the FileReader object to the
BufferedReader object. Please note that the file object is taking a String input as
the file name. See the example below for more details.
Example 10
import java.io.FileReader;
import java.io.BufferedReader;
class BufferedReaderExample{
public static void main(String[] args) {
// create an array of character to store the stream-input
char[] charArray = new char[100];
try {
// create a FileReader
FileReader file = new FileReader("my_test_file.txt");
148
// create a BufferedReader
BufferedReader buffer = new BufferedReader(file);
// reads character-input
buffer.read(charArray );
System.out.println("Input from the file: ");
System.out.println(charArray);
catch(Exception e) {
e.getStackTrace();
}
}
}
7.4.3 FileWriter
The FileWriter class from java.io can be used to write in a file. If the file does not
exist, the FileWriter will create the file and write to it.
Example 11
import java.io.FileWriter;
try {
// create a FileWriter object
FileWriter output = new FileWriter("my_output_file.txt");
catch (Exception e) {
e.getStackTrace();
149
}
}
}
The above code first creates an object of FileWriter and passes a filename to it.
The FileWriter object is then used to write in the file using the write method.
Finally, the FileWriter object is used to close the file.
7.4.4 BufferedWriter
One of the drawbacks of FileWriter is that it writes directly to a file, so it is only
good for situations in which a small amount of writing is needed. Additionally, it
is limited to a set number of characters or string length. When it comes to writing
a large text, then BufferedWriter can be good choice. It is almost similar to
FileWriter. However, it uses an internal buffer to write data into files. So, if more
frequent writing is needed, then BufferedWriter is a good choice.
Example 12
import java.io.FileWriter;
import java.io.BufferedWriter;
try {
catch (Exception e) {
e.getStackTrace();
}
150
}
}
Example 13
import java.io.*;
import java.util.Scanner;
class Main {
public static void main(String[] args) throws IOException {
// Open the file.
File file = new File("input.txt");
Scanner inputFile = new Scanner(file);
// Read and display the file's contents.
while (inputFile.hasNext())
{
System.out.println(inputFile.nextLine());
}
// Close the file.
inputFile.close();
}
}
Example 14
import java.io.*;
import java.util.Scanner;
class Main {
151
public static void main(String[] args){
// Open the file.
try{
File file = new File("input.txt");
Scanner inputFile = new Scanner(file);
// Read and display the file's contents.
while (inputFile.hasNext()){
System.out.println(inputFile.nextLine());
}
// Close the file.
inputFile.close();
catch(FileNotFoundException e)
{
System.out.println("There was some problem opening the file");
}
}
}
As mentioned earlier, there could be multiple reasons for having run-time errors
in file handling. Run-time errors are not exactly programming errors. It is
important to handle run-time errors so that a program can continue to function
without disrupting its natural flow. In file handling, there could be several
reasons for having run-time errors. Trying to read a non-existent file and trying
to write to a file that the program or user does not have access to it offer two
examples. This could happen as a program is moved from one system to another.
To avoid this type of unwanted situation, a programmer must use proper
exception handling for file handling. Simple “try ... catch” block can help to ease
the program flow.
152
7.7 Practical Examples and Exercises
Handling CSV files is a major advantage in Java programming. CSV stands for
comma-separated values, which means all the data stored in a CSV file is usually
separated by commas. For example, John, Doe, 2, 998888, USA. The file
extension for a CSV file is .csv.
Example 15
// import libraries
import java.io.*;
import java.util.Scanner;
public class Csv_file_handline {
public static void main(String[] args) throws Exception {
// passing the file name
Scanner sc = new Scanner(new File("test.csv"));
// specifiying the delimiter
// sets the delimiter pattern
sc.useDelimiter(",");
// returns a boolean value
while (sc.hasNext())
{
// find and returns
// the next complete token from this scanner
System.out.print(sc.next());
}
// closes the scanner
sc.close();
}
}
The above example shows step-by-step how to read a CSV file using Java.
Example 16
import java.io.file.Files;
import java.io.*;
import java.util.stream.Stream;
153
public class FileHandlingExamples {
// read in bluk
public static void ReadFile_Files_ReadAllBytes(String fileName)
throws IOException {
//String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
// Line
public static void main(String[] args) throws
FileNotFoundException, IOException {
String filename = "file100KB.txt";
154
long start1 = System.nanoTime();
// reads all at once
ReadFile_Files_ReadAllBytes(filename);
long time1 = System.nanoTime() - start1;
System.out.printf("Read bulk took %.3f seconds\n", time1 / 1e9);
long start2 = System.nanoTime();
// line by line
ReadFile_Files_Lines(filename);
long time2 = System.nanoTime() - start2;
System.out.printf("Read line by line took %.3f seconds\n", time2 /
1e9);
long start3 = System.nanoTime();
// read a character at a time
ReadFile_BufferedReader_Char(filename);
long time3 = System.nanoTime() - start3;
System.out.printf("Read character by character took %.3f seconds\n",
time3 / 1e9);
The above example shows that reading in bulk is faster than reading line by line
and reading character by character. Also, reading line by line is faster than
reading character by character. Which means reading character by character is
the slowest than the rest, and reading in bulk is fastest. The output of the above
program may look like the following:
7.8 Exercise
1. Write a Java program to create a new file.
2. Write a Java program to read the content of a text file and display the
information on the screen.
3. Write a Java program to read the content of a text file (e.g., first.txt) and
write the information on another text file (e.g., second.txt).
155
5. Write a Java program to read a file line by line.
7. Write a Java program to find the line that matches a given word.
8. Write a Java program that allows you to write a new line to an existing file.
The existing file may or may not have content, and the new write should not
remove previous content. Hints: append.
10. Write a Java program to read a file line by line and store it into a variable.
156
References
Chapters 1-5
A modern-day laptop computer–. https://pixabay.com/photos/business-
technology-notebook-laptop-2717063/. Accessed: 7-22-2022.
Tony Gaddis, Soumen Mukherjee, and Arup Kumar Bhattacherjee. Starting out
with Java: From control structures through objects. Pearson Education
International, 2010.
Chapter 6
AppDividend. C++ if-else statements example. https://appdividend.com/
2019/09/05/cif-else-statements-example/
157
Florida State University. Java methods. https://www.cs.fsu.edu/myers/cgs3416/
notes/methods.html.
Gaddis, T., Mukherjee, S., & Bhattacherjee, A. K. (2010). Starting Out with Java:
From Control Structures through Objects. Pearson Education International.
Simplilearn (2023, February 22). What are Java classes and objects and how do
you implement them?. https://www.simplilearn.com/tutorials/java-tutorial/java-
classes-and-objects.
W3resource (2022, August 1). Java string: Exercises, practice, solution. https://
www.w3resource.com/java-exercises/string/index.php.
Chapter 7
A modern day laptop computer–. https://pixabay.com/photos/business-
technology-notebook-laptop-2717063/. Accessed: 7-22-2022.
Tony Gaddis, Soumen Mukherjee, and Arup Kumar Bhattacherjee. Starting out
with Java: From control structures through objects. Pearson Education
International, 2010.
158
Herbert Schildt. Java: The complete reference (ISBN: 978-0-07-180856-9)
What are Java classes and objects and how do you implement them? https://
www.simplilearn.com/tutorials/java-tutorial/java-classes-and-objects.
159