0% found this document useful (0 votes)
2 views30 pages

MCA Lab On Java Programming Unit 1 Introduction To Java

Uploaded by

surajpawar0229
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

MCA Lab On Java Programming Unit 1 Introduction To Java

Uploaded by

surajpawar0229
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lab on Java Programming

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.

Java is a popular programming language for developing a wide variety of


applications like,

● 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.

1.2.1 Arithmetic operators


Arithmetic operators perform basic mathematical calculations on numerical values.
Java provides several arithmetic operators that allow you to perform addition,
multiplication, subtraction, division, and more.

● Addition (+): Adds two values together.


● Subtraction (-): Subtracts the second value from the first.
● Multiplication (*): Multiplies two values together.
● Division (/): Divides the first value by the second.
● Modulus/Remainder (%):Divides the first value by the second value, and then
returns the remainder.
● Increment (++) and Decrement (--): Increases or decreases the value of a
variable by 1.

Example of using Arithmetic Operators in Java:


public class ArithmeticOperatorsExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
// Addition
int sum = num1 + num2;
[Link](“Sum: “ + sum);
// Subtraction
int difference = num1 - num2;

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 program outputs:


Sum: 15
Difference: 5
STUDY NOTE
Product: 50
Quotient: 2 Increment and
Remainder: 0 decrement operators
Increment: 10 can be used in two
Decrement: 5 ways: Pre-increment/
decrement and post-
The program declares two integer variables of increment/decrement.
integer datatype ‘num1’ and ‘num2’ with initial Pre first increments or
values of 10 and 5, respectively. Using the decrements the value
addition operator (+), it calculate the sum of the and then return the
both integers and store it in the variable ‘sum’. updated value. Post
Similarly, it uses the subtraction (-), multiplication returns the current value
(*), division (/), remainder operator (%) to calculate and then increment or
and store the result in variables ‘difference’, decrement it.
‘product’, ‘quotient’, and ‘remainder’ respectively.

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.2.2 Relational Operators


Relational operators in Java are used to compare values and determine the
relationship between them. Relational operators return a boolean value (true or
false) based on the comparison result. Java provides several relational operators
that allow you to compare values.
03
NOTES ● Equal to (==): Compares two values to see if they are equal.
● Not equal to (!=): Determines whether two values are not equal.
● Greater than (>): Checks if first value is greater than second.
● Less than (<): Checks if second value is greater than the first.
● Greater than or equal to (>=): Determines whether the first value is greater
than or equal to the second.
● Less than or equal to (<=): Determines whether the first value is less than or
equal to the second.
Example of using Relational Operators in Java:
public class RelationalOperatorsExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
// Equal to
boolean isEqual = num1 == num2;

[Link](“Is num1 equal to num2? “ +
isEqual);
// Not equal to
boolean isNotEqual = num1 != num2;

[Link](“Is num1 not equal to num2? “ +
isNotEqual);
// Greater than
boolean isGreater = num1 > num2;

[Link](“Is num1 greater than num2? “ +
isGreater);
// Less than
boolean isLess = num1 < num2;

[Link](“Is num1 less than num2? “ +
isLess);
// Greater than or equal to
boolean isGreaterOrEqual = num1 >= num2;

[Link](“Is num1 greater than or equal to
num2? “ + isGreaterOrEqual);
// Less than or equal to
boolean isLessOrEqual = num1 <= num2;

[Link](“Is num1 less than or equal to num2?
“ + isLessOrEqual);
}
}

The program outputs:


Is num1 equal to num2? false
Is num1 not equal to num2? true
Is num1 greater than num2? true
Is num1 less than num2? false
Is num1 greater than or equal to num2? true
Is num1 less than or equal to num2? false
04
The program compares variables ‘num1’ and ‘num2’ using the equal to operator
(==). Since ‘num1’ is 10 and ‘num2’ is 5, they are not equal, so the result is false.
NOTES
Next, The program compares variables ‘num1’ and ‘num2’ using the equal to
operator (!=). Since ‘num1’ is 10 and ‘num2’ is 5, they are not equal, so the result
is true.
Similarly, the program compares the two variables ‘num1’ and ‘num2’ using the
other operators.
1.2.3 Logical Operators
Java uses logical operators to combine many conditions or boolean expressions and
determine the truth value of each. The three logical operators offered by Java are
logical AND, NOT and OR. These operators allow you to perform logical operations
on boolean values and determine the final result.

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);
}
}

The program outputs:


a AND b: false
a OR b: true
NOT a: false

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 operators performs operations on individual bits of integral data types.


Unlike arithmetic, relational, and logical operators, bitwise operators operate on
binary representations of numbers at the bit level.

● 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).

Example of using Bitwise Operators in Java:


public class BitwiseOperatorsExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
// Bitwise AND
int result1 = num1 & num2;
[Link](“Bitwise AND: “ + result1);
// Bitwise OR
int result2 = num1 | num2;
[Link](“Bitwise OR: “ + result2);
// Bitwise XOR
int result3 = num1 ^ num2;
[Link](“Bitwise XOR: “ + result3);
// Bitwise Complement
int result4 = ~num1;
[Link](“Bitwise Complement: “ + result4);
// Left Shift
int result5 = num1 << 2;
[Link](“Left Shift: “ + result5);

06
// Right Shift
int result6 = num1 >> 2;
NOTES
[Link](“Right Shift: “ + result6);
}
}

The program outputs:


Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -11
Left Shift: 40
Right Shift: 2

The bitwise AND of 10 (binary: 1010) and 5 (binary:


0101) results in 0 (binary: 0000) STUDY NOTE

The bitwise OR of 10 (binary: 1010) and 5 (binary: Nested if statements


0101) results in 15 (binary: 1111) allow for multiple levels
of conditional branching,
The bitwise XOR of 10 (binary: 1010) and 5 (binary: enabling the program to
0101) results in 15 (binary: 1111) make decisions based
The bitwise complement of 10 (binary: 1010) on multiple conditions.
results in -11 (binary: 111111111111111111111111111
10101) in two’s complement representation
The left shift of 10 (binary: 1010) by 2 positions results in 40 (binary: 101000)
The right shift of 10 (binary: 1010) by 2 positions results in 2 (binary: 10)

CHECK YOUR PROGRESS


1. Suppose the value of ‘num’ is 10. Consider the code snippet ‘int result =
num++’. What will be the value of ‘num’ after execution of the line of code?
2. The bitwise XOR operator returns true if both operands are true [True/False]
3. The result of a right shift operation is equivalent to dividing the number by 2
raised to the power of the shift amount [True/False]
4. Write a program that converts a decimal number to binary number. Use
appropriate operators and formulas for the calculation.

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.

Example for if statement:


public class IfExample {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
[Link](“The number is positive.”);
}
[Link](“This statement is always executed.”);
}
}

The program outputs:


The number is positive.
This statement is always executed.

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.

Example for if-else statement:


public class IfElseExample {
public static void main(String[] args) {
int number = 0;
if (number > 0) {
[Link](“The number is positive.”);
} else {
[Link](“The number is either zero or nega-
tive.”);
}
[Link](“This statement is always executed.”);
}
}

The program outputs:


The number is either zero or negative.
This statement is always 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.

1.3.3 switch Statement:


Depending on the result of an expression or a variable, the switch statement can
be used to decide which of several code blocks should be run. It has the following
syntax:

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.

Example for switch statement:

public class SwitchExample {


public static void main(String[] args) {
int dayOfWeek = 3;
String dayName;

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;
}

[Link](“The day is: “+dayName);


}
}

The program outputs:


The day is: Wednesday

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.

CHECK YOUR PROGRESS


5. The ___ statement allows you to execute different blocks of code based on
different conditions.
6. The ___ statement is used to select one of many code blocks to be executed
based on the value of a variable or an expression.
7. The condition in an if statement must always evaluate to a boolean value
[True/False]
8. While purchasing certain items, a discount of 10% is offered if the quantity
purchased is more than 100. If quantity and price per item are stored in two
variables, write a program to calculate the total expenses.

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.

1.4.1 while loop:


The while loop repeatedly executes a block of STUDY NOTE
code as long as a specified condition is true. It Java allows to control
has the following syntax: the flow of the
loops using keyword
while (condition) {
‘continue’ and ‘break’.
// code to be executed
The ‘continue’ keyword
}
allows skipping the
Each cycle begins with an evaluation of the current iteration of a
condition. The code block is run if the condition is loop and moving to the
satisfied. The condition is reevaluated after each next iterations, and the
time the code block is executed. The loop keeps ‘break’ keyword allows
running if the condition is still true. The loop ends terminating the loop
if the condition changes to false, and the program entirely.
moves on to the statement that follows the loop.

Example for while loop:


public class WhileLoopExample
{
public static void main(String[] args)
{
int count = 1;
while (count <=5)
{
[Link](“Count: “ + count);
count++;
}
[Link](“While loop has ended.”);
}
}

The program outputs:


Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
While loop has ended.
12
In the example above, a while loop executes a code block as long as the condition
‘count <= 5’ is true. The ‘count’ variable is initially set to 1. The code block inside
NOTES
the while loop prints the current value of ‘count’ and then increments it by 1 using
the ‘count++’ statement.

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.

1.4.2 do-while loop:


While and do-while loops are similar, but there is a small distinction between them.
It runs a block of code at least once before checking the condition. It has the
following syntax:

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.

Example for do-While loop:


public class DoWhileLoopExample
{
public static void main(String[] args)
{
int count = 1;
do
{
[Link](“Count: “ + count);
count++;
}while (count <=5);
[Link](“While loop has ended.”);
}
}

The program outputs:


Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
While loop has ended.

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.

1.4.3 for loop:


The for loop provides a compact way to iterate over a range of values or perform a
specific number of iterations. It has the following syntax:
for (initialization; condition; update) {
// code to be executed
}
The initialization step is executed only once before the loop starts. The condition is
evaluated before each iteration, and if it is true, the code block is executed. After
each execution of the code block, the update statement is executed. Then the
condition is re-evaluated, and if it is still true, the loop continues to execute. If the
condition becomes false, the loop terminates, and the program continues with the
next statement after the loop.
Example of for loop:
public class ForLoopExample
{
public static void main(String[] args)
{
for (int i=1; i<=5; i++) {
[Link](“Count: “ + i);
}
[Link](“For loop has ended.”);
}
}

The program outputs:


Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
For loop has ended.

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.

CHECK YOUR PROGRESS


9. The ___ loop executes a block of code at least once, and then repeatedly
executes the code block as long as a specified condition is true.
10. The initialization in a for loop is executed after each iteration [True/False]
11. All three types of loops (while, do-while, for) can be used interchangeably
[True/False]
12. Write a do-while loop that asks the user to enter two numbers. The numbers
should be added and the sum displayed. The loop should ask the user
whether he or she wishes to perform the operation again. If so, the loop
should repeat; otherwise, it should terminate.

Activity
Use nested loops to print the pattern of Asterisks(*) as given below:
*
**
***
****
*****

1.5
Summary

● Operators in Java are symbols or keywords that perform operations on


operands, allowing tasks such as arithmetic calculations, comparisons, logical
operations, bitwise manipulations, assignment, and more.

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.

Some examples of how Java is being used in India:


Banking and finance: Java is used to develop a variety of applications in the
banking and finance industry, such as online banking systems, mobile banking
apps, and ATMs.

Healthcare: Java is used to develop a variety of applications in the healthcare


industry, such as electronic health records (EHRs), patient portals, and medical
imaging systems.

Manufacturing: Java is used to develop a variety of applications in the manufacturing


industry, such as asset tracking systems, production planning systems, and quality
control systems.

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.

Some of the benefits of using Java in India:


Cost savings: Outsourcing to India can save businesses a significant amount of
money on development costs.

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

SHORT ANSWER QUESTION


1. Implement a program that determines a student’s grade depending on the
grades they receive. Ask the user to enter the marks for different subjects.
Calculate the average marks and display the corresponding grade according to
a predetermined grading scale.
2. Write a program that calculates given number’s factorial. User will enter a
positive integer, and then calculate its factorial using a loop. Display the result
to the user.
3. Create a program to generate a random number between 1 and 100. Prompt
the user to guess the number and provide feedback (higher, lower, or correct)
based on their input. Use a loop to allow the user to continue guessing until
they guess the correct number. Keep track of the number of attempts and
display it once the correct number is guessed.

LONG ANSWER QUESTION


1. Provide an example where you would use a “do-while” loop and a “while” loop
to accomplish the same task in Java. Explain the scenario and the difference
in behavior between the two loops. Discuss when you would prefer to use a
“do-while” loop and when a “while” loop would be more suitable in real-world
programming situations.
2. Design a program that simulates an ATM transaction process. Prompt the
user to enter their account type (savings or checking) and the transaction
type (withdrawal or deposit). Based on the account type and transaction type,
implement the corresponding actions and display appropriate messages to the
user. Use nested if statements to handle different combinations of account
types and transaction types.

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

CHECK YOUR PROGRESS


1. To be solved by student 4. To be solved by student
2. False 5. if
3. True 6. Switch
20
7. True 10. False
NOTES
8. To be solved by student 11. False
9. While 12. To be solved by student

SHORT ANSWER QUESTION


1. import [Link];
public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter the marks for subject 1:
“);
int marks1 = [Link]();
[Link](“Enter the marks for subject 2:
“);
int marks2 = [Link]();
[Link](“Enter the marks for subject 3:
“);
int marks3 = [Link]();
// Calculate average marks
double averageMarks = (marks1 + marks2 + marks3)
/ 3.0;

[Link](“Average marks: “ +
averageMarks);
// Determine the grade based on the average marks
char grade;
if (averageMarks >= 90) {
grade = ‘A’;
} else if (averageMarks >= 80) {
grade = ‘B’;
} else if (averageMarks >= 70) {
grade = ‘C’;
} else if (averageMarks >= 60) {
grade = ‘D’;
} else {
grade = ‘F’;
}
[Link](“Grade: “ + grade);
[Link]();
}
}
2. import [Link];
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter a positive integer: “);
int number = [Link]();
if (number < 0) {
21
NOTES [Link](“Error: Invalid input.
Please enter a positive integer.”);
} else {
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
[Link](“Factorial of “ + number +
“ is: “ + factorial);
}
[Link]();
}
}
3. import [Link];
import [Link];
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Random random = new Random();
int lowerBound = 1;
int upperBound = 100;
int randomNumber = [Link](upperBound -
lowerBound + 1) + lowerBound;
int guess;
int attempts = 0;
[Link](“Welcome to the Number Guess-
ing Game!”);
[Link](“I have selected a random num-
ber between 1 and 100. Try to guess it.”);
do {
[Link](“Enter your guess: “);
guess = [Link]();
attempts++;
if (guess < randomNumber) {
[Link](“Try higher!”);
} else if (guess > randomNumber) {
[Link](“Try lower!”);
} else {
[Link](“Congratulations!
You’ve guessed the correct number: “ + randomNumber);
[Link](“It took you “ + at-
tempts + “ attempts.”);
}
} while (guess != randomNumber);
[Link]();
}
}

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

MULTIPLE CHOICE QUESTIONS


1. In a nested if statement, what happens if a condition in an inner if statement is
false?
a) 
The code block inside the inner if statement will be skipped, and the
program will move to the next outer if statement (if any).
b) The code block inside the inner if statement will be executed, regardless of
the condition evaluation.

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

You might also like