Program: MCA Online PARUL UNIVERSITY
Course: : JAVA Programming
Name : Rahul Teli
Roll Number: 24227521010066
Semester: 1st
Internal Assignment: 1
Theory Questions
1. Explain the different primitive data types available in Java and their respective sizes.
How do Java’s data types differ from those in other programming languages like C++
or Python?
->
Primitive Data Types in Java and Their Sizes
Java provides eight primitive data types, which are predefined by the language and serve as
the building blocks for data manipulation. These data types, along with their sizes and default
values, are:
Data
Size (in bytes) Default Value Range
Type
byte 1 0 -128 to 127 (-2^7 to 2^7 - 1)
short 2 0 -32,768 to 32,767 (-2^15 to 2^15 - 1)
-2,147,483,648 to 2,147,483,647 (-2^31 to 2^31 -
int 4 0
1)
-9,223,372,036,854,775,808 to
long 8 0L
9,223,372,036,854,775,807 (-2^63 to 2^63 - 1)
Approximately ±3.4 × 10^38 (Single precision,
float 4 0.0f
32-bit IEEE 754)
Approximately ±1.8 × 10^308 (Double precision,
double 8 0.0d
64-bit IEEE 754)
Data
Size (in bytes) Default Value Range
Type
'\u0000' (null
char 2 0 to 65,535 (Stores a single Unicode character)
character)
1 (JVM true or false (No size explicitly defined in Java
boolean false
dependent) specification)
Comparison with C++ and Python
Java’s data types have several differences compared to C++ and Python:
Feature Java C++ Python
Strongly typed but allows
Type Safety Strongly typed Dynamically typed
implicit conversions
Varies based on system
Fixed (e.g., int is Arbitrary precision (int
Integer Sizes architecture (e.g., int could
always 4 bytes) has no limit)
be 2 or 4 bytes)
boolean (only true or bool (internally treated as 0 bool (subclass of int,
Boolean Type
false) or 1) True is 1, False is 0)
char (2 bytes, char (1 byte, ASCII or No char type, uses
Character Type
Unicode) extended ASCII) single-character strings
IEEE 754 (float = 4 IEEE 754 (float, double, Uses float (≈ 8 bytes,
Floating-Point
bytes, double = 8 and long double with IEEE 754 double
Precision
bytes) varying precision) equivalent)
Memory Automatic (Garbage Automatic (Garbage
Manual (new and delete)
Management Collection) Collection)
Key Takeaways
Java has fixed primitive data type sizes, unlike C++, where sizes depend on the
architecture.
Java is strictly type-safe, preventing implicit type conversions that C++ allows.
Python does not have primitive data types, instead, all data types are objects, leading
to more flexibility but higher memory usage.
Boolean values in Java and Python are strict, whereas C++ treats 0 as false and any
nonzero value as true.
2. What is the difference between a class and an object in Java? Describe how to define
a class and create an object from it. Provide an example of a simple class definition and
object instantiation.
->
Difference Between a Class and an Object in Java
1. Class
A class is a blueprint or template for creating objects.
It defines attributes (fields/variables) and methods (behaviors/functions) that objects
will have.
It does not consume memory until an object is created.
2. Object
An object is an instance of a class.
When a class is instantiated (using the new keyword), an object is created.
Each object has its own copy of instance variables and can invoke methods defined in
the class.
Defining a Class in Java
To define a class, use the class keyword followed by the class name. It typically contains:
Instance variables (fields): Store object data.
Methods: Define object behavior.
Constructors (optional): Initialize objects.
Example: Defining a Simple Class
// Defining a class named 'Car'
class Car {
// Attributes (Instance variables)
String brand;
int speed;
// Constructor to initialize object properties
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
// Method to display car details
void displayInfo() {
System.out.println("Car Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
Creating an Object from the Class
Use the new keyword to allocate memory and call the constructor.
Access object properties using the dot (.) operator.
Example: Creating an Object and Using Methods
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Tesla", 200);
// Calling a method using the object
myCar.displayInfo();
Output:
Car Brand: Tesla
Speed: 200 km/h
Key Takeaways
Feature Class Object
Definition A blueprint for creating objects An instance of a class
Memory Memory is allocated when new is
No memory is allocated
Allocation used
Example class Car {} Car myCar = new Car("Tesla", 200);
Defines properties and
Purpose Represents a real-world entity
behaviors
3. Describe how Java's control flow statements work. Provide examples of the usage of
if, else, switch, case, and default statements in controlling the flow of a Java program.
->
Java Control Flow Statements
Control flow statements in Java determine the execution order of statements in a program.
These include decision-making statements (if, if-else, switch) that allow the program to
execute specific code blocks based on conditions.
1. if Statement
The if statement executes a block of code only if a specified condition is true.
Example: Using if
public class IfExample {
public static void main(String[] args) {
int num = 10;
if (num > 5) { // Condition is true
System.out.println("Number is greater than 5");
}
}
Output:
Number is greater than 5
2. if-else Statement
The if-else statement provides an alternative block of code that runs when the condition is
false.
Example: Using if-else
public class IfElseExample {
public static void main(String[] args) {
int num = 3;
if (num > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is 5 or less");
Output:
Number is 5 or less
3. if-else if-else Statement
When multiple conditions need to be checked, if-else if-else can be used.
Example: Using if-else if-else
public class IfElseIfExample {
public static void main(String[] args) {
int num = 0;
if (num > 0) {
System.out.println("Positive number");
} else if (num < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
}
Output:
Zero
4. switch Statement
The switch statement allows selecting a block of code to execute from multiple options based
on a variable's value.
Syntax:
switch(expression) {
case value1:
// Code block
break;
case value2:
// Code block
break;
default:
}
Each case represents a possible value of the variable.
break is used to exit the switch after a case executes.
default is executed when no matching case is found.
Example: Using switch-case
public class SwitchExample {
public static void main(String[] args) {
int day = 3; // 1 = Monday, 2 = Tuesday, etc.
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
Output:
Wednesday
Key Differences Between if-else and switch
Feature if-else switch
Used for Checking conditions Checking fixed values
Supports relational (>, <, ==, Works with int, char, String, enum, byte,
Data types
etc.) short
Faster for large cases (compiles to jump
Performance Slower if many conditions
table)
Flexibility Supports complex conditions Limited to exact matches
4. Discuss the purpose of loops in Java. Explain the differences between for, while, and
do-while loops, and provide examples of when to use each type of loop.
->
Loops in Java
Loops in Java repeat a block of code until a specific condition is met. They help automate
repetitive tasks and reduce code duplication.
Java provides three types of loops:
1. for loop – Best for loops with a known number of iterations.
2. while loop – Best when the number of iterations is unknown (runs as long as a
condition is true).
3. do-while loop – Similar to while, but executes the loop at least once before checking
the condition.
1. for Loop
Used when the number of iterations is known.
Contains initialization, condition, and update in a single line.
Syntax:
for(initialization; condition; update) {
Example: Printing numbers from 1 to 5
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) { // i starts at 1, runs until 5
System.out.println("Number: " + i);
} }}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2. while Loop
Used when the condition is checked before execution.
Ideal for cases where the number of iterations is unknown.
Syntax:
while(condition) {
// Code block to execute
Example: Printing numbers from 1 to 5 using while
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) { // Condition is checked before execution
System.out.println("Number: " + i);
i++; // Increment to avoid infinite loop
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. do-while Loop
Executes the loop at least once, even if the condition is false initially.
The condition is checked after the first iteration.
Syntax:
do {
// Code block to execute
} while(condition);
Example: Printing numbers from 1 to 5 using do-while
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Number: " + i);
i++; // Increment
} while (i <= 5); // Condition is checked after the first run
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Key Differences Between for, while, and do-while
Feature for loop while loop do-while loop
Condition Before each
Before each iteration After each iteration
Check iteration
Known iteration Ensures at least one
Use Case Unknown iteration count
count execution
Common Iterating arrays, User input validation, event- Menu-driven
Usage counters based execution applications
5. What are getter and setter methods in Java? Explain their purpose and provide an
example of how to implement and use these methods within a class.
->
Getter and Setter Methods in Java
Purpose
In Java, getter and setter methods are used to access and modify private fields in a class. They
help encapsulate data by restricting direct access and allowing controlled modification.
Why Use Getters and Setters?
Encapsulation – Protects data by making fields private.
Data Validation – Ensures valid values before updating fields.
Flexibility – Allows changes in logic without affecting external code.
Read-Only or Write-Only Fields – Limits access based on requirements.
How Getters and Setters Work
1. Getter (Accessor) Method
o Retrieves the value of a private field.
o Named as getVariableName().
o Returns the value.
2. Setter (Mutator) Method
o Updates the value of a private field.
o Named as setVariableName(value).
o May include validation before assignment.
Example: Using Getters and Setters
class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
// Getter for name
public String getName() {
return name;
// Setter for name
public void setName(String name) {
this.name = name;
// Getter for age
public int getAge() {
return age;
// Setter for age with validation
public void setAge(int age) {
if (age > 0) {
this.age = age;
} else {
System.out.println("Invalid age");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object
Person person = new Person("Alice", 25);
// Using getters
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Using setters
person.setName("Bob");
person.setAge(30);
// Displaying updated values
System.out.println("Updated Name: " + person.getName());
System.out.println("Updated Age: " + person.getAge());
// Trying to set an invalid age
person.setAge(-5);
Expected Output
Name: Alice
Age: 25
Updated Name: Bob
Updated Age: 30
Invalid age
Comparison of Getters and Setters
Feature Getter Setter
Purpose Retrieve field value Modify field value
Naming getVariableName() setVariableName(value)
Return Type Field type Usually void
Example getName() setName("Bob")
When to Use?
Use getters to provide controlled access to private fields.
Use setters to modify values safely with validation.
Practical Problems
1. Write a Java program that demonstrates the use of different primitive data types.
Include examples of int, float, char, and boolean. Perform basic operations using these
data types and print the results.
Code :
public class PrimitiveDataTypesExample {
public static void main(String[] args) {
// Integer type
int a = 10, b = 5;
int sum = a + b; // Addition
int product = a * b; // Multiplication
// Floating-point type
float x = 5.5f, y = 2.2f;
float division = x / y; // Division
// Character type
char letter = 'A';
char nextLetter = (char) (letter + 1); // Getting next character
// Boolean type
boolean isJavaFun = true;
boolean isCodingHard = false;
// Output results
System.out.println("Integer Operations:");
System.out.println("Sum of " + a + " and " + b + " = " + sum);
System.out.println("Product of " + a + " and " + b + " = " + product);
System.out.println("\nFloating-point Operations:");
System.out.println("Division of " + x + " by " + y + " = " + division);
System.out.println("\nCharacter Operations:");
System.out.println("Current Letter: " + letter);
System.out.println("Next Letter: " + nextLetter);
System.out.println("\nBoolean Values:");
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Is coding hard? " + isCodingHard);
Output :
+
2. Create a Java class named Person with private fields for name and age. Implement
getter and setter methods for these fields. Write a main method to create an instance of
Person, set its properties using the setter methods, and retrieve them using the getter
methods.
Code :
// Person.java
public class Person {
// Private fields
private String name;
private int age;
// Getter method for name
public String getName() {
return name;
// Setter method for name
public void setName(String name) {
this.name = name;
}
// Getter method for age
public int getAge() {
return age;
// Setter method for age
public void setAge(int age) {
if (age > 0) { // Ensuring age is positive
this.age = age;
} else {
System.out.println("Age must be a positive number.");
// Main method to demonstrate the usage
public static void main(String[] args) {
// Creating an instance of Person
Person person = new Person();
// Setting values using setter methods
person.setName("John Doe");
person.setAge(25);
// Retrieving and displaying values using getter methods
System.out.println("Person Details:");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
OUTPUT :
3. Develop a Java program that uses control flow statements. Include examples of if-else
and switch statements. For instance, create a program that takes a numeric grade as
input and prints the corresponding letter grade using a switch statement.
Code :
// GradeEvaluator.java
import java.util.Scanner;
public class GradeEvaluator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking numeric grade input
System.out.print("Enter the numeric grade (0-100): ");
int grade = scanner.nextInt();
// Using if-else to check for valid range
if (grade < 0 || grade > 100) {
System.out.println("Invalid grade! Please enter a number between 0 and 100.");
} else {
// Convert numeric grade to letter grade using switch
String letterGrade;
switch (grade / 10) {
case 10: // 100
case 9:
letterGrade = "A";
break;
case 8:
letterGrade = "B";
break;
case 7:
letterGrade = "C";
break;
case 6:
letterGrade = "D";
break;
default:
letterGrade = "F";
break;
// Display the result
System.out.println("The letter grade is: " + letterGrade);
scanner.close();
}
Output :
4. Write a Java program that demonstrates the use of different types of loops. Create a
for loop to print numbers from 1 to 10, a while loop to print even numbers from 2 to 20,
and a do-while loop to print numbers from 10 to 1 in descending order.
Code :
// LoopDemo.java
public class LoopDemo {
public static void main(String[] args) {
// For loop: Print numbers from 1 to 10
System.out.println("For Loop - Numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
System.out.println("\n");
// While loop: Print even numbers from 2 to 20
System.out.println("While Loop - Even numbers from 2 to 20:");
int num = 2;
while (num <= 20) {
System.out.print(num + " ");
num += 2;
System.out.println("\n");
// Do-while loop: Print numbers from 10 to 1 in descending order
System.out.println("Do-While Loop - Numbers from 10 to 1:");
int count = 10;
do {
System.out.print(count + " ");
count--;
} while (count >= 1);
System.out.println();
}
Output :
5. Create a Java class with a method that overrides a method from its superclass. Define
a superclass named Animal with a method makeSound(). Create a subclass named Dog
that overrides the makeSound() method. In the main method, instantiate a Dog object
and call the makeSound() method.
Code :
// MethodOverriding.java
class Animal {
// Superclass method
public void makeSound() {
System.out.println("The animal makes a sound.");
}
// Subclass Dog that overrides makeSound()
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks: Woof! Woof!");
// Main class
public class MethodOverriding {
public static void main(String[] args) {
// Creating a Dog object
Dog myDog = new Dog();
// Calling the overridden method
myDog.makeSound();
}
Output :