0% found this document useful (0 votes)
33 views31 pages

PPL Unit 3

Java is considered secure due to its use of the Java Virtual Machine (JVM), bytecode verification, and a security manager that prevents unauthorized access to system memory. It is portable because Java code is compiled into bytecode, allowing it to run on any system with a JVM, embodying the 'write once, run anywhere' philosophy. Additionally, Java is dynamic as it supports runtime class loading and reflection, enabling flexibility in code execution.

Uploaded by

Vaibhav Joshi
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)
33 views31 pages

PPL Unit 3

Java is considered secure due to its use of the Java Virtual Machine (JVM), bytecode verification, and a security manager that prevents unauthorized access to system memory. It is portable because Java code is compiled into bytecode, allowing it to run on any system with a JVM, embodying the 'write once, run anywhere' philosophy. Additionally, Java is dynamic as it supports runtime class loading and reflection, enabling flexibility in code execution.

Uploaded by

Vaibhav Joshi
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
You are on page 1/ 31

Q: Explain why Java is Secure, Portable, and Dynamic?

Which concept in Java


ensures these?

1. Java is Secure because:

• Java does not use pointers (which can lead to memory access issues).

• Runs in the Java Virtual Machine (JVM) – avoids direct access to system memory.

• Has Security Manager and bytecode verification.

• Supports exception handling, preventing unexpected crashes.

• Classes from unknown sources are verified before execution.

Concept responsible:

• Bytecode Verification

• JVM (Java Virtual Machine)

• Security Manager

2. Java is Portable because:

• Java code is compiled into Bytecode, not machine code.

• This Bytecode can run on any system with JVM (Windows, Linux, Mac, etc.)

• "Write once, run anywhere" is Java’s motto.

Concept responsible:

• Bytecode

• JVM (Platform independence)

3. Java is Dynamic because:

• Supports dynamic loading of classes at runtime.

• Uses Reflection API to inspect and modify code at runtime.

• Can link code during runtime, not just compile-time.

Concept responsible:

• Class Loader

• Dynamic Linking

• Reflection
Conclusion:

Java is secure, portable, and dynamic mainly because of the JVM, Bytecode, and class-loading
mechanisms. These features make Java platform-independent, safe, and adaptable.

What are strings in java? Explain following operations of class strings in java with example.
[9] i) ii) iii) To find length of string To compare strings Extraction of characters from string
iv) To search a substring

What are Strings in Java?

• A String is a group of characters enclosed in double quotes.

• In Java, strings are objects of the String class.

• Strings are immutable, meaning their value cannot be changed after creation.

• Java provides many methods to work with strings.

i) To Find Length of String

Theory:

• The .length() method returns the number of characters in the string.

• Spaces are also counted.

Example:

java

CopyEdit

String str = "Java Programming";

int len = str.length();

System.out.println("Length: " + len);

Output:
Length: 16

ii) To Compare Strings

Theory:

• .equals() checks if two strings are exactly same (case-sensitive).

• .compareTo() compares two strings alphabetically.

Example:

java
CopyEdit

String s1 = "Java";

String s2 = "Java";

System.out.println(s1.equals(s2)); // true

Output:
true

iii) Extraction of Characters from String

Theory:

• The .charAt(index) method is used to get a single character from the string.

• Index starts from 0.

Example:

java

CopyEdit

String word = "Hello";

char ch = word.charAt(1);

System.out.println("Character at index 1: " + ch);

Output:
Character at index 1: e

iv) To Search a Substring

Theory:

• The .indexOf("substring") method returns the starting position of a word inside a string.

• Returns -1 if not found.

Example:

java

CopyEdit

String sentence = "Java is fun";

int index = sentence.indexOf("fun");

System.out.println("Position: " + index);

Output:
Position: 8
Question:

What is a constructor? Show with example the use and overloading of default, parameterized, and copy
constructor?

Answer 1: In Simple English Only

What is a Constructor?

• A constructor is a special method used to initialize objects.

• It has the same name as the class and no return type.

• It is called automatically when an object is created.

Types of Constructors:

1. Default Constructor:

• Takes no parameters.

• Sets default values to object properties.

2. Parameterized Constructor:

• Takes parameters to initialize object with given values.

3. Copy Constructor:

• Creates a new object by copying data from an existing object.

Example of Constructor Overloading (All three types):

java

CopyEdit

class Student {

int id;

String name;

// Default constructor

Student() {

id = 0;

name = "Unknown";

}
// Parameterized constructor

Student(int i, String n) {

id = i;

name = n;

// Copy constructor

Student(Student s) {

id = s.id;

name = s.name;

void display() {

System.out.println("ID: " + id + ", Name: " + name);

public class Main {

public static void main(String[] args) {

Student s1 = new Student(); // default constructor

Student s2 = new Student(101, "Alice"); // parameterized constructor

Student s3 = new Student(s2); // copy constructor

s1.display();

s2.display();

s3.display();

Output:
yaml

CopyEdit

ID: 0, Name: Unknown

ID: 101, Name: Alice

ID: 101, Name: Alice

Question:

What do you mean by method overloading? Demonstrate through a program in Java how method overloading
is used to add two integers and three integers respectively.

Answer 1: In Simple English Only (With Extra Theory Points)

What is Method Overloading?

• Method overloading is a feature that allows more than one method to have the same name but with
different parameters (either in number or type) inside the same class.

• It helps to increase the readability of the program by using the same method name for similar
actions.

• The return type can be the same or different, but the method signature must differ.

• It is a way of compile-time polymorphism or static polymorphism in Java.

• The compiler decides which method to call based on the number or type of arguments passed.

Example: Adding Two and Three Integers Using Method Overloading

java

CopyEdit

class Calculator {

// Method to add two integers

int add(int a, int b) {

return a + b;

// Overloaded method to add three integers

int add(int a, int b, int c) {

return a + b + c;

}
}

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

int sum1 = calc.add(10, 20); // Calls method with 2 parameters

int sum2 = calc.add(10, 20, 30); // Calls method with 3 parameters

System.out.println("Sum of two numbers: " + sum1);

System.out.println("Sum of three numbers: " + sum2);

Output:

yaml

CopyEdit

Sum of two numbers: 30

Sum of three numbers: 60

Question:

Explain following features of Java in detail:


i) Security
ii) Platform Independence
iii) Object-oriented

Answer 1: In Simple English Only

i) Security

• Java provides a secure environment for running applications.

• It has built-in security features like bytecode verification, sandboxing, and no direct access to
memory.

• Java programs run inside a Java Virtual Machine (JVM), which prevents harmful operations.

• It protects the system from viruses and malicious programs.


ii) Platform Independence

• Java is platform-independent because of its “Write Once, Run Anywhere” capability.

• Java code is compiled into bytecode, which can run on any system having JVM.

• JVM acts as a bridge between the bytecode and the operating system, making Java portable.

• This means the same Java program runs without changes on Windows, Linux, Mac, etc.

iii) Object-oriented

• Java follows the Object-Oriented Programming (OOP) concept.

• Everything in Java is based on objects and classes.

• It supports key OOP principles:

o Encapsulation: Hiding data using classes.

o Inheritance: One class inherits properties of another.

o Polymorphism: One method behaves differently based on objects.

o Abstraction: Showing only important details, hiding complexity.

• This makes Java programs modular, reusable, and easy to maintain.

Question:

Write short note on:


i) Garbage Collector
ii) this

Answer 1: In Simple English Only

i) Garbage Collector

• Garbage Collector (GC) in Java automatically removes unused objects from memory.

• It helps to free up memory by deleting objects that are no longer referenced.

• This prevents memory leaks and improves program performance.

• Programmers don’t need to manually free memory like in other languages.

ii) this

• this is a keyword in Java used to refer to the current object.

• It helps to distinguish between instance variables and parameters when they have the same name.
• It can be used to call another constructor in the same class (this()), or access current object’s fields
and methods.

Question:

Define constructor. Which are the types of constructor used in Java? Explain with example.

Answer 1: In Simple English Only

What is a Constructor?

• A constructor is a special method in Java used to create and initialize objects.

• It has the same name as the class and no return type.

• It is automatically called when an object is created.

Types of Constructors in Java:

1. Default Constructor

o Takes no parameters.

o Sets default values to object fields.

2. Parameterized Constructor

o Takes parameters to initialize the object with user-defined values.

3. Copy Constructor

o Creates a new object by copying values from another object.

Example of All Three Constructors:

java

CopyEdit

class Student {

int id;

String name;

// Default Constructor

Student() {

id = 0;

name = "Unknown";
}

// Parameterized Constructor

Student(int i, String n) {

id = i;

name = n;

// Copy Constructor

Student(Student s) {

id = s.id;

name = s.name;

void display() {

System.out.println("ID: " + id + ", Name: " + name);

public class Main {

public static void main(String[] args) {

Student s1 = new Student(); // Default constructor

Student s2 = new Student(101, "Ravi"); // Parameterized constructor

Student s3 = new Student(s2); // Copy constructor

s1.display();

s2.display();

s3.display();

}
Output:

yaml

CopyEdit

ID: 0, Name: Unknown

ID: 101, Name: Ravi

ID: 101, Name: Ravi

Question:

Explain following features of Java in detail:


i) Portability
ii) Architecture Neutral
iii) Distributed

Answer 1: In Simple English Only

i) Portability

• Java programs are portable, meaning they can run on any platform without changes.

• Java code is compiled into bytecode, not machine code.

• Bytecode can be run on any machine that has a Java Virtual Machine (JVM).

• This makes Java programs easy to move between Windows, Linux, and other systems.

ii) Architecture Neutral

• Java is architecture neutral, which means it does not depend on hardware or operating system.

• The bytecode generated by Java compiler can be run on any system with a JVM.

• So, Java code behaves the same way on all platforms, whether it's 32-bit or 64-bit system.

iii) Distributed

• Java supports distributed computing, meaning it can work across multiple computers over a network.

• It has built-in support for networking features using packages like java.net.

• Java programs can share data and files easily over the internet.

• It also supports technologies like Remote Method Invocation (RMI) and CORBA

Question:

Write short note on:


i) final
ii) finalize()
Answer 1: In Simple English Only

i) final

• final is a keyword in Java used to make variables, methods, or classes unchangeable.

• Final variable: Value cannot be changed after initialization.

• Final method: Cannot be overridden by subclasses.

• Final class: Cannot be inherited by other classes.

• It is used to provide safety and control in code.

Example:

java

CopyEdit

final int x = 10;

// x = 20; // Error: cannot change final variable

ii) finalize()

• finalize() is a method in Java that is called by the Garbage Collector before destroying an object.

• It is used to clean up resources (like closing a file or database connection) before the object is
removed.

• It is defined in the Object class, so every class can override it.

• But it is rarely used now in modern Java because other methods like try-with-resources are better.

Example:

java

CopyEdit

protected void finalize() {

System.out.println("Object is destroyed");

Question:

Explain one-dimensional and multi-dimensional arrays used in Java with suitable examples.

Answer 1: In Simple English Only

What is an Array in Java?


• An array is a collection of similar type of elements stored in a single variable.

• Arrays can be one-dimensional or multi-dimensional.

i) One-Dimensional Array:

• It is a linear array, like a list.

• Used to store values in a single row.

Syntax:

java

CopyEdit

int[] arr = new int[5];

Example:

java

CopyEdit

public class OneDArray {

public static void main(String[] args) {

int[] arr = {10, 20, 30, 40, 50};

for(int i = 0; i < arr.length; i++) {

System.out.println("Element at index " + i + ": " + arr[i]);

Output:

perl

CopyEdit

Element at index 0: 10

Element at index 1: 20

Element at index 2: 30

Element at index 3: 40

Element at index 4: 50

ii) Multi-Dimensional Array:


• It stores data in rows and columns (like a table).

• The most common is a 2D array.

Syntax:

java

CopyEdit

int[][] arr = new int[2][3];

Example:

java

CopyEdit

public class MultiDArray {

public static void main(String[] args) {

int[][] arr = {

{1, 2, 3},

{4, 5, 6}

};

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

for(int j = 0; j < 3; j++) {

System.out.print(arr[i][j] + " ");

System.out.println();

Output:

CopyEdit

123

456

Question:

Describe primitive data types. List the primitive data types in Java and their respective storage capacity.

Answer 1: In Simple English Only


What are Primitive Data Types?

• Primitive data types are the basic built-in data types in Java.

• They are not objects; they store simple values directly in memory.

• Java has 8 primitive data types.

List of Primitive Data Types in Java:

Data Type Description Size Example

byte Small integer 1 byte (8-bit) -128 to 127

short Short integer 2 bytes -32,768 to 32,767

int Integer (default) 4 bytes -2^31 to 2^31-1

long Large integer 8 bytes -2^63 to 2^63-1

float Decimal number (single) 4 bytes 3.4e−038 to 3.4e+038

double Decimal number (double) 8 bytes 1.7e−308 to 1.7e+308

char Single character 2 bytes 'A', 'B', '1'

boolean True/False value 1 bit true, false

Why use primitive data types?

• They are fast and memory efficient.

• Used when we only need to store a basic value like a number, character, or true/false.

Write short notes on Java Virtual Machine (JVM) with diagram.

Definition / Concept

• Java Virtual Machine (JVM) is a part of Java Runtime Environment (JRE).

• It is responsible for executing Java bytecode.

• JVM makes Java platform-independent by allowing the same bytecode to run on any device with JVM.

Key Points / Features of JVM:

• JVM runs the .class (bytecode) file generated by Java compiler.

• It provides security, memory management, and performance optimization.


• JVM is platform-dependent, but Java programs are platform-independent.

• It includes class loader, bytecode verifier, interpreter, and JIT compiler.

• It automatically handles garbage collection.


Question:

State the uses of the final keyword in Java.

Definition / Concept

• final is a keyword in Java used to make something unchangeable.

• It can be applied to variables, methods, and classes.

• Once declared as final, it cannot be modified or overridden.

Uses of final keyword in Java:

1. Final Variable

• Value can be assigned only once.

• Used to declare constants.

Example:

java

CopyEdit
final int SPEED_LIMIT = 60;

// SPEED_LIMIT = 70; // Error: cannot change final variable

2. Final Method

• Method cannot be overridden in a subclass.

• Provides safety in inheritance.

Example:

java

CopyEdit

class Vehicle {

final void run() {

System.out.println("Running safely");

3. Final Class

• Class cannot be extended (no subclass).

• Used for security and preventing modification.

Example:

java

CopyEdit

final class Bank {

void interestRate() {

System.out.println("Interest is 6%");

// class MyBank extends Bank { } // Error

Extra Points for Exam Writing:

• final improves security and stability in code.

• It prevents accidental changes to important parts of the program.

• Often used with static to create constants.


Example: static final double PI = 3.14;
• Final keyword is also used in inner classes and anonymous classes.

• Question:

• Define String in Java. Explain the following operations of class String in Java with example:
i) To find length of the string
ii) To compare two strings
iii) To extract a character from a string
iv) To concatenate two strings

• Definition / Concept

• A String in Java is a sequence of characters enclosed in double quotes (" ").

• Strings are objects of the String class.

• Java strings are immutable (they cannot be changed after creation).

• String Operations in Java

• i) To find length of the string

• The length() method returns the number of characters in a string.

• Example:

• java

• CopyEdit

• String name = "Java";

• System.out.println(name.length()); // Output: 4

• ii) To compare two strings

• Use equals() to compare actual content of two strings.

• Use == to compare reference (not recommended for content comparison).

• Example:

• java

• CopyEdit

• String s1 = "Hello";

• String s2 = "Hello";

• System.out.println(s1.equals(s2)); // Output: true


• iii) To extract a character from a string

• The charAt(index) method returns the character at the given index (starts from 0).

• Example:

• java

• CopyEdit

• String word = "Computer";

• System.out.println(word.charAt(3)); // Output: p

• iv) To concatenate two strings

• The concat() method or + operator is used to join two strings.

• Example:

• java

• CopyEdit

• String first = "Hello";

• String second = "World";

• System.out.println(first.concat(second)); // Output: HelloWorld

• System.out.println(first + " " + second); // Output: Hello World

• Extra Points for Exam Writing:

• String class is part of java.lang package.

• Strings are immutable – every modification creates a new string.

• Common string methods include: length(), charAt(), equals(), concat(), substring(), toUpperCase(), etc.

• Strings are widely used for text processing, display, and input in Java programs.

• Question:

• b) Explain Java’s role in Internet. Justify the following features of Java:


i) Architectural Neutral
ii) Distributed
iii) Secure


• Answer 1: In Simple English

• Java’s Role in Internet:

• Java lets programs run on any device connected to the Internet.

• Java applets run safely inside web browsers.

• It provides built-in networking tools for easy communication over the Internet.

• Java is widely used for web applications, online games, and mobile apps.

• i) Architectural Neutral:

• Java bytecode works on any hardware or operating system.

• Java programs are portable because they run on JVM on any platform.

• ii) Distributed:

• Java supports distributed computing where programs run on multiple machines connected by a
network.

• It uses technologies like RMI (Remote Method Invocation) and sockets for network communication.

• iii) Secure:

• Java provides a secure environment to run code, especially from untrusted sources.

• It uses a bytecode verifier to check code safety before running.

• The sandbox limits what the program can do to protect the system.

• Extra Points:

• Java was designed with the Internet in mind.

• Its features make it popular for network and web applications.

• Security and portability help Java programs run safely anywhere

• Question:

• Summarize different access controls in Java. Explain the situation if you remove the static modifier
from the main method.


• Answer 1: In Simple English


• Different Access Controls in Java:

• Java provides four types of access modifiers to control visibility of classes, methods, and variables:

• public

• Accessible from anywhere (all classes and packages).

• private

• Accessible only within the same class.

• protected

• Accessible within the same package and subclasses (even in different packages).

• default (no modifier)

• Accessible only within the same package (also called package-private).

• What happens if you remove static from main method?

• The main method must be static because Java calls it without creating an object.

• If static is removed, the JVM will not find the main method to start the program.

• This causes a runtime error: NoSuchMethodError: main.

• Extra Points:

• static means the method belongs to the class, not to an object.

• Access modifiers help in data hiding and security.

• Question:

• Write a program to print the area of a circle using a class Area. It should have:

• Method setRadius(double r) to set the radius.

• Method getArea() to return the area.

• Radius should be taken from the keyboard.

• Simple Java Program for Better Understanding

• java

• CopyEdit

• import java.util.Scanner;

• class Area {
• double r; // radius

• void setRadius(double x) {

• r = x;

• }

• double getArea() {

• return 3.14 * r * r; // πr²

• }

• }

• public class Main {

• public static void main(String[] args) {

• Scanner sc = new Scanner(System.in); // For input

• Area a = new Area(); // Create object

• System.out.print("Enter radius: ");

• double input = sc.nextDouble(); // Take input

• a.setRadius(input); // Set radius

• double result = a.getArea(); // Get area

• System.out.println("Area is: " + result); // Print result

• }

• }

• Explanation in Simple English

• Area class has one variable r to store radius.

• setRadius() method sets the radius.

• getArea() method returns area using formula πr².

• In main() method:
• User inputs radius.

• We use object a of Area class to set and get area.

• Final result is printed.

• Question:

• Explain the Garbage Collection concept in Java Programming with code example.

• Answer 1: In Simple English with Code Example

• What is Garbage Collection in Java?

• In Java, Garbage Collection (GC) is the process of automatically deleting unused (unreferenced)
objects from memory.

• Java has no delete keyword like C/C++.

• Garbage Collector runs in the background and frees memory used by objects that are no longer
needed.

• Why Garbage Collection is Important?

• Frees memory → avoids memory leaks

• Improves performance

• Programmer doesn't need to manually manage memory

• When is Object Eligible for GC?

• When there is no reference to the object

• Example:

• java

• CopyEdit

• Student s = new Student(); // object created

• s = null; // now it becomes eligible for GC

• Java Code Example:

• java

• CopyEdit
• class Test {

• // This method is called before object is deleted

• protected void finalize() {

• System.out.println("Object destroyed by Garbage Collector");

• }

• }

• public class Main {

• public static void main(String[] args) {

• Test t1 = new Test();

• Test t2 = new Test();

• t1 = null; // eligible for GC

• t2 = null; // eligible for GC

• System.gc(); // Request JVM to run garbage collector

• }

• }

• Output (May vary):

• vbnet

• CopyEdit

• Object destroyed by Garbage Collector

• Object destroyed by Garbage Collector

• Extra Points to Write in Exam:

• finalize() method is called before object is deleted by GC.

• System.gc() is used to request garbage collection (but JVM may ignore it).

• Helps in automatic memory management.

• Question:

• Explain command line arguments and variable length arguments in Java with an example.

• Answer 1: In Simple English + Code

• 1. Command Line Arguments in Java

• Command line arguments are values passed to the main() method when the Java program is run from
the terminal.

• These values are received as a String[] args array in main().

• Example:

• java

• CopyEdit

• public class CommandLine {

• public static void main(String[] args) {

• System.out.println("Command line arguments are:");

• for (int i = 0; i < args.length; i++) {

• System.out.println("Argument " + i + ": " + args[i]);

• }

• }

• }

• How to Run:

• bash

• CopyEdit

• javac CommandLine.java

• java CommandLine Hello 123 Java

• Output:

• yaml

• CopyEdit

• Command line arguments are:

• Argument 0: Hello

• Argument 1: 123

• Argument 2: Java


• 2. Variable Length Arguments (Varargs)

• Sometimes we don't know how many arguments we need.

• Java allows variable number of arguments using ... (three dots).

• Syntax:

• java

• CopyEdit

• void myMethod(int... numbers)

• Example:

• java

• CopyEdit

• public class VarArgsExample {

• static void display(String... names) {

• for (String name : names) {

• System.out.println("Name: " + name);

• }

• }

• public static void main(String[] args) {

• display("Amit", "Rahul");

• display("Sneha", "Neha", "Meena");

• }

• }

• Output:

• makefile

• CopyEdit

• Name: Amit

• Name: Rahul

• Name: Sneha

• Name: Neha

• Name: Meena


• Extra Points for Exam:

• args[] is used to receive command line inputs.

• ... (three dots) is used to define variable number of arguments.

• You can pass 0 or more values using varargs.

• Varargs must always be the last parameter in method.

Question:

Write a program in Java using switch-case statement to perform Addition, Subtraction,


Multiplication, and Division of given two numbers and print the result.

Answer 1: In Simple English + Code


java
CopyEdit
import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Take input from user


System.out.print("Enter first number: ");
int a = sc.nextInt();

System.out.print("Enter second number: ");


int b = sc.nextInt();

System.out.println("Choose operation: ");


System.out.println("1 = Addition");
System.out.println("2 = Subtraction");
System.out.println("3 = Multiplication");
System.out.println("4 = Division");
int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.println("Addition = " + (a + b));
break;
case 2:
System.out.println("Subtraction = " + (a - b));
break;
case 3:
System.out.println("Multiplication = " + (a * b));
break;
case 4:
if (b != 0) {
System.out.println("Division = " + (a / b));
} else {
System.out.println("Cannot divide by zero!");
}
break;
default:
System.out.println("Invalid choice!");
}
}
}

Output Example:
yaml
CopyEdit
Enter first number: 10
Enter second number: 5
Choose operation:
1 = Addition
2 = Subtraction
3 = Multiplication
4 = Division
3
Multiplication = 50

Extra Points for Exam (Theory):


• switch-case is used to perform different operations based on user choice.
• Each case checks for a specific operation:
o 1: Addition (+)
o 2: Subtraction (-)
o 3: Multiplication (*)
o 4: Division (/)
• default is used if input is not 1-4.
• break is used to stop after one case is executed.
• Always check for division by zero to avoid errors.

Question:

Write a program which receives n integers, stores them in an array, and prints how many are odd and even.

Answer 1: In Simple English + Code

java

CopyEdit

import java.util.Scanner;

public class CountEvenOdd {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Take size of array

System.out.print("Enter how many numbers: ");

int n = sc.nextInt();

int[] arr = new int[n];

int even = 0, odd = 0;

// Take input numbers

System.out.println("Enter " + n + " numbers:");

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

arr[i] = sc.nextInt();

// Check even or odd

if (arr[i] % 2 == 0)

even++;

else

odd++;

// Display results

System.out.println("Total Even numbers: " + even);

System.out.println("Total Odd numbers: " + odd);

Sample Output:

yaml

CopyEdit

Enter how many numbers: 5


Enter 5 numbers:

Total Even numbers: 2

Total Odd numbers: 3

Extra Theory Points (Simple for Exam):

• Array is used to store n numbers.

• Loop is used to read numbers and check if number is even (num % 2 == 0) or odd.

• Two counters: even and odd to keep count.

• Simple logic using % operator.

You might also like