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

solution of java question paper1

The document contains a series of questions and answers related to Java programming concepts, covering topics such as operators, data types, object-oriented programming principles, and control structures. It provides explanations for various Java features, including method overloading, exception handling, and the structure of a Java program. Additionally, it includes examples to illustrate key concepts and differences between programming paradigms.

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

solution of java question paper1

The document contains a series of questions and answers related to Java programming concepts, covering topics such as operators, data types, object-oriented programming principles, and control structures. It provides explanations for various Java features, including method overloading, exception handling, and the structure of a Java program. Additionally, it includes examples to illustrate key concepts and differences between programming paradigms.

Uploaded by

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

Q.

1 JDK stands for:

Answer: a) Java Development Kit

Q.2 What is the output of 10/3:

Answer: a) 3

Explanation: In Java, when both operands of a division are integers, integer division is
performed, which means that the fractional part is discarded. So, 10 / 3 equals 3.

Q.4 Decrement operator -- decreases the value of the variable by what


number?

Answer: d) 1

Explanation: The decrement operator -- decreases the value of a variable by 1.

Q.5 Which of the following is not a Java keyword?

Answer: c) then

Explanation: "then" is not a recognized keyword in Java. Other options like if, switch, and
class are indeed Java keywords.

Q.6 Every statement in JAVA language should end with what?

Answer: c) Semicolon

Explanation: In Java, every statement must end with a semicolon (;). This tells the compiler
that the statement is complete.

Q.7 ++ is what kind of operator?

Answer: b) Unary

Explanation: The increment operator ++ is a unary operator, which means it operates on a


single operand to increase its value by 1.

Q.8 In which year was JAVA developed?

Answer: c) 1995

Explanation: Java was officially released in 1995 by Sun Microsystems as a programming


language designed for use on the internet.

Q.9 What does the expression float a = 15/0 return?


Answer: c) Infinity

Q.10 What is the extension of a JAVA file?

Answer: b) .java

Q.11 Who developed JAVA?

Answer: Answer not provided in the options; however, the correct answer is: Sun
Microsystems

Q.12 What is the purpose of the Break statement?

Answer: The break statement is used to exit from a loop or a switch statement.

Q.13 Expand OOPS.

Answer: Object-Oriented Programming System

Q.14 Define Constant.

Answer: A constant is a fixed value that cannot be altered during the execution of a program.

Q.15 Define Compiler.

Answer: A compiler is a program that translates source code written in a high-level


programming language (like Java) into machine code or bytecode.

Q.16 Write the syntax of a for Loop.

Answer:

for (initialization; condition; increment/decrement) {


// code to be executed
}

Q.17 Define Exception.

Answer: An exception is an event that disrupts the normal flow of a program's execution.

Q.18 Define Object.

Answer: An object is an instance of a class that contains data (attributes) and methods that
operate on that data.

Q.19 Define Dot.

Answer: The dot (.) operator in Java is used to access members of a class or interface.
Q.20 Define Polymorphism.

Answer: Polymorphism is the ability of a single function or method to operate in different


ways based on the object that it is acting upon.

Q.21 Define Exception. How is it handled in Java?

Answer: An exception is an unexpected event that occurs during program execution,


disrupting the normal flow of instructions. In Java, exceptions are objects that represent these
unexpected conditions.

How Exceptions are Handled in Java:

 try block: Code that might throw an exception is enclosed here.


 catch block: If an exception occurs, this block handles it.
 finally block: This block executes after the try-catch, regardless of whether an exception was
thrown, often used for cleanup.

Example:

try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}

Q.22 Difference between while & do-while loop

Answer:

 While Loop:
 Syntax: while (condition) { // code }
 The condition is checked before executing the loop body.
 The loop may not execute at all if the condition is false.
 Do-While Loop:
 Syntax: do { // code } while (condition);
 The loop body executes at least once because the condition is checked after the loop
body runs.

Example:
// While Loop Example
int count = 0;
while (count < 5) {
System.out.println(count);
count++;
}

// Do-While Loop Example


int count2 = 0;
do {
System.out.println(count2);
count2++;
} while (count2 < 5);

Summary:

 Use a while loop when you want to check the condition before executing, and a do-while
loop when you need at least one execution of the loop regardless of the condition.

Q23: Explain features of JAVA

JAVA is a widely-used programming language known for its distinct features:

1. Platform Independence: JAVA code is compiled into bytecode, which can be run on
any platform with a Java Virtual Machine (JVM). This allows for the "write once, run
anywhere" (WORA) capability.
2. Object-Oriented: Java follows the principles of Object-Oriented Programming
(OOP), including encapsulation, inheritance, polymorphism, and abstraction,
promoting code reuse and modularity.
3. Robustness: Java provides strong memory management features with automatic
garbage collection, exception handling, and type checking during compile-time,
reducing runtime errors.
4. Security: Java includes several security features, such as bytecode verification and
the security manager, which restricts access to system resources, ensuring safer
execution of Java applications.
5. Multi-threading: Java supports multi-threading, allowing multiple threads to run
simultaneously, which enhances the performance of applications and improves
responsiveness.

Q24: Explain if statement with example

The if statement in Java is a conditional statement that executes a block of code based on
whether the specified condition evaluates to true.

Syntax:

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

Example:

int number = 10;


if (number > 0) {
System.out.println("The number is positive.");
}
In this example, because the condition number > 0 is true, the message "The number is
positive." will be printed to the console.

Q25: What is method overloading? How is it implemented in JAVA?

Method overloading is a feature that allows a class to have multiple methods with the same
name but different parameter lists (signature), helping in code readability and reusability.

Implementation in JAVA: To implement method overloading, define multiple methods with


the same name but different parameter types or counts.

Example:

class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


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

// Method to add two double values


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

In this example, the add method is overloaded with different parameter types and numbers.

Q26: Explain single inheritance

Single inheritance is a feature of object-oriented programming where a class (child class)


inherits properties and behaviors (methods) from one single parent class. This enhances code
efficiency, allows for method overriding, and promotes a clear class hierarchy.

Example:

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

class Dog extends Animal {


void bark() {
System.out.println("Barking...");
}
}

In this example, Dog inherits the eat method from the Animal class, demonstrating single
inheritance.

Q27: How comments are written in JAVA

Comments in Java are used to explain the code and make it more readable. They can be
single-line or multi-line.

1. Single-line comment: Starts with // and continues to the end of the line.

// This is a single-line comment

2. Multi-line comment: Starts with /* and ends with */.

/* This is a
multi-line comment */

3. Documentation comment: Starts with /** and is used for generating documentation.

/**
* This is a documentation comment
* documentation for the method
*/

Q28: Difference between class & object

Class: A class is a blueprint or template that defines the properties (attributes) and behaviors
(methods) of objects. It represents a category of objects.

Object: An object is an instance of a class. It is a concrete entity that has state and behavior.
Objects hold data (attributes) and methods to perform actions.

Example:

class Car {
String color;
void drive() {
System.out.println("Driving...");
}
}

Car myCar = new Car(); // myCar is an object of class Car

In this example, Car is the class, and myCar is an object of that class.
Q29: Define function. Explain its types

A function is a block of code that performs a specific task, has a name, and can return a
value. Functions can take parameters and can be called multiple times from different parts of
a program.

Types of Functions:

1. Built-in Functions: Provided by Java (e.g., Math.sqrt()).


2. User-defined Functions: Created by the user to perform specific tasks.

// User-defined function
int add(int a, int b) {
return a + b;
}

Q30: Explain for Loop with example

The for loop is a control structure that allows repeated execution of a block of code for a
specified number of iterations. It consists of three parts: initialization, condition, and
increment/decrement.

Syntax:

for (initialization; condition; increment/decrement) {


// code to be executed
}

Example:

for (int i = 0; i < 5; i++) {


System.out.println("Iteration: " + i);
}

This loop will print "Iteration: 0" through "Iteration: 4".

Q31: Write a program in JAVA to print factorial of a number

Here’s a simple Java program to calculate and print the factorial of a number using recursion.

import java.util.Scanner;

public class Factorial {


static int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}

Q32: Difference between POP & OOPS

POP (Procedural Oriented Programming):

 Based on procedures or functions.


 Focuses on sequential execution of tasks.
 Code is organized in functions, making it less reusable.

OOPS (Object-Oriented Programming):

 Based on objects and classes.


 Encapsulates data and functions together.
 Promotes code reusability through inheritance and polymorphism.

In summary, OOP is more suited for larger systems while POP is simpler for smaller, more
straightforward tasks.

Q33: Define constructor. Explain with example

A constructor is a special method invoked when an object of a class is created. Constructors


have the same name as the class and do not have a return type.

Example:

class Car {
String color;

// Constructor
Car(String c) {
color = c;
}

void display() {
System.out.println("Car color is: " + color);
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car("Red"); // Constructor called
myCar.display();
}
}
In this example, the Car constructor initializes the color attribute.

Q34: Explain various data types available in JAVA

Java has two main categories of data types:

1. Primitive Data Types:

 int: Integer data type (e.g., int age = 25;)


 float: Single-precision floating-point (e.g., float price = 19.99f;)
 double: Double-precision floating-point (e.g., double pi = 3.14;)
 char: Character data type (e.g., char grade = 'A';)
 boolean: Represents true or false values (e.g., boolean isJavaFun = true;)

2. Reference Data Types:

 String: A sequence of characters (e.g., String name = "John";)


 Arrays: A collection of similar types (e.g., int[] numbers = {1, 2, 3};)
 Objects: Instances of classes.

Q35: Explain the structure of JAVA program

A typical Java program structure includes various components:

1. Package Declaration: Specifies the package to which the class belongs.

package myPackage;

2. Import Statements: Used to import other classes and packages.

import java.util.Scanner;

3. Class Declaration: Defines the class.

public class MyClass {

4. **Main

Q.36 Explain various concepts of OOP (Object-Oriented Programming)

Answer: Object-Oriented Programming (OOP) is a programming paradigm based on


the concept of "objects," which can contain data and code. The key concepts of OOP
include:

1. Classes and Objects:


o A class is a blueprint for creating objects (specific instances of classes) that
define properties (attributes) and behaviors (methods).
o An object is an instance of a class.

Example:

class Dog {
String breed; // attribute

void bark() { // method


System.out.println("Woof!");
}
}

Dog myDog = new Dog(); // creating an object


myDog.bark(); // calling a method

2. Encapsulation:

o Encapsulation is the technique of bundling the data (attributes) and the


methods (functions) that operate on the data into a single unit called a class. It
restricts direct access to some of the object's components.
o Access modifiers (like private, public) are commonly used to implement
encapsulation.

Example:

class Account {
private double balance; // private attribute

public void setBalance(double amount) {


balance = amount; // public method to set balance
}

public double getBalance() {


return balance; // public method to get balance
}
}

3. Inheritance:

o Inheritance is a mechanism wherein one class can inherit the fields and
methods of another class. This promotes code reuse.
o The class that inherits is called the subclass (or derived class), and the class
from which it inherits is called the superclass (or base class).

Example:

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

class Cat extends Animal { // Cat is a subclass of Animal


void meow() {
System.out.println("Meow");
}
}

4. Polymorphism:

o Polymorphism allows methods to do different things based on the object it is


acting upon, even if they share the same name.
o It can be achieved through method overriding (runtime polymorphism) or
method overloading (compile-time polymorphism).

Example:

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

class Dog extends Animal {


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

Animal myDog = new Dog(); // Upcasting


myDog.sound(); // Outputs: Dog barks

5. Abstraction:

o Abstraction is the concept of hiding complex realities while exposing only the
necessary parts. It allows defining abstract classes or interfaces that can be
implemented by subclasses.

Example:

abstract class Shape {


abstract void draw(); // abstract method
}

class Circle extends Shape {


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

Q.37 Explain various operators available in JAVA

Answer: Java provides several types of operators that can be used to perform
operations on variables and values:

5. Arithmetic Operators:
o Used for basic mathematical operations.
o Examples: +, -, *, /, and % (modulus).

int sum = a + b; // addition


int product = a * b; // multiplication

2. Relational Operators:

o Used to compare two values.


o Examples: ==, !=, >, <, >=, <=.

if (a > b) {
// true if 'a' is greater than 'b'
}

3. Logical Operators:

o Used to combine multiple boolean expressions.


o Examples: && (logical AND), || (logical OR), ! (logical NOT).

if (a > 10 && b < 5) {


// true if both conditions are true
}

4. Bitwise Operators:

o Used to perform operations on bits.


o Examples: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right
shift).

int result = a & b; // bitwise AND

5. Assignment Operators:

o Used to assign values to variables.


o Examples: =, +=, -=, *=, /=, etc.

a += b; // equivalent to a = a + b

6. Conditional (Ternary) Operator:

o A shorthand for if-else statements.


o Syntax: condition ? expression1 : expression2

int max = (a > b) ? a : b; // returns a if true, else b

7. Instanceof Operator:

o Tests whether an object is an instance of a specific class or subclass.

if (myDog instanceof Dog) {


// true if myDog is a Dog
}

Q.38 Explain various types of array with example

Answer: Arrays in Java are used to store multiple values of the same type in a single
variable. They can be categorized as follows:

7. Single-Dimensional Array:

o A linear array, where each item is accessed using a single index.


o Syntax: dataType[] arrayName = new dataType[size];

Example:

int[] numbers = new int[5]; // single-dimensional array


numbers[0] = 10;
numbers[1] = 20;

2. Multi-Dimensional Array:

o Arrays that contain other arrays. The most common is the two-dimensional
array, also known as a matrix.
o Syntax: dataType[][] arrayName = new dataType[rows][columns];

Example:

int[][] matrix = new int[3][3]; // 2D array


matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[1][0] = 3; // Accessing elements

You might also like