Unit 2 Notes
Unit 2 Notes
An object is any entity that has a state and behavior. For example, a bicycle is an
object. It has
Before we learn about objects, let's first know about classes in Java.
Java Class: A class is a blueprint for the object. Before we create an object, we
first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the
details about the floors, doors, windows, etc. Based on these descriptions we build
the house. House is the object.
Since many houses can be made from the same description, we can create many
objects from a class.
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
Here, fields (variables) and methods represent the state and behavior of the object
respectively.
class Bicycle {
// state or field
// behavior or method
System.out.println("Working of Braking");
In the above example, we have created a class named Bicycle. It contains a field
named gear and a method named braking().
Here, Bicycle is a prototype. Now, we can create any number of bicycles using the
prototype. And, all the bicycles will share the fields and methods of the prototype.
Objects model an entity that exists in the real world. Modeling entities require you
to identify the state and set of actions that can be performed in that object. This
way of thinking is key to object-oriented programming. It is important to
disambiguate an Object with an instantiated object in Java.
class Student {
int id;
String name;
// creating an object of
// Student
System.out.println(s1.id);
System.out.println(s1.name);
}
Difference between Java Class and Objects: The differences between class and
object in Java are as follows:
Class Object
Branching statements allow the flow of execution to jump to a different part of the
program. The common branching statements used within other control structures
include: break, continue, and return.
2. Continue Statement
3. Return Statement
class BreakStatementDemo
if (i == 5)
break;
System.out.println("Loop complete.");
The continue statement is used to skip a part of the loop and continue with the next
iteration of the loop. It can be used in combination with for and while statements.
class ContinueStatementDemo
if (i%2 == 0)
continue;
Return Statement in Java: This is the most commonly used branching statement
of all. The return statement exits the control flow from the current method and
returns to where the method was invoked. The return statement can return a value
or may not return a value. To return a value, just put the value after the return
keyword. But remember data type of the returned value must match the type of the
method’s declared return value. And so when a method is declared void, use return
without a return value.
class ReturnStatementDemo
boolean t = true;
if (t)
return;
// after return
Iteration in Java: Java provides a set of looping statements that executes a block
of code repeatedly while some condition evaluates to true. Looping control
statements in Java are used to traverse a collection of elements, like arrays.
while Loop: The while loop statement is the simplest kind of loop statement. It is
used to iterate over a single statement or a block of statements until the specified
boolean condition is false. The while loop statement is also called the entry-control
looping statement because the condition is checked prior to the execution of the
statement and as soon as the boolean condition becomes false, the loop
automatically stops. You can use a while loop statement if the number of iterations
is not fixed. Normally the while loop statement contains an update section where
the variables, which are involved in while loop condition, are updated.
System.out.println(num);
// Update Section
num--;
do-while Loop: The Java do-while loop statement works the same as the while
loop statement with the only difference being that its boolean condition is
evaluated post first execution of the body of the loop. Thus it is also called exit
controlled looping statement. You can use a do-while loop if the number of
iterations is not fixed and the body of the loop has to be executed at least once.
do {
System.out.println(num);
num--;
for Loop: Unlike the while loop control statements in Java, a for loop statement
consists of the initialization of a variable, a condition, and an increment/decrement
value, all in one line. It executes the body of the loop until the condition is false.
The for loop statement is shorter and provides an easy way to debug structure in
Java. You can use the for loop statement if the number of iterations is known.
In a for loop statement, execution begins with the initialization of the looping
variable, then it executes the condition, and then it increments or decrements the
looping variable. If the condition results in true then the loop body is executed
otherwise the for loop statement is terminated.
}}
In for-each loop statement, you cannot skip any element of the given array or
collection. Also, you cannot traverse the elements in reverse order using the for-
each loop control statement in Java.
}
Decision-Making Statements: Decision-making statements in Java are similar to
making a decision in real life, where we have a situation and based on certain
conditions we decide what to do next.
1. if Statement: These are the simplest and yet most widely used control
statements in Java. The if statement is used to decide whether a particular block of
code will be executed or not based on a certain condition. If the condition is true,
then the code is executed otherwise not.
if(role == "admin") {
if(role == "admin") {
else {
// person is an adult
if (gender == "male") {
// person is a male
System.out.println(
);
} else {
// person is a female
} else {
4. switch Statement: Switch statements are almost similar to the if-else-if ladder
control statements in Java. It is a multi-branch statement. It is a bit easier than the
if-else-if ladder and also more user-friendly and readable. The switch statements
have an expression and based on the output of the expression, one or more blocks
of codes are executed. These blocks are called cases. We may also provide a
default block of code that can be executed when none of the cases are matched
similar to the else block.
switch (browser)
case "safari":
break;
case "edge":
break;
case "chrome":
break;
default:
class Main {
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
A constructor must not have any return type. Not even void.
Unlike, Constructors in C++, Java doesn’t allow the constructor definition outside
the class.
Constructors usually make use to initialize all the data members (variables) of the
class.
In addition, more than one constructor can also declare inside a class with different
parameters. It’s called “Constructor Overloading.”
Name of a constructor is same name as that of the Name of the method can be different from the class
class. name.
Constructors are invoked implicitly by system. Methods are invoked explicitly by programmer.
b. Non-Primitive Data Types- These data types are special types of data which
are user defined, i,e, the program contains their definition. Some examples are-
classes, interfaces etc.
Java primitive data types are the ones which are predefined by the programming
language which in this case is Java. Without primitive data types it would be
impossible to frame programs. Primitive data types are also the building blocks of
Non-primitive data types.
a. Integer Datatype in Java: int is used for storing integer values. Its size is 4
bytes and has a default value of 0. The maximum values of integer is 2^31 and the
minimum value is -2^31. It can be used to store integer values unless there is a
need for storing numbers larger or smaller than the limits
Example- int a=56;
b. Float Datatype in Java: float is used for storing decimal values. Its default
value is 0.0f and has a size of 4 bytes. It has an infinite value range. However its
always advised to use float in place of double if there is a memory constraint.
Currency should also never be stored in float datatype. However it has a single
precision bit.
c. Character Datatype in Java: char as the name suggests is useful for storing
single value characters. Its default value is ‘\u0000’ with the max value being
‘\uffff’ and has a size of 2 bytes.
It must be confusing for you to see this new kind of data ‘/u000’. This is the
unicode format which java uses inplace of ASCII.
d. Boolean Datatype in Java: boolean is a special datatype which can have only
two values ‘true’ and ‘false’. It has a default value of ‘false’ and a size of 1 byte. It
comes in use for storing flag values.
e. Byte Datatype in Java: It’s an 8 bit signed two’s complement . The range of
values are -128 to 127. It is space efficient because it is smaller than integer
datatype. It can be a replacement for int datatype usage but it doesn’t have the size
range as the integer datatype.
f. Short Datatype in Java: This datatype is also similar to the integer datatype.
However it’s 2 times smaller than the integer datatype. Its minimum range is -
32,768 and maximum range is 32,767. It has a size of
h. Double Datatype in Java: This is similar to the float datatype. However it has
one advantage over float datatype i.e, it has two bit precision over the float
datatype which has one bit precision. However it still shouldnt be used for
precision sensitive data such as currency. It has a range of -2^31 to (2^31)-1.
Class variable{
int a = 10;
short s = 2;
byte b = 6;
long l = 125362133223l;
float f = 65.20298f;
double d = 876.765d;
2. Non-primitive Data Types in Java :These are the datatypes which have instances
like objects. Hence they are called reference variables. They are primarily classes,
arrays, strings or interfaces.
a. Classes in Java: These are the special user defined data type. It has member
variables and class methods. They are blueprinted by objects.
class DataFlair {
int a,
b,
c;
void teach() {
void learn() {
Example:
String s=”DataFlair is a fun place to learn”;
String sub=s.substring(0,9);
System.out.println(sub);
c. Arrays in Java : Arrays are special memory locations that can store a collection
of homogeneous data. They are indexed. Arrays always start indexing from 0.
Dynamic allocation of arrays is there in Java. Arrays in Java can be passed as
method parameters, local variables and static fields.
Java Identifiers:Identifiers are used to name classes, methods and variables. It can
be a sequence of uppercase and lowercase characters. It can also contain '_'
(underscore) and '$' (dollar) sign. It should not start with a digit(0-9) and not
contain any special characters.
int var=100;
int g;
char c,d; // declaring more than one variable in a statement
Explanation:
In the first line,we are declaring a variable of type int and name var and
initialising it with a value.
The second line is just the declaration of an integer.
The third line is declaring two characters in one statement.
Rules for Naming a Variable-
A variable may contain characters, digits and underscores.
The underscore can be used in between the characters.
Variable names should be meaningful which depicts the program logic.
Variable name should not start with a digit or a special character.
A variable name should not be a keyword.
Java Keywords: Keywords are also known as reserved words in Java. They carry
some predefined meaning and are used throughout the program. They cannot be
used as a variable name. Example: abstract,package,class
EXAMPLE:
public void add(int a, int b){
int c = a + b;
System.out.println(c);
}
Program File Name: So, you must be wondering about the process of naming
your file in Java. In Java, we have to save the program file name with the same
name as that of the name of public class in that file.
The above is a good practice as it tells JVM that which class to load and where to
look for the entry point (main method).
The extension should be java. Java programs are run using the following two
commands:
javac fileName.java // To compile the Java program into byte-code
java fileName // To run the program
Arrays in Java can hold primitive data types (Integer, Character, Float, etc.) and
non-primitive data types(Object). The values of primitive data types are stored in a
memory location, whereas in the case of objects, it's stored in heap memory.
Assume you have to write a code that takes the marks of five students. Instead of
creating five different variables, you can just create an array of lengths of five. As
a result, it is so easy to store and access data from only one place, and also, it
is memory efficient. An array is a data structure or container that stores the same
typed elements in a sequential format.
Here, type specifies the type of data being allocated, size determines the number of
elements in the array, and var-name is the name of the array variable that is linked
to the array. To use new to allocate an array, you must specify the type and number
of elements to allocate.
Example:
OR
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java.
Accessing Java Array Elements using for Loop: Each element in the array is
accessed via its index. The index begins with 0 and ends at (total array size)-1. All
the elements of array can be accessed using Java for Loop.
Implementation: Java
class G {
int[] arr;
arr[0] = 10;
arr[1] = 20;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Syntax :
or
datatype arrayrefvariable[][];
Syntax: Java
import java.io.*;
class GFG {
// Syntax
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
System.out.println();
}
}
Inheritance:
Subclass: It is also known as the child class or the derived class that inherits
the properties of the parent class.
Parent class: It is also known as the superclass or the base class from which
other subclasses inherit the properties.
Code:
class A {
String name;
class B extends A {
class Main {
obj.name = "Inheritance";
obj.display();
obj.getName("learning");
A subclass can have only one superclass but a superclass can have any
number of subclasses.
A subclass can inherit all the members (methods and fields) of the parent
class except the private members.
The constructors are not considered members of a class and are not inherited
by subclasses.
While constructors are not inherited by subclasses, subclasses can call their
parent class's constructors using the super keyword, and a default
constructor is automatically created by the Java compiler only if no explicit
constructors are defined in the class.
Method Overriding In Java Inheritance: Have you ever wondered what will
happen if a specific method is present both in the subclass and the superclass? In
such cases, methods of the subclass override the methods of the parent class and
hence, this is known as method overriding in Java. For method overriding, methods
must have the same name & the same number of parameters in the parent and the
child class. This concept is important to achieve run-time polymorphism.
// Parent class
class One {
}
// Subclass derived from class One
@Override
class Main {
obj.name("Inheritance");
Types Of Inheritance In Java: There are five types of Java Inheritances and now,
we will study them with their implementation code in Java :
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
// Parent class
class One {
System.out.print("Single ");
// Subclass
System.out.println("Inheritance");
class Main {
obj.print_single();
obj.print_inheritance();
// Parent class
class One {
System.out.print("Multi");
System.out.println("level");
System.out.println("Inheritance");
}
}
class Main {
obj.print_multi();
obj.print_level();
obj.print_inheritance();
For example:
// Parent Class
class A {
System.out.println("Class A");
class B extends A {
public void print_B() {
System.out.println("Class B");
class C extends A {
System.out.println("Class C");
class Main {
obj.print_A();
obj.print_B();
obj2.print_A();
obj2.print_C();
}
4. Multiple Inheritance (Not Supported by Java): In Multiple Inheritance, one
subclass is derived from more than one superclass. Java doesn't support multiple
inheritances because of high complexity and logic issues but as an alternative, we
can implement multiple inheritances in Java using interfaces.
For example:
interface One {
interface Two {
System.out.print("Hierarchical ");
System.out.print("Inheritance ");
System.out.print("Implementation");
class Main {
obj.print_Hierarchical();
obj.print_Inheritance();
obj.print_Implementation();
For example:
class C { C
class A extends C {
System.out.println("A");
class B extends C {
System.out.println("B");
class D extends A {
class Main {
obj.display();
class Perimeter {
int length;
int breadth;
this.length = length;
this.breadth = breadth;
}
public void getPerimeter() {
class Main {
rectangle.getPerimeter();
Data Hiding
Access modifiers are used to achieve data hiding. Access modifiers are the
keywords that specify the accessibility or the scope of methods, classes, fields, and
other members.
Difference between encapsulation and data hiding is that Encapsulation is a way of
bundling data whereas Data Hiding prevents external unauthorized access to the
sensitive data.
The four types of access modifiers in Java are:
Public: A public modifier is accessible to everyone. It can be accessed from
within the class, outside the class, within the package, and outside the
package.
class A {
// public variables
public int a;
public int b;
// public methods
// Method logic
}}
Private: A private modifier can not be accessed outside the class. It provides
restricted access. Example:
class A {
// private variables
private String a;
private int b;
class A {
// protected variables
protected String a;
protected int b;
A Private Access Modifier is used for the purpose of Data Hiding. Example of
Data Hiding:
class Employee {
// private variables
newObj.name = "James";
System.out.println(newObj.name);
}
Getter and Setter Methods: As we can't directly read and set the values of private
variables/fields, Java provides us with getter and setter methods to do so.
How to implement Encapsulation in Java?
We need to perform two steps to achieve the purpose of Encapsulation in Java.
Use the private access modifier to declare all variables/fields of class as
private.
Define public getter and setter methods to read and modify/set the values of
the abovesaid fields.
class Book {
//private fields
return author;
this.author = a;
return title;
this.title = t;
return id;
this.id = i;
newObj.setAuthor("Jane Austen");
newObj.setId(775);
Here, an overridden child class method is called through its parent's reference.
Then the method is evoked according to the type of object. In runtime, JVM
figures out the object type and the method belonging to that object.
Runtime polymorphism in Java occurs when we have two or more classes, and all
are interrelated through inheritance. To achieve runtime polymorphism, we must
build an "IS-A" relationship between classes and override a method.
Method overriding
If a child class has a method as its parent class, it is called method overriding. If
the derived class has a specific implementation of the method that has been
declared in its parent class is known as method overriding.
class Parent {
void print() {
System.out.println("Hi I am parent");
}
void print() {
System.out.println("Hi I am children");
Method overloading: Consider a class where multiple methods have the same
name. It will be difficult for the compiler to distinguish between every method.
In other words, a class can have multiple methods of the same name, and each
method can be differentiated either by bypassing different types of parameters or
bypassing a different number of parameters.
class Overload {
Parent obj1;
obj1.print();
obj1.print();
obj2.statement("Soham.");
obj2.statement("Soham", "Medewar.");
}
Abstraction: Abstraction in Java is a process of hiding the implementation details
from the user and showing only the functionality to the user. It can be achieved by
using abstract classes, methods, and interfaces. An abstract class is a class that
cannot be instantiated on its own and is meant to be inherited by concrete classes.
An abstract method is a method declared without an implementation. Interfaces, on
the other hand, are collections of abstract methods.
Abstraction is a key concept in OOP and in general as well. Think about real world
objects, they are made by combining raw materials like electrons, protons, and
atoms, which we don't see due to the abstraction that nature exposes to make the
objects more understandable. Similarly, in computer science, abstraction is used to
hide the complexities of hardware and machine code from the programmer.
This is achieved by using higher-level programming languages like Java, which are
easier to use than low-level languages like assembly.
Abstraction in Java can be achieved using the following tools it provides :
Abstract classes
Interface
Interface:
An interface is a fully abstract class. It includes a group of abstract methods
(methods without a body).
We use the interface keyword to create an interface in Java. For example,
interface Language {
public void getType();
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
Output
The area of the rectangle is 30
In the above example, we have created an interface named Polygon. The interface
contains an abstract method getArea().
Here, the Rectangle class implements Polygon. And, provides the implementation
of the getArea() method.
Similar to classes, interfaces can extend other interfaces. The extends keyword is
used for extending interfaces. For example,
interface Line {
// members of Line interface
}
// extending interface
interface Polygon extends Line {
// members of Polygon interface
// members of Line interface
}
Here, the Polygon interface extends the Line interface. Now, if any class
implements Polygon, it should provide implementations for all the abstract
methods of both Line and Polygon.
Abstract class:
Generally, an abstract class in Java is a template that stores the data members and
methods that we use in a program. Abstraction in Java keeps the user from viewing
complex code implementations and provides the user with necessary information.
We cannot instantiate the abstract class in Java directly. Instead, we can subclass
the abstract class. When we use an abstract class as a subclass, the abstract class
method implementation becomes available to all of its parent classes.
The important rules that we need to follow while using an abstract class in Java are
as follows:
The keyword "abstract" is mandatory while declaring an abstract class in
Java.
Abstract classes cannot be instantiated directly.
An abstract class must have at least one abstract method.
An abstract class includes final methods.
An abstract class may also include non-abstract methods.
An abstract class can consist of constructors and static methods.
Program:
// Abstract class
abstract class Sunstar {
abstract void printInfo();
}
System.out.println(name);
System.out.println(age);
System.out.println(salary);
// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
s.printInfo();
}
}
Now that the differences between an interface and abstract class are clear, let us
move forward. The next part will explore the crucial advantages and disadvantages
that we must consider while using an abstract class in Java
Packages:
A Java package is a collection of similar types of sub-packages, interfaces, and
classes. In Java, there are two types of packages: built-in packages and user-
defined packages. The package keyword is used in Java to create Java packages.
Let’s find out why we even need packages in the first place. Say you have a laptop
and a bunch of data you want to store. Data includes your favorite movies, songs,
and images.
So, do you store them all in a single folder or make a separate category for each
one and store them in their corresponding folder?
It is obvious that anyone would like to create separate folders for images, videos,
songs, movies, etc. And the reason is the ease of accessibility and manageability.
User-defined packages
User-defined packages are those that developers create to incorporate different
needs of applications. In simple terms, User-defined packages are those that the
users define. Inside a package, you can have Java files like classes, interfaces, and
a package as well (called a sub-package).
Sub-package:A package defined inside a package is called a sub-package. It’s used
to make the structure of the package more generic. It lets users arrange their Java
files into their corresponding packages. For example, say, you have a package
named cars. You’ve defined supporting Java files inside it.
Extends: In Java, the extends keyword is used to indicate that the class which is
being defined is derived from the base class using inheritance. So basically,
extends keyword is used to extend the functionality of the parent class to the
subclass. In Java, multiple inheritances are not allowed due to ambiguity.
Therefore, a class can extend only one class to avoid ambiguity.