Java Preparation Unit - 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Java Preparation

Unit-2
Derived Syntactical constructs in java
2 Marks
1. Explain constructor with suitable example.
OR
Define Constructor. List its types.
Ans) • Constructor is a special member function used to initialize the object.
• A constructor has the same name as the class.
• It doesn't have a return type, not even void.

Types of constructor are:


▪ Default Constructor
▪ Parameterised Constructor
▪ Copy constructor

For Example:
class Test
{
Test()
{
// constructor body
}
}

2. Name the wrapper class methods of the following:


(i)To convert String object to primitive int
(ii)To convert primitive int to String object.
Ans) (i) To convert string objects to primitive int:
String str=”5”;
int value = Integer.parseInt(str);

(ii) To convert primitive int to string objects:


int value=5;
String str=Integer.toString(value);

3. State the use of finalize() method with its syntax.


Ans) Finalize() Method:
• The finalize() method in Java is a special method that belongs to the Object class.
• It is called by the garbage collector when an object is about to be garbage
collected, just before the object is reclaimed by the memory management system.
• The purpose of the finalize() method is to perform any necessary cleanup or
resource releasing operations before an object is destroyed.
• The finalize() method is declared with the protected access modifier, which
means it can only be accessed within the same package or by subclasses of the
class where it is defined.
• The method has a return type of void, meaning it does not return any value.
It can optionally throw a Throwable object, allowing subclasses to override and

throw exceptions if necessary.
Syntax:
protected void finalize() throws Throwable {
// Cleanup and resource releasing operations
// Code to be executed before the object is garbage collected
}

4. Define class and object with example.


Ans) Class:
• A class in Java is a blueprint or template that defines the structure and behavior of
objects.
• It encapsulates data (attributes) and methods (behaviors) that operate on that
data.
• Classes serve as the foundation for creating objects in Java.

Object:
• An object is an instance of a class.
• It represents a specific instance of the class, with its own unique identity, state,
and behavior.
• Objects encapsulate data and behavior defined by their class.

Common Example:
public class Car {
String make;
String model;
int year;
}
public class Main
{
public static void main(String[] args)
{
Car car1 = new Car();

car1.make = "Toyota";
car1.model = "Camry";
car1.year = 2020;
}
}

5. Give use of garbage collection in java.


Ans) • Garbage collection in Java is an automatic memory management process that helps
in reclaiming memory occupied by objects that are no longer in use.
• The primary purpose of garbage collection is to free up memory that is no longer
referenced by any part of the program, improving the efficiency of memory usage.
• Garbage collection relieves developers from manually deallocating memory, as it
automatically identifies and collects objects that are no longer needed.
• Garbage collection prevents memory leaks by reclaiming memory occupied by
objects that are no longer reachable or referenced by the program.
• Garbage collection improves application performance by efficiently managing
memory resources.
• Garbage collection allows for dynamic memory allocation, where memory is
allocated as needed during program execution.

4 Marks
1. Compare array and vector. Explain elementAt() and addElement() method.
OR
Difference between array and vector.
Ans) Difference between array and vector:

Sr.no Array Vector


1. Arrays are fixed size data structures Vectors are dynamic size data
in Java. structures in Java
2. They can hold elements of the same They can hold elements of any data
data type type
3. Arrays are not dynamic Their size Vectors automatically resize
cannot be changed once defined themselves when needed
4. Arrays are faster and more memory Vectors are synchronised, making them
efficient than vectors thread safe, but slower than arrays
5. Array is not a class Vector is a class
6. Array can store primitive type data Vectors can store nonprimitive type
elements data elements
7. No methods are provided for adding Vector provides method for adding and
and removing elements removing elements
8. In array wrapper classes are not Wrapper classes are used in vector.
used.

❖ elementAt() Method (Vector):


• The elementAt() method is used to retrieve the element at a specified index in
a vector.
• Syntax: Object elementAt(int index)
• Example:
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int value = numbers.elementAt(1);

❖ addElement() Method (Vector):


• The addElement() method is used to add an element to the end of a vector.
• Syntax: void addElement(Object obj)
• Example:
Vector<String> names = new Vector<>();
names.add("Alice");
names.add("Bob");
names.addElement("Charlie");

2. Explain the type of constructor in java and suitable example of copy constructor.
OR
Explain the types of constructors in Java with suitable example.
OR
What is constructor? List types of constructor. Explain parameterized constructor
with suitable example.
OR
Explain the type of constructor with example of parameterized constructor.
Ans) Constructor:
• Constructor is a special member function used to initialize the object.
• A constructor has the same name as the class.
• It doesn't have a return type, not even void.

Types of constructor are:


▪ Default Constructor
▪ Parameterised Constructor
▪ Copy constructor

1. Default Constructor:
• A default constructor is provided by Java if no constructor is explicitly defined in
a class.
• It initializes the object with default values (e.g., 0 for numeric types, null for
reference types).
• The default constructor has no parameters.
• Example:
public class MyClass {
int value;

public MyClass() {
value = 0;
}

public static void main(String[] args) {


MyClass obj = new MyClass();
System.out.println("Default value: " + obj.value);
}
}
2. Parameterized Constructor:
• A parameterized constructor is a constructor with parameters.
• It allows initialization of objects with specific values passed as arguments.
• Parameterized constructors are used to initialize object properties based on
provided values.
• Example:
public class MyClass {
int value;
public MyClass(int val) {
value = val;
}

public static void main(String[] args) {


MyClass obj = new MyClass(10);
System.out.println("Value: " + obj.value);
}
}

3. Copy Constructor:
• A copy constructor is used to create a new object as a copy of an existing object.
• It initializes the new object with the values of another object of the same class.
• Copy constructors take an object of the same class as a parameter.
• Example:
public class MyClass {
int value;

public MyClass(MyClass original) {


value = original.value;
}

public static void main(String[] args) {


MyClass obj1 = new MyClass(20);
MyClass obj2 = new MyClass(obj1);
System.out.println("Copied value: " + obj2.value);
}
}
Common Example:
public class MyClass {
int value;

public MyClass() {
value = 0;
}

public MyClass(int val) {


value = val;
}

public MyClass(MyClass original) {


value = original.value;
}

public static void main(String[] args) {


MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass(10);
MyClass obj3 = new MyClass(obj2);

System.out.println("Default value: " + obj1.value);


System.out.println("Value: " + obj2.value);
System.out.println("Copied value: " + obj3.value);
}
}

3. Describe instance Of and (.) operators in java with suitable example.


Ans) 1. Instanceof Operator (instanceof):
• The instanceof operator is used to test whether an object is an instance of a
particular class or interface.
• It returns true if the object is an instance of the specified class or interface,
otherwise, it returns false.
• Syntax: object instanceof ClassName
• Example:
// Example class hierarchy
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

public class Main {


public static void main(String[] args) {
Animal animal = new Dog();
System.out.println(animal instanceof Animal); // Output: true
System.out.println(animal instanceof Dog); // Output: true
System.out.println(animal instanceof Cat); // Output: false
}
}

2. Dot Operator (.):


• The dot (.) operator is used to access members of a class, including fields,
methods, and nested classes.
• It is also used to access static members of a class using the class name.
• Syntax: object.field, object.method(), ClassName.staticField,
ClassName.staticMethod()
• Example:
class MyClass {
int value;
void display() {
System.out.println("Value: " + value);
}
static int staticValue = 10;
static void staticMethod() {
System.out.println("Static value: " + staticValue);
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.value = 20;
obj.display();
System.out.println(obj.value);

MyClass.staticMethod();
System.out.println(MyClass.staticValue);
}
}

4. Difference between String and String Buffer.


Ans) Sr.no String String Buffer
1. String is a major class String buffer is a peer glass of string
2. The length of the string object is The length of the string buffer object
fixed. can be increased
3. String object is immutable String buffer object is mutable
4. It is Slower during concatenation It is faster during concatenation
5. It consumes more memory It consumes less memory
6. Ex:- String s=”abc”‖; Ex:- StringBuffer s=new StringBuffer
(“abc”);
7. Methods of string class: Methods of StringBuffer class:
toLowerCase(), setCharAt(),
toUpperCase(), append(),
replace(), insert(),
trim(), append(),
equals(), reverse(),
length(), delete()
charAt(),
concat(),
substring(),
compareTo()
.
5. Describe final variable and final method.
Ans) 1. Final Variable:
• A final variable is a variable whose value cannot be changed once it has been
assigned.
• It is a constant and can only be initialized once.
• Once initialized, the value of a final variable remains constant throughout the
program.
• Final variables must be initialized either at the time of declaration or within a
constructor.
• Syntax: final dataType variableName = value;
• Example:
public class MyClass {
final int MAX_VALUE = 100;

public static void main(String[] args) {


MyClass obj = new MyClass();
// obj.MAX_VALUE = 200; // Compilation error: Cannot assign a value to
final variable
System.out.println("Max value: " + obj.MAX_VALUE);
}
}

2. Final Method:
• A final method is a method that cannot be overridden by subclasses.
• Once a method is declared final in a superclass, subclasses cannot override it.
• Final methods provide stability and security in class hierarchies by preventing
modification of critical behavior.
• Final methods are typically used to define immutable behavior or critical
functionality that should not be altered.
• Syntax: final returnType methodName(parameters) { // Method body }
• Example:
class Parent
{
final void display() {
System.out.println("Displaying from Parent");
}
}

class Child extends Parent {


// void display() { } // Compilation error: Cannot override the final method
from Parent
}

public class Main {


public static void main(String[] args) {
Parent obj = new Parent();
obj.display();
}
}

6. List any four methods of string class and state the use of each.
Ans) Methods of string class:
1. charAt(int index):
• This method returns the character at the specified index within the string.
• Example:
String str = "Hello";
char ch = str.charAt(0); // Returns 'H'
2. length():
• This method returns the length of the string.
• Example use:
String str = "Hello";
int length = str.length(); // Returns 5

3. substring(int beginIndex):
• This method returns a new string that is a substring of the original string,
starting from the specified index.
• Example use:
String str = "Hello World";
String substr = str.substring(6); // Returns "World"

4. indexOf(String str):
• This method returns the index of the first occurrence of the specified
substring within the string, or -1 if the substring is not found.
• Example use:
String str = "Hello World";
int index = str.indexOf("World"); // Returns 6

7. List any four methods of string buffer class and state the use of each.
Ans) 1. append(String str):
• This method appends the specified string to the end of the StringBuffer
object.
• Example use:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Result: "Hello World"

2. insert(int offset, String str):


• This method inserts the specified string at the specified offset position
within the StringBuffer object.
• Example use:
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World"); // Result: "Hello World"

3. delete(int start, int end):


• This method deletes the characters within the specified range from the
StringBuffer object.
• Example use:
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11); // Result: "Hello"

4. reverse():
• This method reverses the characters in the StringBuffer object.
• Example use:
StringBuffer sb = new StringBuffer("Hello");
sb.reverse(); // Result: "olleH"
8. Any four method of vector class with example.
OR
Describe the use of any methods vector class with their syntax.
Ans) 1. addElement(E element):
• This method appends the specified element to the end of the vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);

2. insertElementAt(E element, int index):


• This method inserts the specified element at the specified index in the
vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.insertElementAt(15, 1); // Inserts 15 at index 1

3. removeElementAt(int index):
• This method removes the element at the specified index from the vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);
vector.removeElementAt(1); // Removes the element at index 1 (20)

4. clear():
• This method removes all elements from the vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);
vector.clear(); // Removes all elements

5. indexOf(Object o):
• This method returns the index of the first occurrence of the specified
element in the vector, or -1 if the element is not found.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);
int index = vector.indexOf(20); // Returns 1

6. equals(Object obj):
• This method compares the specified object with the vector for equality.
• Example:
Vector<Integer> vector1 = new Vector<>();
vector1.addElement(10);
vector1.addElement(20);

Vector<Integer> vector2 = new Vector<>();


vector2.addElement(10);
vector2.addElement(20);

boolean isEqual = vector1.equals(vector2); // Returns true

9. Explain dynamic method dispatch in Java with suitable example.


Ans) • Dynamic method dispatch is a mechanism by which a call to an overridden
method is resolved at runtime rather than compile time.
• It enables polymorphism in Java, allowing objects of different classes to respond
to the same method call differently.
• It is achieved through method overriding, where a subclass provides a specific
implementation for a method defined in its superclass.
• The actual method invoked is determined by the runtime type of the object and
not by the reference type.
• It facilitates code reusability and flexibility in object-oriented programming by
promoting subtype polymorphism.
• Dynamic method dispatch is a key feature of runtime polymorphism in Java,
enhancing the extensibility and maintainability of code.

Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void makeSound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


void makeSound() {
System.out.println("Cat meows");
}
}

public class DynamicDispatchExample {


public static void main(String[] args) {
Animal animal;
animal = new Dog(); // Upcasting
animal.makeSound(); // Calls Dog's version of makeSound()

animal = new Cat(); // Upcasting


animal.makeSound(); // Calls Cat's version of makeSound()
}
}

6 Marks
1. Explain the command line arguments with suitable example.
Ans) • Command-line arguments are parameters passed to a program when it is executed
from the command line or terminal.
• These arguments provide input data to the program and can be accessed within the
program's main method.
• In Java, command-line arguments are stored as strings in the args parameter of the
main method.

Here's how command-line arguments are used in Java:


public class CommandLineExample
{
public static void main(String[] args)
{
// Display the number of command-line arguments
System.out.println("Number of arguments: " + args.length);

// Display each command-line argument


for (int i = 0; i < args.length; i++)
{
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}

When running this program from the command line, you can provide command-line
arguments separated by spaces.

For example:
javac CommandLineExample.java
java CommandLineExample arg1 arg2 arg3

Output:
Number of arguments: 3
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
2. Explain vector with the help of example. Explain any 3 methods of vector
class.
Ans) Vector:
• A Vector in Java is a dynamic array-like data structure that allows elements to be
added or removed dynamically.
• It is similar to an ArrayList but is synchronized, making it thread-safe.
• Vectors can hold elements of any data type.
• They automatically resize themselves as needed.

Example:
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
Vector<String> names = new Vector<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("Vector elements: " + names);
System.out.println("Element at index 1: " + names.get(1));
names.remove(2);
System.out.println("After removing element at index 2: " + names);
}
}

Methods of Vectors:
1. addElement(E element):
• This method appends the specified element to the end of the vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);

2. insertElementAt(E element, int index):


• This method inserts the specified element at the specified index in the
vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.insertElementAt(15, 1); // Inserts 15 at index 1

3. removeElementAt(int index):
• This method removes the element at the specified index from the vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);
vector.removeElementAt(1); // Removes the element at index 1 (20)

4. clear():
• This method removes all elements from the vector.
• Example:
Vector<Integer> vector = new Vector<>();
vector.addElement(10);
vector.addElement(20);
vector.clear(); // Removes all elements

You might also like