Object Oriented Programming Java
Object Oriented Programming Java
ON
Object Oriented Programming using Java
(24ACSE32T)
Course Outcomes:
At the end of the course, the student will be able to
1. Use Java data types, operators, control structures, and arrays to write structured programs.
2. Design and implement classes, methods, constructors, and object-oriented features in Java.
3. Apply inheritance, access control, and exception handling to build robust Java applications.
4. Develop multithreaded programs and use generics for type-safe and reusable code.
5. Implement lambda expressions and work with the Java Collections Framework to manage data
efficiently.
Reference Books:
1. [Link] and F.A. Hosch, An Introduction to programming and OO design using Java, John
Wiley&sons.
2. Y. Daniel Liang, Introduction to Java programming, Pearson Education. 6th Edition
3. R.A. Johnson- Thomson, An introduction to Java programming and object oriented
application development,
4. [Link] and Gary,Cornell, Core Java 2, Vol. 1, Fundamentals, Pearson
Education. 7th Edition,
5. P. Radha Krishna, Object Oriented Programming through Java, University Press.
UNIT-I
Many java versions have been released till now. The current stable release of Java is Java SE 10.
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is release in
March month and an odd version released in September month.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc.
Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere
(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get
rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close"
to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-media,
Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
1. a process-oriented model
2. an object-oriented model
Many programming languages support both the paradigms like python. Python allows the users to code
using both process-oriented and object-oriented methodologies. However, Java is exclusively object-
oriented.
For example, a car state includes its name, colour, brand, and its behaviour includes moving, slowing
down, and changing gears.
Therefore, the goal of an object oriented paradigm is to represent the real world while writing code.
OOP breaks a problem into a number of entities called objects and then builds data and
functions around them.
It treats data as a critical element in the program development and therefore restricts the
flow of data.
OOP protects the data from accidental modification from outside functions.
Objects of the different classes can interact easily through functions.
The object-oriented paradigm follows a bottom-up approach.
5. Abstraction
Ans:
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will
learn more about in the next chapter).
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class:
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
2)Inheritance:
one class is allowed to inherit the features (fields and methods) of another class. We are achieving
inheritance by using extends keyword. Inheritance is also known as “is-a” relationship.
Compile-Time Polymorphism
It is also known as static polymorphism. This type of polymorphism is achieved by function
overloading or operator overloading.
Method Overloading
When there are multiple functions with the same name but different parameters then these functions
are said to be overloaded. Functions can be overloaded by changes in the number of arguments
or/and a change in the type of arguments.
Polymorphism in Java:
Let's see what is the meaning of class, public, static, void, main, String[], [Link]().
Step 4:
Use the following command to compile the Java program. It generates a .class file in the same folder. It
also shows an error if any.
javac [Link]
Step 5:
Use the following command to run the Java program:
java Demo
9. Data Types in Java
Ans:
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and [Link]
12
3.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
boolean type
The boolean data type has two possible values, either true or false.
Boolean data type represents only one bit of information either true or false which is intended to
represent the two truth values of logic and Boolean algebra
Default value: false.
They are usually used for true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Syntax:
boolean booleanVar;
example:
class Main
{
public static void main(String[] args)
{
boolean flag = true;
[Link](flag); // prints true
}
}
2)Byte Data Type:
The byte data type can have values from -128 to 127 (8-bit signed two's complement integer).
If it's certain that the value of a variable will be within -128 to 127, then it is used instead of int to save
memory.
Default value: 0
The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
Syntax:
byte byteVar;
class Main
{
public static void main(String[] args)
{
byte range;
range = 124;
[Link](range); // prints 124
}
}
3. short type:
The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save
memory in large arrays, in situations where the memory savings actually matters.
The short data type in Java can have values from -32768 to 32767 (16-bit signed two's complement
integer).
Default value: 0
The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
Syntax:
short shortVar;
class Main {
public static void main(String[] args) {
short temperature;
temperature = -200;
[Link](temperature); // prints -200
}
}
[Link] Data Type:
It is a 32-bit signed two’s complement integer.
If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a minimum value
of 0 and a maximum value of 232-1. To learn more, visit How to use the unsigned integer in java 8?
Default value: 0
Syntax:
int intVar;
example:
class Main {
public static void main(String[] args) {
int range = -4250000;
[Link](range); // print -4250000
}
}
[Link] type
The range of a long is quite large. The long data type is a 64-bit two’s complement integer and is useful
for those occasions where an int type is not large enough to hold the desired value. The size of the Long
Datatype is 8 bytes (64 bits).
Syntax:
long longVar;
example:
class LongExample {
public static void main(String[] args) {
long range = -42332200000L;
[Link](range); // prints -42332200000
}
}
6. double type:
The double data type is a double-precision 64-bit floating-point.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0d)
class Main {
public static void main(String[] args) {
double number = -42.3;
[Link](number); // prints -42.3
}
}
7. float type:
The float data type is a single-precision 32-bit floating-point. Learn more about single-precision and
double-precision floating-point if you are interested.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0f)
class Main {
public static void main(String[] args) {
float number = -42.3f;
[Link](number); // prints -42.3
}
}
8. char type
It's a 16-bit Unicode character.
The minimum value of the char data type is '\u0000' (0) and the maximum value of the is '\uffff'.
Default value: '\u0000'
class Main {
public static void main(String[] args) {
char letter = '\u0051';
[Link](letter); // prints Q
}
}
(or)
class Main {
public static void main(String[] args) {
char letter1 = '9';
[Link](letter1); // prints 9
char letter2 = 65;
[Link](letter2); // prints A
}
}
Single program:
// Java Program to Demonstrate Char Primitive Data Type
// Class
class GFG {
short s = 56;
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware
that the variable exists.
A local variable cannot be defined with "static" keyword.
import [Link].*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java
array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
arrayRefVar=new datatype[size];
Example of Java Array
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements
one by one. It holds an array element in a variable, then executes the body of the loop.
for(data_type variable:array){
//body of the loop
}
Example:
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i);
}}
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.
[Link](min);
}
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise ^
exclusive OR
bitwise |
inclusive OR
logical OR ||
Ternary ternary ? :
Output:
15
50
0
Arithmetic Operator Example:
public class OperatorExample{
public static void main(String args[]){
[Link](10*10/5+3-1*4/2);
}}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
Example
public class OperatorExample{
public static void main(String args[]){
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240
}}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the number of
bits specified by the right operand.
public OperatorExample{
public static void main(String args[]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
The logical || operator doesn't check the second condition if the first condition is true. It checks the second
condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
The logical || operator doesn't check the second condition if the first condition is true. It checks the second
condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
Output:
true
true
true
10
true
11
Ternary Operator:
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.
Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Output:
2
Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.
Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
[Link](a);
[Link](b);
}}
Output:
14
16
13. Control statement (or) control flow statement
Ans:
Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which
provides a smooth flow of program.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon
the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java,
there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement
if(condition) {
statement 1; //executes when condition is true
}
Example:
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Example:
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
1. }
2. }
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words,
we can say that it is the chain of if-else statements that create a decision tree where the program may
enter in the block of code where the condition is true. We can also define an else statement at the end
of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
[Link]("city is meerut");
}else if (city == "Noida") {
[Link]("city is noida");
}else if(city == "Agra") {
[Link]("city is agra");
}else {
[Link](city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
[Link]
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of
the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported since version
7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
[Link]
Output:
2
While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order.
The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax
and condition checking time.
1. for loop
2. while loop
3. do-while loop
Output:
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
Output:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop,
the initialization and increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed.
while(condition){
//looping statements
}
Example
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
while(i<=10) {
[Link](i);
i = i + 2;
}
}
}
Output:
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop statements. When
the number of iteration is not known and we have to execute the loop at least once, we can use do-while
loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of
the do-while loop is given below.
do
{
//statements
} while (condition);
Example
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}
}
Output:
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.
0
1
2
3
4
5
6
continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part
of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
if(j == 4)
{
continue;
}
[Link](j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
1. By reference variable
2. By method
3. By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]([Link]+" "+[Link]);//printing members with a white space
}
}
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
[Link]=101;
[Link]="Sonoo";
[Link]=102;
[Link]="Amit";
//Printing data
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
}
}
Output:
101 Sonoo
102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by
invoking the displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation()
{[Link](rollno+" "+name);
}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
2) Object and Class Example: Initialization through a constructor
An constructor is similar to method
Syntx of constructor : class name with parenthesis
Object and Class Example: Employee
Let's see an example where we are maintaining records of employees.
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){[Link](id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee(); // Employee() is constructor
Employee e2=new Employee();
Employee e3=new Employee();
[Link](101,"ajeet",45000);
[Link](102,"irfan",25000);
[Link](103,"nakul",55000);
[Link]();
[Link]();
[Link]();
}
}
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
In real time development, we create classes and use it from another class. It is a better approach than
previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a
single Java source file, it is a good idea to save the file name with the class name which has main() method.
16. method
ans:
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation.
It is used to achieve the reusability of code. We write a method once and use it many times. We
do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code.
The method is executed only when we call or invoke it.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we
have shown in the following figure.
Syntax:
type name(parameter-list)
{ // body of method }
Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use
void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Types of Method
There are two types of methods in Java
Predefined Method
User-defined Method
Predefined Method:
n Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly
use these methods just by calling them in the program at any point. Some pre-defined methods are
length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program,
a series of codes related to the corresponding method runs in the background that is already stored in
the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in the
[Link] class. It prints the statement that we write inside the method. For example,
print("Java"), it prints Java on the console.
Understanding these techniques is essential for effectively utilizing method parameters in Java.
Types of Parameters:
1. Formal Parameter:
A variable and its corresponding data type are referred to as formal parameters when they exist in the
definition or prototype of a function or method. As soon as the function or method is called and it serves
as a placeholder for an argument that will be supplied. The function or method performs calculations or
actions using the formal parameter.
Syntax:
{
// Function body
// Use the parameterName within the function
}
2. Actual Parameter:
The value or expression that corresponds to a formal parameter and is supplied to a function or method
during a function or method call is referred to as an actual parameter is also known as an argument. It
offers the real information or value that the method or function will work with.
Syntax:
functionName(argument)
In the above syntax:
1. Call-by-Value:
In Call-by-value the copy of the value of the actual parameter is passed to the formal parameter of the
method. Any of the modifications made to the formal parameter within the method do not affect the
actual parameter.
Call-by-Reference:
call by reference" is a method of passing arguments to functions or methods where the memory address
(or reference) of the variable is passed rather than the value itself. This means that changes made to the
formal parameter within the function affect the actual parameter in the calling environment.
In "call by reference," when a reference to a variable is passed, any modifications made to the parameter
inside the function are transmitted back to the caller. This is because the formal parameter receives a
reference (or pointer) to the actual data.
Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Parameterized Constructors
The main purpose of using this keyword is to solve the confusion when we have same
variable name for instance and local variables.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example
class A
{
void m()
{
[Link]("hello m");
}
void n()
{
[Link]("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
Output:
hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
class A
{
A()
{
[Link]("hello a");
}
A(int x)
{
this();
[Link](x);
}
}
class TestThis5
{
public sta c void main(String args[])
{
A a=new A(10);
}
}
Output:
hello a
10
In Java, if there is a local variable in a method with the same name as the instance variable, then the
local variable hides the instance variable. If we want to reflect the change made over to the instance
variable, this can be achieved with the help of this reference.
// Java Program to Illustrate Instance Variable Hiding
// Class 1
// Helper class
class Test
{
// Instance variable or member variable
private int value = 10;
// Method
void method()
{
// This local variable hides instance variable
int value = 40;
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
1. By anonymous object: Anonymous objects are those objects in Java which are created
without any reference variable. As a result, after creation, we have no way to access the
anonymous object.
new Student();
In the above code, even though an object of Student class is created, it has no reference
variable and cannot be used after creation, but it acquires memory.
2. By nulling reference: When an object is referenced to null value, it is considered an
unreferenced object as it holds only null value.
Student s = new Student();
s = null;
Here, s is an unreferenced object that holds null value. It is considered garbage by JVM.
3. By assigning a reference to another object: When one object is assigned to another, first
object is of no use and can be considered as garbage.
Student s1 = new Student();
Student s2 = new Student();
s1 = s2;
After the last statement s1 = s2 is executed, the first object becomes unreferenced and can
be considered for garbage collection.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
Example 1
public class Java nalizeExample1
{
public static void main(String[] args)
{
Java nalizeExample1 obj = new Java nalizeExample1();
[Link]([Link]());
obj = null;
// calling garbage collector
[Link]();
[Link]("end of garbage collection");
}
@Override
protected void nalize()
{
[Link]("finalize method called");
}
}
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading
Method overloading increases the readability of the program.
In this example, we are crea ng sta c methods so that we don't need to create instance for calling methods.
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}
}
Output:
22
24.9
Student()
{
[Link]("this a default constructor");
}
Student(int i, String n)
{
id = i;
name = n;
}
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
class Add {
int a;
int b;
29. Recursion
Ans:
Java supports recursion. Recursion is the process of defining something in terms of itself.
As
it relates to Java programming, recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. For
example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use of a
recursive method:
// A simple example of recursion.
class Factorial
{
// this is a recursive method
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
If you are unfamiliar with recursive methods, then the operation of fact( ) may seem a
bit confusing. Here is how it works. When fact( ) is called with an argument of 1, the
function
returns 1; otherwise, it returns the product of fact(n–1)*n. To evaluate this expression, fact(
)
is called with n–1. This process repeats until n equals 1 and the calls to the method begin
returning
To better understand how the fact( ) method works, let’s go through a short example.
When you compute the factorial of 3, the first call to fact( ) will cause a second call to be
made with an argument of 2.
This invocation will cause fact( ) to be called a third time with an argument of 1.
This call will return 1, which is then multiplied by 2 (the value of n in the second
invocation).
This result (which is 2) is then returned to the original invocation of fact( ) and multiplied
by 3 (the original value of n). This yields the answer, 6.
You might find it interesting to insert println( ) statements into fact( )
30. A Closer Look at Argument Passing
Ans:
In general, there are two ways that a computer language can pass an argument to a subroutine.
The first way is call-by-value. This approach copies the value of an argument into the formal
parameter of the subroutine. Therefore, changes made to the parameter of the subroutine
have no effect on the argument. The second way an argument can be passed is call-by-reference.
In this approach, a reference to an argument (not the value of the argument) is passed to the
parameter. Inside the subroutine, this reference is used to access the actual argument specified
in the call. This means that changes made to the parameter will affect the argument used to
call the subroutine. As you will see, Java uses both approaches, depending upon what is passed.
In Java, when you pass a primitive type to a method, it is passed by value. Thus, what
occurs to the parameter that receives the argument has no effect outside the method. For
example, consider the following program:
// Primitive types are passed by value.
class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
[Link]("a and b before call: " +
a + " " + b);
[Link](a, b);
[Link]("a and b after call: " +
a + " " + b);
}
}
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20
As you can see, the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10.
UNIT-2
1. Access Modifiers in Java
(Or )access control
Ans:
There are two types of modifiers in Java: access modifiers and non-access modifiers.
access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods,
constructors, data members, and the setter methods.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. 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.
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. 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.
There are many non-access modi ers, such as sta c, abstract, synchronized, na ve, vola le, transient, etc.
Here, we are going to learn the access modi ers only.
1) Private:
The private access modifier is accessible only within the class.
we have created two classes A and Simple. A class contains private data member and private method.
We are accessing these private members from outside the class, so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
[Link]("Hello java");
}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public sta c void main(String args[])
{
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
3) Protected:
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
class Animal
{
// protected method
protected void display()
{
[Link]("I am an animal");
}
}
// public method
public void display()
{
[Link]("I am an animal.");
[Link]("I have " + legCount + " legs.");
}
}
// [Link]
public class Main
{
public static void main( String[] args )
{
// accessing the public class
Animal animal = new Animal();
In those situations, we can use the static keyword in Java. If we want to access class members
without creating an instance of the class, we need to declare the class members static.
The Math class in Java has almost all of its members static. So, we can access its members without
creating instances of the Math class. For example,
1. Variable
2. Method
3. Block
4. Nested class
1) Java static variable:
If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
In Java, the final method cannot be overridden by the child class. For example,
class FinalDemo
{
// create a final method
public final void display()
{
[Link]("This is a final method.");
}
}
4. arrays revisited
ans:
Specifically, the size of an array—that is, the number of elements that an array can hold—is found in its length
instance variable. All arrays have this variable, and it will always hold the size of the array. Here is a
program that demonstrates this property:
// This program demonstrates the length array member.
class Length {
class Stack {
stck[++tos] = item;
else
return stck[tos--];
}
}
class TestStack2 {
push some numbers onto the stack for(int i=0; i<5; i++)
[Link](i); for(int i=0; i<8; i++) [Link](i);
[Link]([Link]());
[Link]("Stack in mystack2:");
for(int i=0; i<8; i++)
[Link]([Link]());
}
}
Notice that the program creates two stacks: one five elements deep and the
other eight elements deep. As you can see, the fact that arrays maintain their
own length information makes it easy to create stacks of any size.
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
There are two ways to create String object:
1. By string literal
2. By new keyword
1) By string literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
2) By new keyword
String s=new String("Welcome");
In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in a heap (non-pool).
java
strings
example
6. Inheritance basics
Ans:
The process of creating new class from existing class is know as inheritance .
Inheritance in Java is a concept that acquires the properties from one class to other classes; for
example, the relationship between father and son. Inheritance in Java is a process of acquiring all
the behaviors of a parent object.
The new class that is created is known as subclass (child or derived class) and the existing class from
where the child class is derived is known as superclass (parent or base class).
The extends keyword is used to perform inheritance in Java.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example.
// A simple example of inheritance.
// Create a superclass.
class A
{
int i, j;
void showij()
{
[Link]("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
[Link]("k: " + k);
}
void sum()
{
[Link]("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
[Link]("Contents of superOb: ");
[Link]();
[Link]();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
[Link]("Contents of subOb: ");
[Link]();
[Link]();
[Link]();
[Link]("Sum of i, j and k in subOb:");
[Link]();
}
}
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
7. Member Access and Inheritance
Ans:
Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private. For example, consider the
following simple class hierarchy:
/* In a class hierarchy, private members remain
private to their class.
This program contains an error and will not
compile.
*/
// Create a superclass.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}
This program will not compile because the reference to j inside the sum( ) method of B causes an
access violation. Since j is declared as private, it is only accessible by other members of its own
class. Subclasses have no access to it.
8. A More Practical Example
Ans:
class Vehicle
{
protected String brand = "Ford"; // Vehicle attribute
public void honk()
{
// Vehicle method
[Link]("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
[Link]();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
[Link]([Link] + " " + [Link]);
}
}
// instance variable
String name = "helloworld is the name";
void print()
{
[Link]("This is the helloworld class");
}
}
// derived class
class GFG1 extends helloworld
{
Suppose, there are two classes named Father and Child and we want to inherit the properties of the
Father class in the Child class. We can achieve this by using the extends keyword.
Syntax:
//inherits the properties of the Father class
class Child extends Father
{
//functionality
}
Types of Inheritance
Java supports the following four types of inheritance:
Single Inheritance
Multi-level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.
In the above figure, Employee is a parent class and Executive is a child class. The Executive class
inherits all the properties of the Employee class.
//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
[Link]("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
[Link]("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
[Link]("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
[Link](0987);
[Link]();
[Link](78);
[Link]();
[Link](68.7);
[Link]();
}
}
Output:
registration number= 0987
marks= 78.0
score= 68.7
Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical inheritance.
In the above figure, the classes Science, Commerce, and Arts inherit a single parent class named
Student.
Let's implement the hierarchical inheritance mechanism in a Java program.
//parent class
class Student
{
public void methodStudent()
{
[Link]("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
[Link]("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
[Link]("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
[Link]("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
[Link]();
[Link]();
[Link]();
}
}
Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.
Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more types
of inheritance.
In the above figure, GrandFather is a super class. The Father class inherits the properties of the
GrandFather class. Since Father and GrandFather represents single inheritance. Further, the Father
class is inherited by the Son and Daughter class. Thus, the Father becomes the parent class for Son
and Daughter. These classes represent the hierarchical inheritance. Combinedly, it denotes the
hybrid inheritance.
Let's implement the hybrid inheritance mechanism in a Java program.
//parent class
class GrandFather
{
public void show()
{
[Link]("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
[Link]("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
[Link]("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
[Link]("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
[Link]();
}
}
Output:
I am daughter.
Multiple Inheritance (not supported)
Java does not support multiple inheritances due to ambiguity. For example, consider the
following Java program.
class Wishes
{
void message()
{
[Link]("Best of Luck!!");
}
}
class Birthday
{
void message()
{
[Link]("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
[Link]();
}
}
Output:
The above code gives error because the compiler cannot decide which message() method is to be
invoked.
Due to this reason, Java does not support multiple inheritances at the class level but can be achieved
through an interface.