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

JAVA

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including key elements such as objects, classes, inheritance, and polymorphism. It explains various types of variables, constructors, and methods, along with examples demonstrating their usage. Additionally, it covers interfaces, abstract classes, and the significance of accessor and mutator methods in managing object state.

Uploaded by

Shreyan Saha
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)
5 views

JAVA

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including key elements such as objects, classes, inheritance, and polymorphism. It explains various types of variables, constructors, and methods, along with examples demonstrating their usage. Additionally, it covers interfaces, abstract classes, and the significance of accessor and mutator methods in managing object state.

Uploaded by

Shreyan Saha
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
You are on page 1/ 18

DAY - 1

04 November 2024 09:18

OOPS in JAVA consists of the following:


○ Object

○ Class

○ Abstraction

○ Encapsulation

○ Inheritance

○ Polymorphism

OBJECT
An object can be represented as an entity that has state and behaviour.
The state of an object is a data item that can be represented in value such as price of car, color,
consider them as variables in programming.

The behaviour is like a method of the class, it is a group of actions that together can perform a task.
For example, gear change is a behaviour as it involves multiple subtasks such as speed control, clutch,
gear handle movement.
class House {
String address;
String color;
double area;
void openDoor() {
//Write code here
}
void closeDoor() {
//Write code here
}
...
...
}

CLASS

A class can be considered as a blueprint which you can use to create as many objects as you like

JAVA VARIABLES

1. local variable
2. class variable (static variables)
3. instance variable (non-static variable)

In Java, a local variable is a variable that is declared within a method,


constructor, or block of code. These variables are only accessible within the
scope in which they are declared, meaning they cannot be accessed from outside
the method or block

Lifetime: Local variables are created when the block of code in which they are
declared is entered and destroyed when the block is exited. They do not retain
their values between method calls.

Initialization: Local variables must be initialized before they are used. Java does
not provide a default value for local variables, so you must explicitly assign a value
before using them.

In Java, a class variable, also known as a static variable, is a variable that is declared
with the static keyword within a class but outside any method, constructor, or block.

Class variables are shared among all instances of a class, meaning that they have the
same value for every instance unless explicitly changed.

Shared Across Instances: Class variables are shared by all instances of the class.
If one instance changes the value of a class variable, the change is reflected across
all instances.

Example:

JAVA Page 1
CONSTRUCTORS

The new keyword here creates the object of


class MyClass and invokes the constructor to
initialize this newly created object.

1. Default Constructor

JAVA Page 2
2. No-arg constructor

Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.

3. Parametrized Constructor
Constructor with arguments(or you can say parameters) is known as Parameterized constructor.

JAVA Page 3
public class JavaExample { Fill in the code block such that it checks if str and str2
public static void main(String[] args) { have the same content or not and prints "Equal" if they have
string str = "xyz" the same content and "Not Equal" otherwise
string str2 = new String("xyz")

//code block

}
}

Output : Welcome Home

JAVA Page 4
import java.util.*;
//Add your code for Class Student here
public class Test{
// Define the method getMax() here
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student[] arr = new Student[3];
for(int i = 0; i < 3; i++){
String name = sc.next();
double[] m = {sc.nextDouble(),
sc.nextDouble(), sc.nextDouble()};
arr[i] = new Student(name, m);
}
System.out.println(getMax(arr));
}
}

import java.util.*;
class Employee{
String name;
String[] projects;
//***** Define constructor(s) here--> write here
public void setName(String n) {
name = n;
}
public void setProject(int index, String proj) {
projects[index] = proj;
}
public String getName() {
return name;
}
public String getProject(int indx) {
return projects[indx];
}
}
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] proj = {"PJ1", "PJ2", "PJ3"};
Employee e1 = new Employee("Surya", proj);
Employee e2 = new Employee(e1);
e2.setName(sc.next());
e2.setProject(0, sc.next());
System.out.println(e1.getName() + ": " +
e1.getProject(0));
System.out.println(e2.getName() + ": " +
public Employee(String name, String[] projects) e2.getProject(0));
{ this.name = name; this.projects = }
projects.clone(); } }

public Employee(Employee e) { this.name =


e.name; this.projects = e.projects.clone();}

import java.util.Scanner;
class Faculty{
private String name;
private double salary;
public Faculty(String name, double salary) {
this.name = name;
this.salary = salary;
}
public double bonus(float percent){
return (percent/100.0)*salary;
}
// Define method getDetails()
// Override method getDetails(float percent)
}
class Hod extends Faculty{
private String personalAssistant;
public Hod(String name, double salary, String pa) {
super(name, salary);
this.personalAssistant = pa;
}
// Override method bonus(float percent)
// Override method getDetails()
// Override method getDetails(float percent)

}
public class InheritanceTest{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Faculty obj1 = new Faculty(sc.next(), sc.nextDouble());
Faculty obj2 = new Hod(sc.next(), sc.nextDouble(),
sc.next());
System.out.println(obj1.getDetails());
System.out.println(obj1.getDetails(10));
System.out.println(obj2.getDetails());
System.out.println(obj2.getDetails(10));
}
}

JAVA Page 5
Faculty obj1 = new Faculty(sc.next(), sc.nextDouble());
Faculty obj2 = new Hod(sc.next(), sc.nextDouble(),
sc.next());
System.out.println(obj1.getDetails());
System.out.println(obj1.getDetails(10));
System.out.println(obj2.getDetails());
System.out.println(obj2.getDetails(10));
}
}

Subclass (child) -> the class that inherits from another class
Superclass(parent) -> The class being inherited from
To inherit from a class, we use 'extends' keyword

If you don't want other classes to inherit from a class, use the final keyword:

➢ Method overriding

class Animal {
// method in the superclass
public void eat() {
System.out.println("I can eat");
}

public void makeSound() {


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

// Dog inherits Animal


class Dog extends Animal {
// overriding the eat() method
@Override
public void eat() {
// Call the parent class eat() method
System.out.println("Before eating dog food, like any
animal...");
super.eat(); // This calls Animal's eat() method
System.out.println("I eat dog food");
}

// Demonstrating super in another method


@Override
public void makeSound() {
super.makeSound(); // First call parent's method
System.out.println("Dog barks: Woof Woof!");
}

// new method in subclass


public void bark() {
System.out.println("I can bark");
}
}

class Main {
public static void main(String[] args) {
// create an object of the subclass
Dog labrador = new Dog();

// Demonstrate calling methods


System.out.println("Calling eat():");
labrador.eat();

System.out.println("\nCalling makeSound():");

JAVA Page 6
System.out.println("\nCalling makeSound():");
labrador.makeSound();
}
}

OUTPUT: Discount available

JAVA Page 7
Accessor Methods

Accessor methods, also known as getter methods, are methods that allow you to retrieve the value of
an object's private instance variables. These methods provide read-only access to the object's state.
By using accessor methods, you can ensure that the object's state is not modified accidentally or
maliciously by external code.

Mutator Methods
Mutator methods, also known as setter methods, are methods that allow you to modify the value of an
object's private instance variables. These methods provide write-only access to the object's state. By
using mutator methods, you can ensure that the object's state is modified only through a controlled
interface.

In this example, we have defined three accessor methods: getName(), getAge(), and getEmail(), and
three mutator methods: setName(), setAge(), and setEmail(). The accessor methods return the value of
the corresponding instance variable, while the mutator methods set the value of the corresponding
instance variable.

Reference-typed return values

In Java, a reference-typed return value refers to a method that returns an object rather than a primitive data type. This means
the method returns a reference to an instance of a class.

Reference-Typed Return Value: The createCar method in the Main


class is an example of a method with a reference-typed return
value. It returns a reference to a Car object. The method takes
two parameters, model and color, and returns a new Car object
initialized with these values.

Using the Returned Object: In the main method, we call createCar


and store the returned reference in the myCar variable. We then
use this reference to call the displayDetails method on the Car
object

Static Variables

Key Characteristics of Static Variables


Class-Level Scope: Static variables are declared at the class level and are shared among all instances of the class.

Single Copy: Only one copy of a static variable exists, regardless of how many objects are created from the class.

Memory Allocation: Static variables are stored in the static memory area, which is allocated when the class is loaded.

Access: They can be accessed directly using the class name, without needing to create an instance of the class.

JAVA Page 8
Static Variable count: This variable is declared as static,
meaning it is shared across all instances of the Counter
class. Every time a new Counter object is created, the
constructor increments this variable.

Static Method getCount(): This method is also static,


allowing it to be called without an instance of the class. It
returns the current value of the static variable count.

Use of 'this' keyword

1.Distinguishing Instance Variables from Parameters

When a method or constructor has parameters


with the same name as instance variables, this is
used to differentiate between the two.

In this example, this.model and this.year refer to


the instance variables, while model and year refer
to the constructor parameters.

2. Invoking Other Constructors

this can be used to call another constructor in the same class. This is known as constructor chaining.

this can be used to call another constructor in the same class. This is known as
constructor chaining.

Here, the no-argument constructor calls the parameterized constructor using


this("Unknown", 0).

3. Returning the Current Class Instance

this can be used to return the current class instance from a method. This is often used in method chaining.

4. Passing the Current Object as a Parameter

In this example, this is used to pass the current object to the


printCarDetails method.

5. Accessing Members of the Current Object

this can be used to access fields and methods of the current object,
though it's often implicit and not required.

JAVA Page 9
INTERFACE An abstract method is a method declared without
an implementation. It’s used to define the
signature of a method that must be implemented
Interfaces: by non-abstract subclasses. Abstract methods
An interface is a blueprint for a class. It contains only abstract methods and constants. A are declared using the abstract keyword and do
class can implement multiple interfaces, allowing it to inherit behavior from multiple not contain a method body. Any class containing
sources. one or more abstract methods must be declared
as abstract
abstract class Shape {
// Abstract method (does not have a body)
public abstract double area();
// Concrete method (has a body)
public void display() {
System.out.println("This is a shape.");
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Implementing abstract method
public double area() {
return length * width;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// Implementing abstract method
public double area() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape rect = new Rectangle(5, 4);
Shape circle = new Circle(3);
rect.display();
System.out.println("Area of rectangle: " + rect.area());
circle.display();
System.out.println("Area of circle: " + circle.area());
}
}

JAVA Page 10
interface FirstInterface {
// Interface public void myMethod(); // interface
interface Animal { method
public void animalSound(); // interface }
method (does not have a body) interface SecondInterface {
public void sleep(); // interface method public void myOtherMethod(); //
(does not have a body) interface method
} }
// Pig "implements" the Animal interface class DemoClass implements FirstInterface,
class Pig implements Animal { SecondInterface {
public void animalSound() { public void myMethod() {
System.out.println("The pig says: wee System.out.println("Some text..");
wee"); }
} public void myOtherMethod() {
public void sleep() { System.out.println("Some other
System.out.println("Zzz"); text...");
} }
} }
class Main { class Main {
public static void main(String[] args) { public static void main(String[] args) {
Pig myPig = new Pig(); // Create a DemoClass myObj = new DemoClass();
Pig object myObj.myMethod();
myPig.animalSound(); myObj.myOtherMethod();
myPig.sleep(); }
} }
}

import java.util.*;
abstract class StringOperations{
public abstract String reverse(String s);
public abstract int vowelCount(String s);
}
// Class that extends StringOperations and implements reverse
method
class StringReverse extends StringOperations {

// Placeholder implementation for vowelCount method


@Override
public int vowelCount(String s) {

}
}

// Class that extends StringReverse and implements vowelCount


method

class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
UpdatedStrings str = new UpdatedStrings();
System.out.println("Reverse of "+ s + " is "+ str.reverse(s));
System.out.println("Vowel count of "+ s + " is "+
str.vowelCount(s));
}
}

import java.util.*;
abstract class UPIPayment{
abstract void payment();
abstract void rewards();
}
class PhonePay extends UPIPayment{
private int amount;
public PhonePay(int amount) {
this.amount = amount;
}
// Override method payment()
// Override method rewards()
}
class Paytm extends UPIPayment{
private int amount;
public Paytm(int amount) {
this.amount = amount;
}
// Oveeride method payment()
// Override method rewards()
}
class UPIUser{
public void transferAndGetRewards(UPIPayment obj) {
obj.payment();
}
}
public class AbstractTest {

JAVA Page 11
class UPIUser{
public void transferAndGetRewards(UPIPayment obj) {
obj.payment();
}
}
public class AbstractTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a1 = sc.nextInt();
int a2 = sc.nextInt();
UPIUser u = new UPIUser();
u.transferAndGetRewards(new PhonePay(a1));
u.transferAndGetRewards(new Paytm(a2));
}
}

import java.util.*;
interface Appraisable {
default void appraisal(Teacher t) {
t.setSalary(t.getSalary() + (t.getstuPassPer() / 100) *
5000);
}
void checkAndUpdateSalary();
}

interface SpecialAppraisable extends Appraisable {


default void spAppraisal(Teacher t) {
t.setSalary(t.getSalary() + (t.getstuPassPer() / 100) *
10000);
}
}

class Teacher implements SpecialAppraisable{


private String name;
private double salary;
private double stuPassPer;
public Teacher(String name, double salary, double stuPassPer) {
this.name = name;
this.salary = salary;
this.stuPassPer = stuPassPer;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getstuPassPer() {
return stuPassPer;
}
public String toString() {
return name + ", " + salary + ", " + stuPassPer;
}
public void checkAndUpdateSalary() {
if(stuPassPer >= 60 && stuPassPer < 75)
appraisal(this);
else if(stuPassPer >= 75 && stuPassPer <= 100)
spAppraisal(this);
}
}
public class InterfaceTest {
public static void printUpdatedTeachList(Teacher[] tList) {
for (Teacher t : tList) {
t.checkAndUpdateSalary();
}
for (Teacher t : tList) {
System.out.println(t);
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Teacher tArr[] = new Teacher[3];
for (int i = 0; i < tArr.length; i++)
tArr[i] = new Teacher(sc.next(), sc.nextDouble(), sc.nextDouble());
InterfaceTest.printUpdatedTeachList(tArr);
}
}

\\ Define interface Evaluatable


\\ Define interface SpecialEvaluatable

class Student implements SpecialEvaluatable {


private String name;
private double grade;
private double attendance;

public Student(String name, double grade,


double attendance) {
this.name = name;
this.grade = grade;
this.attendance = attendance;
}

public void setGrade(double grade) {


this.grade = grade;
}

public double getGrade() {


return grade;
}

public double getAttendance() {


return attendance;
}

@Override
public String toString() {
return name + " " + grade + " " + attendance;
}
\\ Method assessAndUpdateGrade
}

class StudentTest {
public static void
printUpdatedStudentList(Student[] sList) {
for (Student s : sList) {
s.assessAndUpdateGrade();

JAVA Page 12
class StudentTest {
public static void
printUpdatedStudentList(Student[] sList) {
for (Student s : sList) {
s.assessAndUpdateGrade();
}
for (Student s : sList) {
System.out.println(s);
}
}

public static void main(String[] args) {


Student[] sArr = {
new Student("Alice", 85, 80),
new Student("Bob", 78, 95),
new Student("Charlie", 90, 88)
};

printUpdatedStudentList(sArr);
}
}

import java.util.Scanner;

interface Generatable {
abstract void feeGenerate(Student s);
}

class Student {
private String name;
private double fee;
private int backlogs;

public Student(String name, int backlogs) {


this.name = name;
this.backlogs = backlogs;
}

public void setFee(double fee) {


this.fee = fee;
}

public int getBacklogs() {


return backlogs;
}

public String toString() {


return name + ", " + fee + ", " + backlogs;
}
}

class ExamBranch {
private class Regular implements Generatable {
public void feeGenerate(Student s) {
s.setFee(1500.00);
}
}

private class Supple implements Generatable {


public void feeGenerate(Student s) {
if (s.getBacklogs() == 1)
s.setFee(2000.00);
else if (s.getBacklogs() == 2)
s.setFee(2500.00);
else if (s.getBacklogs() >= 3)
s.setFee(3500.00);
}
}

public Generatable getRegularFee() {


return new Regular();
}

public Generatable getSuppleFee() {


return new Supple();
}
}

public class PrivateClassTest {


public static Student[] getStudentsFee(Student sList[]) {
ExamBranch examBranch = new ExamBranch();
for (Student s : sList) {
if (s.getBacklogs() == 0) {
examBranch.getRegularFee().feeGenerate(s);
} else {
examBranch.getSuppleFee().feeGenerate(s);
}
}
return sList;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Student[] sArr = new Student[3];
for (int i = 0; i < sArr.length; i++) {
sArr[i] = new Student(sc.next(), sc.nextInt());
}
sArr = PrivateClassTest.getStudentsFee(sArr);
for (Student s : sArr) {
System.out.println(s);
}
sc.close();
}
}

Consider the code given below. Consider the code given below.

public interface Shape{ public interface Flyable{


public double area(); public void fly();
public default double volume() { public default void travel() {
return -1.0; System.out.println("travel with wings");
} }
} }

public interface Printable{ public interface Movable{


public default void print() { public void move();

JAVA Page 13
public default double volume() { public default void travel() {
return -1.0; System.out.println("travel with wings");
} }
} }

public interface Printable{ public interface Movable{


public default void print() { public void move();
System.out.println("not implemented"); public default void travel() {
} System.out.println("travel with legs");
} }
}
public class Rectangle implements Shape, Printable{
private double w, h; public class Bird implements Flyable, Movable{
public Rectangle(double w_, double h_) { public void fly() {
w = w_; System.out.println("fly with wings");
h = h_; }
} public void move() {
public double area() { System.out.println("move with legs");
return w * h; }
} }
public void print() {
System.out.print(area() + " "); public class FClass{
System.out.print(volume()); public static void main(String[] args) {
} Bird b = new Bird();
} b.fly();
b.move();
public class FClass{ b.travel();
public static void main(String[] args) { }
Rectangle r = new Rectangle(20.0, 50.0); }
r.print();
} Q: Either find the output of the above code or if it gives a
} compilation error explain why?

If.isFossilFuel(fuelType) - Line 1
e.maxMileage(fType[i]) - Line 2

JAVA Page 14
This code generates a compilation error because
myMethod is not defined in class Child.

Consider the program given below and predict the


output.

import java.util.*;
public class Example{
public static void main(String args[]){
ArrayList<String> str=new
ArrayList<String>();
str.add("Joker");
str.add("Locker");
for(int i:str){
System.out.println(i);
}
}
}

JAVA Page 15
Write the missing line (LINE 1) such that the
output is norm is : 5.0

In the following code, method findMax , returns the maximum element in an array of integers.

return Math.max(arr[n - 1], findMax(arr, n - 1));


Backtracking:
Example : arr = {1, 5, 3, 6, 2, 8} Now the recursion starts returning values:

Step-by-Step Execution: findMax(arr, 2) → Math.max(5, 1) = 5


findMax(arr, 3) → Math.max(3, 5) = 5
Initial Call: findMax(arr, 6) findMax(arr, 4) → Math.max(6, 5) = 6
Compares arr[5] = 8 with findMax(arr, 5).
findMax(arr, 5) → Math.max(2, 6) = 6
Recursive Call: findMax(arr, 5) findMax(arr, 6) → Math.max(8, 6) = 8
Compares arr[4] = 2 with findMax(arr, 4).

Recursive Call: findMax(arr, 4)


Compares arr[3] = 6 with findMax(arr, 3).

Recursive Call: findMax(arr, 3)


Compares arr[2] = 3 with findMax(arr, 2).

Recursive Call: findMax(arr, 2)


Compares arr[1] = 5 with findMax(arr, 1).

JAVA Page 16
Compares arr[1] = 5 with findMax(arr, 1).

Base Case: findMax(arr, 1)


Returns arr[0] = 1.

Create an abstract class StringOperations that has the following import java.util.*;
abstract class StringOperations{
abstract methods:
public abstract String reverse(String s);
String reverse(String s) public abstract int vowelCount(String s);
int vowelCount(String s) }

// Class that extends StringOperations and implements


Create StringReverse class that extends StringOperations class
reverse method
but defines only String reverse(String s) method. It reverses the class StringReverse extends StringOperations {
string which is passed as parameter and returns the reversed @Override
string. public String reverse(String s) {
---Write the code---- //Line 1
Create UpdatedStrings class that extends StringReverse class and
}
defines int vowelCount(String s) method. It counts the vowels in
the string which is passed as parameter and returns the count. // Placeholder implementation for vowelCount method
------- Write the code here------- // Line2
}
LINE 1 :
// Class that extends StringReverse and implements
return new StringBuilder(s).reverse().toString();
vowelCount method
LINE 2 : class UpdatedStrings extends StringReverse {
public int vowelCount(String s) { @Override
return 0; } public int vowelCount(String s) {
LINE 3 :
----Write the code here----- //Line 3
int count = 0;
for (char c : s.toLowerCase().toCharArray()) { }
if ("aeiou".indexOf(c) != -1) { class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
count++; String s = sc.next();
} UpdatedStrings str = new UpdatedStrings();
} System.out.println("Reverse of "+ s + " is "+ str.reverse(s));
System.out.println("Vowel count of "+ s + " is "+
return count;
str.vowelCount(s));
} }
}

Q:
Given a string find its first uppercase letter import java.io.*;

class GFG {

// Function to find string which has


if(str.charAt(i)=='\0'){
// first character of each word.
return 0;
}
static char first(String str, int i) {
if(Character.isUpperCase(str.charAt(i))) {
// Write the code
return str.charAt(i);
}
}
try {
// Driver code
return first(str, i + 1);
public static void main(String args[])
}
{
catch(Exception e){
String str = "geeksforGeeKS";
System.out.println("Exception occurs");
char res = first(str,0);
}
if (res == 0)
return 0;
System.out.println("No uppercase letter");
}
else

JAVA Page 17
{
catch(Exception e){
String str = "geeksforGeeKS";
System.out.println("Exception occurs");
char res = first(str,0);
}
if (res == 0)
return 0;
System.out.println("No uppercase letter");
}
else
System.out.println (res );
}
}

JAVA Page 18

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy