Java Unit 2
Java Unit 2
1Q. Define class and object.Explain how to create a class and object with a
suitable example.
Ans: Class: In Java, a class is a blueprint or a template that defines the structure
and behavior of objects. It encapsulates data (attributes) and methods (functions) that
operate on the data.
Object: An object is an instance of a class. It represents a real-world entity and is
created based on the blueprint provided by the class. Objects have state (attributes)
and behavior (methods) defined by the class.
Creating a Class and Object in Java:
Example: Let's create a simple class named Car with attributes like make, model,
and year, along with methods to set and display the information.
// Car class definition
public class Car {
// Attributes
String make;
String model;
int year;
// Constructor (optional, used to initialize object attributes)
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Method to display information about the car
public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
// Method to start the car (example of behavior)
public void start() {
System.out.println("The car is starting.");
}
}
Now, let's create objects of the Car class:
// Creating objects of the Car class
public class Main {
public static void main(String[] args) {
// Creating two Car objects
Car car1 = new Car("Toyota", "Camry", 2022);
Car car2 = new Car("Honda", "Accord", 2021);
// Calling methods on the objects
car1.displayInfo(); // Display information about car1
car1.start(); // Start car1
System.out.println(); // Adding a line break for clarity
car2.displayInfo(); // Display information about car2
car2.start(); // Start car2
}
}
When you run the Main class, you'll see output displaying information about
both cars, and it will indicate that each car is starting.
Make: Toyota Make: Honda
Model: Camry Model: Accord
Year: 2022 Year: 2021
The car is starting. The car is starting.
2Q. Define Constructor? Explain its properties?
Ans: Constructor in Java: A constructor in Java is a special type of method that
is called when an object is created. It is used to initialize the state of an object by
providing values to its attributes. Constructors have the same name as the class they
belong to and do not have a return type, not even void.
Properties of Constructors:
Name: The name of a constructor is the same as the class name.
public class MyClass {
public MyClass() {
// Constructor body
No Return Type: Constructors do not have a return type, not even void.
public class MyClass {
// Constructor with no return type
public MyClass() {
// Constructor body
}
}
2. Static Methods:
Static methods belong to the class, and they can be called without creating an
instance of the class. They are often used for utility functions that do not depend on
the state of any particular instance.
Declaration:
public class MyClass {
static void staticMethod() {
// Method body
}
// Other non-static members...
}
final Keyword in Java: The final keyword in Java is a modifier that can be applied to classes,
methods, and variables. It indicates that the element marked as final cannot be changed or
overridden.
final Variable: A final variable, also known as a constant, cannot be modified once it has been
assigned a value.
public class Example {
final int constantValue = 100;
public void modifyValue() {
// Cannot modify the value of a final variable
// Error: The final field Example.constantValue cannot be assigned
// constantValue = 200;
}
}
Ans: Method Overloading in Java is a feature that allows a class to have multiple
methods with the same name but different parameter lists. The methods must have
a different number, type, or order of parameters. Method overloading enhances
code readability and reusability.
public class Calculator {
// Method overloading examples
System.out.println("Sum (int): " + calculator.add(5, 10));
System.out.println("Sum (int): " + calculator.add(5, 10, 15));
System.out.println("Sum (double): " + calculator.add(2.5, 3.5));
System.out.println("Concatenation: " + calculator.concatenate("Hello", "World"));
}
}
The Calculator class has multiple add methods with different parameter lists:
add(int a, int b) takes two integers.
add(int a, int b, int c) takes three integers.
add(double a, double b) takes two doubles.
The class also has a concatenate method that takes two strings and concatenates
them.
When the add and concatenate methods are called in the main method, Java
determines which version of the method to invoke based on the number and types of
arguments provided.
7Q. List and describe methods of StringBuffer class in Java.
Ans: The StringBuffer class in Java provides methods for manipulating mutable
sequences of characters. It is part of the java.lang package and is often used when
there is a need to modify strings frequently.
1. append(String str):
Appends the specified string to the end of the current StringBuffer object.
Returns a reference to the current StringBuffer object.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
4. reverse():
Reverses the characters in the current StringBuffer object.
Returns a reference to the current StringBuffer object.
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
Output:
Command Line Arguments:
Argument 1: arg1
Argument 2: arg2
Argument 3: arg with spaces
Argument 4: arg4
• In this output, the program displays each command line argument along with
its position in the array. The order and content of the arguments depend on
what is provided when running the program from the command line.
• Command line arguments are useful for providing input parameters to a
program dynamically, allowing it to adapt its behavior based on external
information.
The addAndDisplay method is a subroutine that takes two parameters (num1 and
num2), representing integers.
The main method calls addAndDisplay twice with different sets of arguments.
When the method is called with addAndDisplay(5, 7), the values 5 and 7 are passed
as arguments to num1 and num2 inside the method.
Similarly, when the method is called with addAndDisplay(10, 20), the values 10 and
20 are passed as arguments.
Output:
In this example:
The calculateSquare method is declared as static, making it a static method.
It takes an integer parameter number and returns the square of that number.
The main method calls the static method twice with different values (5 and 8)
without creating an instance of the class.
Output:
Square of 5 is: 25
Square of 8 is: 64
13Q. Explain about usage of this keyword with examples.
Ans: this Keyword in Java:
The this keyword in Java is a reference variable that refers to the current object. It is
often used inside a method or a constructor to refer to the instance variables of the
current object or to invoke the current object's methods.
In this example, this.name refers to the instance variable name of the current object,
and this is used to distinguish the instance variable from the constructor parameter.
14Q. What is meant by constructor overloading? Explain with an example.
Ans: Constructor overloading in Java refers to the ability to define multiple
constructors within a class, each with a different parameter list. The constructors
have the same name but differ in the number, types, or order of their parameters.
This allows objects to be instantiated with different sets of initial values based on
the constructor used.
public class Person {
String name;
int age;
public Person() {
name = "Unknown";
age = 0;
}
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
Person person1 = new Person(); // Default constructor
Person person2 = new Person("Alice"); // Constructor with name
Person person3 = new Person("Bob", 25); // Constructor with name and
age
System.out.println("Person 1:");
person1.displayInfo();
System.out.println("\nPerson 2:");
person2.displayInfo();
System.out.println("\nPerson 3:");
person3.displayInfo();
}
}
In this example:
The Person class has three constructors:
The default constructor initializes name with "Unknown" and age with 0.
The second constructor takes a String name parameter and initializes name with the
provided value, leaving age as default.
The third constructor takes both String name and int age parameters and initializes
both instance variables.
When you run this program, it will output:
Person 1:
Name: Unknown
Age: 0
Person 2:
Name: Alice
Age: 0
Person 3:
Name: Bob Age: 25
15Q. Compare and contrast String and StringBuffer classes
Ans: String Class:
Immutability: Strings in Java are immutable, meaning their values cannot be changed
after they are created.
Operations that appear to modify a String actually create a new String object.
Memory Usage: Since strings are immutable, the original and modified strings coexist in
memory until garbage collection occurs.
This can lead to increased memory usage, especially during frequent string modifications.
Thread Safety: Strings are thread-safe, making them suitable for situations where
multiple threads might access the same string concurrently.
Methods: String provides various methods for string manipulation, comparison, and
extraction.
Common methods include concat(), length(), substring(), charAt(), and equals().
Usage: Suitable for situations where the content of the string remains constant or changes
infrequently.
StringBuffer Class:
Mutability: StringBuffer is mutable, meaning the content of the StringBuffer can be
changed without creating a new object.
Operations on StringBuffer modify the existing object, making it more memory-efficient
for frequent modifications.
Memory Usage: StringBuffer is more memory-efficient for concatenation and
modification operations, as it can be modified in-place.
Thread Safety: StringBuffer is thread-safe due to synchronized methods.
However, the synchronization might lead to decreased performance in a multithreaded
environment.
Methods:StringBuffer provides methods for appending, deleting, inserting, and modifying
characters in the buffer.
Common methods include append(), delete(), insert(), and reverse().
Usage: Suitable for situations where frequent modifications to the content of the string are
needed, especially in a multithreaded environment.
16Q. Discuss briefly about compiling and execution of passing arguments at runtime.
Ans: Compilation: Write the Java Code: Create a Java source code file with the
.java extension. This file contains the program's code.
Compile the Code: Open a command prompt or terminal.
Navigate to the directory where your Java source code file is located.
javac YourProgram.java
Execution: Run the Program: After successful compilation, use the java command to run the
program.
java YourProgram arg1 arg2 "arg with spaces" arg4
Accessing Runtime Arguments: In your Java code, you can access the runtime arguments
through the args.
Parsing and Using Arguments: The elements of the args array are strings. If you need to use
them as other data types, you may need to parse them. For example, converting a string to an
integer using Integer.parseInt().
Example:
public class CommandLineArguments {
public static void main(String[] args) {
System.out.println("Number of runtime arguments: " + args.length);
// Displaying each runtime argument
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
O/P: Number of runtime arguments: 4
Argument 1: arg1
Argument 2: arg2
Argument 3: arg with spaces
Argument 4: arg4