MCA Lab On Java Programming Unit 1 Introduction To Java
MCA Lab On Java Programming Unit 1 Introduction To Java
Introduction
to Java
SELF LEARNING MATERIAL
SEM - I (107)
MCA
UNIT-1 INTRODUCTION TO JAVA
TABLE OF CONTENTS
1.1 Introduction
1.2 Operators in Java
1.3 Control structures in Java
1.4 Iterative statements in Java
1.5 Summary
1.6 Case Study
1.7 Terminal Questions
1.8 Answers
1.9 Assignment
1.10 References
Learning Objectives
• To apply Java operators for performing arithmetic, relational, logical, and bitwise
operations
• To implementing control structures for conditional program execution
• To understand the usage of iterative statements
NOTES
1.1
Introduction
Java is a general-purpose, class-based, object-oriented programming
language designed for having lesser implementation dependencies. It is
a compiled language and not an interpreted language. Any Java Virtual
Machine (JVM) can run the bytecode created from the Java source code.
The runtime environment for Java programs is offered by JVM.
● Mobile applications
● Desktop applications
● Web applications
● Games
● Enterprise applications
● Embedded systems
Advantages of Java:
● Platform independence: Any platform with a JVM installed can execute
Java programs.
● Object-oriented: Because Java is an object-oriented language, writing
modular, reusable code is simple.
01
NOTES ● Security: Java is a secure language that has built-in security features to
protect against common security threats.
● Robustness: Java is a robust language that is designed to be reliable and
efficient.
● Portable: Any platform with a JVM installed can run Java code after it has
been compiled into bytecode.
1.2
Operators in Java
Operators are special symbols or keywords to perform operations on variables,
constants, and expressions. They are used to manipulate data and control the flow
of program execution. Java provides a wide range of operators categorized into
several types, such as arithmetic, logical, relational, and bitwise operators.
02
[Link](“Difference: “ + difference);
// Multiplication
NOTES
int product = num1 * num2;
[Link](“Product: “ + product);
// Division
int quotient = num1 / num2;
[Link](“Quotient: “ + quotient);
// Remainder
int remainder = num1 % num2;
[Link](“Remainder: “ + remainder);
// Increment
int increment = num1++;
[Link](“Increment: “ + increment);
// Decrement
int decrement = num2--;
[Link](“Decrement: “ + decrement);
}
}
The increment operator (++) increments num1’s value by 1 and assigns the result
to the variable ‘increment’. Because, it is a post-increment operator, the variable
‘num1’ value changes after the assignment operation. So, the value 10 is saved in
the variable ‘increment’. Similarly, The decrement operator (--) decreases ‘num2’
value by 1 and result is assigned to the variable ‘decrement’.
1. Logical AND (&&): It returns true if both the left and right operands are true;
otherwise, it returns false.
2. Logical OR (||): If either or both of the operands are true, the logical OR operator
returns true. Otherwise, it returns false.
3. Logical NOT (!): A unary operator that flips the logical state of its operand is
the logical NOT operator. It returns false if the operand is true and true if the
operand is false.
Example of using Logical Operators in Java:
public class LogicalOperatorsExample {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
// Logical AND
boolean result1 = a && b;
[Link](“a AND b: “ + result1);
// Logical OR
boolean result2 = a || b;
[Link](“a OR b: “ + result2);
// Logical NOT
boolean result3 = !a;
[Link](“NOT a: “ + result3);
}
}
In the case of ‘a AND b’ since ‘a’ is ‘true’ and ‘b’ is ‘false’ the result is ‘false’
because both conditions are not satisfied. For ‘a OR b’ the result is true because
at least one of ‘a’ and ‘b’ is ‘true’. The logical NOT operator negates the value of ‘a’,
so the result of ‘Not a’ is false.
05
NOTES 1.2.4 Bitwise Operators
● Bitwise AND (&): Carries out a bitwise AND operation on each operand’s
corresponding bit. If both bits are 1, the outcome is 1, otherwise, it is 0.
● Bitwise OR (|): Performs a bitwise OR operation on each corresponding bit of
the operands. The result is 1 if either of the bits is 1; otherwise, it is 0.
● Bitwise XOR (^): Performs a bitwise exclusive OR (XOR) operation on each
corresponding bit of the operands. The result is 1 if the bits are different;
otherwise, it is 0.
● Bitwise Complement (~): Flips the bits of its STUDY NOTE
operand. It changes 1 to 0 and 0 to 1. Shifting a number to the
● Left Shift (<<): The left-hand operand’s bits left by one position is
are shifted to the left by the number of places equivalent to multiplying
provided by the right-hand operand. Zeros are the number by 2.
inserted into the empty bits on the right. Shifting the number to
● Right Shift (>>): Shifts the left-hand operand’s the right by one position
bits by the number of positions provided by is equivalent to dividng
the right-hand operand, starting at bit position the number by 2.
zero. The vacant bits on the left are filled with
the sign bit (the leftmost bit).
06
// Right Shift
int result6 = num1 >> 2;
NOTES
[Link](“Right Shift: “ + result6);
}
}
Activity
Instead of using integer type, declare two variables of string data type. Analyze
the output of the program produced by using different arithmetic and relational
operators on string variables.
07
NOTES 1.3
Control Structures
Control structures in Java are used to control execution flow of program based on
certain conditions or criteria. These control structures allow you to make decisions,
perform different actions based on different conditions, and switch between
different code blocks. In Java, the main control structures are the if , if-else, and
switch statement.
1.3.1 if Statement:
A block of code is only run by the if statement when a specific condition is met.
This is how the syntax looks:
if (condition) {
// code to execute if the condition is true
}
The code block surrounded in curly brackets will be run if the condition is evaluated
as true. The code block is skipped and the program moves on to the following
statement if the condition is false.
In the example above, if statement checks if the ‘number’ variable is greater than
0. If the condition evaluates to ‘true’, the code block inside the if statement is
executed, which prints the message “The number is positive.” After that, the
program continues to execute the next statement outside the if block, which prints
the message “This statement is always executed.”
If the ‘number’ variable had a negative or zero value, the condition ‘number > 0’
would evaluate to ‘false’, and the code block inside the if statement would be
skipped.
08
1.3.2 if-else Statement:
NOTES
You can run separate pieces of code in response to various conditions using the
if-else expression. It has the following syntax:
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
If the condition is true, the code block inside the if block will be executed. If the
condition is false, the code block inside the else block will be executed.
In the example above, if-else statement checks if the ‘number’ variable is greater
than 0. If the condition evaluates to ‘true’, the code block inside the if statement
is executed, which prints the message “The number is positive.” If the condition
evaluates to ‘false’, the code block inside the else statement is executed, which
prints the message “The number is either zero or negative.” After that, the program
continues to execute the next statement outside the if-else block, which prints the
message “This statement is always executed.”
In this case, since the ‘number’ variable has a value of 0, the condition ‘number
> 0’ evaluates to ‘false’. Therefore, the code block inside the else statement is
executed, and the message “The number is either zero or negative” is printed.
09
NOTES switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// more case statements
default:
// code to execute if none of the cases match
break;
}
The expression in the switch statement is evaluated, and it is then contrasted with
the values in the case statements. If a match is discovered, the associated code
block is run. The switch block is terminated with the break statement. The default
case (optional) code block will be executed if no match is found.
switch (dayOfWeek) {
case 1:
dayName = “Monday”;
break;
case 2:
dayName = “Tuesday”;
break;
case 3:
dayName = “Wednesday”;
break;
case 4:
dayName = “Thursday”;
break;
case 5:
dayName = “Friday”;
break;
case 6:
dayName = “Saturday”;
break;
case 7:
dayName = “Sunday”;
break;
10
default:
dayName = “Invalid day”;
NOTES
break;
}
In the example above, a switch statement evaluates the value of the ‘dayOfWeek’
variable. Based on the value, the corresponding case is executed. In this case,
since the value of ‘dayOfWeek’ is 3, the code block inside the case 3 is executed,
which assigns the value “Wednesday” to the ‘dayName’ variable.
If none of the cases match the value of the ‘dayOfWeek’ variable, the code block
inside the ‘default’ case is executed. In this example, since the value of ‘dayOfWeek’
is valid (between 1 and 7), the default case is not executed.
After the switch statement, the program prints the value of the ‘dayName’ variable,
which is “Wednesday” in this case.
Activity
In a company, worker efficiency is determined on the basis of the time required
for a worker to complete a particular job. If the time taken by the worker is
between 2 – 3 hours, then the worker is said to be highly efficient. If the time
required by the worker is between 3 – 4 hours, then the worker is ordered to
improve speed. If the time taken is between 4 – 5 hours, the worker is given
training to improve his speed, and if the time taken by the worker is more than
5 hours, then the worker has to leave the company. Write a program in Java to
find the efficiency of a worker using if-else if statement.
11
NOTES 1.4
Iterative Statements in Java
Java uses iterative statements, commonly referred to as loops, to continually run
a piece of code until a particular condition is met. There are three main iterative
statements: while, do-while, and for loop.
During the first iteration, the value of count is 1, and it gets printed. The count
is then incremented to 2. This process continues until the value of count
reaches 6, which makes the condition ‘count <= 5’ false. At that point, the
while loop terminates, and the program continues with the next statement
after the loop.
The output shows the numbers from 1 to 5 being printed, and then the message
“While loop has ended” is displayed.
do {
// code to be executed
} while (condition);
The code block is run first in the do-while loop, and then the condition is checked.
The loop keeps running if the condition is true. The loop ends and the program
moves on to the statement that follows it if the condition is false.
13
NOTES In the example above, a do-while loop that executes a code block and then checks
the condition ‘count <= 5’. The ‘count’ variable is initially set to 1. The code block
inside the do-while loop prints the current value of count and then increments it by
1 using the ‘count++’ statement.
The key difference between the do-while loop and the while loop is that the do-
while loop guarantees that the code block is executed at least once before checking
the condition. After the first execution, the condition ‘count <= 5’ is evaluated. If
the condition is true, the loop continues to execute. If the condition is false, the
loop terminates, and the program continues with the next statement after the loop.
In the example above, a for loop that consists of three parts: initialization, condition,
and update. The initialization ‘int i = 1’ is executed once at the beginning of the
loop. The condition ‘i <= 5’ is evaluated before each iteration. If the condition is
true, the code block inside the for loop is executed. After each iteration, the update
‘i++’ statement is executed to increment the value of ‘i’.
14
In this example, the for loop runs for ‘i’ values from ‘i’ to 5. During each iteration,
the current value of ‘i’ is printed. After the value of ‘i’ becomes 6, the condition ‘i
NOTES
<= 5’ evaluates to false, and the for loop terminates. The program continues with
the next statement after the loop, which prints the message “For loop has ended.”
The output shows the numbers from 1 to 5 being printed, and then the message
“For loop has ended” is displayed.
The for loop is commonly used when the number of iterations are known in advance
or when iterating over a range of values. It provides a compact and structured way
to perform a specific number of iterations.
Activity
Use nested loops to print the pattern of Asterisks(*) as given below:
*
**
***
****
*****
1.5
Summary
15
NOTES ● Arithmetic operators in Java perform mathematical calculations on numeric
operands, including addition (+), subtraction (-), multiplication (*), division (/),
and modulus (%), enabling various computations in Java programs.
● Relational operators in Java compare values and determine relationships
between operands, including equal to (==), greater than (>), not equal to (!=),
less than (<), less than or equal to (<=) and greater than or equal to (>=),
facilitating comparisons and decision-making in Java programs.
● Logical operators in Java combine boolean expressions and perform logical
operations, including logical AND (&&), logical OR (||), and logical NOT (!),
allowing for complex boolean evaluations and conditional branching in Java
programs.
● Bitwise operators in Java manipulate individual bits of integer values, including
bitwise AND (&), bitwise XOR (^), bitwise OR (|), left shift (<<), bitwise
complement (~), and right shift (>>), enabling efficient bitwise operations and
bit-level manipulations in Java programs.
● Java’s conditional statements, such as if-else and switch, let programmers
control how code is executed based on specific circumstances or scenarios.
For example, they can pick and run particular code blocks based on the
interpretation of boolean expressions or variable values.
● Java’s “if” statement gives programmers the ability to conditionally execute a
block of code based on the result of a boolean expression, allowing them to
manage the execution of a program and make decisions.
● Java’s “if-else” statement offers a mechanism to run various code segments in
response to the result of a boolean expression, enabling conditional branching
and decision-making within a program.
● Java’s “switch” statement offers a practical method for multi-way branching
based on the result of an expression, enabling the systematic and effective
management of numerous cases or conditions in a program.
● Loop statements in Java, including for, while, and do-while loops, enable
repeated execution of a block of code, allowing for iteration and looping over
a specific range or until a certain condition is met, facilitating efficient and
controlled repetition in Java programs.
● The “for” loop statement in Java provides a concise and structured way to
repeatedly execute a code block for a specified number of iterations, allowing
for efficient looping and iteration over a range of values or elements in arrays or
collections in Java programs.
● The “while” loop statement in Java allows for repeated execution of a code block
as long as a given condition remains true, providing a flexible and controlled
way to iterate and loop until a specific condition is no longer satisfied in Java
programs.
● The “do-while” loop statement in Java executes a block of code at least once,
and then repeats the execution as long as a given condition remains true,
providing a way to ensure that the block of code is executed before evaluating
the loop condition in Java programs.
16
1.6 NOTES
Case Study
Java evaluation in Indian Market
Java is one of the most popular programming languages in the world, and India is
one of the leading countries in Java development. There are many reasons for this,
including:
A large pool of skilled Java developers. India has a large population of skilled Java
developers, many of whom have been trained in top universities and colleges. This
makes it a cost-effective option for businesses to outsource their Java development
needs to India.
As a result of these factors, Java has become a major industry in India. The Indian
Java market is expected to grow at a CAGR of 12.5% from 2022 to 2027. This growth
is being driven by the increasing demand for Java-based applications and services
in a variety of industries, including banking and finance, healthcare, manufacturing,
and retail.
Retail: Java is used to develop a variety of applications in the retail industry, such
as point-of-sale (POS) systems, inventory management systems, and customer
relationship management (CRM) systems.
Java is well-suited for a wide range of applications. The large pool of skilled Java
developers in India, the affordable development costs, and the favorable business
environment make India a great place to outsource Java development.
Access to skilled developers: India has a large pool of skilled Java developers
who are available to work on projects.
17
NOTES Faster development times: Outsourcing to India can help businesses to get their
projects developed faster.
Better quality: Indian developers are known for their high quality of work.
Questions:
1. As India has a large pool of Java developers, Which factors contribute to India’s
prominence in Java development?
2. Discuss about variety of applications used in India and what are some examples
of industries in India that extensively use Java?
1.7
Terminal Questions
18
MULTIPLE CHOICE QUESTION
NOTES
1. What is the result of the expression “10 > 5 && 5 < 2” in Java?
a) true b) false
c) compilation error d) runtime error
2. What is the value of x after executing the following code?
int x = 10;
x += 5;
a) 10 b) 15
c) 5 d) 20
3. Which operator is used for assigning a value to a variable in Java?
a) == b) =
c) + d) *
4. What is the result of the expression “7 % 3” in Java?
a) 2 b) 3
c) 1 d) 0
5. Which of the following is a unary operator in Java?
a) + b) &&
c) > d) /
6. What is the value of y after executing the following code?
int x = 5;
int y = ++x;
a) 4 b) 5
c) 6 d) 10
7. Which operator is used for concatenating two strings in Java?
a) + b) &
c) - d) *
8. What is the value of z after executing the following code?
int x = 10;
int y = 5;
int z = (x > y) ? x : y;
a) 10 b) 5
c) 15 d) 0
9. Which control structure allows you to choose between two or more alternative
paths of execution based on different conditions?
a) if-else b) switch
c) for loop d) while loop
10. Which keyword is used to terminate the execution of a loop in Java?
a) break b) continue
c) exit d) stop
19
NOTES 11. What is the purpose of the “default” case in a switch statement in Java?
a) It is executed when none of the cases match the switch expression.
b) It is executed before any other case in the switch statement.
c) It is executed when the switch expression is equal to 0.
d) It is executed when the switch expression is equal to 1.
12. What happens if the condition of a for loop in Java is omitted?
a) The loop will run indefinitely.
b) The loop will not execute at all.
c) The loop will execute once and then terminate.
d) The loop will execute an infinite number of times.
13. What happens if the condition of an outer if statement is false in a nested if-
else statement?
a) The code block inside the outer if statement will be skipped.
b) The code block inside the outer if statement will always be executed.
c) The code block inside the outer if statement will be executed only if the
inner if condition is true.
d) The code block inside the outer if statement will be executed regardless of
the inner if condition.
14. How many levels of nesting can be used in Java for if statements?
a) Only one level of nesting is allowed.
b) Up to two levels of nesting are allowed.
c) Up to three levels of nesting are allowed.
d) There is no limit to the number of levels of nesting.
15. What is the purpose of the break statement in a loop?
a) To exit the loop and continue with the next iteration.
b) To skip the remaining code inside the loop and move to the next iteration.
c) To terminate the loop completely and continue with the program execution.
d) None of the above
1.8
Answers
22
LONG ANSWER QUESTION
NOTES
1. Let’s consider a scenario where we want to prompt the user to enter a positive
integer and keep asking until a valid input is provided. We can use both a “do-
while” loop and a “while” loop to accomplish this task.
Using a “do-while” loop:
import java. util. Scanner;
public class DoWhileExample {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
int number;
do {
[Link](“Enter a positive integer:
“);
number = [Link]();
} while (number <= 0);
[Link](“You entered a positive inte-
ger: “ + number);
}
}
Using a “while” loop:
import [Link];
public class WhileExample {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
int number;
[Link](“Enter a positive integer: “);
number = [Link]();
while (number <= 0) {
[Link](“Invalid input! Enter a pos-
itive integer: “);
number = [Link]();
}
[Link](“You entered a positive inte-
ger: “ + number);
}
}
Difference in behavior: The main distinction between a “while” loop and a
“do-while” loop is that the latter always runs its code block at least once. After
the first execution, it checks the condition and repeats the loop if the condition
is true. On the other hand, a “while” loop checks the condition before executing
the code block, which means if the condition is initially false, the loop will not
be executed at all.
In the given scenario, if the user enters a non-positive number initially, the “do-
while” loop will execute the code block at least once, prompting the user for
input. The loop will continue until the user enters a positive integer. However,
23
NOTES in the “while” loop, if the user enters a non-positive number initially, the loop
will not execute at all.
When to use “do-while” loop: A “do-while” loop is useful when you want
to execute a block of code at least once, regardless of the condition. It is
commonly used when you need to validate user input or perform an action that
must be executed at least once before checking the condition.
When to use “while” loop: A “while” loop is suitable when you want to
execute a block of code repeatedly based on a condition. It is commonly used
when you want to perform a specific action as long as the condition remains
true.
In real-world programming situations, you would use a “do-while” loop when
you want to ensure that a block of code is executed at least once. This is often
used for input validation or menu-driven programs. On the other hand, a “while”
loop is more suitable when you want to execute a block of code repeatedly as
long as a condition remains true, such as iterating over a collection of data or
running a continuous process.
2. import java. util. Scanner;
public class ATMTransaction {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link](“Enter your account type (sav-
ings/checking): “);
String accountType = [Link]();
[Link](“Enter the transaction type
(withdrawal/deposit): “);
String transactionType = [Link]();
if ([Link](“savings”)) {
if ([Link](“with-
drawal”)) {
[Link](“Performing savings
account withdrawal...”);
// Logic for savings account withdrawal
}
else if ([Link]-
Case(“deposit”)) {
[Link](“Performing savings
account deposit...”);
// Logic for savings account deposit
} else {
[Link](“Invalid transaction
type.”);
}
}
else if ([Link]
(“checking”)) {
if ([Link](“with-
drawal”)) {
[Link](“Performing checking
24
account withdrawal...”);
// Logic for checking account withdrawal
NOTES
} else if ([Link]-
Case(“deposit”)) {
[Link](“Performing checking
account deposit...”);
// Logic for checking account deposit
} else {
[Link](“Invalid transaction
type.”);
}
} else {
[Link](“Invalid account type.”);
}
}
}
MCQS ANSWERS
1. b) False 6. c) 6
2. b) 15 7. a) +
3. b) = 8. a) 10
4. c) 1 9. a) if-else
5. a) + 10. a) break
11. a) It is executed when none of the cases match the switch expression.
12. c) The loop will execute once and then terminate.
13. a) The code block inside the outer if statement will be skipped.
14. d) There is no limit to the number of levels of nesting.
15. c) To terminate the loop completely and continue with the program execution.
1.9
Assignment
25
NOTES c)
The code block inside the inner if statement will be skipped, and the
program will terminate.
d) The behavior depends on the condition of the outer if statement.
2. What is the purpose of the continue statement in a loop?
a) To exit the loop and continue with the next iteration.
b) To skip the remaining code inside the loop and move to the next iteration.
c) To terminate the loop completely and continue with the program execution.
d) None of the above
3. You want to calculate the factorial of a given number. Which control structure
would be most suitable for implementing the factorial calculation?
a) if-else statement b) switch statement
c) for loop d) while loop
4. You are developing a game where players take turns until a specific condition
is met. Which control structure would be most suitable for managing the game
flow?
a) if-else statement b) switch statement
c) for loop d) while loop
5. You are developing a program that requires you to swap the values of two
variables without using a temporary variable. Which bitwise operator can be
used to accomplish this task?
a) & b) |
c) ^ d) ~
QUESTIONS
1. Create a program that acts as a simple calculator. Prompt the user to enter two
numbers and an operator (+, -, *, /). Based on the operator chosen, perform the
corresponding arithmetic operation and display the result.
2. Write a program that generates the Fibonacci series. Prompt the user to enter
the length of the series, and then display the Fibonacci numbers up to that
length using a loop.
3. Write a Java program to print the following complex pattern:
*
***
*****
*******
*********
*******
*****
***
*
4. Create an Armstrong number checker that returns a Boolean TRUE if the input
number is an Armstrong number.
26
5. Write a Java program to simulate a game of Bingo. The program should generate
a random Bingo card and allow the player to mark numbers as they are called.
NOTES
Use nested loops to generate the Bingo card.
The program should simulate the following steps:
1. Generate a random Bingo card consisting of a 5x5 grid with numbers from
1 to 25.
2. Start a loop to simulate calling out numbers.
3. Generate a random number between 1 and 25.
4. Check if the called number is present on the Bingo card.
● If true, mark the called number on the Bingo card and continue to the
next iteration of the loop.
● If false, continue to the next iteration of the loop.
5. Check if the player has achieved a Bingo pattern (e.g., a row, column, or
diagonal with marked numbers).
● If true, display a message indicating the player has won the game and
break out of the loop.
● If false, continue to the next iteration of the loop.
6. Repeat steps 3-5 until the player achieves a Bingo pattern or all numbers
have been called.
7. Display a message indicating the player has lost the game if a Bingo pattern
was not achieved.
1.10
References
Books:
● [Link]
● [Link]
pAMQAACAAJ&redir_esc=y
● [Link]
Learn_It_Well.html?id=4vZJvgAACAAJ&redir_esc=y
Web References:
● [Link]
utm_campaign=20080455599&utm_content=149145304496&utm_term=
learn%20java%20for%20beginners&gclid=CjwKCAjwyqWkBhBMEiwAp2yUF
rjwTrwPazOA32Qu-TRmsZowYVbj_bUbTBExpDDh-4G_k7tnChqwLBoCOq
YQAvD_BwE
● [Link]
● [Link]
● [Link]
27