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

OOPs Solution

The document provides an introduction to Java programming, covering syntax errors, runtime errors, and logic errors with examples. It explains various types of operators, the concept of the Java Virtual Machine (JVM), features of Java, and the principles of object-oriented programming (OOP). Additionally, it discusses type casting, method definitions, method overloading, constructors, and polymorphism with relevant examples.

Uploaded by

vivekt1020
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)
15 views

OOPs Solution

The document provides an introduction to Java programming, covering syntax errors, runtime errors, and logic errors with examples. It explains various types of operators, the concept of the Java Virtual Machine (JVM), features of Java, and the principles of object-oriented programming (OOP). Additionally, it discusses type casting, method definitions, method overloading, constructors, and polymorphism with relevant examples.

Uploaded by

vivekt1020
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/ 22

UNIT 1 : Introduction to java and elementary programming

1. What are syntax errors, runtime errors, and logic errors? Discuss with
examples.
--> Syntax Errors:

These are mistakes in writing the code that break the rules of the Java language.

The program won't compile if there's a syntax error.

It’s like making a spelling or grammar mistake in English.

Example : public class Example {

public static void main(String[] args) {

System.out.println("Hello, World!")

🔴 Error: Missing semicolon (;) at the end of the println statement

--> Runtime Errors:

These errors occur while running the program.

The program compiles successfully, but crashes or behaves unexpectedly during execution.

Often caused by dividing by zero, accessing invalid array indexes, or incorrect input.

Example : public class Example {

public static void main(String[] args) {

int num = 10;

int result = num / 0; // Division by zero

System.out.println(result);

🔴 Error: ArithmeticException: / by zero

--> Logic Errors:

These errors don't cause the program to crash, but the output is incorrect or unexpected.

The program runs smoothly, but the logic or formula used is wrong.
Usually, it's a mistake in thinking or planning.

Example : public class Example {

public static void main(String[] args) {

int num1 = 5;

int num2 = 3;

int sum = num1 * num2; // Wrong logic: Used multiplication instead of addition

System.out.println("Sum: " + sum);

🔴 Error: The output will be Sum: 15 instead of Sum: 8.

(The logic should have been num1 + num2.)

2. Explain types of operators.


In Java, operators are symbols that perform operations on variables and values. They help in
calculations, comparisons, logical operations, and more. Let's look at the types of operators in Java
with simple explanations and examples.

i) Arithmetic Operators:

Used for basic mathematical operations.

+ (Addition)

- (Subtraction)

* (Multiplication)

/ (Division)

% (Modulus — Remainder)

Example:

int a = 10;

int b = 3;

System.out.println(a + b); // 13
System.out.println(a - b); // 7

System.out.println(a * b); // 30

System.out.println(a / b); // 3 (integer division)

System.out.println(a % b); // 1 (remainder)

ii) Relational Operators:

Used to compare two values. The result is true or false.

== (Equal to)

!= (Not equal to)

> (Greater than)

< (Less than)

>= (Greater than or equal to)

<= (Less than or equal to)

Example :

int x = 5;

int y = 8;

System.out.println(x == y); // false

System.out.println(x != y); // true

System.out.println(x > y); // false

System.out.println(x < y); // true

System.out.println(x >= y); // false

System.out.println(x <= y); // true

iii) Logical Operators:

Used for combining multiple conditions. Result is true or false.

&& (Logical AND) — true if both conditions are true.

|| (Logical OR) — true if at least one condition is true.


! (Logical NOT) — reverses the condition.

Example :

boolean a = true;

boolean b = false;

System.out.println(a && b); // false (both should be true)

System.out.println(a || b); // true (one is true)

System.out.println(!a); // false (reverse of true)

iv) 4. Assignment Operators:

Used to assign values to variables.

= (Assign)

+= (Add and assign)

-= (Subtract and assign)

*= (Multiply and assign)

/= (Divide and assign)

%= (Modulus and assign)

Example :

int num = 10;

num += 5; // num = num + 5

System.out.println(num); // 15

num *= 2; // num = num * 2

System.out.println(num); // 30

v) Unary Operators:

Work with one operand.

+ (Positive)
- (Negative)

++ (Increment)

-- (Decrement)

! (Logical NOT)

Example : int a = 5;

System.out.println(+a); // 5

System.out.println(-a); // -5

System.out.println(++a); // 6 (Increment: a = a + 1)

System.out.println(--a); // 5 (Decrement: a = a - 1)

vi) Bitwise Operators:

Operate on binary (bit-level) values.

& (Bitwise AND)

| (Bitwise OR)

^ (Bitwise XOR)

~ (Bitwise NOT)

<< (Left Shift)

>> (Right Shift)

Example :

int a = 5; // Binary: 0101

int b = 3; // Binary: 0011

System.out.println(a & b); // 1 (0101 & 0011 = 0001)

System.out.println(a | b); // 7 (0101 | 0011 = 0111)

System.out.println(a ^ b); // 6 (0101 ^ 0011 = 0110)

System.out.println(~a); // -6 (Inverts all bits of 5)

vii) Conditional (Ternary) Operator:


Shortcut for if-else.

Syntax:

result = (condition) ? value_if_true : value_if_false;

Example:

int a = 10;

int b = 20;

String result = (a > b) ? "A is greater" : "B is greater";

System.out.println(result); // B is greater

3. Justify Statement: JVM is Platform Dependant.


JVM (Java Virtual Machine) is platform-dependent because each operating system (Windows, Linux,
Mac) has its own version of JVM.

The Java program (.class file) is platform-independent, meaning it can run on any OS. However, the
JVM that executes this program is specific to the OS. Each OS has a different way of handling system
resources, memory, and files, so a separate JVM is needed for each platform.

👉 Conclusion: The bytecode is platform-independent, but the JVM that runs it is platform-
dependent.

4. Explain Features of JAVA & Explain Concept Of OOP.


Features of Java:

Java has several key features that make it popular and powerful:

Simple: Easy to learn with a clear syntax similar to C++.

Object-Oriented: Uses classes and objects to organize code.

Platform-Independent: Write once, run anywhere — Java bytecode runs on any JVM.

Secure: Provides features like bytecode verification, no pointers, and built-in security.

Portable: Java programs can be easily moved and run on different systems.

Robust: Strong memory management, exception handling, and type checking.

Multithreaded: Supports multitasking by running multiple threads simultaneously.


Distributed: Can work on distributed systems through networking and RMI (Remote Method
Invocation).

High Performance: Uses Just-In-Time (JIT) compiler for faster execution.

Dynamic: Supports dynamic loading of classes and methods at runtime.

Concept of OOP (Object-Oriented Programming):

OOP is a programming style that uses objects and classes to organize code. It helps in creating
modular, reusable, and efficient code.

Key Concepts of OOP:

Class: A blueprint for creating objects (like a car's design).

Object: An instance of a class (a specific car).

Inheritance: Acquiring properties from a parent class (child inherits from parent).

Polymorphism: One task performed in different ways (method overloading/overriding).

Encapsulation: Hiding data and providing access through methods (like a capsule).

Abstraction: Hiding complex details and showing only essentials (like driving a car without knowing
its internal mechanism).

UNIT 2 : Selections , Mathematical functions and loops


1. What is Type Casting? Explain its Types.
Type casting in Java is converting one data type into another. It is useful when we need to perform
operations between different types of data.

Types of Type Casting in Java:

i. Implicit Type Casting (Widening)

Automatically done by Java when converting a smaller data type to a larger one.

No data loss occurs.

🔹 Example:

int num = 10;

double result = num; // Automatic conversion from int to double

System.out.println(result); // 10.0
ii. Explicit Type Casting (Narrowing)

Manually done by the programmer using (dataType).

Converts a larger data type to a smaller one.

May cause data loss.

🔹 Example:

double num = 10.99;

int result = (int) num; // Manual conversion from double to int

System.out.println(result); // 10 (Decimal part lost)

✔ Widening (Implicit Casting) → Automatic, No data loss.

✔ Narrowing (Explicit Casting) → Manual, Data loss possible.

2. Write a single Java program that demonstrates the usage of the following
keywords: import,new, this, break, continue.
Code : // import keyword: Importing Scanner class for user input

import java.util.Scanner;

class Example {

int num;

// Using 'this' keyword to refer to the current object's variable

Example(int num) {

this.num = num;

void showNumbers() {

for (int i = 1; i <= 10; i++) {

if (i == 5) {

continue; // Skip number 5 and continue loop

if (i == 8) {
break; // Stop loop when i reaches 8

System.out.println(i);

public class KeywordDemo {

public static void main(String[] args) {

// Using 'new' keyword to create an object

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int num = scanner.nextInt();

Example obj = new Example(num); // Creating object using 'new'

obj.showNumbers(); // Calling method

scanner.close();

Explanation of Keywords:

import → Imports Scanner class for user input.

new → Creates an object of Scanner and Example class.

this → Refers to the instance variable inside the constructor.

break → Stops the loop when i == 8.

continue → Skips i == 5 and moves to the next iteration.

UNIT 3 : Methods and Arrays


1. Explain Pass by Value and Pass by Reference With Examples.
i) Pass by Value (Primitive Data Types)

When primitive data types (int, float, char, etc.) are passed, Java creates a copy of the variable.

Any changes made inside the method do not affect the original variable.

Example:

class Test {

void modify(int num) {

num = num + 10; // Changes only local copy

System.out.println("Inside method: " + num);

public static void main(String[] args) {

int x = 20;

Test obj = new Test();

obj.modify(x);

System.out.println("Outside method: " + x); // Original value remains unchanged

🔹 Output:

Inside method: 30

Outside method: 20

👉 Here, x remains 20 outside the method because Java passes a copy of the value.

Ii) Pass by Reference (Objects - Indirectly)

Java does not support pass by reference, but when an object reference is passed, changes made
inside the method reflect on the original object because both point to the same memory location.

Example:

class Example {

int num;

Example(int num) {
this.num = num;

void modify(Example obj) {

obj.num += 10; // Changes the original object's value

public static void main(String[] args) {

Example obj = new Example(20);

System.out.println("Before method: " + obj.num);

obj.modify(obj); // Passing object reference

System.out.println("After method: " + obj.num); // Value is modified

🔹 Output:

Before method: 20

After method: 30

👉 Here, obj.num changes because the method modifies the same object in memory.

2. How is a method defined & What is Method Overloading ?


i) How is a Method Defined in Java?

A method in Java is a block of code that performs a specific task. It helps in code reusability and
modularity.

Syntax of a Method:

returnType methodName(parameters) {

// method body

return value; // (if returnType is not void)

ii) What is Method Overloading?


Method Overloading means defining multiple methods with the same name but different
parameters in the same class. Java decides which method to call based on the number and type of
arguments.

Rules for Method Overloading:

✅ Methods must have the same name

✅ Different parameters (different number or types of parameters)

✅ Return type does NOT matter

Example : class Calculator {

// Method with two int parameters

int add(int a, int b) {

return a + b;

// Overloaded method with three int parameters

int add(int a, int b, int c) {

return a + b + c;

// Overloaded method with double parameters

double add(double a, double b) {

return a + b;

UNIT 4: Objects and Classes


1. What is a constructor? Explain any one with an example.
A constructor is a special method used to initialize objects when they are created. It has the same
name as the class and no return type (not even void).
Types of Constructors in Java :

Default Constructor → No parameters, assigns default values.

Parameterized Constructor → Takes parameters, assigns custom values.

Copy Constructor → Creates a new object by copying values from another object.

Example: Parameterized Constructor

A parameterized constructor allows passing values while creating an object.

Example:

class Student {

String name;

int age;

// Parameterized Constructor

Student(String n, int a) {

name = n;

age = a;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

public static void main(String[] args) {

// Creating objects using the constructor

Student s1 = new Student("Alice", 20);

Student s2 = new Student("Bob", 22);

s1.display();

s2.display();

🔹 Output:
Name: Alice, Age: 20

Name: Bob, Age: 22

👉 Here, the constructor initializes name and age for each student object when it is created.

UNIT 5: Object oriented thinking


1.Write a program that shows an example of function overloading .
class MathOperations {

// Method with two int parameters

int add(int a, int b) {

return a + b;

// Overloaded method with three int parameters

int add(int a, int b, int c) {

return a + b + c;

// Overloaded method with double parameters

double add(double a, double b) {

return a + b;

public static void main(String[] args) {

MathOperations obj = new MathOperations();

System.out.println(obj.add(5, 10)); // Calls add(int, int)

System.out.println(obj.add(5, 10, 15)); // Calls add(int, int, int)

System.out.println(obj.add(5.5, 2.5)); // Calls add(double, double)

O/P :
15

30

8.0

OR Difference Between Function Overloading and Overriding.


Feature Function Overloading Function Overriding
Definition Multiple methods in the same Subclass provides a new
class with same name but version of a method that
different parameters. already exists in the parent
class.
Return Type Can be different but should Must be the same or
differ in parameters. covariant.
Parameters Must be different (in number, Must be exactly the same as
type, or both). the parent method.
Inheritance Required? ❌ No ✅ Yes, must be in subclass
Static/Dynamic Binding Static Binding (Resolved at Dynamic Binding (Resolved at
compile-time). runtime).
Method Signature Can differ in number or type of Must be identical to the parent
parameters. class method.

OR Write a program that shows an example of function overriding.


// Parent Class

class Animal {

void sound() {

System.out.println("Animals make sounds");

// Child Class

class Dog extends Animal {

// Overriding method

@Override

void sound() {

System.out.println("Dog barks");

}
public static void main(String[] args) {

Animal a = new Animal(); // Parent class object

a.sound(); // Calls parent class method

Dog d = new Dog(); // Child class object

d.sound(); // Calls overridden method in Dog class

Animal ref = new Dog(); // Parent reference, child object

ref.sound(); // Calls overridden method (dynamic binding)

O/P:

Animals make sounds

Dog barks

Dog barks

3. What is Polymorphism ? Explain Any One Type.

Polymorphism means "many forms". It allows a single method or object to behave


differently in different situations.

Types of Polymorphism in Java:

1. Compile-time Polymorphism (Method Overloading)


2. Runtime Polymorphism (Method Overriding)

Explaining One Type: Method Overriding (Runtime Polymorphism)

🔹 Method Overriding allows a subclass to provide a new implementation for a method


already defined in the parent class.
🔹 It is an example of dynamic (runtime) polymorphism, as the method that gets executed
is determined at runtime.

Example of Method Overriding:


// Parent Class
class Animal {
void makeSound() {
System.out.println("Animals make sounds");
}
}

// Child Class
class Dog extends Animal {
// Overriding method
@Override
void makeSound() {
System.out.println("Dog barks");
}

public static void main(String[] args) {


Animal a = new Animal(); // Parent class object
a.makeSound(); // Calls parent class method

Dog d = new Dog(); // Child class object


d.makeSound(); // Calls overridden method in Dog class

Animal ref = new Dog(); // Parent reference, child object


ref.makeSound(); // Calls overridden method (dynamic binding)
}
}

🔹 Output:

Animals make sounds


Dog barks
Dog barks

UNIT 6 : Exception Handling, I/O, abstract classes and interfaces

1. Differentiate between checked and unchecked exceptions in Java.


Feature Checked Exceptions Unchecked Exceptions
Definition Exceptions that are checked Exceptions that occur at runtime and
at compile-time. are not checked at compile-time.
Handling Required? Yes, must be handled using No, handling is optional.
try-catch or declared using
throws.
Examples IOException, NullPointerException,
SQLException, ArrayIndexOutOfBoundsException,
FileNotFoundException ArithmeticException
Where They Occur? External factors like file Programming errors like accessing null
handling, database access, objects or dividing by zero.
etc.
Belongs To? Subclasses of Exception Subclasses of RuntimeException.
(except
RuntimeException).

2.Exemplify throw and throws clauses of exception handling.


Feature throw throws
Definition Used to explicitly throw an Declares exceptions that a
exception in a method or method might throw.
block.
Usage Used inside the method Used in the method
body. signature.
Type Can be used to throw Used only to declare
checked or unchecked checked exceptions.
exceptions.
Follows With Followed by an exception Followed by exception class
object. names.
Handling Required? Handling is optional but If a checked exception is
recommended. declared, it must be
handled by the calling
method.

3. Differentiate between an abstract class and an interface

Difference Between Abstract Class and Interface in Java :

1. Definition
o An abstract class is a class that can have both abstract (without body) and concrete
(with body) methods. It is used to provide a base for other classes to extend.
o An interface is a completely abstract type that only contains abstract methods
(before Java 8) and default/static methods (since Java 8). It defines a contract that
classes must follow.
2. Method Implementation
o In an abstract class, methods can be fully implemented, partially implemented, or
completely abstract.
o In an interface, all methods are public and abstract by default (except static/default
methods in Java 8+).
3. Inheritance
o A class can extend only one abstract class (single inheritance).
o A class can implement multiple interfaces, allowing multiple inheritance in Java.
4. Variables
o An abstract class can have instance variables (with or without final and static).
o An interface can only have public, static, and final variables (constants).
5. Constructors
o Abstract classes can have constructors.
o Interfaces cannot have constructors because they cannot be instantiated.
6. Usage
o Use abstract classes when you want to share common behavior among multiple
related classes.
o Use interfaces when you want to define a common contract that multiple classes
from different hierarchies can implement.
4. Explain the Comparable and Cloneable interfaces in Java.

Comparable vs Cloneable Interface in Java

1. Comparable Interface

 Used to define natural sorting order of objects.


 Has compareTo(T obj) method, which returns:
o Negative → if current object is smaller.
o Zero → if objects are equal.
o Positive → if current object is greater.
 Used with Collections.sort() and Arrays.sort().

2. Cloneable Interface

 Used to create a duplicate (clone) of an object.


 It is a marker interface (has no methods).
 Requires overriding clone() from Object class.
 If a class does not implement Cloneable, calling clone() throws an exception.

Key Differences

 Comparable is for sorting, requires compareTo().


 Cloneable is for object duplication, requires clone().
 Comparable works with sorting algorithms, Cloneable allows object copying.

UNIT 9: Binary I/O ,Recursion and Generics

1. Write a difference between Text I/o and Binary I/0.

 Data Representation:

 Text I/O: Stores data as readable text (characters).


 Binary I/O: Stores data in raw binary format (0s and 1s).

 File Size:

 Text I/O: Larger file size due to character encoding (e.g., UTF-8).
 Binary I/O: Smaller file size as it stores raw data directly.

 Readability:

 Text I/O: Human-readable, can be opened in text editors.


 Binary I/O: Not human-readable, needs special programs to read.

 Speed & Performance:


 Text I/O: Slower, as it needs conversion between text and data types.
 Binary I/O: Faster, as it directly reads and writes raw data.

 Usage:

 Text I/O: Used for storing plain text, logs, configuration files, etc.
 Binary I/O: Used for images, videos, audio, and serialized objects.

2. Explain file I/O using byte stream with an appropriate example.

Byte streams in Java are used for reading and writing binary data such as images, audio,
video, and non-text files. They work with raw bytes and do not perform character encoding.

Important Byte Stream Classes:

 FileInputStream → Reads data from a file in bytes.


 FileOutputStream → Writes data to a file in bytes.

Example :

import java.io.*;

public class ByteStreamExample {

public static void main(String[] args) throws IOException {

String data = "Hello, Byte Stream!"; // Data to write

// Writing to a file using FileOutputStream

FileOutputStream fos = new FileOutputStream("bytefile.dat");

fos.write(data.getBytes()); // Convert string to bytes and write

fos.close(); // Close the stream

// Reading from a file using FileInputStream

FileInputStream fis = new FileInputStream("bytefile.dat");

int i;
while ((i = fis.read()) != -1) { // Read byte by byte

System.out.print((char) i); // Convert byte to character

fis.close(); // Close the stream

3. Explain file I/O using character stream with an appropriate example.

Character streams are used for reading and writing text files (i.e., .txt, .csv). Unlike byte
streams, they handle characters instead of raw bytes, making them ideal for text-based data.

Important Character Stream Classes:

 FileReader → Reads data from a file as characters.


 FileWriter → Writes data to a file as characters.

import java.io.*;

public class CharacterStreamExample {

public static void main(String[] args) throws IOException {

String data = "Hello, Character Stream!"; // Data to write

// Writing to a file using FileWriter

FileWriter fw = new FileWriter("charfile.txt");

fw.write(data); // Writing characters to the file

fw.close(); // Close the stream

// Reading from a file using FileReader

FileReader fr = new FileReader("charfile.txt");

int i;

while ((i = fr.read()) != -1) { // Read character by character

System.out.print((char) i); // Convert int to char and print

}
fr.close(); // Close the stream

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy