JAVA-Notes-Unit-1_Part 2
JAVA-Notes-Unit-1_Part 2
Object-Oriented Paradigm
The object-oriented paradigm in Java is a programming model that uses objects
to represent and manipulate data. It's a widely used approach in software development.
Object
Class
Encapsulation
Abstraction
Inheritance
Polymorphism
// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(name+ ", " + rollNo + ", " + section);
}
// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.print("Student Details: ");
System.out.println(name+ ", " + rollNo + ", " + section);
}
}
// initialize attributes
Student(String name, int rollNo, String section)
{
this.name= name;
this.rollNo = rollNo;
this.section = section;
}
// print details
public void printDetails()
{
System.out.println("Student Details: ");
System.out.println(this.name+ ", " + this.rollNo + ", " + section);
}
}
}
Abstraction: Showing the Essential Features and hiding their implementation details
The real-world example of an abstraction is a Car, the internal details such as the
engine, process of starting a car, process of shifting gears, etc. are hidden from the
user, and features such as the start button, gears, display, break, etc are given to the
user. When we perform any action on these features, the internal process works.
Subclass: The class that inherits the other class is known as subclass (also known
as derived or extended or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
Polymorphism
1. Method Overloading
2. Method Overriding
// Child Class
class Child extends Parent
{
// Method Overriding
public void m1(int a)
{
System.out.println("Child Method m1 with parameter: " + a);
}
}
// Main Method
class Poly
{
public static void main(String args[])
{
Parent p = new Parent();
p.m1();
p.m1(5);
Child c = new Child();
c.m1(4);
}
}
Applications of OOPs
Java is one of the most prominent programming languages that fully embrace the
OOP paradigm. The application of OOP in Java is extensive, spanning various types of
software, including desktop applications, web applications, enterprise software, mobile
apps, and games. Java's rich set of libraries, frameworks, and tools are built on OOP
principles, making it an ideal choice for developing scalable and maintainable
applications.
Java Constructors
Java constructors are special types of methods that are used to initialize
an object when it is created. It has the same name as its class and is syntactically
similar to a method. However, constructors have no explicit return type.
All classes have constructors, whether you define one or not because Java
automatically provides a default constructor that initializes all member variables to
zero. However, once you define your constructor, the default constructor is no longer
used.
Rules for Creating Java Constructors
You must follow the below-given rules while creating Java constructors:
The name of the constructors must be the same as the class name.
Java constructors do not have a return type. Even do not use void as a return
type.
There can be multiple constructors in the same class, this concept is known as
constructor overloading.
The access modifiers can be used with the constructors, use if you want to
change the visibility/accessibility of constructors.
Java provides a default constructor that is invoked during the time of object
creation. If you create any type of constructor, the default constructor (provided
by Java) is not invoked.
Creating a Java Constructor
To create a constructor in Java, simply write the constructor's name (that is the
same as the class name) followed by the brackets and then write the constructor's body
inside the curly braces ({}).
Syntax
class ClassName
{
ClassName()
{
Statements;
}
}
There are three different types of constructors in Java, we have listed them as follows:
1. Default Constructor
2. No-Args Constructor
3. Parameterized Constructor
1. Default Constructor
If you do not create any constructor in the class, Java provides a default
constructor that initializes the object.
As the name specifies, the No-argument constructor does not accept any
arguments. By using the No-Args constructor you can initialize the class data members
and perform various activities that you want on object creation.
3. Parameterized Constructor
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added to a method,
just declare them inside the parentheses after the constructor's name.
Constructor overloading means multiple constructors are defined with the same
signature with different parameter list in a class. When you have multiple constructors
with different parameters listed, then it will be known as constructor overloading.
// Printing details
System.out.println("------------");
System.out.println("std1 Details");
st1.printDetails();
System.out.println("------------");
System.out.println("std2 Details");
st2.printDetails();
System.out.println("------------");
System.out.println("std3 Details");
st3.printDetails();
}
}
Java Methods
Java Methods are blocks of code that perform a specific task. A method
allows us to reuse code, improving both efficiency and organization. All methods in
Java must belong to a class. Methods are similar to functions and expose the
behavior of objects.
Syntax
AccessModifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the
statements.
For using a method, it should be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).
Output
class Swap
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj.a, obj.b);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}
Although values of x and y are interchanged, those changes are not reflected
on a and b. Memory representation of variables is shown in below figure:
class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class Swap
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}
The changes performed inside the method swap are reflected on a and b as we
have passed the reference obj into ref which also points to the same memory locations
as obj. Memory representation of variables is shown in below figure:
Note: In Java, parameters of primitive types are passed by value which is same as pass-
by-value and parameters of reference types are also passed by value (the reference is
copied) which is same as pass-by-reference. So, in Java all parameters are passed by
value only.
Access Control in Java refers to the mechanism used to restrict or allow access
to certain parts of a Java program, such as classes, methods, and variables. Java’s
access control mechanism promotes code encapsulation, and information hiding, and
reduces the likelihood of errors and security vulnerabilities in the program. It is
implemented by using access control modifiers, which are keywords placed before the
declaration of the class member.
1. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
2. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
outside
Access within outside
within class package by
Modifier package package
subclass only
Public Y Y Y Y
Private Y N N N
Protected Y Y Y N
Default Y Y N N
this Keyword
In Java, ‘this’ is a reference variable that refers to the current class object. It can
be used to call current class methods and fields, to pass an instance of the current class
as a parameter, and to differentiate between the local and instance variables. Using
“this” reference can improve code readability and reduce naming conflicts.
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that receives 'this' keyword as parameter
void display(Test obj)
{
System.out.println("a = " + obj.a+ " b = " + obj.b);
}
static Keyword
The static keyword in Java is used for memory management. The static
keyword belongs to the class rather than an instance of the class.
1. Belongs to the class: When a member is declared as static, it is associated with the
class rather than with instances of the class.
2. Accessed without creating an instance: Since static members are associated with the
class itself, they can be accessed using the class name, without needing to create an
instance of the class. For example, ClassName.staticMethod().
3. Shared among all instances: Since there is only one copy of a static member per
class, it is shared among all instances of the class. This can be useful for maintaining
common data or behavior across all instances.
4. Can access other static members directly: static members can directly access
other static members of the same class, but they cannot directly access non-static
(instance) members. This is because static members exist independently of any
particular instance.
5. Initialization: static variables are initialized only once, at the start of the execution,
before the initialization of any instance variables. They are initialized in the order
they are declared.
6. Used for utility methods and constants: static methods are commonly used for
utility methods that perform a task related to the class, but do not require any
instance-specific data. static variables are often used for constants that are shared
among all instances of the class.
Static variables
When a variable is declared as static, then a single copy of the variable is created
and shared among all objects at the class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables:
We can create static variables at the class level only.
static block and static variables are executed in the order they are present in a
program.
Static methods
When a method is declared with the static keyword, it is known as the static
method. The most common example of a static method is the main( ) method. As
discussed above, any static member can be accessed before any objects of its class are
created, and without reference to any object. Methods declared as static have several
restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
Static blocks
If you need to do the computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
public class StaticEx
{
public static int count = 0;
public int id;
// static block
static
{
System.out.println("Inside static block");
}
public StaticEx()
{
count++;
id = count;
}
Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-
level class with a static modifier but can declare nested classes as static. Such types of
classes are called Nested static classes. Nested static class doesn’t need a reference of
Outer class. In this case, a static class cannot access non-static members of the Outer
class.
// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
StClass.MyNestedClass obj = new StClass.MyNestedClass();
obj.disp();
}
}
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of the
class in which it is nested. But the enclosing class does not have access to the
member of the nested class.
1. static nested class: Nested classes that are declared static are called static
nested classes.
Syntax:
class OuterClass
...
class NestedClass
...
// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
StClass.MyNestedClass obj = new StClass.MyNestedClass();
obj.disp();
}
}
Inner classes
To instantiate an inner class, you must first instantiate the outer class. Syntax:
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;
// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
System.out.println("outer_y = " + outer_y);
// can also access a private member of the outer class
System.out.println("outer_private = "+ outer_private);
}
}
}
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}
Recursion in Java
Recursion in Java is a process in which a method calls itself continuously. A
method that calls itself is called a recursive method. A few Java recursion examples
are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph, etc.
The garbage collector automatically finds and removes objects that are no
longer needed, freeing up memory in the heap. It runs in the background as a daemon
thread, helping to manage memory efficiently without requiring the programmer’s
constant attention.
Strings
A String in Java is a sequence of characters that can be used to store and
manipulate text data and it is basically an array of characters that are stored in a
sequence of memory locations.
All the strings in Java are immutable in nature, i.e. once the string is created we
can’t change it.
1. String s="VJIT";
2. char[] ch={'H','y','d','e','r','a','b','a','d'};
String s=new String(ch);
1. By String literal
2. By new keyword
1) String Literal
String s="welcome";
2) By new keyword
class Strings
{
public static void main(String[] args)
{
// create a string
String s = "Hello! World";
System.out.println("String: " + s);
//substring
String st = "Hello, World!";
System.out.println(st.substring(7, 12));
// create 3 strings
String s1 = "java programming";
String s2 = "java programming";
String s3 = "python programming";
//Replace
String st1 = "Hello";
System.out.println(st1.replace('l', 'p'));
String txt = "Hello World";
//trim
String str = " Java World! ";
System.out.println(str);
System.out.println(str.trim());
}
}
Object class
Object class is the base class for all classes in Java. The Object class resides
within the java.lang package. It serves as a foundation for all classes, directly or
indirectly. If a class doesn't extend any other class, it's a direct child of Object; if it
extends another class, it's indirectly derived. Consequently, all Java classes inherit the
methods of the Object class.
import java.util.*;
ObjEx(int stno)
{
this.stno=stno;
}