JAVA
JAVA
○ 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)
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
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
}
}
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(); } }
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");
}
class Main {
public static void main(String[] args) {
// create an object of the subclass
Dog labrador = new Dog();
System.out.println("\nCalling makeSound():");
JAVA Page 6
System.out.println("\nCalling makeSound():");
labrador.makeSound();
}
}
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.
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.
Static Variables
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.
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.
this can be used to return the current class instance from a method. This is often used in method chaining.
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 {
}
}
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();
}
@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);
}
}
printUpdatedStudentList(sArr);
}
}
import java.util.Scanner;
interface Generatable {
abstract void feeGenerate(Student s);
}
class Student {
private String name;
private double fee;
private int backlogs;
class ExamBranch {
private class Regular implements Generatable {
public void feeGenerate(Student s) {
s.setFee(1500.00);
}
}
Consider the code given below. Consider the code given below.
JAVA Page 13
public default double volume() { public default void travel() {
return -1.0; System.out.println("travel with wings");
} }
} }
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.
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.
JAVA Page 16
Compares arr[1] = 5 with findMax(arr, 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) }
Q:
Given a string find its first uppercase letter import java.io.*;
class GFG {
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