0% found this document useful (0 votes)
19 views17 pages

Java Conditional Statements and OOP Concepts

oops with java

Uploaded by

aswini.ran98
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)
19 views17 pages

Java Conditional Statements and OOP Concepts

oops with java

Uploaded by

aswini.ran98
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

Conditional statement:

import [Link];

public class DecisionDemo {

// 1) nested if-else (simple if-else containing another if)

public static void nestedIfElse(int num) {

if (num > 0) {

[Link]("Nested if-else: Positive");

} else {

if (num < 0) {

[Link]("Nested if-else: Negative");

} else {

[Link]("Nested if-else: Zero");

// 2) else-if ladder (cleaner multiple exclusive conditions)

public static void elseIfLadder(int num) {

if (num > 0) {

[Link]("Else-if ladder: Positive");

} else if (num < 0) {

[Link]("Else-if ladder: Negative");

} else {

[Link]("Else-if ladder: Zero");

}
}

// 3) switch statement (switch on sign value - works because switch matches discrete constants)

public static void switchStatement(int num) {

// [Link] returns -1 for negative, 0 for zero, 1 for positive

int sign = [Link](num);

switch (sign) {

case 1:

[Link]("Switch statement: Positive");

break;

case -1:

[Link]("Switch statement: Negative");

break;

default:

[Link]("Switch statement: Zero");

// no break needed after default at end, but it's okay to include

// --- modern alternative (switch expression syntax; Java 12+/14+):

// switch (sign) {

// case 1 -> [Link]("Switch expression: Positive");

// case -1 -> [Link]("Switch expression: Negative");

// default -> [Link]("Switch expression: Zero");

// }

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

Scanner sc = new Scanner([Link]);

[Link]("Enter an integer: ");

while (![Link]()) {

[Link]("Please enter a valid integer: ");

[Link]();

int num = [Link]();

[Link]("\nResults for number: " + num);

nestedIfElse(num);

elseIfLadder(num);

switchStatement(num);

[Link]();

Ouput:

Enter an integer: 5

Results for number: 5

Nested if-else: Positive

Else-if ladder: Positive

Switch statement: Positive

Output 2:

Enter an integer: -3
Results for number: -3

Nested if-else: Negative

Else-if ladder: Negative

Switch statement: Negative

Output 3:

Enter an integer: -0

Results for number: 0

Nested if-else: Zero

Else-if ladder: Zero

Switch statement: Zero

Oops features or concepts(Any one program either first or second)

// Abstract Class: Abstraction

abstract class BankAccount {

private String accountNumber; // Encapsulation

private String holderName; // Encapsulation

protected double balance; // Protected so subclasses can access

public BankAccount(String accountNumber, String holderName, double balance) {

[Link] = accountNumber;

[Link] = holderName;

[Link] = balance;

}
// Getter and Setter: Encapsulation

public String getAccountNumber() {

return accountNumber;

public String getHolderName() {

return holderName;

public double getBalance() {

return balance;

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

[Link](amount + " deposited. New Balance: " + balance);

} else {

[Link]("Invalid deposit amount!");

// Abstract method: must be implemented by subclasses

public abstract void withdraw(double amount);

// Display account details

public void displayAccountInfo() {


[Link]("Account Number: " + accountNumber);

[Link]("Holder Name: " + holderName);

[Link]("Balance: " + balance);

// Subclass 1: Inheritance + Polymorphism

class SavingsAccount extends BankAccount {

private double withdrawalLimit = 5000; // Encapsulation

public SavingsAccount(String accNum, String name, double balance) {

super(accNum, name, balance);

@Override

public void withdraw(double amount) { // Polymorphism

if (amount > 0 && amount <= withdrawalLimit && amount <= balance) {

balance -= amount;

[Link]("SavingsAccount: " + amount + " withdrawn. New Balance: " + balance);

} else {

[Link]("Withdrawal failed! Limit exceeded or insufficient funds.");

// Subclass 2: Inheritance + Polymorphism

class CheckingAccount extends BankAccount {


private double overdraftLimit = 1000; // Encapsulation

public CheckingAccount(String accNum, String name, double balance) {

super(accNum, name, balance);

@Override

public void withdraw(double amount) { // Polymorphism

if (amount > 0 && (balance + overdraftLimit) >= amount) {

balance -= amount;

[Link]("CheckingAccount: " + amount + " withdrawn. New Balance: " + balance);

} else {

[Link]("Withdrawal failed! Overdraft limit reached.");

// Main Class

public class BankSystem {

public static void main(String[] args) {

// Creating accounts

BankAccount acc1 = new SavingsAccount("SA101", "Alice", 10000);

BankAccount acc2 = new CheckingAccount("CA202", "Bob", 2000);

// Display details

[Link]();

[Link]();
[Link]("\n--- Transactions ---");

[Link](2000);

[Link](3000); // Savings withdrawal rules apply

[Link](7000); // Exceeds withdrawal limit

[Link](1000);

[Link](2500); // Overdraft allowed

[Link](4000); // Exceeds overdraft limit

Oops concepts or features:

// Abstract Class (Abstraction)

abstract class BankAccount {

private String accountHolder; // Encapsulation

private double balance; // Encapsulation

// Constructor

public BankAccount(String accountHolder, double balance) {

[Link] = accountHolder;

[Link] = balance;

// Getter and Setter (Encapsulation)

public String getAccountHolder() {

return accountHolder;

}
public double getBalance() {

return balance;

protected void setBalance(double balance) {

[Link] = balance;

// Abstract Method (must be implemented by subclasses)

public abstract void displayAccountInfo();

// Common Method for deposit

public void deposit(double amount) {

balance += amount;

[Link](amount + " deposited. New balance: " + balance);

// Common Method for withdrawal

public void withdraw(double amount) {

if (balance >= amount) {

balance -= amount;

[Link](amount + " withdrawn. New balance: " + balance);

} else {

[Link]("Insufficient balance!");

}
}

// Inheritance & Polymorphism

class SavingsAccount extends BankAccount {

private double interestRate;

public SavingsAccount(String accountHolder, double balance, double interestRate) {

super(accountHolder, balance);

[Link] = interestRate;

@Override

public void displayAccountInfo() { // Polymorphic behavior

[Link]("Savings Account");

[Link]("Holder: " + getAccountHolder());

[Link]("Balance: " + getBalance());

[Link]("Interest Rate: " + interestRate + "%");

// Inheritance & Polymorphism

class CheckingAccount extends BankAccount {

private double overdraftLimit;

public CheckingAccount(String accountHolder, double balance, double overdraftLimit) {

super(accountHolder, balance);

[Link] = overdraftLimit;
}

@Override

public void withdraw(double amount) { // Polymorphism (overrides withdrawal rule)

if (getBalance() + overdraftLimit >= amount) {

setBalance(getBalance() - amount);

[Link](amount + " withdrawn. New balance: " + getBalance());

} else {

[Link]("Overdraft limit exceeded!");

@Override

public void displayAccountInfo() { // Polymorphic behavior

[Link]("Checking Account");

[Link]("Holder: " + getAccountHolder());

[Link]("Balance: " + getBalance());

[Link]("Overdraft Limit: " + overdraftLimit);

// Main class

public class BankSystem {

public static void main(String[] args) {

// Polymorphism: parent reference to child objects

BankAccount acc1 = new SavingsAccount("Alice", 5000, 4.5);

BankAccount acc2 = new CheckingAccount("Bob", 2000, 1000);


[Link]();

[Link](500);

[Link](2000);

[Link]();

[Link]();

[Link](1000);

[Link](3500); // allowed due to overdraft

Type casting.

Type casting in Java means converting a value from one data type to another.
Java supports two main types of type casting:

Widening Casting (Implicit Casting)

 Also called: Upcasting, Type Promotion


 Converting a smaller data type into a larger data type automatically.

Narrowing Casting (Explicit Casting) Also called: Downcasting

 Converting a larger data type into a smaller data type manually using a cast operator(
).

public class TypeCastingDemo {

public static void main(String[] args) {

// 1. Converting float to int (Narrowing Conversion - Explicit)

float floatNumber = 10.75f;

int intNumber = (int) floatNumber; // explicit type casting

[Link]("Original float value: " + floatNumber);


[Link]("After converting float to int: " + intNumber);

// 2. Converting int to float (Widening Conversion - Implicit)

int anotherInt = 25;

float anotherFloat = anotherInt; // automatic conversion

[Link]("\nOriginal int value: " + anotherInt);

[Link]("After converting int to float: " + anotherFloat);}}

1. Concept

Procedure-Oriented Programming (POP) Object-Oriented Programming (OOP)

Focuses on functions or procedures (step-by-step Focuses on objects that combine data and
instructions). methods.

Data and methods are bundled together in


Data and functions are separate entities.
classes.

2. Approach

POP OOP

Top-down approach (breaks the program into Bottom-up approach (designs objects first, then
smaller functions). combines them).

3. Data Handling

POP OOP

Data is mostly global and can be accessed by Data is encapsulated inside objects and accessed via
any function. methods.

4. Security

POP OOP

Less secure — global data can be More secure — access control through access modifiers
modified by any function. (private, protected, public).
5. Reusability

POP OOP

Reuse is limited — functions can be reused, but High reusability — classes and objects can be reused
data structures are not easily reusable. through inheritance and composition.

6. Example

Procedure-Oriented (C style):

#include <stdio.h>
void display(int a) {
printf("Value: %d", a);
}
int main() {
int x = 10;
display(x);
return 0;
}

Object-Oriented (Java):

class Display {
private int value; // Encapsulation

public Display(int value) {


[Link] = value;
}

public void show() {


[Link]("Value: " + value);
}
}

public class Main {


public static void main(String[] args) {
Display obj = new Display(10); // Object creation
[Link]();
}
}

Operator:
import [Link];

public class Calculator {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input two numbers
[Link]("Enter first number: ");
double num1 = [Link]();

[Link]("Enter second number: ");


double num2 = [Link]();

// Input operator
[Link]("Enter an operator (+, -, *, /, %): ");
char operator = [Link]().charAt(0);

double result;

// Perform operation based on operator


switch (operator) {
case '+':
result = num1 + num2;
[Link]("Result: " + result);
break;
case '-':
result = num1 - num2;
[Link]("Result: " + result);
break;
case '*':
result = num1 * num2;
[Link]("Result: " + result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
[Link]("Result: " + result);
} else {
[Link]("Error: Division by zero is
not allowed.");
}
break;
case '%':
if (num2 != 0) {
result = num1 % num2;
[Link]("Result: " + result);
} else {
[Link]("Error: Division by zero is
not allowed.");
}
break;
default:
[Link]("Invalid operator!");
}

[Link]();
}
}
class Employee {
// Data members

int empId;

String name;

double salary;

// Method to assign employee details

void setDetails(int id, String empName, double empSalary) {

empId = id;

name = empName;

salary = empSalary;

// Method to display employee details

void displayDetails() {

[Link]("Employee ID: " + empId);

[Link]("Name: " + name);

[Link]("Salary: " + salary);

employee

// Main class

public class EmployeeTest {

public static void main(String[] args) {

// Create Employee object

Employee emp1 = new Employee();

// Assign details
[Link](101, "Alice", 55000);

// Display details

[Link]();

Common questions

Powered by AI

The switch statement in Java can be more efficient than if-else ladders when dealing with discrete conditions because it directly maps case values to respective code blocks, facilitating optimized execution paths through techniques like jump tables. This structured form makes the logic more readable and maintains clarity by reducing nesting complexity. In contrast, if-else ladders check conditions sequentially until a true condition is met, which can be less efficient both computationally and in terms of readability for cases where conditions map directly to distinct known values .

Encapsulation promotes modularity in Java by bundling data (attributes) and methods (functions) that operate on the data into a single unit or class. By controlling access to these data through private fields and public methods, unnecessary interference is minimized, and internal implementation details are hidden from the external codebase. This organizes the code into clear, logical segments where responsibilities are well-defined, making the codebase easier to understand, modify, and debug .

In Java, type casting allows conversion between different data types. Widening casting (implicit) involves converting a smaller data type to a larger one automatically, such as int to float, with minimal risk since larger data types can accommodate the values of smaller types. Narrowing casting (explicit), however, involves converting a larger data type into a smaller one, such as float to int. This conversion may lead to data loss because the casting process truncates the decimal part, and if not handled carefully, it can cause loss of precision and possible runtime exceptions .

The nested if-else structure evaluates conditions in a layered manner where one if or else condition can contain other if conditions, making it potentially complex for logic with multiple conditions. The else-if ladder is a more streamlined approach for evaluating multiple exclusive conditions where each condition is checked sequentially. The switch statement is used when one value matches against a set of discrete constants, offering a more efficient way to handle fixed values through cases, often improving readability for such conditions .

Polymorphism in Java allows subclasses to define specialized behaviors for methods declared in a base class or an interface. This enables the same method to behave differently based on the object's actual instance (subclass instance), which is particularly powerful in class hierarchies where a base class reference refers to a subclass object. For instance, the withdraw method is overridden in SavingsAccount and CheckingAccount classes, allowing each subclass to implement specific withdrawal rules and limits. This dynamic method invocation enhances flexibility and reusability of the code .

The bottom-up approach in Object-Oriented Programming (OOP) focuses on designing and building reusable and well-defined objects first, which can then be integrated to create larger systems. This modularity enhances code reusability, maintainability, and flexibility. In contrast, the top-down approach in Procedure-Oriented Programming (POP) involves breaking the program into smaller, procedural steps. This can make complex systems harder to manage due to less reusability and difficulties in abstraction, as functions and data are not as closely bound together .

A class is made abstract in Java when it is declared with the abstract keyword, indicating that it cannot be instantiated directly and may contain abstract methods that must be implemented by its subclasses. This enforces abstraction by defining a template for derived classes to follow, hiding specific implementations from the client code. This allows developers to define methods with contractual behavior while deferring detailed implementations to the subclasses, thus promoting high-level design over specifics .

In Object-Oriented Programming (OOP), encapsulation restricts access to internal states and data through access modifiers (e.g. private, protected, public), ensuring that data is only accessible through specified methods. This contrasts with Procedure-Oriented Programming (POP) where data is often global and can be modified by any function, thus less secure. Abstraction in OOP hides complex implementation details behind simpler interfaces, allowing safer interaction with the data .

The main method in the Calculator class exemplifies good programming practices by using a Scanner object to handle user input, thus managing input streams efficiently. It includes validation checks such as ensuring the divisor is not zero during division operations, thereby preventing runtime exceptions and enhancing program robustness. Additionally, closing the scanner object at the end of input usage prevents resource leaks, adhering to best practices for managing resources in Java .

The withdrawal implementations in SavingsAccount and CheckingAccount classes demonstrate polymorphism by providing different withdrawal logics customized to their specific banking rules. SavingsAccount limits withdrawals based on a fixed limit and account balance, whereas CheckingAccount allows withdrawals up to a specified overdraft limit. This polymorphic behavior allows objects of these classes to perform the same action (withdrawal) with differing effects based on their class type, illustrating how polymorphism can cater to varied class-specific functionalities under a uniform interface .

You might also like