0% found this document useful (0 votes)
11 views15 pages

Oop With Java

Java concept ooo

Uploaded by

hzala2337
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views15 pages

Oop With Java

Java concept ooo

Uploaded by

hzala2337
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

ANS:-1(A)

1. Justify Java is Platform Independent:

Java is platform-independent because its bytecode runs on any system that has a JVM, ensuring
"Write Once, Run Anywhere" compatibility.

2. List Primitive Data Types of Java with its Size and Range:

 byte: 1 byte, range: -128 to 127


 short: 2 bytes, range: -32,768 to 32,767
 int: 4 bytes, range: -2,147,483,648 to 2,147,483,647
 long: 8 bytes, range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
 float: 4 bytes, range: ±1.4 × 10^−45 to ±3.4 × 10^38
 double: 8 bytes, range: ±4.9 × 10^−324 to ±1.8 × 10^308
 char: 2 bytes, range: 0 to 65,535
 boolean: 1 bit, values: true or false

3. Write Syntax for Creating and Initializing an Array:


// Creation
datatype[] arrayName = new datatype[size];

// Initialization
datatype[] arrayName = {value1, value2, value3, ...};

4. List Four Exception Names in Java:

 NullPointerException
 ArrayIndexOutOfBoundsException
 ArithmeticException
 FileNotFoundException

5. Write a Code Snippet Showing Simple Inheritance:


class Animal {
void sound() { System.out.println("Animal sound"); }
}

class Dog extends Animal {


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

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Output: Dog barks
}
}

6. Describe Four Methods of Wrapper Classes:

 parseXxx(String s): Converts a string to a primitive.


 valueOf(Xxx arg): Converts a primitive or string to its wrapper object.
 xxxValue(): Converts a wrapper object to a primitive.
 toString(): Converts the wrapper object to a string.

7. Describe Generic Class with Example:

A generic class allows creating classes that can handle any data type with compile-time type
safety.

class Box<T> {
private T value;
public void setValue(T value) { this.value = value; }
public T getValue() { return value; }
}

ANS:-2(a)

Object-Oriented Programming (OOP) Concepts

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design


around objects rather than functions and logic. These objects represent entities in the real world
and have attributes (data) and methods (functions) that operate on the data. Below are the core
OOP concepts:

1. Class and Object

 Class: A blueprint or prototype for creating objects (instances). It defines a type,


including its attributes (data members) and behaviors (methods).
o Example: class Car { int speed; void accelerate() { speed++; } }
 Object: An instance of a class. It is the actual entity created based on the class definition.
o Example: Car myCar = new Car();

2. Encapsulation

 Definition: Encapsulation is the concept of bundling the data (attributes) and methods
(functions) that operate on the data into a single unit, i.e., a class. It also hides the internal
state of an object from the outside world and only exposes a controlled interface.
 Purpose: To protect an object's state and ensure that it is only accessed in a controlled
manner (using getter and setter methods).
o Example:
o class Person {
o private String name;
o public String getName() { return name; }
o public void setName(String name) { this.name = name; }
o }

3. Inheritance

 Definition: Inheritance is a mechanism where a new class (subclass/child class) can


inherit the properties and behaviors (methods) from an existing class (superclass/parent
class). It allows for reusability and the creation of hierarchical relationships between
classes.

4. Polymorphism

 Definition: Polymorphism allows objects of different classes to be treated as objects of a


common superclass. It enables a single method or operator to work in different ways
depending on the type of object it is acting on.
o Method Overloading: Same method name with different parameters.
o Method Overriding: Subclass provides a specific implementation of a method
already defined in the superclass.
 Purpose: To allow a single interface to represent different underlying forms (data types
or behaviors).

5. Abstraction

 Definition: Abstraction is the process of hiding the complex implementation details


and showing only the essential features of the object. It can be achieved through abstract
classes and interfaces.

6. Association, Aggregation, and Composition


These are relationships between classes that determine how objects of one class relate to objects
of another class.

 Association: A general relationship where objects of one class are associated with objects
of another class.
o Example: A Student can be associated with a Course.
 Aggregation: A special form of association, where one object "owns" another, but both
can exist independently.
o Example: A Library can aggregate many Books, but a Book can exist without a
Library.
 Composition: A stronger form of aggregation where one object "owns" another, and if
the owning object is destroyed, the owned object is also destroyed.
o Example: A House has Rooms; if the House is destroyed, the Rooms are also
destroyed.

7. Constructor

 Definition: A constructor is a special method used to initialize objects when they are
created. It has the same name as the class and does not have a return type.
 Purpose: To ensure that an object is properly initialized with default or provided values
upon creation.
o Example:
o class Car {
o String color;
o Car(String color) { // Constructor
o this.color = color;
o }
o }

8. Overloading and Overriding

 Overloading: The ability to define multiple methods with the same name but different
parameters (method signature).
 Overriding: A subclass provides a specific implementation of a method that is already
defined in its superclass.

ANS-2(B)

Type Casting in Java

Type casting is the process of converting one data type into another. This is typically done when
you need to convert a variable of one type to another type to perform specific operations. In Java,
type casting is necessary when working with variables of different data types to ensure that they
are compatible.
Reasons for Type Casting:

1. Compatibility: To make variables of different types compatible when performing


arithmetic or logical operations.
2. Storage Optimization: To store values of larger types (like double) into smaller types
(like int).
3. Precision Adjustment: When you need to adjust for precision loss or promotion, such as
converting an integer to a floating-point type for more accurate calculations.
4. Interface Implementation: Type casting is used in object-oriented programming when
casting objects to different types in inheritance hierarchies or interfaces.

Types of Type Casting in Java

There are two main types of type casting in Java:

1. Implicit Type Casting (Widening Casting)


2. Explicit Type Casting (Narrowing Casting)

1. Implicit Type Casting (Widening Casting)

 Definition: Implicit casting is done automatically by the Java compiler when you assign
a smaller data type to a larger data type. This is safe because no data will be lost, and the
larger data type can hold all values of the smaller type.
 Example:
 public class ImplicitCasting {
 public static void main(String[] args) {
 int num = 100; // int data type
 double result = num; // Implicit casting from int to double
 System.out.println("The value of result is: " + result); //
Output: 100.0
 }
 }

Explanation:

o Here, the integer value 100 is implicitly cast to a double type. This is because a
double can hold larger values, including integers, without any loss of data.

2. Explicit Type Casting (Narrowing Casting)


 Definition: Explicit casting is required when you want to convert a larger data type to a
smaller one. This type of casting can potentially result in loss of data or precision (e.g.,
truncating a decimal point when converting from double to int).
 Example:
 public class ExplicitCasting {
 public static void main(String[] args) {
 double num = 100.99; // double data type
 int result = (int) num; // Explicit casting from double to int
 System.out.println("The value of result is: " + result); //
Output: 100
 }
 }

Explanation:

o The double value 100.99 is explicitly cast to int. The fractional part .99 is lost
during the casting, and the value becomes 100. This is an example of narrowing
casting, where data may be truncated or rounded.

ANS-3(A)

Method Overloading in Java

Method Overloading is a feature in Java that allows a class to have more than one method with
the same name, but with different parameter lists. The methods must differ in either the number
of parameters, the type of parameters, or both.

Overloading is a form of compile-time polymorphism, meaning the method to be invoked is


determined at compile time based on the method signature (name and parameters).

Key Points About Method Overloading:

1. Same Method Name: The method name remains the same.


2. Different Parameters: Methods must have different parameter lists, either in the number
of parameters or the type of parameters.
3. Return Type Doesn't Matter: Overloading is determined by the parameter list, not the
return type. You cannot overload methods only by changing the return type.

Why Use Method Overloading?

 Improves Code Readability: You can use the same method name to perform similar
operations on different types or numbers of parameters.
 Increases Code Flexibility: Allows a method to work with different data types, without
needing to use different method names.
Example of Method Overloading
public class Calculator {

// Method to add two integers


public int add(int a, int b) {
return a + b;
}

// Method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double numbers


public double add(double a, double b) {
return a + b;
}

// Method to add one integer and one double


public double add(int a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator();

Explanation:

 add(int a, int b): This method takes two integers as arguments.


 add(int a, int b, int c): This method takes three integers as arguments.
 add(double a, double b): This method takes two double values as arguments.
 add(int a, double b): This method takes one integer and one double as arguments.

Each method has the same name add, but they differ in the number or type of parameters. Java
determines which method to call based on the method signature (number and type of parameters)
at compile time.

Key Benefits of Method Overloading:

1. Simplifies Code: You don't need to have multiple method names for similar operations.
2. Flexible: One method name can handle different types or numbers of inputs.
3. Improves Maintainability: By using the same method name, it's easier to update the
4. logic in one place.

ANS-3(B)

Passing and Returning Objects as Parameters in Java


In Java, objects are passed to methods by reference (actually, by the reference to the object),
which means that when you pass an object to a method, the method can modify the object's state
(i.e., the object's instance variables). However, you cannot change the reference itself within the
method (i.e., you cannot reassign the object to a new instance and have the calling method reflect
that change).

Similarly, when an object is returned from a method, the reference to the object is returned, not a
copy of the object itself. This allows the method to return an object that can be used outside of
the method.

Key Concepts:

 Passing Objects as Parameters: When you pass an object to a method, you're passing a
reference to the object, not the actual object.
 Returning Objects from Methods: Methods can return objects by returning a reference
to the object.

1. Passing Objects as Parameters

When you pass an object as a parameter to a method, the method operates on the object via its
reference, and changes made to the object within the method will affect the original object.
However, if you assign a new object to the parameter, it will not affect the original object.

Example: Passing Objects as Parameters


class Person {
String name;
int age;

// Constructor to initialize Person object


Person(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display Person information


void display() {
System.out.println("Name: " + name + ", Age: " + age);
}

// Method to update Person information (changes the state of the object)


void updateAge(int newAge) {
this.age = newAge;
}
}

public class PassObjectExample {

// Method that takes a Person object as a parameter


static void modifyPerson(Person p) {
p.updateAge(30); // Changing the state of the object
p.name = "John Doe"; // Directly modifying the object's attributes
}

public static void main(String[] args) {


// Creating a Person object
Person person = new Person("Alice", 25);

// Before modifying
System.out.println("Before modify:");
person.display(); // Output: Name: Alice, Age: 25

// Passing the Person object to the modifyPerson method


modifyPerson(person);

// After modifying
System.out.println("After modify:");
person.display(); // Output: Name: John Doe, Age: 30
}
}

2. Returning Objects from Methods

In Java, a method can return an object by returning the reference to the object. The calling code
can then use this returned reference to access the object's state and methods.

Example: Returning Objects from Methods


class Rectangle {
int length;
int width;

// Constructor to initialize Rectangle object


Rectangle(int length, int width) {
this.length = length;
this.width = width;
}

// Method to calculate area of the rectangle


int calculateArea() {
return length * width;
}
}

public class ReturnObjectExample {

// Method that returns a Rectangle object


static Rectangle createRectangle(int length, int width) {
// Creating and returning a new Rectangle object
return new Rectangle(length, width);
}

public static void main(String[] args) {


// Calling createRectangle method and storing the returned object in a
variable
Rectangle rect = createRectangle(10, 20);

// Accessing the properties and methods of the returned Rectangle


object
System.out.println("Area of rectangle: " + rect.calculateArea()); //
Output: 200
}
}

ANS-5(A)

Methods of String Class in Java

The String class in Java is a part of the java.lang package and represents a sequence of
characters. It is immutable, meaning once a String object is created, its value cannot be
changed.

Here is a list of common methods in the String class along with explanations and examples:

1. length()

 Description: Returns the length of the string (the number of characters).


 Syntax: int length()
 Example:
 String str = "Hello";
 System.out.println(str.length()); // Output: 5

2. charAt(int index)

 Description: Returns the character at the specified index.


 Syntax: char charAt(int index)
 Example:
 String str = "Hello";
 System.out.println(str.charAt(1)); // Output: 'e'

3. substring(int beginIndex)

 Description: Returns a new string that is a substring of the original string, starting from the
specified beginIndex to the end of the string.
 Syntax: String substring(int beginIndex)
 Example:
 String str = "Hello";
 System.out.println(str.substring(2)); // Output: "llo"
4. substring(int beginIndex, int endIndex)

 Description: Returns a new string that is a substring of the original string, starting from
beginIndex to endIndex - 1.
 Syntax: String substring(int beginIndex, int endIndex)
 Example:
 String str = "Hello";
 System.out.println(str.substring(1, 4)); // Output: "ell"

5. indexOf(String str)

 Description: Returns the index of the first occurrence of the specified substring. If the substring
is not found, it returns -1.
 Syntax: int indexOf(String str)
 Example:
 String str = "Hello";
 System.out.println(str.indexOf("e")); // Output: 1

6. equals(Object obj)

 Description: Compares the string with the specified object. Returns true if the strings are equal
(case-sensitive), and false otherwise.
 Syntax: boolean equals(Object obj)
 Example:
 String str1 = "Hello";
 String str2 = "Hello";
 System.out.println(str1.equals(str2)); // Output: true

Methods of StringBuffer Class

The StringBuffer class is part of the java.lang package and is used to create mutable
sequences of characters. Unlike String, objects of StringBuffer can be modified after
creation. It is more efficient when performing many modifications to a string, such as appending,
deleting, or inserting characters.

Here are some common methods of the StringBuffer class:

1. append(String str)

 Description: Appends the specified string to the end of the current StringBuffer.
 Syntax: StringBuffer append(String str)
 Example:
 StringBuffer sb = new StringBuffer("Hello");
 sb.append(" World");
 System.out.println(sb); // Output: "Hello World"
2. insert(int offset, String str)

 Description: Inserts the specified string at the given position (offset) in the StringBuffer.
 Syntax: StringBuffer insert(int offset, String str)
 Example:
 StringBuffer sb = new StringBuffer("Hello World");
 sb.insert(5, " Beautiful");
 System.out.println(sb); // Output: "Hello Beautiful World"

3. delete(int start, int end)

 Description: Deletes characters from the StringBuffer starting from start index to end -
1 index.
 Syntax: StringBuffer delete(int start, int end)
 Example:
 StringBuffer sb = new StringBuffer("Hello World");
 sb.delete(5, 11);
 System.out.println(sb); // Output: "Hello"

4. reverse()

 Description: Reverses the characters in the StringBuffer.


 Syntax: StringBuffer reverse()
 Example:
 StringBuffer sb = new StringBuffer("Hello");
 sb.reverse();
 System.out.println(sb); // Output: "olleH"

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

 Description: Replaces the characters in the specified range (from start to end - 1) with the
given string.
 Syntax: StringBuffer replace(int start, int end, String str)
 Example:
 StringBuffer sb = new StringBuffer("Hello World");
 sb.replace(6, 11, "Java");
 System.out.println(sb); // Output: "Hello Java"

6. capacity()

 Description: Returns the current capacity of the StringBuffer. The capacity is the amount of
space allocated for the string data.
 Syntax: int capacity()
 Example:
 StringBuffer sb = new StringBuffer("Hello");
 System.out.println(sb.capacity()); // Output: 16 (default capacity of
StringBuffer)

ANS-5(b)

Byte Stream Classes in Java

In Java, Byte Streams are used to handle input and output (I/O) of raw binary data. Byte streams
work with 8-bit bytes and are used to read and write all kinds of I/O, including binary data, such
as images, audio files, and serialized objects. Byte streams are designed for handling data in the
form of raw bytes, which allows them to be used for reading and writing any kind of data.

Java provides two main types of byte stream classes:

1. InputStream (for reading byte data)


2. OutputStream (for writing byte data)

These classes are the superclasses of the various specialized byte stream classes that read and
write data from specific sources such as files, memory, or network connections.

1. InputStream (Abstract Class)

InputStream is an abstract class in Java that represents all byte input streams. It is the parent
class of many specific input stream classes that allow reading from various sources, such as files
or arrays.

Common Methods of InputStream:

 int read(): Reads the next byte of data from the input stream. Returns -1 if the end of the
stream is reached.
 int read(byte[] b): Reads up to b.length bytes of data into an array of bytes. Returns
the number of bytes read, or -1 if the end of the stream is reached.
 long skip(long n): Skips over n bytes of data from the input stream.
 int available(): Returns the estimated number of bytes that can be read (or skipped)
without blocking.
 void close(): Closes the input stream and releases any system resources associated with it.

Subclasses of InputStream:

 FileInputStream: Reads data from a file.


 ByteArrayInputStream: Reads data from an array of bytes.
 BufferedInputStream: Adds buffering to an existing input stream for improved efficiency.
 DataInputStream: Allows reading Java primitive data types (like int, float, etc.) from an input
stream.
2. OutputStream (Abstract Class)

OutputStream is an abstract class that represents all byte output streams. It provides the base
functionality to write data to various output destinations such as files, memory buffers, and
network connections.

Common Methods of OutputStream:

 void write(int b): Writes the specified byte to the output stream.
 void write(byte[] b): Writes b.length bytes from the specified byte array to the output
stream.
 void write(byte[] b, int off, int len): Writes len bytes from the specified byte
array, starting from position off, to the output stream.
 void flush(): Ensures that all data is written to the underlying output stream. This is
important when data is buffered.
 void close(): Closes the output stream and releases any system resources associated with it.

Subclasses of OutputStream:

 FileOutputStream: Writes data to a file.


 ByteArrayOutputStream: Writes data to a byte array in memory.
 BufferedOutputStream: Adds buffering to an existing output stream for improved efficiency.
 DataOutputStream: Allows writing Java primitive data types (like int, float, etc.) to an output
stream.

3. Common Byte Stream Classes

FileInputStream

FileInputStream is used to read byte data from a file. It is the most commonly used class for
file input operations.

 Example: Reading bytes from a file.


 FileInputStream fis = new FileInputStream("input.txt");
 int byteData;
 while ((byteData = fis.read()) != -1) {
 System.out.print((char) byteData); // Output the bytes as
characters
 }
 fis.close();
FileOutputStream

FileOutputStream is used to write byte data to a file. It writes data in raw bytes (not
characters).

 Example: Writing bytes to a file.


 FileOutputStream fos = new FileOutputStream("output.txt");
 String str = "Hello, World!";
 fos.write(str.getBytes()); // Convert string to byte array and write to
file
 fos.close();
BufferedInputStream

BufferedInputStream is used to read data from an input stream more efficiently by buffering
the data. It is often used in conjunction with other input stream classes, such as
FileInputStream, to improve performance, especially when reading large amounts of data.

BufferedOutputStream

BufferedOutputStream is used to write data to an output stream more efficiently by buffering


the data. It is commonly used with other output streams, like FileOutputStream, to improve
performance.

 ;
ByteArrayInputStream

ByteArrayInputStream is used to read byte data from a byte array, which makes it ideal for
scenarios where the input data is available in memory rather than from an external source like a
file.

ByteArrayOutputStream

ByteArrayOutputStream is used to write byte data to an in-memory byte array. It is useful


when you need to accumulate data in memory before writing it to another destination (e.g., a file,
or a network socket).

You might also like