0% found this document useful (0 votes)
5 views42 pages

MCA Java Programming Unit 1 Introduction To Java

This document serves as a self-learning material for an introductory course on Java programming, covering fundamental concepts such as Java basics, execution of a simple Java program, and the roles of the Java compiler and JVM. It emphasizes Java's platform independence, object-oriented features, and provides step-by-step instructions for setting up the Java Development Kit (JDK) and Eclipse IDE. Additionally, it includes learning objectives, case studies, assignments, and references for further study.

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)
5 views42 pages

MCA Java Programming Unit 1 Introduction To Java

This document serves as a self-learning material for an introductory course on Java programming, covering fundamental concepts such as Java basics, execution of a simple Java program, and the roles of the Java compiler and JVM. It emphasizes Java's platform independence, object-oriented features, and provides step-by-step instructions for setting up the Java Development Kit (JDK) and Eclipse IDE. Additionally, it includes learning objectives, case studies, assignments, and references for further study.

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

Java Programming

Introduction to
Java
SELF LEARNING MATERIAL

SEM - I (103)

MCA
UNIT-1 INTRODUCTION TO JAVA
TABLE OF CONTENTS

1.1 Introduction
1.2 Java Basics
1.3 Executing First Java Program
1.4 Role of Java Compiler and JVM
1.5 Java - Platform Independent and Secure
1.6 Java Data Types
1.7 Control Structures in Java
1.8 Functions in Java
1.9 Summary
1.10 Case Study
1.11 Terminal Questions
1.12 Answers
1.13 Assignment
1.14 References

Learning Objectives
• To execute abasicJava program
• To learn about the data types and control structures
• To implement functions in Java
NOTES

1.1
Introduction
A powerful and flexible programming language is Java, frequently used to
create various applications. It is a well-liked option among programmers all
around the world because of its simplicity, portability, and resilience.

Java’s platform independence is a key advantage. Java programs can be


created on one platform and executed on any other platform with a Java
Virtual Machine (JVM) thanks to its “Write Once, Run Anywhere” approach.
This portability allows Java applications to be deployed across different
operating systems without major modifications. Additionally, Java’s object-
oriented programming approach improves the maintainability, modularity,
and reuse of code, making development easier of complex applications. The
language’s extensive standard library provides pre-built classes and methods
for common programming tasks, saving time and effort. Java also benefits
from a vibrant developer community, offering extensive documentation,
forums, libraries, and frameworks to support Java development.

01
NOTES Some definitions of Java by different authors are given below:

“Java is a programming language designed to be small, simple, and portable


across platforms and operating systems, both at the source and at the binary
level.”
James Gosling

“Java is a class-based, object-oriented programming language that is designed


to have as few implementation dependencies as possible.”
Oracle Corporation

1.2
Java Basics

History of Java
Java’s beginnings may be traced back to the middle of the 1990s, when James
Gosling and a group of Sun Microsystems developers began working on a project
called “Oak.” With an emphasis on portability, security, and simplicity, the team
set out to develop a language and platform for programming consumer electrical
devices like set-top boxes and handheld gadgets.

As the internet started to gain popularity, the team shifted their focus towards
creating a language that could be used for developing applications for the emerging
World Wide Web. Oak was renamed to “Java” to reflect its new direction. The
name “Java” was inspired by a type of coffee grown in Indonesia, reflecting the
team’s appreciation for coffee.

In 1995, Sun Microsystems officially released Java to the public. It quickly gained
attention due to its unique features, such as platform independence and robustness.
Java applets, which were small programs embedded within web pages, became
particularly popular as they allowed for interactive content on websites.

When Java 2 was released in 1998, the language underwent considerable


improvements, including introducing the JVM, which enhanced performance
and portability. A complete set of tools and libraries for Java development, the
Java Development Kit (JDK) and Java 2 Standard Edition (J2SE), were also made
available with Java 2.

Over the years, Java has continued to evolve through various versions and updates.
Notable milestones in Java’s history include the introduction of Java Enterprise
Edition (J2EE) for enterprise application development, Java Micro Edition (J2ME) for
mobile and embedded devices, and the open-sourcing of Java by Sun Microsystems
in 2006, resulting in the creation of the OpenJDK project.
02
In 2010, Oracle Corporation acquired Sun Microsystems, becoming the new
steward of Java. Oracle has continued to release new versions of Java, introducing
NOTES
characteristics like lambda expressions, modularization (Project Jigsaw), and
enhancements to the Java Virtual Machine performance.

Java has remained popular over time and continues to be used extensively for
a wide range of applications, including desktop software, mobile apps, web
development, and business systems. A strong global developer community
supports its extensive ecosystem of libraries, frameworks, and tools.

Features of Java
● Object-oriented programming: Java
follows the object-oriented programming STUDY NOTE
(OOP) paradigm, where programs are Java has a strong
structured around objects that represent emphasis on backward
real-world entities. This approach promotes compatibility, meaning
code reusability, modularity, and easier newer versions of
maintenance. Java aim to maintain
● Platform independence: Java code is compatibility with
transformed into bytecode, which can be run older versions.
on a compatible JVM platform. This “write This allows existing
once, run anywhere” capability makes Java Java applications to
highly portable. run without major
● Garbage collection: Java utilizes garbage modifications on newer
collection to manage memory automatically. Java environments,
The JVM handles memory management, ensuring a smooth
freeing developers from memory-related flaws transition and reducing
and vulnerabilities by eliminating the need for maintenance efforts.
manual memory allocation and deallocation.
● Rich standard library: An extensive collection of class libraries is provided
by Java and Application Programming Interfaces that offer ready-to-use
components for common programming tasks, such as networking, input/
output, database access, and graphical user interfaces (GUI).
● Security: There are security features in Java that protect against malicious
code. The JVM runs Java code in a sandboxed environment, enforcing security
restrictions and preventing unauthorized access to system resources.
● Multithreading: Java offers multithreading capability for concurrent
programming. Multiple threads of operation can be created by developers within
a single program, enabling effective use of system resources and concurrent
task execution.
● Distributed: Java Offers a rich set of features and APIs specifically designed for
distributed computing. One of the key features is Remote Method Invocation
(RMI) which allows objects residing on different Java Virtual Machines to
communicate with each other.

03
NOTES Installations of JDK and eclipse as IDE
Java Development Kit (JDK) needs to be correctly installed on our machine before
starting to writea program. It is a full-featured Java development kit that comes
with everything you might possibly need, such as a compiler, the Java Runtime
Environment (JRE), java debuggers, java manuals, etc. A Java program must be
installed on the system to be written, compiled, and run.
The procedures below should be followed to install Eclipse IDE and the JDK (Java
Development Kit):

JDK Installation:
● Visit the Java SE Downloads section of the Oracle website: Java Downloads |
Oracle.
● Accept the license agreement for the JDK version you want to download.
● Decide which JDK package to download for Windows, macOS, or Linux,
depending on your operating system.
● Run the downloaded installer Now, install the JDK by adhering to the on-screen
directions. (Note the installation directory).

Eclipse IDE Installation:


● Go to [Link] to access the Eclipse website’s
download section. The option “Eclipse IDE for Java Developers” is available.
● Select the appropriate Eclipse package for your operating system (Windows,
macOS, or Linux) and download it.
● Extract the downloaded package to a directory of your choice. This directory
will be referred to as the Eclipse installation directory.
● Configure Eclipse with JDK:
1. Find the “[Link]” file on opening the Eclipse installation directory.
2. Open the “[Link]” file in a text editor, say, Notepad.
3. Include the following line at the file’s beginning:
-vm
[path_to_jdk]/bin/java
(Replace [path_to_jdk] with the actual path to your JDK installation directory).
1. Save and close the “[Link]” file.
● Launch Eclipse:
1. Navigate to the Eclipse installation directory and run the “eclipse” executable
file specific to your operating system.
2. Choose a workspace location where your projects will be stored.
3. Eclipse will start, and you can begin using it as your Java IDE.

After completing these steps, you will have the JDK installed on your system, and
Eclipse will be set up as your Java IDE. You can create new Java projects, write
code, and run Java programs within the Eclipse environment. Remember to set up
project-specific JDK configurations within Eclipse if you have multiple JDK versions
installed on your system.
04
CHECK YOUR PROGRESS
NOTES
1. Java was designed to be _______, so it could run on various platforms,
following the concept of Write Once Run Anywhere.
2. Java helps to reduce the risk of _______ and other programming errors.
3. James Gosling developed Java, which was initially called _____ .
4. Byte code is the program written in ________ form while machine codes are
expressed using alphanumeric characters.

1.3
Executing First Java Program

Let’s write first Java application to print “Hello World!” on screen step-by-step:

Step 1: Go to File > New > Project in Eclipse. This step starts the new Java project.

05
NOTES Step 2: A wizard dialog box opens for a new project. Choose the option “Java
Project” from the given options.

Step 3: A new dialog box appears. Enter the name “HelloWorld” as project name
and click on “Finish”.

06
Step 4: On the project name, select “right click” from the menu. Choose New >
Package from the context menu.
NOTES

Step 5: Enter the package’s name here. For example, we have entered com.
[Link] here:

07
NOTES Click Finish. A freshly created package will show up on the left [Link]’s now time
to write a Java class.

Step 6: To add a new Java class to the package perform a right-click on it and select
New > Class from the context menu:

Step 7: Type “HelloWorld” for the class name and choose to create the main()
method automatically.

08
ClickFinish. The HelloWorld class is now generated.
NOTES
Step 8: Edit the ‘HelloWorld’ java class as per the following code.

package [Link];
public class HelloWorld {
public static void main(String[] args) {
[Link](“Hello World!”);
}
}

Step 9: Execute The Code. Go to the context menu by right-clicking “HelloWorld.


java” and selecting “Run As > Java Application.”

Following the program running, the following output is produced:

09
NOTES A straightforward Java application with the
message “Hello World!” printed to the console is STUDY NOTE
shown in the provided code. It is customary in Java
for the class name and
The package to which the class HelloWorld
file name to match. The
belongs is declared with the line package com.
main class method is
[Link];. The line public
where a Java program’s
class HelloWorld { declares a class named
execution begins when
“HelloWorld.” In Java, every program consists of
it is run by the Java
at least one class, and the class name must match
Virtual Machine (JVM).
the filename (in this case, [Link]). The
Developers may ensure
syntax for the main method declaration is public
that the JVM can find
static void main(String[] args). It is a unique way
the main method and
that acts as the program’s entrance. The main
properly execute the
method is where the Java program begins when
program by following
it is run.
the convention that the
Within the main method, the line [Link]. main class name should
println(“Hello World!”); is used to print the match the program file
text “Hello World!” to the console. The System. name.
[Link]() method is part of the System
class in Java and is used for standard output. The
message inside the double quotes is the text that
will be displayed on the console.

CHECK YOUR PROGRESS


5. In Java, every program must contain a special method called ________ which
serves as the entry point of the program.
6. The ________ statement is used to output text or values to the console in
Java.
7. A Java program can have multiple classes, but only one class can contain the
main method. [True/False]

Activity
Research and gather information on how to run a Java program without using
an IDE. Refer to online tutorial, Java documentation or other relevant resources.
Once, the required information is gathered, write a simple program of printing
“Hello World” on console using a text editor and then compile and execute
program using terminal.

10
1.4 NOTES
Role of Java Compiler and JVM

Java source code is translated by the Java compiler into bytecode that the Java
Virtual Machine can execute. A file with a ‘.class’ extension is created by the
compiler that checks that the code adheres to the syntax and rules of the Java
programming language and contains the produced [Link] ensures that the
source code is converted into bytecode, enabling Java’s platform independence,
and may be executed on any system with a suitable JVM.

Files with [Link] extension that are plain text used to store Java [Link] source
code, which may comprise classes, methods, variables, and other components,
is kept in these [Link] must use the “javac” command containing the Java
source file’s name you want to compile to build Java [Link] example, “javac
[Link].” The source code file is read by the compiler, checks for syntax
errors, and performs various static checks, such as type checking and name
[Link] the source code is valid and contains no errors, the Java compiler
generates bytecode, which is a platform-independent representation of the code.
The compiled byte code is saved in a file with the source’s name file but with the
‘.class’ extension. For example, ‘[Link]’ would produce ‘MyProgram.
class’.

Java Virtual Machine: The generated bytecode is not directly executable by


the operating system. Instead, it is carried out by the JVM, which is in charge of
deciphering or Just-In-Time (JIT) converting the bytecode into hardware-compatible
machine [Link] JVM loads the bytecode from the .class file, starts executing
the program, and displays the output on the console. Use the ‘java’ command and
the class’s name to access the main function to run a Java program that has been
[Link] example: “java MyProgram”.

11
NOTES CHECK YOUR PROGRESS
8. You have developed a Java application called “[Link]” that runs
without any issues on your local machine. However, when you try to run the
same application on a different computer, you encounter an error message
stating “Exception in thread ‘main’ [Link]:
Unsupported [Link] version.” What could be the possible cause of the
“Unsupported [Link] version” error, and how would you resolve it?
9. The JVM is responsible for executing ________ code on different platforms.
10. The Java compiler translates Java source code into machine code directly.
[True/Fase]

1.5
Java - Platform Independent
and Secure

Java is regarded as platform-independent because it can function on various


hardware and operating systems without requiring code adjustments. The following
mechanisms are used to achieve this platform independence:

● Java Virtual Machine: Java applications are transformed into bytecode, a


representation of the source code that is platform-independent. The JVM,
specific to each operating system, interprets this bytecode and executes it.
The JVM functions as a layer of abstraction between the program and the
underlying technology operating system to protect the Java program from
variations in hardware and operating systems.
● Write Once, Run Anywhere (WORA): Java adheres to the adage “write once,
run anywhere.” Once compiled into bytecode, a Java program can be executed
on any system with a compatible JVM installed. This implies that the same Java
program can execute on several platforms like Windows, macOS, Linux, etc.,
without requiring code alterations.
● Java Development Kit (JDK): There are several platforms where the JDK,
which contains the Java compiler (javac), is accessib--le. It enables programmers
to create, build, and package Java applications on a single platform before
disseminating the produced bytecode for execution on several platforms that
support compatible JVMs.
● Secure: Java is often regarded as a secure programming language due to
several key features and design principles that prioritize security.

12
● Bytecode Verification: The Java Virtual Machine executes bytecode created
during the compilation of Java programs. The JVM does bytecode verification
NOTES
prior to execution, which looks for potential security flaws and confirms that
the code complies with specified safety regulations. This verification process
helps prevent malicious code from executing and protects against memory
corruption or other vulnerabilities.
● Memory Management: Java utilizes garbage collection to manage memory
automatically. This function assists in preventing typical security problems like
memory leaks and buffer overflows, which can cause system failures or allow
unauthorised access to private data.
● Security Manager: Java provides a Security Manager class that allows fine-grained
control over the permissions and actions of Java applications. By defining a security
policy, developers can restrict certain operations, such as file access or network
connections, ensuring that Java applications operate within defined boundaries.
● Exception Handling: Errors and exceptions can be handled in an organized
manner thanks to Java’s exception handling mechanism. By catching and
handling exceptions appropriately, developers can prevent sensitive information
from being exposed during error conditions.
● Strong Type System: Java’s strong type system ensures that variables and
data types are well-defined and enforced during compilation. This reduces
the risk of common programming errors, such as type mismatch or incorrect
memory access, which can lead to security vulnerabilities.
● Regular Security Updates: The Java development community, including
Oracle, regularly releases security updates and patches to address any
identified vulnerabilities. These updates help ensure that Java remains secure
and protected against evolving security threats.

CHECK YOUR PROGRESS


11. Memory management, garbage collection, and security checks are
implemented by the _____ and are not dependent on the underlying platform.
12. Oracle consistently releases ________ to help keep the Java ecosystem
protected against emerging security threats.
13. The JVM serves as an _________ layer between the Java program and the
underlying operating system or hardware.

1.6
Java Data Types
Data types
There are numerous built-in data types in Java that let you store and work with
various types of data. 13
NOTES Primitive Data Types Reference Data Types (objects in memory)
Byte: Represents a signed 8-bit String: Represents a sequence of
integer value. characters.
Short: Represents a signed 16- Array: Represents a collection of elements
bit integer value. of the same type.
Int: Represents a signed 32-bit Class: Represents a class type.
integer value. Interface: Represents an interface type.
Long: Represents a signed 64- Enum: Represents an enumeration type.
bit integer value.
Object: Represents the base class for all
Float: Represents a 32-bit Java objects.
floating-point value.
Double: Represents a 64-bit
floating-point value.
Boolean: Represents a boolean
value (true or false).
Char: Represents a single
character (16-bit Unicode).

In addition to these built-in data types, Java also allows to design sophisticated
data structures and encapsulate behaviour within objects by allowing to create
custom data types using classes and [Link] classes are also available
in Java for each primitive data type (e.g., Integer, Double, Boolean) that allow to
treat them as objects and provide additional functionality.

Variables
In a Java application, data is managed and stored via variables. They are designated
memory areas that store particular types of values. Before they may be used, they
must first be declared. The declaration includes the variable’s data type, name, and
sometimes, an initial value. For example,

int age; //Declaration


double pi = 3.14159; //Declaration with initialization

Naming Conventions: In Java, variable names


must adhere to particular conventions. They STUDY NOTE
must start with a letter, underscore, or dollar Java’s operator’s
sign and may be followed by letters, numbers, precedence and
underscores, or dollar signs. ‘age’ and ‘Age’ are associatively control the
regarded as separate variables in Java because of order in which operators
its case-sensitivity. in an expression are
assessed to ensure
Each variable has a scope that specifies the area
accurate computation
of the program where it is accessible and visible.
and prevent ambiguity.
The surrounding piece of code, such as a method,
loop, or if statement, usually establishes the
scope. A block’s stated variables are only accessible within that block and cannot
be accessed outside.
14
Operators
NOTES
Java offers a number of operators that let you carry out various operations on
variables and values.

Arithmetic Operators: Assignment Operators:


Addition Operator: + Assignment Operator: =
Subtraction Operator: - Addition Assignment: +=
Multiplication Operator: * Subtraction Assignment Operator: -=
Division Operator: / Multiplication Assignment Operator: *=
Modulo (remainder) Operator: % Division assignment Operator: /=
Modulo assignment Operator: %=

Comparison Operators: Bitwise Operators:These operators


Equal to: == perform operations on individual bits of
integers.
Not equal to: !=
Bitwise AND: &
Greater than: >
Bitwise OR: |
Less than: <
Bitwise XOR (exclusive OR): ^
Greater than or equal to: >=
Bitwise complement: ~
Less than or equal to: <=
Left shift: <<
Right shift: >>
Unsigned right shift: >>>

Logical Operators:These operators Increment and Decrement Operators:


perform logical operations on Increment by 1: ++
boolean values and expressions.
Decrement by 1: --
Logical AND (Return ‘true’ if both
The pre-increment/decrement operators
operands are true. Otherwise, return
increments/decrements the value of a
‘false’): &&
variable by 1 before using the updated
Logical OR (Return ‘true’ if either value. The post-increment/decrement
of the operands is true. Otherwise, operator increments/decrements the
return ‘false’) : || value of a variable by 1 after using the
Logical NOT (Negates the boolean current value in an expression.
value): !

Ternary Operator:
condition? expression1: expression2:
Evaluates a condition and returns
either ‘expression1’ or ‘expression2’
based on the result. If the conditions
is ‘true’. It evaluates ‘expression1’,
otherwise it evaluates ‘expression2’.

15
NOTES Expressions
In Java, expressions are combinations of operators, variables, and constants that
produce a value. They are used to perform calculations, make comparisons, and
produce results within a program. For example,

int score;
score = 90;

Here, “score = 90” is an expression that returns an int.

Double a = 2.2, b = 3.4, result;


result = a + b - 3.4;

Here, “a + b - 3.4” is an expression.

Type Cast and Type Conversion


Type casting in Java involves explicitly converting one data type to another, typically
when the target type can accommodate the source type. The target type should be
enclosed in parentheses before the value or expression being cast to indicate that
type casting is taking place.

int x = 10;
double y = (double) x; // Explicitly casting int to double

In this instance, the value of x is explicitly transformed to a double type by enclosing


double in parenthesis. The toy is given the value that results.

Type conversion in Java refers to the procedure for altering a variable’s data
type, expression implicitly or explicitly. Type conversion can involve both widening
(implicit) and narrowing (explicit) conversions.

Without losing any information, a value of a smaller data type is automatically


converted to a larger data type precision or data, a process known as widening
conversion or implicit type conversion. This conversion is performed by the Java
compiler.

public class TypeCastingExample {


public static void main(String[] args) {
int x = 7;
//automatically converts the integer type into long
type
long y = x;
//automatically converts the long type into float type
float z = y;
[Link](“Before conversion, int value “+x);
[Link](“After conversion, long value “+y);
[Link](“After conversion, float value “+z);
}
}

16
The program outputs:
NOTES
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0

In the above program, the integer variablexis automatically converted to a long


type. This is because a long data type can accommodate larger values than an
int data [Link] long variableyis automatically converted to a float type. This
is because a float data type can handle decimal values, while a long data type
cannot.

Narrowing conversion is the process of converting a value from a wider data type
to a narrower one sometimes known as explicit type conversion. This process may
cause data loss or loss of precision. When converting a type directly, the intended
type is stated in parentheses before the value is cast.

public class TypeConversionExample {


public static void main(String[] args) {
double num = 3.14;
// Explicit type conversion (narrowing)
int result = (int) num; // double to int
[Link](“Result: “ + result);
// String to numeric conversion
String str = “123”;
int num1 = [Link](str);
double num2 = [Link](str);
[Link](“Num 1: “ + num1);
[Link](“Num 2: “ + num2);
}
}

The program outputs:


Result: 3
Num 1: 123
Num 2: 123.0

In the above program, The line int result = (int) num; explicitly converts the
double value 3.14 to an int type using type casting (narrowing conversion). The
decimal part is truncated, and the resulting value is assigned to the variable result.
The output will be: Result: 3. The line int num1 = [Link](str);
converts the string “123” to an int type using the [Link]() method.
The string is parsed as an integer value, and the resulting value is assigned to
the variable num1. The output will be: Num 1: 123. The line double num2 =
[Link](str); converts the string “123” to a double type using
the [Link]() method. The string is parsed as a double value, and
the resulting value is assigned to the variable num2. The output will be: Num 2:
123.0.

17
NOTES CHECK YOUR PROGRESS
14. The value of a variable can be changed using the _______________ operator.
15. Identify the output:
double num= 4.25
int result = (int) num;
[Link](result);
16. Find the value:
!(true && false) || true

Activity
Think of practical scenarios where pre-increment/decrement or post-increment/
decrement operators can be useful. Engage in a class discussion to improve
understanding and clear doubts.

1.7
Control Structures in Java

1.7.1 if and if-else Statements


if and if-else statements are used in Java for conditional branching, enabling to
modify the course of your program depending on specific circumstances.

if statement:

For Java conditional execution, use the if


statement. It enables the specification of a block of
code that will only run in specified circumstances.
The syntax is as follows: False
Condition
if (condition) {
True
// code to be executed if the
condition is true
if Condition
}

This is shown using the below flowchart:


username code
For example:

int num = 15;


if (num> 0) {
18
[Link](“The number is positive.”);
}
NOTES
The if statement in the example above determines whether the value of num is
larger than 0. Since the condition is true, the code block inside the if expression is
executed (15 is greater than 0) is true, printing “The number is positive” as output.

if-else statement:

The if-else clause offers another course of action. Which block of code will execute
when a condition is true and which block will execute when the condition is false
can be specified. The following is the syntax:

if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}

This is shown using the below flowchart:

START

If Condition

True False

If Body Else Body

Statement Just Below If

Exit

For example:
int num = -5;
if (num> 0) {
[Link](“The number is positive.”);
} else {
[Link](“The number is negative.”);
}

In the illustration above, the if-else clause determines whether the value of num is
larger than 0. The code block inside the else statement is performed because the
condition is false (-5 is not greater than 0), printing “The number is negative” as
output.

19
NOTES 1.7.2 Switchstatement

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.

switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
// more case statements...
default:
// code to be executed if expression doesn’t match any
case
}

This is shown using the below flowchart:

Switch
Conditional Statement

True Statement
Case 1 Break;

False

True Statement
Case 2
Break;

False

True Statement
Case 3 Break;

False

True Statement
Case n
Break;

True Statement
Default
Break;
Statement
after Switch

For example:
int day = 2;
String dayName;
switch (day) {
case 1:
20
dayName = “Sunday”;
break;
NOTES
case 2:
dayName = “Monday”;
break;
case 3:
dayName = “Tuesday”;
break;
// ...
default:
dayName = “Invalid day”;
}
[Link](“Today is “ + dayName);

In the above example, the switch statement checks the value of the variable day
and matches it with different cases. In this case, the value of day is 2, so the code
block under the case 2 is executed. It assigns the value “Monday” to the variable
dayName. Finally, it prints “Today is Monday” as output.

1.7.3 Loops
Using loops, a block of code can be repeated several times depending on specific
criteria.

while loop:
While a defined condition is true, a while loop runs a code block repeatedly. It is
helpful when the number of iterations is not known in advance. The syntax is as
follows:

while (condition) {
// code to be executed
}

Java’s while loop determines whether a given condition is true or false. If the
condition is met, the statements that make up the loop’s body are executed; if not,
control is transferred to the first statement after the loop. The loop’s body keeps
running as long as the condition is still true. Statements that update the variable
being processed for the following iteration often make up the loop body. The loop
ends, ending the condition’s life cycle if it evaluates to false.

This is shown using the below flowchart:

Condition If true
Start Statement
Checking

If false

21
NOTES For example,

int count = 1;
while (count <= 5) {
[Link](“Count: “ + count);
count++;
}

In the above example, the while loop checks if the value of count is less than or equal
to 5. As long as the condition is true, the code block inside the while loop is executed. It
prints the current value of count and increments it. The loop continues until the condition
becomes false.

do-while loop:
While the do-while loop is comparable to the while loop, it ensures that the code
block is run at least once, regardless of whether the condition is true. As for the
syntax:

do {
// code to be executed
} while (condition);

The do-while loop is an exit control loop that starts by carrying out the statement(s)
for the first iteration without doing any condition checks. The condition is tested for
a true or false value after the statements have been executed and the variable value
has been updated. The loop moves on to the following iteration if the condition
is true. It keeps repeating until the condition evaluates to false, at which point
the loop’s life cycle is complete. Importantly, the do-while loop ensures that each
statement is carried out at least once before the condition is checked.

This is shown using the below flowchart:

If true

Condition
Start Statement Checking

If false

END

For example:

int count = 1;
do {
[Link](“Count: “ + count);
count++;
} while (count <= 5);

22
The do-while loop initially executes the code block within the do statement in the
example above. It increments the count while printing the most recent value. The
NOTES
condition count = 5 is then verified. The loop keeps running if the condition is true.
The loop ends if the condition is false.

Difference between while and do-while loop:


While loop Do-while loop

The condition is examined before Before verifying the condition, the do-
executing the while loop’s main while loop performs the body of the loop
body. If the condition is initially false, first. This guarantees that the body of the
the loop’s body is never executed. loop is executed at least once, even if the
condition is satisfied right away.
Depending on whether the condition is Regardless of the starting value of the
true or false at the start, the loop may condition, at least one execution of the
or may not execute. loop’s body is ensured.
int i = 5;
while (i< 5) {
[Link](“Inside while loop”); // This code is nev-
er executed because the condition is false initially.
}
int i = 5;
do {
[Link](“Inside do-while loop”); // This code is
executed once, regardless of the condition.
} while (i< 5);

for loop:
A block of code can be run repeatedly for a predetermined number of times using the
for loop. It offers a clear method for setting up, checking, and updating a loop variable.
A useful technique for iterating a predetermined number of times is the for loop.
Its three parts are initialization, condition, and iteration statement. The condition
is checked once at the beginning and once before each repetition. The iteration
statement is carried out at the end of each iteration. The syntax is:

for (initialization; condition; iteration) {


// code to be executed
}

This is shown using the below flowchart:

Increment/
Decrement

Condition If true
Start Initialization Statement
Checking

If false

END
23
NOTES For example:

for (int i = 0; i< 5; i++) {


[Link](“Count: “ + i);
}
In the above example, the for loop initializes
the loop variablei to 1, checks ifiis less than or STUDY NOTE
equal to 5, executes the code block, and then Lambda expressions
incrementsi by 1. This process continues untiliis were introduced in
no longer less than or equal to 5. Java to allow for writing
The break and continue keywords are control flow concise and functional-
statements used within loops in Java to modify style code. These
the execution of the [Link] statement is simplify the creation
used to terminate the loop prematurely. When of small, anonymous
encountered, it immediately exits the loop, functions, making the
skipping any remaining [Link] code more readable and
statement is used to skip the current iteration expressive.
of the loop and proceed to the next iteration. It
allows you to bypass certain iterations based on a specific condition.

CHECK YOUR PROGRESS


17. The condition in a for loop is optional, and you can omit it if you want an
infinite loop. [True/False]
18. In a while loop, the code block is executed at least once, even if the condition
is initially false. [True/False]
19. In a switch statement, the default case must be placed at the end after all
the case blocks. [True/False]

Activity
Think of practical scenarios where pre-increment/decrement or post-increment/
decrement operators can be useful. Engage in a class discussion to improve
understanding and clear doubts.

1.8
Functions in Java
A function in Java is a section of code that executes one particular task several
times throughout a program. Modularity and reusability of functions comes from
their ability to condense a group of instructions into a single entity. They have the

24 ability to take inputs, carry out processes, and, if desired, return a value.
Need of functions:
NOTES
● Code Reusability: Functions allow you to write reusable code that can be called
from different parts of a program, reducing code duplication and improving
maintainability.
● Modularity: Code can be made more understandable and easier to maintain
by using functions to group it into logical pieces. Each function completes a
certain purpose, improving the readability of the code.
● Abstraction: Functions provide an abstraction layer by hiding the
implementation details. Other parts of the program can use a function without
knowing how it is implemented internally.
● Encapsulation: Functions encapsulate a set of instructions, data, and
operations, promoting better code organization and reducing complexity.
● Division of Labor: Functions allow developers to divide a program’s functionality
into smaller, manageable parts, enabling teams to work on different functions
concurrently.
● Code Structuring: Functions facilitate the structuring of complex programs
by breaking them down into smaller, more manageable units, improving code
organization and maintainability.

Syntax:
returnTypefunctionName(parameterType parameter1, parameterType
parameter2, ...) {
// Function body
// Code to be executed
// Optional return statement
}

Example:

public class Calculator {


public static int add(int numA, int numB) {
int sum = numA + numB;
return sum;
}
public static void main(String[] args) {
int result = add(5, 3);
[Link](“The sum is: “ + result);
}
}

The program outputs:


The sum is: 8

A function called add is defined in the example above, and it has two integer
parameters, numA and numB. The result of the function’s addition of numA and
numB values is saved in the variable total. The function then returns the sum
value.

25
NOTES The add function is called in the main method with the arguments 5 and 3, and the
result variable is then used to store the returned value.
The [Link] statement then prints the message “The sum is: “
followed by the value of result.
So, when the program is executed, it will output “The sum is: 8” since the add
function performs the addition of 5 and 3, resulting in 8.
Java uses pass-by-value for all method invocations. For primitive types, the value
itself is passed, and for objects, the reference to the object is passed by value.

Pass-by-Value:
Java allows for the passing of arguments to methods as values. This indicates that
a copy of the value, rather than the original variable itself, is produced and supplied
to the procedure. The original variable outside the method is unaffected by any
modifications made to the parameter inside the method.

For example:
public class PassByValueExample {
public static void modifyValue(int value) {
value = 10;
[Link](“Inside method: “ + value);
}
public static void main(String[] args) {
int number = 5;
[Link](“Before method call: “ + number);
modifyValue(number);
[Link](“After method call: “ + number);
}
}

The program outputs:


Before method call: 5
Inside method: 10
After method call: 5

Pass-by-Reference for Objects:


It’s vital to remember that even though Java uses pass-by-value, an object reference
is supplied to a method as its value. This indicates that even when the method
obtains a copy of the reference, it points to the same memory object. Because of
this, any modifications made to the object’s state (such as changing its properties)
within the method will impact the original object.

For example:
public class ParameterPassingExample {
public static void modifyPersonName(Person person) {
[Link](“John”); // Changes the ‘name’ property of the
original Person object.
}
public static void main(String[] args) {
26
Person p = new Person(“Alice”);
modifyPersonName(p);
NOTES
[Link]([Link]()); // Output: John
}
}
class Person {
private String name;
public Person(String name) {
[Link] = name;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
}

Output:
John

Return Statement:
Java methods employ the return statement to return values. The sort of value that
a method will return is determined by its return type. When a method’s return
statement is encountered, the method’s execution is interrupted, and the caller
receives the provided value (if any).

For example:
public class ReturnExample {
public static int calculateSum(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
int result = calculateSum(3, 5);
[Link](“The sum is: “ + result);
}
}

The program outputs:


The sum is: 8

Static Methods
Instead of being linked to a class instance, static methods are part of the class
itself. They are useful for utility methods or calculations that don’t require storing
state because they may be accessed directly by the class name.

For example,
public class MathUtils {
public static int multiply(int num1, int num2) {
27
NOTES }
return num1 * num2;

public static void main(String[] args) {


int result = [Link](5, 3);
[Link](“The product is: “ + result);
}
}

The program outputs:

The product is: 15

A class called MathUtils was built in the example above, and its static function
was called multiply. It is not necessary to build a MathUtils class instance in order
to use the static method. Instead, the method is called directly by utilizing the
class name ([Link]) and the method name. The method receives the
necessary arguments, and the returned value is put into the result variable.

CHECK YOUR PROGRESS


20. Functions are invoked using their name, followed by parentheses and any
required arguments, from the main method or another function. [True/False]
21. Functions declared as static in Java belong to the class rather than an
instance of the class. [True/False]
22. Functions in Java can have the same name as long as the number or types
of their parameters differ. [True/False]

Activity
Explore the role of static functions in enhancing efficiency, code reusability,
performing optimization, or simplifying complex tasks. Present your research
findings, discussing the specific use cases, benefits and challenges associated
with it.

1.9
Summary

● Java is a widely-used programming language known for its platform


independence and object-oriented approach.
● The JDK (Java Development Kit) is a software development environment that
offers resources for creating Java programs, including tools and libraries.
28
● Eclipse is an integrated development environment (IDE) widely used for Java
programming. It provides a user-friendly interface for writing, compiling, and
NOTES
debugging Java code.
● Platform independence is achieved by Java program’s ability to execute on any
system that has the Java Virtual Machine (JVM) installed.
● Java has built-in security features, such as a sandbox environment, bytecode
verification, and automatic memory management, which help prevent security
vulnerabilities.
● Java supports various data types, including primitive types (e.g., int, double)
and reference types (e.g., String, Arrays).
● Variables are used to store and manipulate data in Java. They have a data type
and can be assigned values.
● Java provides various operators, such as arithmetic, assignment, comparison,
logical, and bitwise operators, to perform operations on data.
● Expressions are combinations of operators, variables, and literals that produce
a value when evaluated.
● Type casting is the process of converting one data type to another, while type
conversion is the automatic conversion between compatible data types.
● Control statements, such as if, if-else, switch, while, do-while, and for, are used
to control the flow of execution in a program.
● Functions in Java are blocks of code that perform specific tasks. They can
accept parameters, return values, and provide code modularity and reusability.
● Java passes function arguments by value, meaning a copy of the value is
passed to the function, and modifications inside the function do not affect the
original variable.
● Functions can return values using the return statement. The return type specifies
the type of value returned by the function.
● Static methods belong to a class and can be accessed without creating an
instance of the class. They are invoked using the class name.
● Java concepts related to variables, operators, expressions, control statements,
and functions were presented in a true/false format to test understanding.

1.10
Case Study

Type casting and conversion in digital payment platform Paytm


Paytm, founded by Vijay Shekhar Sharma, started as a mobile wallet service but has
evolved into a comprehensive digital payments platform in India. Paytm facilitates
various types of financial transactions, including mobile recharges, bill payments,
ticket bookings, and online shopping.
29
NOTES Paytm deals with different data types and performs conversions to ensure
seamless financial transactions. For example, when a user adds funds to their
Paytm wallet, the system accepts various types of inputs, such as integers for
whole numbers or floating-point numbers for decimal values. Paytm’s backend
system utilizes appropriate type casting and conversion techniques to process
these inputs accurately.

Additionally, Paytm supports various payment methods, including credit cards,


debit cards, net banking, and UPI (Unified Payments Interface). During payment
processing, Paytm handles different data formats, such as converting user-provided
card details into encrypted formats for secure transactions. These conversions
involve type casting and data conversion techniques to ensure compatibility and
consistency in data handling.

Paytm’s digital payment platform showcases the importance of type casting and
conversion in real-world scenarios. The company’s system utilizes these techniques
to handle diverse data inputs, perform calculations, and ensure data integrity and
security throughout the payment process.

Questions:
1. How do you think Paytm’s use of type casting and data conversion techniques
contributes to a seamless user experience during financial transactions? Explain
the potential challenges that Paytm may face in handling diverse data inputs
and ensuring accuracy in processing.
2. Discuss the significance of data integrity and security in Paytm’s digital
payment platform. How do you think the proper implementation of type casting
and conversion techniques helps Paytm in maintaining the confidentiality and
integrity of user data, particularly during payment processing and encryption of
sensitive information?

1.11
Terminal Questions

SHORT ANSWER QUESTIONS


1. Write a Java program to find the largest number among three given integers
using conditional statements.
2. Write a Java program to calculate the factorial of a given number.
3. How can you check if a given string is a palindrome or not using loops?

30
LONG ANSWER QUESTIONS
NOTES
1. You are building a program that calculates the grade for a student based on their
exam scores. The program should prompt the user to enter three exam scores
(each out of 100) and calculate the average score. Based on the average score,
use if-else statements to determine the corresponding letter grade according
to the following criteria:
● Average score 90 or above: A
● Average score between 80 and 89: B
● Average score between 70 and 79: C
● Average score between 60 and 69: D
● Average score below 60: F Display the calculated average score and letter
grade as output. Handle any exceptional cases, such as scores outside the
valid range or invalid inputs.
2. You’re creating a computer software to mimic a guessing game. A random
number between 1 and 100 should be generated by the computer, and the
user should then be asked to estimate it. Use a do-while loop to ask the user
for their estimate several times until they get it right. After each guess, give
the user relevant feedback letting them know if their guess was too high or too
low. When the right number is guessed, show how many tries it took the user
to get it right.

MCQ QUESTIONS
1. What is the output of the following Java code snippet?
public class MyClass {
public static void main(String[] args) {
String str1 = “Test”;
String str2 = new String(“Test”);
[Link](str1 == str2);
}
}
a) true b) false
c) Compilation error d) Runtime exception
2. Which of the following statements is true regarding the “static” keyword in
Java?
a) A static variable is initialized when an object of the class is created.
b) A static method can access instance variables directly.
c) Static methods can be overridden in Java.
d) Static variables are shared among all instances of the class.
3. What is the purpose of the Just-In-Time (JIT) compiler in the JVM?
a) It compiles Java source code into bytecode.
b) It interprets the bytecode and executes it.
c) It optimizes the bytecode and compiles it into machine code.
d) It manages memory allocation and garbage collection.
31
NOTES 4. Which of the following variable declarations is NOT valid in Java?
a) int myNumber = 10;
b) float pi = 3.14;
c) String name = “John”;
d) double 3.5 = 3.5;
5. What is the default value of a boolean variable in Java if it is not explicitly
initialized?
a) true b) false
c) null d) 0
6. What is the role of the JDK (Java Development Kit) in Java programming?
a) It provides the Java Virtual Machine (JVM) for executing Java programs.
b) It includes the Java compiler for converting Java source code into bytecode.
c) It provides the Java Runtime Environment (JRE) for running Java applications.
d) It manages memory allocation and garbage collection in Java programs.
7. What is the purpose of the “java” command in the JDK?
a) It is used to compile Java source code.
b) It is used to execute a compiled Java program.
c) It is used to create JAR (Java Archive) files.
d) It is used to manage the Java classpath.
8. Which of the following operators has the highest precedence in Java?
a) Assignment operators (e.g., =, +=, -=)
b) Logical operators (e.g., &&, ||)
c) Unary operators (e.g., ++, --)
d) Arithmetic operators (e.g., +, -, *, /)
9. What is the output of the following code snippet?
int x = 2;
switch (x) {
case 1:
[Link](“A”);
case 2:
[Link](“B”);
case 3:
[Link](“C”);
break;
default:
[Link](“D”);
}
a) B b) B C
c) B C D d) D

32
10. What is the output of the following code snippet?
int x = 10;
NOTES
if (x > 5) {
if (x < 15) {
[Link](“A”);
} else {
[Link](“B”);
}
} else {
[Link](“C”);
}
a) A b) B
c) C d) Compilation error
11. What is the output of the following code snippet?
int i = 0;
while (i< 5) {
[Link](i + “ “);
i = i + 2;
}
a) 0 1 2 3 4 b) 0 2 4
c) 0 2 4 6 8 d) Compilation error
12. Which loop statement in Java is best suited for situations where the number of
iterations is known before the loop starts?
a) while loop
b) do-while loop
c) for loop
d) All of the above
13. Which of the following is NOT a valid way to call a function in Java?
a) functionName();
b) functionName;
c) [Link]();
d) [Link]();
14. Which of the following is a valid way to call a static method in Java?
a) [Link]();
b) [Link]();
c) methodName();
d) [Link]();
15. Which of the following is not a valid data type in Java?
a) boolean b) character
c) decimal d) long

33
NOTES 1.12
Answers

CHECK YOUR PROGRESS


1. Portable 12. security updates
2. memory leaks 13. abstraction
3. Oak 14. assignment (=) operator
4. binary 15. To be solved by student
5. main 16. True
6. [Link] 17. True
7. True 18. False
8. To be done by students 19. False
9. bytecode 20. True
10. False 21. True
11. JVM 22. True

SHORT ANSWER QUESTIONS


1. import [Link];
public class LargestNumber {
public static void main (String [] args) {
Scanner scanner = new Scanner ([Link]);
[Link](“Enter three numbers: “);
int num1 = [Link]();
int num2 = [Link]();
int num3 = [Link]();
int largest = num1;
if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}
[Link](“The largest number is: “ + largest);
}
}
2. import [Link];
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter a number: “);
int number = [Link]();

34
int factorial = 1;
if (number >= 0) {
NOTES
for (int i = 1; i<= number; i++) {
factorial *= i;
}
[Link](“The factorial of “ + number + “ is: “
+ factorial);
} else {
[Link](“Factorial is not defined for negative
numbers.”);
}
}
}
3. public class PalindromeChecker {
public static void main (String [] args) {
String input = “madam”; // Change this to your in-
put string
booleanisPalindrome = true;
for (int i = 0; i<[Link]() / 2; i++) {
if ([Link](i) != [Link](input.
length() - 1 - i)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
[Link](input + “ is a palindrome.”);
} else {
[Link](input + “ is not a palindrome.”);
}
}
}

LONG ANSWER QUESTIONS


1. import [Link];
public class GradeCalculator {
public static void main (String [] args) {
Scanner scanner = new Scanner ([Link]);
[Link](“Enter three exam scores (out of 100):”);
int score1 = [Link]();
int score2 = [Link]();
int score3 = [Link]();
if (isValidScore(score1) &&isValidScore(score2)
&&isValidScore(score3)) {

double averageScore = (score1 + score2 + score3)
/ 3.0;
[Link](“Average Score: “ + averageScore);

35
NOTES if (averageScore>= 90) {
[Link](“Letter Grade: A”);
} else if (averageScore>= 80) {
[Link](“Letter Grade: B”);
} else if (averageScore>= 70) {
[Link](“Letter Grade: C”);
} else if (averageScore>= 60) {
[Link](“Letter Grade: D”);
} else {
[Link](“Letter Grade: F”);
}
} else {
[Link](“Invalid score entered. Please enter
scores between 0 and 100.”);
}
}
private static booleanisValidScore(int score) {
return score >= 0 && score <= 100;
}
}
2. import [Link];
import [Link];
public class GuessingGame {
public static void main (String [] args) {
Random random = new Random ();
int randomNumber = [Link](100) + 1;
Scanner scanner = new Scanner ([Link]);
int guess;
int attempts = 0;
[Link](“Welcome to the Guessing Game!”);
do {
[Link](“Enter your guess (between 1 and 100): “);
guess = [Link]();
attempts++;
if (guess <randomNumber) {
[Link](“Too low! Try again.”);
} else if (guess >randomNumber) {
[Link](“Too high! Try again.”);
} else {
[Link](“Congratulations! You guessed the cor-
rect number.”);
[Link](“Number of attempts: “ + attempts);
}
} while (guess! =randomNumber);
}
}

36
MCQS ANSWERS
NOTES
1. b) False
2. d) Static variables are shared among all instances of the class.
3. c) It optimizes the bytecode and compiles it into machine code.
4. d) double 3.5 = 3.5; (Variable name cannot start with a number)
5. b) False
6. b) It includes the Java compiler for converting Java source code into bytecode.
7. b) It is used to execute a compiled Java program.
8. c) Unary operators (e.g., ++, --)
9. c) B C
10. c) For loop
11. b) 0 2 4
12. c) For loop
13. b) functionName;
14. d) [Link]();
15. c) Decimal

1.13
Assignment

MULTIPLE CHOICE QUESTIONS


1. What is the output of the following Java code snippet?
public class MyClass {
public static void main (String [] args) {
int x = 5;
int y = 10;
int z = x++ + ++y - --x * y--;
[Link](z);
}
}
a) -9
b) 15
c) 16
d) Compilation error

37
NOTES 2. Give the output of the following Java code snippet:
int x = 10;
int y = x >5? (x <15 ?1: 2): 0;
[Link](y);
a) 0 b) 1
c) 2 d) 10
3. What is the result of the following type casting operation in Java?
int num1 = 5;
double num2 = (double) num1;
a) num2 = 5.0 b) num2 = 5
c) Compilation error d) Runtime error
4. Which loop statement in Java executes the loop body at least once, even if the
condition is initially false?
a) for loop b) while loop
c) do-while loop d) switch statement
5. What is the purpose of a return statement in a function?
a) It terminates the execution of the function.
b) It specifies the type of the function.
c) It specifies the access modifier of the function.
d) It returns a value from the function.

QUESTIONS
1. Write a Java program to convert a decimal number to binary.
2. Implement a Java program using functions to generate the Fibonacci sequence
up to a given number.
3. Write a Java program (using functions) that prompts the user to enter three
numbers: an integer, a floating-point number, and a character. Implement type
casting to convert the integer to a floating-point number and the character to its
corresponding ASCII value. Perform arithmetic operations (addition, subtraction,
multiplication) using the converted numbers and display the results.
4. You are developing a program to calculate the area and circumference of various
geometric shapes. Design a Java class called “ShapeCalculator” that contains
methods for calculating the area and circumference of a circle, rectangle, and
triangle. Each method should accept the necessary parameters and return the
calculated value. Additionally, implement a main method that prompts the user
to enter the shape type and required dimensions, and then calls the appropriate
method to calculate and display the result. Handle any potential errors or
exceptional cases, such as invalid input or negative dimensions.

38
5. You are building a program to perform currency conversion. Design a Java class
called “CurrencyConverter” that contains a static method for converting a given
NOTES
amount of money from one currency to another. The static method should
accept the amount, source currency, and target currency as parameters, and
return the converted amount. Additionally, create a main method that prompts
the user to enter the amount, source currency, and target currency, and then
calls the static method from the “CurrencyConverter” class to perform the
conversion and display the converted amount.

1.14
References

Books:
● h tt p s : / / w w w. g o o g l e . c o . i n / b o o k s / e d i t i o n / I n t r o d u c t i o n _ t o _ J a v a _
Programming/wVJ7AgAAQBAJ?hl=en&gbpv=1&dq=introduction+to+
java&printsec=frontcover
● h tt p s : / / w w w. g o o g l e . c o . i n / b o o k s / e d i t i o n / I n t r o d u c t i o n _ t o _ JAVA _
Programming/fI6dl1flmk8C?hl=en&gbpv=1&bsq=introduction+to+
java&dq=introduction+to+java&printsec=frontcover

Web References:
● [Link]
● [Link]
● [Link]

39

You might also like