MCA Java Programming Unit 1 Introduction To Java
MCA Java Programming Unit 1 Introduction To Java
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.
01
NOTES Some definitions of Java by different authors are given below:
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.
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).
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!”);
}
}
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.
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’.
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
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.
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,
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;
int x = 10;
double y = (double) x; // Explicitly casting int to double
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.
16
The program outputs:
NOTES
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0
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.
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
if statement:
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
}
START
If Condition
True False
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
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
}
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.
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.
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.
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:
Increment/
Decrement
Condition If true
Start Initialization Statement
Checking
If false
END
23
NOTES For example:
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:
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);
}
}
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);
}
}
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;
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.
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
1.10
Case Study
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
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
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.”);
}
}
}
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
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