Java Main Notes Part3
Java Main Notes Part3
Programming Paradigms
○ Procedural Programming
○ Functional Programming
Important Note:
What is OOP?
● In OOP:
1. Objects
a) State (Attributes)
○ name
○ age
○ height
○ weight
b) Behavior (Methods)
○ walk()
○ talk()
○ run()
○ sleep()
2. Classes
● A class defines:
● From one class, we can create multiple objects, each with different data values.
Example:
● Class: Human
○ Humans
○ Animals
○ Vehicles
○ Trees
○ Books
● Even though all humans share common characteristics, their values differ.
● This similarity + variation is perfectly modeled using classes and objects in OOP.
Possible classes:
○ Customer
○ Account
○ Loan
○ Transaction
○ Card
Customer class
● Easier to understand
● Easier to manage
● Easier to scale
Features of Object-Oriented Programming (OOP)
● OOP provides several powerful features that improve code quality, reusability, and
maintainability.
1. Encapsulation
Feature:
Benefits:
2. Inheritance
Feature:
Benefits:
3. Polymorphism
Feature:
● It enables a method to behave differently based on the object that calls it.
● Method Overriding:
Subclass provides its own implementation of a superclass method
● Method Overloading:
Same method name with different parameters in the same class
Benefits:
4. Abstraction
Feature:
Benefits:
● Simplified Interfaces: Reduce complexity for users
What is a Class?
● A class in Java is a blueprint or template used to create objects.
● It defines:
● Attributes (fields) → represent the state of an object
● Every object created from a class is called an instance of that class, and each instance
has its own copy of instance variables.
Explanation:
● { } → class body
○ All fields, methods, constructors, and blocks must be inside these braces.
Components of a Java Class
A class may contain:
3. Constructors
● Hard Disk (Secondary Memory) – Permanent storage (files, programs, .class files)
Types of Memory:
Component Role
2. Object-Specific
Each object has its own independent copy.
○ int → 0
○ double → 0.0
○ boolean → false
○ reference → null
package [Link];
public class Main {
[Link](y); // OK
// [Link](x); // ERROR
}
}
Why Error?
● main() is static
● x is non-static
● static methods cannot directly access non-static members
1. Static Members
2. Non-Static Members
Component Stored In
Syntax:
Example:
obj1.x = 50;
Main obj2 = new Main();
[Link](obj2.x); // 10
obj1.x = 50;
[Link](obj2.x); // 50
NullPointerException:
● Occurs when:
● Reference variable is null
● You try to access the instance members
Example:
● Java developers do not need to delete objects manually. The JVM (Java Virtual
Machine) automatically removes unused objects from memory.
Main purpose of GC:
● It is no longer referenced
Example:
Main obj1 = new Main();
obj1= null; // object becomes eligible for GC
Common Scenarios:
● You can request GC, but the JVM may ignore it.
[Link]();
[Link]().gc();
Task:
Example:
[Link]
package [Link];
public class Song {
String artist;
String title;
}
}
Key Points
Static variable initializes with default A non-static variable is initialized with default
values at the time of class loading. values at the time of object creation
All objects of a class share a single copy of Each object has one local copy of the
static variables non-static variables.
Example:
[Link]:
package [Link];
public class Main{
static int x;
int y;
public static void main(String[] args){
Main obj1 = new Main();
obj1.x=10;
obj1.y=20;
Main obj2 = new Main();
obj2.x=50;
obj2.y=80;
[Link](obj1.x); //50
[Link](obj1.y); //20
[Link](obj2.x); //50
[Link](obj2.y); //80
}
}
Example1:
[Link]:
package [Link];
public class Main
{
static int i=10;
public static void fun1(){
[Link]("inside static fun1 of Demo");
}
//using by an object
Main obj=new Main();
[Link](obj.i);
obj.fun1();
}
}
Example2:
[Link]:
package [Link];
public class Account
{
static String bankName;
long accountNumber;
String accountHolderName;
double balance;
● Such a class:
○ Can be compiled
Example:
[Link]:
public class A{
//Empty class
}
● We can also generate the .class file also for this empty Java class.
● But we can not execute the above Java class, because it does not have a main method.
● Remember, the above class is empty, but when we try to create an object of that class,
that object will not be empty; it will have some properties in it.
Creating one class object inside the main method of another class:
Example1:
[Link]:
package [Link];
public class A {
int i=10;
void funA() {
[Link]("inside funA of A class");
}
}
[Link]
package [Link];
Example2:
[Link]:
public class A{
int i = 10;
static int j = 20;
void funA(){
[Link]("inside funA of A class");
}
}
[Link]:
● Note: We can access the static members of a class from anywhere inside the class
(inside static context or inside non-static context) because they are already loaded into
RAM (into the method area). To access the non-static members from the static
context(static method or static area), we need to create an object of the class.
● All non-static members are sharable among themselves, i.e., we can access them
directly from any non-static method.
Example:
[Link]:
package [Link];
public class Employee{
String id="E-1s11";
String name="Ramesh";
double salary=25000.00;
String address="Hyderabad";
public void displayDetails(){
[Link]("Employee Details");
[Link]("-------------------");
[Link]("Employee Id :"+id);
[Link]("Employee Name :"+name);
[Link]("Employee Saslary:"+salary);
[Link]("Employee Address:"+address);
}
}
[Link]:
package [Link];
public class Main{
Relationships in Java
● In Object-Oriented Programming (OOP), a relationship describes how one class is
connected to another class. Relationships help us model real-world connections
between objects and design well-structured applications.
● Represents inheritance
Key Points:
Example:
Example:
[Link]
package [Link];
public class Address{
String city;
String state;
String pincode;
}
[Link]:
package [Link];
public class Employee{
String empId;
String empName;
double salary;
}
}
Note: We can define the Address class inside the Employee class as a static member.
Example1:
[Link]
package [Link];
public class Address{
String city;
String state;
String pincode;
}
[Link]
package [Link];
public class Employee{
String empId;
String empName;
double salary;
[Link]([Link]); // null
[Link]
package [Link];
public class Address{
String city;
String state;
String pincode;
[Link]:
package [Link];
public class Employee{
String empId;
String empName;
double salary;
Address address = new Address();
[Link]:
package [Link];
public class A {
int x = 10;
void funA(){
[Link]("inside funA of A class");
}
}
Here:
[Link]:
package [Link];
public class Main {
Note: The println() method belongs to the “[Link]” class. “out” is a variable of
this PrintStream class, which is statically defined inside the System class.
Example:
Important Note
Example:
If:
● College closes.
● That’s Aggregation
[Link]
class Student {
int roll;
String name;
void show() {
[Link](roll + " " + name);
}
[Link]: (Aggregation)
class College {
String collegeName;
Student student; // Aggregation
void display() {
[Link](collegeName);
[Link]();
}
}
[Link]:
Weak association
Independent life cycle
● If the parent object is destroyed, the child object is also destroyed, then it
is Composition.
Example:
[Link]
class Engine {
void start() {
[Link]("Engine started");
}
[Link]: (Composition)
class Car {
void drive() {
[Link]();
[Link]("Car moving");
[Link]:
}
}
Strong association
Dependent life cycle
Golden Rule:
class College {
class Car {
Engine engine;
void setEngine(Engine e) {
engine = e;
}
}
● If this Engine is used only by this Car and destroyed with it,
● Then logically: Composition
class Car {
void drive() {
[Link]();
[Link]("Car moving");
}
}
● Here, the final keyword prevents reassignment.
To enforce aggregation:
class Car {
Activity Task1:
Activity Task2:
● Teacher
● Department
Requirements
1. Teacher has:
○ id
○ name
○ department name
○ teacher object
Expected Output:
○ House
○ Room
● A house owns rooms, and rooms cannot exist without a house. Implement
Composition.
Requirements
1. The Room class should have a method showRoom()with the message: “Room
is available”.
2. The room object must be created inside the House class.
○ house name
○ room details.
Expected Output:
Room is available
Methods in Java
What is a Method?
● In Java, a method is a block of code designed to perform a specific task.
A method executes only when it is called.
// method body
return value;
}
Explanation:
Naming Rule
1. Concrete Method
● Method declaration
Example:
public void sayHello() {
[Link]("Welcome to Java");
}
2. Abstract Method
● An abstract method only has a declaration (method signature), but no body. The method
must be implemented in a subclass. Abstract methods are found in abstract classes or
interfaces.
Example:
Rules:
Concrete Method Abstract Method
Method Signature
● A method signature uniquely identifies a method.
● Access modifier
● Return type
● Parameter names
● throws clause
Method Declaration Method Signature
● Methods can accept parameters that provide input to the method. This allows the
method to perform an action based on the provided data. Parameters can be of any data
type, including primitive types and reference types (e.g., objects, arrays, etc.).
[Link]:
void fun1(int i) {
[Link]("Inside fun1 of Demo");
[Link]("The value of i is: " + i);
}
byte x = 20;
d1.fun1(x); // Implicit typecasting to int
double n1=100.00;
//d1.fun1(n1); //Error
//d1.fun1((int)n1); //valid
}
}
Note: In this example main() method is calling the fun1() method on the Demo class object.
● As we can take any primitive type as a parameter to a function, we can also take a class
reference also as a parameter.
● If a method takes a concrete class as a parameter, then to call that method, we can pass
the following 3 things as arguments:
2. Its child class object //we will talk about the child classes in the upcoming
session
3. null
Example:
[Link]:
package [Link];
public class A{
int i=10;
void funA(){
[Link]("inside funA of A");
}
}
[Link]:
package [Link];
public class Demo
{
//method with class as parameter
void fun1(A a1){ // here to call this method, we can pass 3 possible values
// [Link] class obj, 2 .child class obj, 3. null
[Link]("inside fun1 of Demo");
[Link]("the value of a1 is : "+a1);
[Link]();
}
public static void main(String[] args)
{
Demo d1=new Demo();
//A a5=new A();
//d1.fun1(a5);
d1.fun1(new A());
}
}
● To the above method call, if we supply the null value, then the fun1() method will be
called, but inside the method, when control reaches [Link](), it will throw a runtime
exception called “NullPointerException”.
● So, it is always recommended to check the null value inside the method definition before
accessing any member from the supplied object.
Example:
[Link]:
package [Link];
public class A{
int i=10;
void funA(){
[Link]("inside funA of A");
}
}
[Link]:
package [Link];
public class Demo
{
void fun1(A a1){ //never use such identifiers
if(a1 != null){
[Link]("inside fun1 of Demo");
[Link]("the value of a1 is : "+a1);
[Link]();
}else
[Link]("supplied value is null");
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.fun1(new A());
d1.fun1(null);
}
}
● The void return type indicates that the method does not return any value; it will perform
some task there only.
● When a method has a return type other than void, then the author of that method should
not close the method body without returning an appropriate value.
[Link]:
package [Link];
public class Demo
{
int fun1(){
[Link]("inside fun1 of Demo");
//return 100;
//int x=200;
//return x;
//we can return any value which is compatible with the int type(smaller than int)
byte b=10;
return b;
//long x=20;
//return x; //Error
//return (int)x; //OK
}
● We can define a method with a class as a return type also, if a method is defined to
return a class type, then that method should return one of the following :
3. null
[Link]:
package [Link];
public class A{
int i=10;
void funA(){
[Link]("inside funA of A");
}
}
[Link]:
package [Link];
public class Demo
{
public A fun1(){ //return type as class A type
[Link]("inside fun1 of Demo");
//A a1=new A();
//return a1;
return new A();
}
public static void main(String[] args)
{
Demo d1=new Demo();
d1.fun1(); //here returned A class object will reach the GC.
//to hold the returned value, we have 2 options:
//[Link] the same class variable
//[Link] the parent class variable
A a1= d1.fun1(); //to the same class variable
[Link]();
Object obj = d1.fun1(); //to the parent class variable
}
}
Note: In Java, there is a class called the Object class, which acts as a parent/super class of any
Java class directly or indirectly. This Object class belongs to the “[Link]” package.
To the variable of the Object class, we can assign any class object.
Polymorphism:
● Polymorphism is a fundamental concept in Object-Oriented Programming (OOP), which
means "many forms." In Java, it allows the same method or function to behave
differently based on the context. This ability to define multiple behaviors for the same
method name in the same or different classes is what makes polymorphism powerful
and flexible.
Advantages of Polymorphism:
● Code Reusability: Promotes the use of the same method for different object types,
reducing code duplication.
● Simplicity: Reduces the need for complex conditional statements, making code more
readable.
● Extensibility: New classes can be added without modifying existing code, supporting
easy system expansion.
● Example:
● Multiple methods with the same name but different parameter types or
counts in the same class.
● Key Points:
● Key Points:
○ It is resolved at runtime.
○ The method invoked is determined by the actual object type (not the
reference type) at runtime.
[Link]:
package [Link];
public class Calculator {
Example2:
[Link]
package [Link];
public class Demo
{
void fun1(byte b){
[Link]("inside fun1(byte) of Demo");
//500 lines of code
}
Example:
[Link]:
package [Link];
public class Demo {
○ Number of parameters
○ Type of parameters
○ Order of parameters
● If two or more overloaded methods are equally suitable, the compiler fails.
Note: There are multiple overloaded println() methods defined inside the
[Link] class.
Such as:
println(primitives)
println(Object)
println(String)
println(char[])
Try it:
[Link](null);
[Link]((String)null);
Why public?
Why void?
● Command-line arguments
● Code compiles
● The JVM initially calls the main method by passing an empty String array object.
Example:
java Demo 10 20
Example:
[Link]:
package [Link];
public class Demo {
public static void main(String[] args) {
[Link](args); //String array object address
[Link]([Link]);// number of argument supplied at runtime
//separated by space
if([Link] == 2) {
String snum1 = args[0];
String snum2= args[1];
int num1= [Link](snum1);
int num2= [Link](snum2);
int result = num1+num2;
//int result = [Link](args[0]) + [Link](args[1]);
[Link]("The Sum of 2 number is: "+result);
}else {
[Link]("please pass 2 numbers as CLA");
}
}
}
10 20
2. Arguments must be:
● Space separated
Student Task:
Question1:
Question2:
● Write a method createStudent() inside the Demo class that returns a Student
object. Print the student details in the main()method of the Demo class.
Question3:
● Create a class Employee with fields id and salary.
Question4:
● Write a program that accepts two numbers from command line arguments and prints:
○ Sum
○ Difference
○ Product