0% found this document useful (0 votes)
35 views

Java Unit 2

Uploaded by

pandu mandala
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)
35 views

Java Unit 2

Uploaded by

pandu mandala
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/ 20

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 {

// Constructor with the same name as the class

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
}
}

Initialization: The primary purpose of a constructor is to initialize the attributes of


an object when it is created.
Overloading: Like methods, constructors can be overloaded by providing different
parameter lists.
Default Constructor: If a class does not explicitly provide any constructor, Java
automatically provides a default constructor (with no parameters) for that class.
Chaining Constructors (Constructor Overloading): Constructors can call other
constructors using this() keyword, allowing for constructor overloading and code
reusability. ----- Initialization Blocks:Constructors can
contain initialization blocks, which are executed when the object is created.
3Q. Explain about parameter passing mechanisms in java?
Ans: In Java, parameter passing refers to how arguments are passed to methods
during method invocation. There are two primary parameter passing mechanisms:
pass by value and pass by reference. However, it's essential to note that in Java, all
arguments are passed by value.
1.Pass by Value: In pass by value, the actual value of the argument is passed to the
method. Any changes made to the parameter inside the method have no effect on the
actual argument outside the method. Java uses pass by value for primitive data types
and objects
public class PassByValueExample {
public static void main(String[] args) {
int num = 10;
System.out.println("Before method call: " + num);
modifyValue(num);
System.out.println("After method call: " + num);
}
static void modifyValue(int x) {
x = x * 2;
System.out.println("Inside method: " + x);
}
}
Output: Before method call: 10
Inside method: 20
After method call: 10

2. Pass by Reference (Misconception): While Java is strictly pass by value, there


might be a misconception related to objects, especially when dealing with object
references. In Java, when an object reference is passed as an argument, the reference
is copied, not the actual object. Both the original reference and the copied reference
point to the same object in memory.
public class PassByReferenceMisconception {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Hello");
System.out.println("Before method call: " + builder);
modifyReference(builder);
System.out.println("After method call: " + builder);
}
static void modifyReference(StringBuilder strBuilder) {
strBuilder.append(" World");
System.out.println("Inside method: " + strBuilder);
}
}
Output: Before method call: Hello
Inside method: Hello World
After method call: Hello World

4Q. Explain about static variables, methods and blocks in Java.


Ans: In Java, static variables, methods, and blocks are associated with the class
rather than with instances (objects) of the class. They are declared using the static
keyword and have certain characteristics that distinguish them from non-static
(instance) elements.
1. Static Variables (Class Variables): Static variables are shared among all
instances of a class. They belong to the class rather than to any specific instance.
There is only one copy of a static variable, regardless of how many instances of the
class are created.
Declaration:
public class MyClass {
static int staticVariable;
// Other non-static members...
}
Access: Static variables can be accessed using the class name or an instance of the
class.
MyClass.staticVariable = 10; // Access using class name
MyClass obj = new MyClass();
obj.staticVariable = 20; // Access using an instance

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...
}

Access: Static methods are called using the class name.


MyClass.staticMethod();

3. Static Initialization Blocks: Static initialization blocks are used to initialize


static variables when the class is loaded into the JVM. They are executed only once,
the first time the class is loaded. Static initialization blocks are declared using the
static keyword and enclosed in curly braces.
Declaration:
public class MyClass {
static {
// Static initialization block
// Initialization code for static variables
}
// Other non-static members...}
5Q. Explain ‘this’ and ‘final’ keywords 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.
public class Person {
String name;
// Constructor with parameter
public Person(String name) {
// Using 'this' to distinguish instance variable from constructor parameter
this.name = name;
}
// Method to display the name
public void displayName() {
// Using 'this' to refer to the instance variable
System.out.println("Name: " + this.name);
}
public static void main(String[] args) {
Person person = new Person("Alice");
person.displayName();
}
}

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;
}
}

6Q. What is method overloading? Explain with an example.

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

2. insert(int offset, String str):


Inserts the specified string at the specified position in the current StringBuffer object.
Returns a reference to the current StringBuffer object.
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb); // Output: Hello World

3. delete(int start, int end):


Removes characters from the current StringBuffer object between the specified start
(inclusive) and end (exclusive) indices.
Returns a reference to the current StringBuffer object.
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(6, 11);
System.out.println(sb); // Output: Hello

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

5. replace(int start, int end, String str):


Replaces the characters in the current StringBuffer object between the specified start
(inclusive) and end (exclusive) indices with the specified string.
Returns a reference to the current StringBuffer object.
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Universe");
System.out.println(sb); // Output: Hello Universe

8Q. What are command line arguments.Explain with an example.


Ans: Command Line Arguments in Java are values or parameters passed to a Java
program during its execution from the command line. These arguments are specified
after the name of the class file when running the Java application. They allow
external input to be provided to the program at runtime.
public class CommandLineExample {
public static void main(String[] args) {
// Checking if any command line arguments are provided
if (args.length == 0) {
System.out.println("No command line arguments provided.");
} else {
System.out.println("Command Line Arguments:");
// Iterating through the command line arguments and printing them
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}
Running the Program: Assuming the compiled class file is named
CommandLineExample.class, you can run the program from the command line as
follows:
java CommandLineExample arg1 arg2 "arg with spaces" arg4

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.

9Q. Define class methods? How to use class methods? Explain.


Ans: Class methods in Java are methods that are associated with the class itself
rather than with instances of the class (objects). They are declared using the static
keyword, making them accessible without creating an instance of the class. Class
methods can be called using the class name, and they often perform operations that
are not dependent on the state of individual objects.
Declaration of Class Method:
public class MyClass {
// Class method (static method)
public static void classMethod() {
// Method implementation
}
// Other members of the class... }
Usage of Class Method:
Calling Class Method Using Class Name:
MyClass.classMethod();
Calling Class Method Using Object (less common, but possible):
MyClass obj = new MyClass();
obj.classMethod(); // Valid, but not recommended

Class methods are declared with the static keyword.


They are associated with the class itself, not with instances of the class.
They can be called using the class name, and it is also possible to call them using an
object reference (though this is not recommended).
Class methods are often used for utility functions, calculations, or operations that
don't depend on the state of individual objects.
Using class methods helps in organizing and encapsulating functionality that is
closely related to the class itself, rather than being tied to specific instances of the
class.

10Q. Explain about parameterized constructor.Give an example for


parameterized constructors in Java.
Ans: A parameterized constructor in Java is a constructor that accepts parameters
or arguments during the object creation process. It allows you to initialize the
instance variables of an object with values provided at the time of object creation.
This enables you to create objects with specific initial states based on the values
passed as parameters.
public class Book {
// Instance variables
String title;
String author;
int year;
// Parameterized constructor
public Book(String title, String author, int year) {
// Initializing instance variables with values passed as parameters
this.title = title;
this.author = author;
this.year = year;
}
// Method to display information about the book
public void displayInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Year: " + year);
}
public static void main(String[] args) {
// Creating a Book object using the parameterized constructor
Book myBook = new Book("Java Programming", "John Doe", 2022);
// Calling the displayInfo method to show information about the book
myBook.displayInfo();
}
}
When you run this program, it will output:
Title: Java Programming
Author: John Doe
Year: 2022

This demonstrates how a parameterized constructor allows you to initialize the


state of an object with specific values during its creation.
11Q. How are pass arguments to a subroutine in java? Give an example.
Ans: In Java, you pass arguments to a subroutine (method) by including them in
the method's parameter list. Parameters act as placeholders for values that you want
to provide when calling the method. The values passed are then used within the
method to perform certain operations.
public class SubroutineExample {
// Subroutine (method) that takes two integers as parameters
public static void addAndDisplay(int num1, int num2) {
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
}
public static void main(String[] args) {
// Calling the method and passing arguments
addAndDisplay(5, 7);
// Calling the method with different arguments
addAndDisplay(10, 20);
}
}

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:

Sum of 5 and 7 is: 12


Sum of 10 and 20 is: 30
12Q. Write a Java program to demostrate the use of static method.
Ans: public class StaticMethodExample {
// Static method that calculates the square of a number
public static int calculateSquare(int number) {
return number * number;
}
public static void main(String[] args) {
// Calling the static method without creating an instance
int result1 = calculateSquare(5);
System.out.println("Square of 5 is: " + result1);
// Calling the static method with a different value
int result2 = calculateSquare(8);
System.out.println("Square of 8 is: " + result2);
}
}

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.

public class Person {


String name;
// Constructor with parameter
public Person(String name) {
// Using 'this' to distinguish instance variable from constructor parameter
this.name = name;
}
// Method to display the name
public void displayName() {
// Using 'this' to refer to the instance variable
System.out.println("Name: " + this.name);
}
public static void main(String[] args) {
Person person = new Person("Alice");
person.displayName();
}
}

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

You might also like