0% found this document useful (0 votes)
3 views22 pages

Java

The document provides an overview of various Java programming concepts, including operators, loops, decision-making structures, inheritance, and method overloading/overriding. It explains different types of operators with examples, describes how to implement loops and conditional statements, and details inheritance types with syntax and examples. Additionally, it includes Java code snippets for generating Fibonacci series, checking for prime numbers, and demonstrating constructor overloading.

Uploaded by

Prince Saket
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)
3 views22 pages

Java

The document provides an overview of various Java programming concepts, including operators, loops, decision-making structures, inheritance, and method overloading/overriding. It explains different types of operators with examples, describes how to implement loops and conditional statements, and details inheritance types with syntax and examples. Additionally, it includes Java code snippets for generating Fibonacci series, checking for prime numbers, and demonstrating constructor overloading.

Uploaded by

Prince Saket
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

U

​ nit–II
Section-A
Long Type Questions
1. What is operator? Define its types with syntax and example
Ans

Operators in Java, a Java toolkit, are being used


as a symbol that performs various operations
according to the code. Some Operators of JAVA
are "+","-","*","/" etc. The idea of using Operators has
been taken from other languages so that it behaves
expectedly.

Types of Operators in Java

There are various types of Operators in Java that are used for
operating. These are,

Arithmetic operators in Java


Relational operators in Java
Logical operators in Java
Assignment operator in Java
Unary operator in Java
Bitwise operator in Java
Comparison operator in Java
Ternary operator in Java
Arithmetic Operators in Java
Arithmetic Operators in Java are particularly used for performing
arithmetic operations on given data or variables. There are various
types of operators in Java, such as

Operators Operations
+ Addition
- Subtraction
x Multiplication
/ Division
% Modulus

Assignment Operator in Java


Assignment Operators are mainly used to assign the values to the
variable that is situated in Java programming. There are various
assignment operators in Java, such as

Operators Examples Equivalent to


= X = Y; X = Y;
+= X += Y; X = X + Y;
-= X -= Y; X = X - Y;
*= X *= Y; X = X * Y;
/= X /= Y; X = X / Y;
%= X %= Y; X% Y

Relational Operators in Java


Java relational operators are assigned to check the relationships
between two particular operators. There are various relational
operators in Java, such as
Operators Description Example

== Is equal to 3 == 5 returns false

!= Not equal to 3 != 5 returns true

> Greater than 3 > 5 returns false

< Less than 3 < 5 returns true

>= Greater than or equal to 3 >= 5 returns false

<= Less than or equal to 3 <= 5 r


eturns true

Logical Operators in Java


Logical Operators in Java check whether the expression is true or
false. It is generally used for making any decisions in Java
programming. Not only that but Jump statements in Java are also
used for checking whether the expression is true or false. It is
generally used for making any decisions in Java programming.

Operators Example. Meaning


&& [ logical AND ] expression1 && expression2 (true) only
if both of the
expressions are true
|| [ logical OR ] expression1 || (true) if one of the
expression2 expressions in true
! [ logical NOT ]. !expression. (true) if the expression
is false and vice-versa
Unary Operator in Java
Unary Operators in Java are used in only one operand. There are
various types of Unary Operators in Java, such as

Operators Description
+ Unary Plus
- Unary Minus
++ Increment operator
-- Decrement Operator
! Logical complement operator

Bitwise Operators in Java


Bitwise Operators in Java are used to assist the performance of the
operations on individual bits. There are various types of Bitwise
Operators in Java, such as. We will see the working of the Bitwise
Operators in the Java Online Compiler.

Operators Descriptions
~ Bitwise Complement
<< Left shift
>> Right shift
>>> Unsigned Right shift
& Bitwise AND
^ Bitwise exclusive OR

Comparison Operators in Java


To compare two values (or variables), comparison operators are
used. This is crucial to programming since it facilitates decision-
making and the search for solutions. A comparison's return value is
either true or false. These are referred to as "Boolean values."

Operators Operations
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Ternary Operators in Java
The only conditional operator that accepts three operands is the
ternary operator in Java. Java programmers frequently use it as a
one-line alternative to the if-then-else expression. The ternary
operator can be used in place of if-else statements, and it can even
be used to create switch statements with nested ternary operators.
The conditional operator uses less space and aids in writing if-else
statements as quickly as possible even if it adheres to the same
algorithm as an if-else statement

2. Write a Program to print a Fibonacci series


Ans
Display Fibonacci Series Using for Loop

import [Link];

public class FibonacciSeries {

// Function to print the Fibonacci series


public static void printFibonacci(int n) {
int a = 0, b = 1;
[Link]("Fibonacci series:");

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


[Link](a + " ");
// Update a and b to the next Fibonacci numbers
int next = a + b;
a = b;
b = next;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Ask user for number of terms


[Link]("Enter the number of terms in the Fibonacci
series: ");
int n = [Link]();
// Call the function to print Fibonacci series
printFibonacci(n);

[Link]();
}
}

Output
Enter the number of terms in the Fibonacci series: 7
Fibonacci series:
0112358

3. What is loop? Define its type with syntax and example.

Ans
Looping in programming languages is a feature that facilitates the
execution of a set of instructions/functions repeatedly while some
condition evaluates to true. Java provides three ways for executing
the loops. While all the ways provide similar basic functionality,
they differ in their syntax and condition-checking time.

In Java, there are three types of Loops which are listed below:

for loop
while loop
do-while loop
for loop
The for loop is used when we know the number of iterations (we
know how many times we want to repeat a task). The for statement
consumes the initialization, condition, and increment/decrement in
one line thereby providing a shorter, easy-to-debug structure of
looping.

Syntax:

for (initialization; condition; increment/decrement) {

// code to be executed

Example: The below Java program demonstrates a for loop that


prints numbers from 0 to 10 in a single line.

// Java program to demonstrates the working of for loop


import [Link].*;

class Geeks {
public static void main(String[] args)
{
for (int i = 0; i <= 10; i++) {
[Link](i + " ");
}
}
}

Output
12345
2. while Loop
A while loop is used when we want to check the condition before
running the code.

Syntax:

while (condition) {

// code to be executed

Example: The below Java program demonstrates a while loop that


prints numbers from 0 to 10 in a single line.

// Java program to demonstrates


// the working of while loop
import [Link].*;

class Geeks {
public static void main(String[] args)
{
int i = 0;
while (i <= 10) {
[Link](i + " ");
i++;
}
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

. do-while Loop
The do-while loop in Java ensures that the code block executes at
least once before the condition is checked.

Syntax:

do {

// code to be executed

} while (condition);

Example: The below Java program demonstrates a do-while loop


that prints numbers from 0 to 10 in a single line.
// Java program to demonstrates
// the working of do-while loop
import [Link].*;

class Geeks {
public static void main(String[] args)
{
int i = 0;
do {
[Link](i + " ");
i++;
} while (i <= 10);
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

4. What is Decision Making with if, if else, ladder if else with


example?
Ans
ming allows a program to choose different execution paths based
on conditions. if, if-else, and if-else-if (or "ladder if-else") statements
are the core tools for this, enabling you to check conditions and
execute specific code blocks accordingly.
1. if Statement:
Purpose: Executes a block of code only if a specified condition is
true.
Syntax:
Code

if (condition) {
// Code to be executed if the condition is true
}
Example (Python).
Python

age = 20
if age >= 18:
print("You are eligible to vote.")
2. if-else Statement:
Purpose: Executes one block of code if the condition is true and
another block if it's false.
Syntax:
Code

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example (Python).
Python

age = 17
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not yet eligible to vote.")
3. if-else-if (Ladder if-else) Statement:
Purpose: Checks multiple conditions sequentially and executes the
corresponding code block when the first true condition is met.
Syntax:
Code

if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is
true
} else if (condition3) {
// Code to be executed if condition1 and condition2 are false,
and condition3 is true
} else {
// Code to be executed if none of the conditions are true
}
Example (Python).
Python

score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")

Section-B
Short Type Questions
Section-C
Very Short Type Questions
.

Unit 3

Long Type Question


1. What is inheritance? Define its types with syntax and example.
Ans
Inheritance is a fundamental object-oriented programming concept
where a class (child/derived class) inherits properties and
behaviors from another class (parent/base class), enabling code
reuse and creating hierarchical relationships. Here's a breakdown
of its types, syntax, and examples:
Types of Inheritance:
Single Inheritance: A derived class inherits from only one base
class.
Syntax:
Code

class BaseClass {
// Base class members
}

class DerivedClass extends BaseClass {


// Derived class members
}
Example (Java).
Java

class Animal {
String name = "Animal";
void makeSound() {
[Link]("Generic animal sound");
}
}

class Mammal extends Animal {


void breathe() {
[Link]("Breathes air");
}
}

class Dog extends Mammal {


void bark() {
[Link]("Woof!");
}
}
Hierarchical Inheritance: Multiple derived classes inherit from a
single base class.
Syntax:
Code

class BaseClass {
// Base class members
}

class DerivedClass1 extends BaseClass {


// Derived class 1 members
}

class DerivedClass2 extends BaseClass {


// Derived class 2 members
}
Example (Java).
Java

class Animal {
String name = "Animal";
void makeSound() {
[Link]("Generic animal sound");
}
}

class Dog extends Animal {


void bark() {
[Link]("Woof!");
}
}

class Cat extends Animal {


void meow() {
[Link]("Meow!");
}
}
Hybrid Inheritance: A combination of two or more types of
inheritance.
Note: Hybrid inheritance can be achieved by combining multiple
inheritance (through interfaces) with other types of inheritance.

2. Write a Program to print a prime or not prime number?


Ans
Here's a simple Java program to check if a number is prime or not:

java
Copy code
import [Link];

public class PrimeNumberCheck {

public static void main(String[] args) {


// Create a scanner object to take input from the user
Scanner scanner = new Scanner([Link]);
// Ask the user to input a number
[Link]("Enter a number: ");
int num = [Link]();

// Check if the number is prime or not


if (isPrime(num)) {
[Link](num + " is a prime number.");
} else {
[Link](num + " is not a prime number.");
}

// Close the scanner object


[Link]();
}

// Method to check if a number is prime


public static boolean isPrime(int num) {
// Prime numbers are greater than 1
if (num <= 1) {
return false;
}

// Check divisibility from 2 to the square root of num


for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false; // num is divisible by i, so it's not prime
}
}
return true; // num is prime
}
}
Explanation:
Input: The program asks the user for an integer input.

Prime check: The isPrime() method checks whether the given


number is prime by iterating through all numbers from 2 to the
square root of the number. If any of these numbers divides the
given number without a remainder, the function returns false,
indicating it's not a prime number.

Output: The program then prints whether the number is prime or


not based on the result of the isPrime() method.

3. What are constructor and constructor overloading? Explain in


detail with example.
Ans
provide.
Example (Java):
Java

public class Main {


public static void main(String[] args) {
Dog dog1 = new Dog("Buddy", "Golden Retriever"); // Calls
constructor 1
Dog dog2 = new Dog("Lucy", "Poodle", 3); // Calls constructor 2
}
}
Benefits of Constructor Overloading:
Flexibility: Provides multiple ways to initialize objects, making the
class more versatile.
Readability: Improves code readability by allowing different
initialization scenarios within the same class.
Maintainability: Simplifies object creation and enhances code
maintainability.

[Link] is overloading and overriding? Differentiate the


overloading and overriding with
example.
Ans
ming, overloading involves defining multiple methods with the
same name but different parameters within the same class, while
overriding occurs when a subclass provides a specific
implementation for a method inherited from its superclass.
Overloading:
Definition: Having multiple methods in the same class with the
same name but different parameter lists (number, type, or order of
parameters).
Example:
Java

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

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


return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
}
In this example, the add method is overloaded because there are
multiple versions with different parameter types and numbers.
Overriding:
Definition: A subclass providing a specific implementation of a
method that is already defined in its superclass.
Example:
Java

class Animal {
public void makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override // Indicates that this method overrides a method
from the superclass
public void makeSound() {
[Link]("Dog barks");
}
}
In this example, the makeSound method in the Dog class overrides
the makeSound method in the Animal class, providing a specific
implementation for dogs.
Key Differences:
Feature. Overloading. Overriding
Scope. Within the same class. Between a superclass and its
subclasses
Method SignatureSame name, different parameters
Same name, same parameters, same return type
Purpose
Provide flexibility in method calls
Provide specialized implementations in subclasses
Polymorphism
Compile-time (static) polymorphism
Runtime (dynamic) polymorphism

You might also like