[go: up one dir, main page]

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

Oops Programs

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)
5 views17 pages

Oops Programs

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
You are on page 1/ 17

Conditional statement:

import java.util.Scanner;

public class DecisionDemo {

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

public static void nestedIfElse(int num) {

if (num > 0) {

System.out.println("Nested if-else: Positive");

} else {

if (num < 0) {

System.out.println("Nested if-else: Negative");

} else {

System.out.println("Nested if-else: Zero");

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

public static void elseIfLadder(int num) {

if (num > 0) {

System.out.println("Else-if ladder: Positive");

} else if (num < 0) {

System.out.println("Else-if ladder: Negative");

} else {

System.out.println("Else-if ladder: Zero");

}
}

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

public static void switchStatement(int num) {

// Integer.signum returns -1 for negative, 0 for zero, 1 for positive

int sign = Integer.signum(num);

switch (sign) {

case 1:

System.out.println("Switch statement: Positive");

break;

case -1:

System.out.println("Switch statement: Negative");

break;

default:

System.out.println("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 -> System.out.println("Switch expression: Positive");

// case -1 -> System.out.println("Switch expression: Negative");

// default -> System.out.println("Switch expression: Zero");

// }

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

Scanner sc = new Scanner(System.in);

System.out.print("Enter an integer: ");

while (!sc.hasNextInt()) {

System.out.print("Please enter a valid integer: ");

sc.next();

int num = sc.nextInt();

System.out.println("\nResults for number: " + num);

nestedIfElse(num);

elseIfLadder(num);

switchStatement(num);

sc.close();

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

this.accountNumber = accountNumber;

this.holderName = holderName;

this.balance = 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;

System.out.println(amount + " deposited. New Balance: " + balance);

} else {

System.out.println("Invalid deposit amount!");

// Abstract method: must be implemented by subclasses

public abstract void withdraw(double amount);

// Display account details

public void displayAccountInfo() {


System.out.println("Account Number: " + accountNumber);

System.out.println("Holder Name: " + holderName);

System.out.println("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;

System.out.println("SavingsAccount: " + amount + " withdrawn. New Balance: " + balance);

} else {

System.out.println("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;

System.out.println("CheckingAccount: " + amount + " withdrawn. New Balance: " + balance);

} else {

System.out.println("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

acc1.displayAccountInfo();

acc2.displayAccountInfo();
System.out.println("\n--- Transactions ---");

acc1.deposit(2000);

acc1.withdraw(3000); // Savings withdrawal rules apply

acc1.withdraw(7000); // Exceeds withdrawal limit

acc2.deposit(1000);

acc2.withdraw(2500); // Overdraft allowed

acc2.withdraw(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) {

this.accountHolder = accountHolder;

this.balance = balance;

// Getter and Setter (Encapsulation)

public String getAccountHolder() {

return accountHolder;

}
public double getBalance() {

return balance;

protected void setBalance(double balance) {

this.balance = balance;

// Abstract Method (must be implemented by subclasses)

public abstract void displayAccountInfo();

// Common Method for deposit

public void deposit(double amount) {

balance += amount;

System.out.println(amount + " deposited. New balance: " + balance);

// Common Method for withdrawal

public void withdraw(double amount) {

if (balance >= amount) {

balance -= amount;

System.out.println(amount + " withdrawn. New balance: " + balance);

} else {

System.out.println("Insufficient balance!");

}
}

// Inheritance & Polymorphism

class SavingsAccount extends BankAccount {

private double interestRate;

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

super(accountHolder, balance);

this.interestRate = interestRate;

@Override

public void displayAccountInfo() { // Polymorphic behavior

System.out.println("Savings Account");

System.out.println("Holder: " + getAccountHolder());

System.out.println("Balance: " + getBalance());

System.out.println("Interest Rate: " + interestRate + "%");

// Inheritance & Polymorphism

class CheckingAccount extends BankAccount {

private double overdraftLimit;

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

super(accountHolder, balance);

this.overdraftLimit = overdraftLimit;
}

@Override

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

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

setBalance(getBalance() - amount);

System.out.println(amount + " withdrawn. New balance: " + getBalance());

} else {

System.out.println("Overdraft limit exceeded!");

@Override

public void displayAccountInfo() { // Polymorphic behavior

System.out.println("Checking Account");

System.out.println("Holder: " + getAccountHolder());

System.out.println("Balance: " + getBalance());

System.out.println("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);


acc1.displayAccountInfo();

acc1.deposit(500);

acc1.withdraw(2000);

System.out.println();

acc2.displayAccountInfo();

acc2.deposit(1000);

acc2.withdraw(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

System.out.println("Original float value: " + floatNumber);


System.out.println("After converting float to int: " + intNumber);

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

int anotherInt = 25;

float anotherFloat = anotherInt; // automatic conversion

System.out.println("\nOriginal int value: " + anotherInt);

System.out.println("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) {


this.value = value;
}

public void show() {


System.out.println("Value: " + value);
}
}

public class Main {


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

Operator:
import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input two numbers
System.out.print("Enter first number: ");
double num1 = sc.nextDouble();

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


double num2 = sc.nextDouble();

// Input operator
System.out.print("Enter an operator (+, -, *, /, %): ");
char operator = sc.next().charAt(0);

double result;

// Perform operation based on operator


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

sc.close();
}
}
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() {

System.out.println("Employee ID: " + empId);

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

System.out.println("Salary: " + salary);

employee

// Main class

public class EmployeeTest {

public static void main(String[] args) {

// Create Employee object

Employee emp1 = new Employee();

// Assign details
emp1.setDetails(101, "Alice", 55000);

// Display details

emp1.displayDetails();

You might also like