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

solution of java question paper 2

The document provides a comprehensive overview of Java programming concepts, including definitions of classes, objects, inheritance, data types, and control statements. It covers various types of inheritance, differences between class and interface, and the use of the Scanner class for user input. Additionally, it includes examples and explanations of loops, exception handling, and constructors.

Uploaded by

jyotivats
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

solution of java question paper 2

The document provides a comprehensive overview of Java programming concepts, including definitions of classes, objects, inheritance, data types, and control statements. It covers various types of inheritance, differences between class and interface, and the use of the Scanner class for user input. Additionally, it includes examples and explanations of loops, exception handling, and constructors.

Uploaded by

jyotivats
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

SECTION A (Objective Type Questions)

1. Define class: A class is a blueprint for creating objects in Java. It defines properties
(fields) and behaviors (methods).
2. One procedural language: C
3. Two keywords of Java: public, static
4. A collection of similar items is called: Array
5. Symbol of increment operator in Java: ++
6. Define keywords: Reserved words in Java that have a predefined meaning (e.g.,
class, if, else).
7. Multiple inheritance can be achieved using: Interfaces
8. JDK stands for: Java Development Kit
9. Byte is a data type to read integer values (True/False): False (Byte stores integer
values, but it’s not used for reading them.)
10. Name of the constructor should be the same as the class name (True/False): True

SECTION B (Very Short Answer Type Questions)

11. Define encapsulation: Encapsulation is the wrapping of data (variables) and code
(methods) into a single unit, like a class.
12. How to declare a one-dimensional array in Java: int arr[] = new int[5];
13. Four relational operators in Java: ==, !=, >, <
14. Syntax of while loop:

15. Give syntax of while loop of JAVA.

while (condition) {
// code to execute repeatedly
}

15. Define object: An object is an instance of a class that holds data and methods.
16. What is multilevel inheritance: When a class inherits from another class, which in
turn inherits from another class.
17. Define bytecode: Bytecode is the intermediate code generated by the Java compiler,
which runs on the JVM.
18. Define interface: An interface is a reference type in Java that defines abstract
methods that must be implemented by a class.
19. What is an exception: An event that disrupts the normal flow of a program, handled
using try-catch.
20. Can we create an object of a class? Yes, using new ClassName();, except for
abstract classes.
21. What is a subclass? A subclass is a derived class that inherits from a parent
(superclass).
22. Purpose of Scanner class: It is used to take user input in Java (Scanner sc = new
Scanner(System.in);).

23. Write short note on Inheritance.

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one


class to inherit properties and behaviors (methods) from another class.
Types of Inheritance:

 Single Inheritance: A class inherits from one superclass.


 Multiple Inheritance: A class can inherit from multiple classes (not directly
supported in Java; instead, we use interfaces).
 Multilevel Inheritance: A class inherits from a class which is also derived from
another class.
 Hierarchical Inheritance: Multiple classes inherit from a single superclass.

Benefits:

 Code reusability: You can use existing code without rewriting it.
 Easier maintenance: Changes in the superclass can automatically affect derived
classes.

24. Give any two differences between while and do while loop.

While Loop:

 Condition Check: The condition is checked before the execution of the loop body. If
the condition is false, the loop body will not execute at all.
 Syntax:

while (condition) {
// code block
}

Do While Loop:

 Condition Check: The loop body executes at least once, as the condition is checked
after the execution of the loop body.
 Syntax:

do {
// code block
} while (condition);

25. Write any two advantages of using arrays.

1. Efficient Storage: Arrays store multiple elements of the same data type in a single
variable, which helps in efficient memory management.
2. Fast Access: Elements can be accessed quickly using their index, making searching
and sorting operations much faster compared to other data structures.

26. Explain the concept of method overriding.

Method Overriding occurs when a subclass provides a specific implementation of a method


that is already defined in its superclass. This allows a subclass to modify the behavior of the
inherited method.
 Polymorphism: Overriding supports polymorphism, which is the ability to call the
same method on different objects and get different behaviors.

Example:

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

class Dog extends Animal {


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

// Usage
Animal myDog = new Dog();
myDog.sound(); // Outputs: Dog barks

27. Write a program to print factorial of a number in JAVA.

Here’s a simple program to calculate the factorial of a number using a loop:

import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int factorial = 1;

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


factorial *= i; // Calculate factorial
}
System.out.println("Factorial of " + num + " is: " + factorial);
}
}

Explanation:

 This program prompts the user to enter a number, which it stores in num.
 A for loop multiplies all integers from 1 to num to compute the factorial.

28. Define abstract class in JAVA.

An abstract class is a class that cannot be instantiated on its own and may contain abstract
methods (methods without a body). This type of class is used to provide a common interface
for its subclasses.

 Purpose: It defines a template for other classes. Subclasses are required to implement
the abstract methods provided in the abstract class.
Example:

abstract class Shape {


abstract void draw(); // Abstract method
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing a Circle");
}
}

// Usage
Shape shape = new Circle();
shape.draw(); // Outputs: Drawing a Circle

29. Give any two differences between class and interface.

1. Definition:

 A class defines the blueprint for creating objects and can contain methods and
variables (fields).
 An interface is a contract that defines methods that a class must implement, but it
cannot contain any implementation (until Java 8 default methods).

2. Instantiation:

 A class can be instantiated directly to create objects.


 An interface cannot be instantiated on its own.

30. How do you define a try block in JAVA?

A try block is used in Java to handle exceptions. It allows you to write code that might cause
an exception, and catch that exception to handle it gracefully.

Example:

try {
// Code that may throw an exception
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // This will throw an exception
} catch (ArrayIndexOutOfBoundsException e) {
// Handling exception
System.out.println("Array index is out of bounds!");
}

31. What is the purpose of the scanner class in JAVA?

The Scanner class is part of the java.util package and is used to read input from various
sources (like keyboard input, files, etc.) easily. It simplifies the process of taking user input.

Common Methods:
 nextInt(): Reads an integer.
 nextLine(): Reads a string.
 nextDouble(): Reads a double.

Example:

import java.util.Scanner;

public class InputExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
}
}

32. Define Constructor.

A constructor is a special method that is called when an object of a class is created. It has the
same name as the class and is used to initialize the new object.

 Types:
 Default Constructor: A constructor with no parameters.
 Parameterized Constructor: A constructor that takes parameters to initialize the
object with specific values.

Example:

class Person {
String name;

// Parameterized constructor
Person(String n) {
name = n; // Initialize the name
}

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

// Usage
Person p = new Person("John");
p.display(); // Outputs: Name: John

Q.33 Compare Object-Oriented and Procedure-Oriented Languages. (CO1)


1. Procedure-Oriented Languages:

 Definition: In procedure-oriented languages, the focus is on functions or procedures


that operate on data. These languages structure the program by breaking it down into
procedures.
 Key Features:
 Function-Based: It emphasizes functions. The data is passed to functions for
processing.
 Data Access: Data is generally accessible by all functions, which can lead to
unintentional changes.
 Flow Control: The logic flows in a straight line, following the sequence of functions
being called.
 Examples: C, BASIC, and Pascal.
 Advantages:
 Suitable for smaller programs.
 Generally faster due to straightforward execution without many layers.
 Disadvantages:
 When the program grows, managing it becomes difficult.
 Less support for reusability and modularity.

2. Object-Oriented Languages:

 Definition: Object-oriented languages deal with "objects" that represent real-world


entities. Each object can contain data (attributes) and code (methods).
 Key Features:
 Encapsulation: Data and functions are bundled together, protecting data and
promoting integrity.
 Inheritance: New classes can inherit properties of existing classes, allowing for
reusability.
 Polymorphism: Objects can be treated as instances of their parent class, promoting
flexibility in program design.
 Examples: Java, C++, and Python.
 Advantages:
 Supports larger programs through modular design.
 Encourages code reuse and easier maintenance.
 Disadvantages:
 Can be more complex to understand initially.
 May require more memory and processing power.

Q.34 Explain Various Conditional Control Statements of Java. (CO3)

1. If Statement:

 Purpose: Only executes a block of code if the given condition is true.


 Syntax:

if (condition) {
// Code to execute if condition is true
}

2. If-Else Statement:

 Purpose: Executes one block of code if the condition is true, and another block if it is
false.
 Syntax:

if (condition) {
// Code for true condition
} else {
// Code for false condition
}

3. Else-If Ladder:

 Purpose: Checks multiple conditions one after the other.


 Syntax:

if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the above are true
}

4. Switch Statement:

 Purpose: Tests a variable against a list of values (cases) and executes the
corresponding block of code.
 Syntax:

switch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case is matched
}

Q.35 Define Data Type; Explain Numeric and Character Data Types of Java.
(CO2)

Data Type:

 A data type defines the type of data a variable can hold. It tells the compiler how to
interpret that data.

Types of Data Types:


1. Primitive Data Types: Basic types directly supported by Java.
2. Non-Primitive Data Types: Objects and arrays are considered non-primitive.

Numeric Data Types:

 Used to represent numbers.

1. Integer Types:

 byte: 8 bits, range from -128 to 127.


 short: 16 bits, range from -32,768 to 32,767.
 int: 32 bits, commonly used. Range: -2,147,483,648 to 2,147,483,647.
 long: 64 bits, for larger numbers. Range: -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.

Example:

int age = 25; // Integer values


long distance = 9876543210L; // Long integer

2. Floating Point Types:

 float: 32 bits, used for decimal values, must have an 'f' or 'F' suffix.
 double: 64 bits, for larger/double precision decimal values, default for decimals.

Example:

float price = 19.99f; // Float value


double pi = 3.14159; // Double value

Character Data Type:

 The char type is used to store a single character.


 It uses 16 bits to represent characters, allowing for Unicode characters.

Example:

char letter = 'A'; // Storing character A

Q.36 Explain the Concept of Inheritance with Suitable Example, and Explain
Various Types of Inheritances. (CO6)

Inheritance:

 Inheritance in Java allows a new class to inherit properties and behaviors of an


existing class. It promotes code reusability and establishes a parent-child relationship.

Example:

// Parent class (Superclass)


class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}

// Child class (Subclass)


class Car extends Vehicle {
void horn() {
System.out.println("Car horn is beeping");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Inherited method
car.horn(); // Car's own method
}
}

Output:

Vehicle is starting
Car horn is beeping

Types of Inheritance:

1. Single Inheritance:

 A subclass inherits from one superclass.


 Example: Class B inherits from class A.

2. Multiple Inheritance:

 A class can inherit features from multiple classes. Java does not support this directly
for classes to prevent ambiguity but allows interfaces.
 Example: Class C can implement both Interface I1 and I2.

3. Multilevel Inheritance:

 A class can inherit from another subclass.


 Example: Class C inherits from class B.

4. Hierarchical Inheritance:

 Multiple subclasses inherit from the same superclass.


 Example: Class B and class C both inherit from class A.

5. Hybrid Inheritance:

 A combination of two or more types of inheritance. Achieved in Java via interfaces.

You might also like