UNIE 2- NOTES.docx
UNIE 2- NOTES.docx
Java is an Object-Oriented programming language. In Java, the classes and objects are the basic
and important features of object-oriented programming system, Java supports the following
● Classes
● Objects
● Inheritance
● Polymorphism
● Encapsulation
● Abstraction
● Instance
● Method
● Message Passing
Java Classes
● A class is a blueprint from which individual objects are created (or, we can say a class is
a data type of an object type). In Java, everything is related to classes and objects. Each
class has its methods and attributes that can be accessed and manipulated through the
objects.
● For example, if you want to create a class for students. In that case, "Student" will be a
class, and student records (like student1, student2, etc) will be objects.
● We can also consider that class is a factory (user-defined blueprint) to produce objects.
● Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
● Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
● Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
data members;
constructors;
methods;
...;
Local Variable:
import java.io.*;
class DNT
{
public static void main(String[] args)
{
int var = 89; // Declared a Local Variable
Instance Variable:
import java.io.*;
class DNT
{
public String student; // Declared Instance Variable
public DNT()
{ // Default Constructor
this.student= "Urmi Bose"; // initializing Instance Variable
}
//Main Method
public static void main(String[] args)
{
// Object Creation
DNT name = new DNT();
System.out.println("Student name is: " + name.student);
}
}
Static Variable:
import java.io.*;
class DNT
{
public static String student= "Urmi Bose"; //Declared static variable
In this example, we are creating a class "Dog". Where, the class attributes are breed, age,
and color.
The class methods are setBreed(), setAge(), setColor(), and printDetails().
Declaring Objects:
Java Objects
If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All
these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, and color, and the behavior is - barking,
wagging the tail, and running.
Creating (Declaring) a Java Object
Object is created from a class. In Java, the new keyword is used to create new objects.
// Printing values
obj.printDetails();
}
}
Output
Dog detials:
Golden Retriever
2
Golden
classMain {
publicstaticvoidmain(String[] args)
{
Demo D1 = newDemo(); // point 1
System.out.println(D1); // point 2
System.out.println(D1.display()); // point 3
}
}
Output
Demo@214c265e
x = 10
0
importjava.io.*;
classDemo {
intx = 10;
intdisplay()
return0;
classMain {
publicstaticvoidmain(String[] args)
// create instance
Demo D1 = newDemo();
System.out.println(D1.x);
// point 3
Output
10
x = 10
Introducing Methods:
a set of instructions that can be called for execution using the method name.
// Java Program to Illustrate Methods
// Class 1
// Helper class
classAddition{
// Method
// To add two numbers
publicintaddTwoInt(inta,intb)
{
// Class 2
// Helper class
classGFG{
Output
Sum of two integer values :3
Here is an example of Java code that introduces methods to add two numbers:
Constructors:
Constructor in Java is used to create the instance of the class. Constructors are almost similar to
methods except two things- name is same as class name and has no return type.
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial values
for object attributes.
Example:
// Create a Main class
publicclassMain{
int x;// Create a class attribute
// Create a class constructor for the Main class
publicMain(){
x =5;// Set the initial value for the class attribute x
}
publicstaticvoidmain(String[] args){
Main myObj =newMain();// Create an object of class Main (This will call the constructor)
System.out.println(myObj.x);// Print the value of x
}
}
// Outputs 5
A default constructor in Java is created automatically by the online Java compiler when the
programmer doesn't create any constructor in the entire program. It is created to assign the
default values to the instance variables of the class when an object is created.2
Example:
parameterized constructor:
In Java, a parameterized constructor is a constructor that takes one or more parameters and is
used to initialize objects with specific values.
// Parameterized constructor
public Calculator(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
I
no-argument constructor
// No-argument constructor
public Calculator() {
num1 = 0;
num2 = 0;
}
copy constructor :
A copy constructor in Java is a special type of constructor that creates a copy of an existing
object. It is a constructor that takes an object of the same class as a parameter and initializes the
new object with the same values as the existing object.
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}
The this keyword refers to the current object in a method or constructor. The most common
use of the this keyword is to eliminate the confusion between class attributes and parameters
with the same name (because a class attribute is shadowed by a method or constructor
parameter).
It helps distinguish between the class attributes and parameters with the same name.
For example, if you have a variable 'x', you can refer to it with 'this. x' inside your class methods.
Garbage Collection.
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or
JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program. Eventually, some objects will no longer be needed.
The garbage collector finds these unused objects and deletes them to free up memory.
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing.
The gc() method is used to invoke the garbage collector to perform cleanup processing.
Example:
Example:
Method overloading in Java means having two or more methods (or functions) in a class with the
same name and different arguments (or parameters).
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output
30
60
31.0
Objects as Parameters:
The Parameter Object design pattern is a way to group multiple parameters into a single object.
Similar to primitive types, Java makes it easier to give objects as parameters to methods. It is crucial to recognize
that sending an object as an argument transmits merely a reference to the item-not a duplicate of it. It means that any
changes made to the object inside the method will have an immediate impact on the original object. In this section,
we will discuss passing an object as a parameter in Java.
Argument Passing
There are different ways in which parameter data can be passed into and out of methods and
functions. Let us assume that a function B() is called from another function A(). In this case A is
called the “caller function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are
called formal arguments.
1. Pass By Value: Changes made to formal parameter do not get transmitted back to the
caller. Any modifications to the formal parameter variable inside the called function or
method affect only the separate storage location and will not be reflected in the actual
parameter in the calling environment. This method is also called as call by value.
class CallByValue {
// Caller
public class Main {
public static void main(String[] args)
{
int a = 10;
int b = 20;
System.out.println("Value of a: " + a
+ " & b: " + b);
Value of a: 10 & b: 20
Value of a: 10 & b: 20
2. Call by reference(aliasing):
Changes made to formal parameter do get transmitted back to the caller through
parameter passing. Any changes to the formal parameter are reflected in the actual
parameter in the calling environment as formal parameter receives a reference (or
pointer) to the actual data. This method is also called as call by reference. This method is
efficient in both time and space.
class CallByReference {
int a, b;
// Caller
public class Main {
// Displaying values
// after calling the function
System.out.println("Value of a: " + object.a
+ " & b: " + object.b);
}
}
Output
Value of a: 10 & b: 20
Value of a: 20 & b: 40
Returning Objects:
From the method side, a reference of type Foo with a name a is declared and it’s initially
assigned to null.
Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since
values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean true will
be return.
if(o.a == a && o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
● Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since
values of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so else
block will execute, and false will be returned.
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}
}
// Main class
public class GFG {
// MAin driver method
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
Output
ob1 == ob2: true
ob1 == ob3: false
Recursion:
Recursion is a process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called a recursive function.
Recursion provides a clean and simple way to write code.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
output:
● 3= 3 *2*1 (6)
● 4= 4*3*2*1 (24)
● 5= 5*4*3*2*1 (120)
Access Control:
Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier
used with the element
Private:
// Constructor
public SumCalculator(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
Public:
Protected:
class Blore
{
void display()
{
System.out.println("Hello World!");
}
}
// Public constructor
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
// Private method
private void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
public class A {
protected void display()
{
System.out.println("we are in VTU");
}
}
class B extends A {
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
public class A
{
public void display()
{
System.out.println("we are in VTU");
}
}
class B {
public static void main(String args[])
{
A obj = new A();
obj.display();
}
}
Understanding static:
The static keyword in Java is mainly used for memory management. The static keyword in Java
is used to share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes.
The static keyword belongs to the class rather than an instance of the class. The static keyword is
used for a constant variable or a method that is the same for every instance of a class.
When you declare a variable or a method as static, it belongs to the class, rather than a specific
instance.
Example:
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
Introducing final:
The final method in Java is used as a non-access modifier applicable only to a variable,
a method, or a class. It is used to restrict a user in Java.
The following are different contexts where the final is used:
Variable
Method
Class
Example:
public class ConstantExample {
public static void main(String[] args) {
// Define a constant variable PI
final double PI = 3.14159;
class GFG {
// a final variable
// direct initialize
final int THRESHOLD = 5;
it is possible to define a class within another class, such classes are known as nested classes.
They enable you to logically group classes that are only used in one place, thus this increases the
use of encapsulation and creates more readable and maintainable code.
// Outer class
public class Calculator {
// Inner class
public class Addition {
public int add(int num1, int num2) {
return num1 + num2;
}
}
// Main method
public static void main(String[] args) {
Calculator calculator = new Calculator();
Calculator.Addition addition = calculator.new Addition();
int num1 = 10;
int num2 = 20;
int sum = addition.add(num1, num2);
System.out.println("Sum: " + sum);
}
}