Alternate solutions : ESE all ans.pdf
QB TT1
Q1. Write separate programs that shows the implementation of (i)static variable and static member function
Static Variable: In Java, a static variable is shared among all instances of a class. It belongs to the class rather than any individual object. This means that all instances of the class share the same static variable.
Example Program:
class Counter {
// Static variable
static int count = 0;
// Constructor
Counter() {
count++;
}
// Method to display the count
void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter obj3 = new Counter();
// Display count for each object
obj1.displayCount(); // Output: Count: 3
obj2.displayCount(); // Output: Count: 3
obj3.displayCount(); // Output: Count: 3
}
}
Static Member Function: A static member function (or method) belongs to the class rather than any specific instance. It can be called without creating an instance of the class. Static methods can only directly access static variables and other static methods.
Example Program:
// Java program to demonstrate the use of static member function
class MathUtils {
// Static method
static int square(int number) {
return number * number;
}
// Non-static method
int cube(int number) {
return number * number * number;
}
}
public class Main {
public static void main(String[] args) {
// Call static method directly using the class name
int result1 = MathUtils.square(5);
System.out.println("Square of 5: " + result1); // Output: Square of 5: 25
// Call non-static method using an instance of the class
MathUtils mathUtils = new MathUtils();
int result2 = mathUtils.cube(3);
System.out.println("Cube of 3: " + result2); // Output: Cube of 3: 27
}
}
(ii)static block concept
A static block in Java is used to initialize static variables when the class is loaded. It is executed only once when the class is first loaded into memory, and it is useful for performing initialization that is more complex than simple assignments.
Example Program 1: Basic Usage of Static Block
In this example, we'll demonstrate how a static block can be used to initialize static variables and perform setup tasks.
class Mobile{
String brand;
int price;
String network;
static String name;
static {
name="Phone";
System.out.println("in static block");
}
public Mobile() {
brand="";
price=200;
// name="Phone";
System.out.println("in constructor");
}
public void show() {
System.out.println(brand+" : "+price+" : "+name);
}
}
public class Demo {
public static void main(String[] args) throws ClassNotFoundException
{
Class.forName("Mobile");
Mobile obj1=new Mobile();
Class.forName("Mobile");
Mobile obj2=new Mobile();
}
}
Q2. Write a program for the addition, subtraction, multiplication and division of two numbers using constructor
class Calculator {
// Instance variables
private int num1;
private int num2;
// Constructor to initialize the numbers
public Calculator(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public int add() {
return num1 + num2;
}
public int subtract() {
return num1 - num2;
}
public int multiply() {
return num1 * num2;
}
public int divide() {
return num1 / num2;
}
}
public class Main {
public static void main(String[] args) {
// Creating an instance of Calculator with two integers
Calculator calc = new Calculator(10, 5);
// Performing and displaying the results of various operations
System.out.println("Addition: " + calc.add()); // Output: Addition: 15
System.out.println("Subtraction: " + calc.subtract()); // Output: Subtraction: 5
System.out.println("Multiplication: " + calc.multiply()); // Output: Multiplication: 50
System.out.println("Division: " + calc.divide()); // Output: Division: 2
}
}
The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into corresponding objects.
Each of the 8 primitive types has corresponding wrapper classes:
There are certain needs for using the Wrapper class in Java as mentioned below:
public class WrapperExample {
public static void main(String[] args) {
// Boxing: Converting primitive to wrapper class
int primitiveInt = 5;
Integer wrapperInt = Integer.valueOf(primitiveInt); // Boxing
System.out.println("Wrapper Integer: " + wrapperInt);
// Unboxing: Converting wrapper class back to primitive
Integer anotherWrapperInt = 10;
int anotherPrimitiveInt = anotherWrapperInt; // Unboxing
System.out.println("Primitive int: " + anotherPrimitiveInt);
}
}
<aside> 💡 Purpose of Wrapper Classes
ArrayList
, HashMap
).String
ClassThe String
class in Java represents immutable sequences of characters. Once a String
object is created, its value cannot be changed. Here are some commonly used methods in the String
class:
length()
: Returns the length of the string.
javaCopy code
String str = "Hello";
int len = str.length(); // len = 5
charAt(int index)
: Returns the character at the specified index.
javaCopy code
char ch = str.charAt(1); // ch = 'e'
substring(int beginIndex, int endIndex)
: Returns a new string that is a substring of the original string.
javaCopy code
String sub = str.substring(1, 4); // sub = "ell"
toLowerCase()
: Returns a new string with all characters converted to lowercase.
javaCopy code
String lower = str.toLowerCase(); // lower = "hello"
toUpperCase()
: Returns a new string with all characters converted to uppercase.
javaCopy code
String upper = str.toUpperCase(); // upper = "HELLO"
trim()
: Removes leading and trailing whitespace from the string.
javaCopy code
String spaced = " Hello ";
String trimmed = spaced.trim(); // trimmed = "Hello"
replace(CharSequence target, CharSequence replacement)
: Returns a new string with all occurrences of the target sequence replaced by the replacement sequence.
javaCopy code
String replaced = str.replace("l", "L"); // replaced = "HeLLo"
indexOf(String str)
: Returns the index of the first occurrence of the specified substring.
javaCopy code
int index = str.indexOf("l"); // index = 2
equals(Object obj)
: Compares the string to the specified object for equality.
javaCopy code
boolean isEqual = str.equals("Hello"); // isEqual = true
split(String regex)
: Splits the string into an array of substrings based on the specified regular expression.
javaCopy code
String[] parts = str.split("l"); // parts = ["He", "", "o"]
StringBuffer
ClassThe StringBuffer
class represents a mutable sequence of characters. Unlike String
, a StringBuffer
object can be modified after creation. Here are some commonly used methods in the StringBuffer
class:
append(String str)
: Appends the specified string to the end of the StringBuffer
.
javaCopy code
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // sb = "Hello World"
insert(int offset, String str)
: Inserts the specified string at the specified position.
javaCopy code
sb.insert(5, " Java"); // sb = "Hello Java World"
delete(int start, int end)
: Deletes the characters between the specified start and end indices.
javaCopy code
sb.delete(5, 10); // sb = "Hello World"
replace(int start, int end, String str)
: Replaces the characters between the specified start and end indices with the specified string.
javaCopy code
sb.replace(6, 11, "Java"); // sb = "Hello Java"
reverse()
: Reverses the sequence of characters in the StringBuffer
.
javaCopy code
sb.reverse(); // sb = "avaJ olleH"
toString()
: Converts the StringBuffer
to a String
.
javaCopy code
String str = sb.toString(); // str = "avaJ olleH"
capacity()
: Returns the current capacity of the StringBuffer
.
javaCopy code
int cap = sb.capacity(); // Returns the capacity of the StringBuffer
length()
: Returns the length of the character sequence currently represented by the StringBuffer
.
javaCopy code
int len = sb.length(); // Returns the length of the StringBuffer
// Class with different types of constructors
class Person {
// Instance variables
private String name;
private int age;
// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
// Method to display the person's details
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Using the default constructor
Person person1 = new Person();
person1.display(); // Output: Name: Unknown, Age: 0
// Using the parameterized constructor
Person person2 = new Person("Alice", 30);
person2.display(); // Output: Name: Alice, Age: 30
// Using the copy constructor
Person person3 = new Person(person2);
person3.display(); // Output: Name: Alice, Age: 30
}
}
class Shape {
// Constructor for Triangle (base and height)
public Shape(double base, double height) {
double area = 0.5 * base * height; // Area formula for triangle
System.out.println("Area of Triangle: " + area);
}
// Constructor for Rectangle (length and breadth)
public Shape(double length, double breadth, boolean isRectangle) {
if (isRectangle) {
double area = length * breadth; // Area formula for rectangle
System.out.println("Area of Rectangle: " + area);
}
}
// Constructor for Circle (radius)
public Shape(double radius) {
double area = Math.PI * radius * radius; // Area formula for circle
System.out.println("Area of Circle: " + area);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects and calling constructors
new Shape(5, 10); // Triangle with base=5, height=10
new Shape(4, 6, true); // Rectangle with length=4, breadth=6
new Shape(7); // Circle with radius=7
}
}
In Java, a constructor is a special type of method that is used to initialize objects. It is called when an object of a class is created. A constructor has the same name as the class and does not have a return type, not even void
. Constructors are primarily used to set the initial state of an object by assigning values to its fields or performing any setup operations.
new
keyword.There are two types of constructors in Java:
Default Constructor (No-argument Constructor):
null
for object references, 0
for numeric types).Example:
class Person {
String name;
int age;
// Default constructor
public Person() {
name = "Unknown";
age = 0;
}
}
Parameterized Constructor:
Example:
class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Copy Constructors
Example:
public ClassName(ClassName object) {
// Copy the values from the object to the current object
}
// Syntax of Copy Constructor
class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Person(Person other) {
this.name = other.name; // Copy the 'name' field from the other object
this.age = other.age; // Copy the 'age' field from the other object
}
// Method to display the values
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of the Person class
Person person1 = new Person("Alice", 30);
// Creating a copy of person1 using the copy constructor
Person person2 = new Person(person1);
// Display the details of both objects
person1.display(); // Output: Name: Alice, Age: 30
person2.display(); // Output: Name: Alice, Age: 30
}
}
Constructor Overloading is a concept where a class can have multiple constructors with the same name but different parameters (different number or types of parameters). The appropriate constructor is called based on the number and type of arguments passed during object creation.
class Box {
double length;
double width;
double height;
// Constructor 1: Default constructor
public Box() {
length = 1;
width = 1;
height = 1;
System.out.println("Default Box created with dimensions: 1x1x1");
}
// Constructor 2: Parameterized constructor with 2 dimensions (length and width)
public Box(double length, double width) {
this.length = length;
this.width = width;
this.height = 1; // Default height
System.out.println("Box created with dimensions: " + length + "x" + width + "x1");
}
// Constructor 3: Parameterized constructor with 3 dimensions (length, width, height)
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
System.out.println("Box created with dimensions: " + length + "x" + width + "x" + height);
}
// Method to calculate and display the volume of the box
public void calculateVolume() {
double volume = length * width * height;
System.out.println("Volume of the box: " + volume);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects using different constructors
Box box1 = new Box(); // Calls default constructor
box1.calculateVolume(); // Output: Volume of the box: 1.0
Box box2 = new Box(4, 5); // Calls parameterized constructor (length, width)
box2.calculateVolume(); // Output: Volume of the box: 20.0
Box box3 = new Box(3, 6, 2); // Calls parameterized constructor (length, width, height)
box3.calculateVolume(); // Output: Volume of the box: 36.0
}
}
| --- | --- | --- |
A default method in Java is a method defined within an interface with the default
keyword. Default methods were introduced in Java 8 to allow interfaces to have concrete methods (i.e., methods with implementation), enabling backward compatibility with older versions of Java.
interface MyInterface {
// Default method with implementation
default void display() {
System.out.println("This is a default method.");
}
}
class MyClass implements MyInterface {
// No need to implement display(), default implementation will be used
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display(); // Output: This is a default method.
}
}
class Parent {
void display() {
System.out.println("Parent class display()");
}
}
class Child extends Parent {
void display() {
super.display(); // Calls the display() method of Parent class
System.out.println("Child class display()");
}
}