0% found this document useful (0 votes)
14 views

OOP-Java_Unit-1-1

This document provides an overview of Object-Oriented Programming (OOP) through Java, detailing its history, features, and applications. It covers Java's development, key concepts of OOP, and the structure of Java programs, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). Additionally, it discusses the advantages and disadvantages of Java, along with its various platforms and editions.

Uploaded by

amreen2825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

OOP-Java_Unit-1-1

This document provides an overview of Object-Oriented Programming (OOP) through Java, detailing its history, features, and applications. It covers Java's development, key concepts of OOP, and the structure of Java programs, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). Additionally, it discusses the advantages and disadvantages of Java, along with its various platforms and editions.

Uploaded by

amreen2825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

OBJECT ORIENTED

PROGRAMMING
THROUGH JAVA

Prepared by GSK
R22 II CSE I SEM
Unit-1
Object oriented thinking and
1
Java Basics
 TEXT BOOKS:
1. Java the complete reference, 7th edition, Herbert
schildt, TMH.

Prepared by GSK
2. Understanding OOP with Java, updated edition,
T. Budd, Pearson education.

• REFERENCE BOOKS:
1. An Introduction to programming and OO design
using Java, J.Nino and F.A. Hosch, John wiley
& sons.
2. 2. An Introduction to OOP, third edition, T.
Budd, Pearson education. 2
Prepared by GSK
CHAPTER-1
OBJECT-ORIENTED THINKING &
JAVA BASICS
3
WHAT IS JAVA

 Java is a programming language and Java is a


high level, object-oriented and secure
programming language.

Prepared by GSK
4
WHO DEVELOPED JAVA?
 James Gosling , Mike Sheridan, and Patrick
Naughton initiated the Java language project in
June 1991.

Prepared by GSK
5
HISTORY OF JAVA
 The Java team members (also known as Green
Team), initiated a project to develop a language
for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for

Prepared by GSK
internet programming. Later, Java technology was
incorporated by Netscape.
 Firstly, it was called "Greentalk" by James
Gosling, and the file extension was .gt
 After that, it was called Oak and was developed as
a part of the Green project.
 Initially developed by James Gosling at Sun
Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995. 6
WHY JAVA WAS NAMED AS "OAK"?

 Oak is a symbol of strength and chosen as a


national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.

Prepared by GSK
 In 1995, Oak was renamed as "Java" because it
was already a trademark by Oak Technologies.

7
WHY JAVA PROGRAMMING NAMED "JAVA"?

 Java is an island in Indonesia where the first


coffee was produced (called Java coffee).
 Java name was chosen by James Gosling while

Prepared by GSK
having a cup of coffee nearby his office
 Notice that Java is just a name, not an acronym.

8
WHEN IT WAS RELEASED?

 JDK 1.0 was released on January 23, 1996.

Now Java is being used in Windows applications,

Prepared by GSK

Web applications, enterprise applications, mobile


applications etc.

 Java SE 22 is the latest release of the Java


Standard Edition platform.

 Release Date: The latest update, Java SE 22.0.2,


was released on July 16, 2024 9
FEATURES OF JAVA / JAVA BUZZWORDS

 The primary objective of Java


programming language creation was to make it

Prepared by GSK
portable, simple and secure programming
language.
 Apart from this, there are also some excellent
features which play an important role in the
popularity of this language.
 The features of Java are also known as Java
buzzwords. 10
Prepared by GSK
11
SIMPLE
 Java is very easy to learn, and its syntax is simple, clean
and easy to understand. According to Sun Microsystem,
Java language is a simple programming language

Prepared by GSK
because:
 Java syntax is based on C++ (so easier for programmers
to learn it after C++).
 Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator
overloading, etc.
 There is no need to remove unreferenced objects because
12
there is an Automatic Garbage Collection in Java.
OBJECT-ORIENTED

 Java is an object-oriented programming


language. Everything in Java is an object.

Prepared by GSK
 Object-oriented means we organize our
software as a combination of different types
of objects that incorporate both data and
behavior.

13
OBJECT-ORIENTED CONT..

Basic concepts of OOPs are:

Object

Prepared by GSK
1.

2. Class

3. Inheritance

4. Polymorphism

5. Abstraction

6. Encapsulation
14
PLATFORM INDEPENDENT

 Java is platform independent


because it is different from other

Prepared by GSK
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 15
SECURED
 With Java, we can develop virus-free systems.
Java is secured because:

No explicit pointer

Prepared by GSK

 Java Programs run inside a virtual


machine.

16
ROBUST
 The English meaning of Robust is strong. Java is
robust because:
 It uses strong memory management.

Prepared by GSK
 There is a lack of pointers that avoids security
problems.
 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.
 There are exception handling and the type checking
17
mechanism in Java. All these points make Java robust
ARCHITECTURE-NEUTRAL

 Java is architecture neutral because there are no


implementation dependent features, for example,

Prepared by GSK
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.
18
PORTABLE

 Java is portable because it facilitates you to carry


the Java byte code to any platform.

Prepared by GSK
 It doesn't require any additional implementation.

19
HIGH-PERFORMANCE

 Java is faster than other traditional interpreted


programming languages like python, ruby and PHP

Prepared by GSK
because Java byte code is "close" to native code.
 It is still a little bit slower than a compiled
language (e.g., C, C++).
 Modern Java has seen significant improvements in
performance due to optimizations in the JVM. The
Just-In-Time (JIT) compiler and other
enhancements have made it faster. 20
DISTRIBUTED

 Java is distributed because it facilitates users to


create distributed applications in Java.

Prepared by GSK
 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.
21
MULTI-THREADED

 A thread is Light weighted sub-process, executing


concurrently.

Prepared by GSK
 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
22
applications, etc.
DYNAMIC

 Java is a dynamic language.

It supports the dynamic loading of classes. It

Prepared by GSK

means classes are loaded on demand.

 Dynamic memory allocation.

23
DISADVANTAGES
 Memory Consumption:
Java program consumes more memory than C/C++
since it runs on top of Java virtual machine.

Prepared by GSK
 Slow:
Java is slower than C/C++ because the additional
work of interpreter to convert the code into
machine language

 Not Freeware:
Oracle charge a fee for the commercial license of
Java 11 and above 24
APPLICATIONS
 Desktop Applications such as acrobat reader, media
player, antivirus, etc.

Prepared by GSK
 Web Applications such as irctc.co.in, javatpoint.com,
etc.
 Enterprise Applications such as banking applications.
 Mobile
 Embedded System
 Robotics
25
 Games, etc.
FIRST JAVA PROGRAM

class HelloWorld
{
public static void main(String args[ ])

Prepared by GSK
{
System.out.println("welcome to java Programming");
} Save the file with class_Name.java
Ex: HelloWorld.java
} Open the CMD & Set the location

Compile:
Syntax: javac Filename.java
Ex: javac HelloWorld.java

Execute: 26
Syntax: java Filename
Ex: java HelloWorld
 class keyword is used to declare a class in Java.

 public keyword is an access modifier that


represents visibility. It means it is visible to all.

Prepared by GSK
 static is a keyword. If we declare any method as
static, it is known as the static method. The core
advantage of the static method is that there is no
need to create an object to invoke the static
method. The main() method is executed by the
JVM, so it doesn't require creating an object to
invoke the main() method. So, it saves memory. 27
 void is the return type of the method. It means it
doesn't return any value.

 main represents the starting point of the program.

Prepared by GSK
 String[ ] args or String args[] is used for command
line argument.

 System.out.println() is used to print


statement followed by a new line. Here, System is a
class, out is an object of the PrintStream class,
println() is a method of the PrintStream class.
28
 System.out.println() is used to print
statement followed by a new line.

 Here, System is a class of java.lang package that

Prepared by GSK
provides access to system-level resources, including
standard input, output.

 out is an object of the PrintStream class, println()


is a method of the PrintStream class. It prints the
arguments passed to it such as int, string etc.

29
JAVA PLATFORMS / EDITIONS
There are 4 platforms or editions of Java:
 1) Java SE (Java Standard Edition)
It is a Java programming platform.

Prepared by GSK

 It includes Java programming packages such as


java.lang, java.io, java.net, java.util, java.sql,
java.math etc.
 It includes core topics like OOPs, String, Regex,
Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.
30
2) Java EE (Java Enterprise Edition)
 It is an enterprise platform which is mainly used to
develop web and enterprise applications.
 It is built on the top of the Java SE platform. It includes
topics like Servlet, JSP, Web Services, EJB, etc.

Prepared by GSK
3) Java ME (Java Micro Edition)
 It is a micro platform which is mainly used to develop
mobile applications.
4) JavaFX
 JavaFX is a software platform used for creating and
delivering rich client applications that can run across a
wide variety of devices. 31
32
JAVA JVM, JDK AND JRE

 Java virtual Machine(JVM) is a virtual Machine that


provides runtime environment to execute java byte

Prepared by GSK
code.

 The JVM doesn't understand Java type, that's why you


compile your *.java files to obtain *.class files that
contain the bytecodes understandable by the JVM.

 JVM controls execution of every Java program.

 It enables features such as automated exception


handling, Garbage-collected heap. 33
Prepared by GSK
34
 Method area : Stores pre-class structure as
constant pool.

 Heap : Heap is a memory area in which objects are


allocated.

Prepared by GSK
 Stack : Local variables and partial results are
store here. Each thread has a private JVM stack
created when the thread is created.

 Program register : Program register holds the


address of JVM instruction currently being
35
executed.
 Native method stack : It contains all native used in
application.

 Executive Engine : Execution engine controls the execute of


instructions contained in the methods of the classes.

Prepared by GSK
 Native Method Interface : Native method interface gives an
interface between java code and native code during
execution.

 Native Method Libraries : The Native Method Interface in


Java, also known as the Java Native Interface (JNI), is a
framework that allows Java code running in the Java Virtual
Machine (JVM) to interact with native applications and
36
libraries written in other languages like C or C++.
DIFFERENCE BETWEEN JDK AND JRE

 JRE : The Java Runtime Environment (JRE)


provides the libraries, the Java Virtual

Prepared by GSK
Machine, and other components to run
applications written in the Java programming
language. JRE does not contain tools and utilities
such as compilers or debuggers for developing
applications.

37
 JDK : The JDK also called Java Development Kit is
a superset of the JRE, and contains everything that
is in the JRE, plus tools such as the compilers and
debuggers necessary for developing applications.

Prepared by GSK
38
Prepared by GSK
39

JDK, JRE AND JVM


VARIABLE IN JAVA
 When we want to store any information, we store it
in an address of the computer. Instead of
remembering the complex address where we

Prepared by GSK
have stored our information, we name that address.
The naming of an address is known as variable.
Variable is the name of memory location.

 In other words, variable is a name which is used to


store a value of any type during program execution.

 syntax: datatype variableName; 40


Prepared by GSK
41
Prepared by GSK
42
INSTANCE VARIABLES IN JAVA
 Instance variables are variables that are declare
inside a class but outside any method, constructor or
block.

Prepared by GSK
 Access modifiers can be given for instance variables.
 Instance variables are created when an object is
created with the use of the keyword 'new' and
destroyed when the object is destroyed
 Instance variables have default values. For
numbers, the default value is 0, for Booleans it is
43
false, and for object references it is null
STATIC/CLASS VARIABLES IN JAVA

 Static are class variables declared with static keyword


within a class outside any method constructor or block.

Prepared by GSK
 Static variables are initialized only once.

 Unlike instance variables, we can only have one copy of


a static variable per class irrespective of how many
objects we create

 Static variables are created at the start of program


execution and destroyed automatically when execution
ends. 44
ADDITIONAL POINTS ON STATIC VARIABLE:

 static variable are also known as class variable.


 static means to remain constant.

Prepared by GSK
 In Java, it means that it will be constant for all
the instances created for that class.
 static variable need not be called from object.
 It is called by classname.static_variable_name
 Note: A static variable can never be defined
inside a method i.e it can never be a local
45
variable.
LOCAL VARIABLES IN JAVA
 Local variables are declared in method, constructor
or block.
 Local variables are initialized when method, constructor

Prepared by GSK
or block start and will be destroyed once its end.
 Local variable reside in stack. Access modifiers are not
used for local variable.
 Local variables are visible only within the declared
method, constructor, or block.
 There is no default value for local variables, so local
variables should be declared and an initial value
should be assigned before the first use. 46
Example program: Types of the variables

public class TypesofVar


{
static int m=100; //static variable
int a=15; //Instance variable

Prepared by GSK
void method()
{
int n=90; //local variable
}
public static void main(String args[])
{
Statement(s);
} 47
} //end of class
Prepared by GSK
48
Prepared by GSK
49
Prepared by GSK
50
Data Type
(=)
Assignment

51
Prepared by GSK
52
Prepared by GSK
53
Prepared by GSK
54
Prepared by GSK
55
JAVA ARRAYS
 Normally, an array is a collection of similar type of
elements which has contiguous memory location.
 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.

56
TYPES OF ARRAY IN JAVA

There are two types of array.


 Single Dimensional Array

 Multidimensional Array

Prepared by GSK
Single Dimensional Array in Java:
 Syntax to Declare an Array in Java

 dataType[ ] arr; (or)

 dataType [ ]arr; (or)

 dataType arr[ ];

 dataType arrayRefVar[ ]=new datatype[size];

57
SET ARRAY ELEMENTS

 int[ ] arr = {10,20,30,40,50}; Here, we are


assigning values at the time of array creation.

Prepared by GSK
 It is useful when we want to store static data
into the array.
 arr[1] = 105 Here, we are assigning a value to
array’s 1 index. It is useful when we want to
store dynamic data into the array.

58
Prepared by GSK
59
Prepared by GSK
60
MULTI-DIMENSIONAL ARRAY

 A multi-dimensional array is very much similar to a


single dimensional array. It can have multiple
rows and multiple columns unlike single

Prepared by GSK
dimensional array, which can have only one row
index.
 It represent data into tabular form in which data
is stored into row and columns.
 Multi-Dimensional Array Declaration

 datatype[ ][ ] arrayName;

61
Example:
Two dimensional array:
int[ ][ ] twoD_arr = new int[10][20];

Three dimensional array:

Prepared by GSK
int[ ][ ][ ] threeD_arr = new int[10][20][30];

62
class TwoDimensional
{
public static void main(String args[])
{
int[ ][ ] a={{10,20},{30,40}}; //declaration and initialization

System.out.println("Two dimensional array elements

Prepared by GSK
are");

System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]); Output:
}
}
63
FOR-EACH LOOP

 In Java, for each loop is used for traversing array


or collection elements.
 In this loop, there is no need for increment or

Prepared by GSK
decrement operator.
For-each loop syntax
 Following is the syntax to declare for-each loop in
the Java.

64
Output:

20
21
22
23
24

Prepared by GSK
In this example, we are traversing array elements using
the for-each loop.
For-each loop terminates automatically when no
element is left in the array object.

65
TYPE CONVERSION
 Java provides various datatypes to store various
data values.
 boolean − Stores 1-bit value representing true or,

Prepared by GSK
false.
 byte − Stores twos compliment integer up to 8 bits.

 char − Stores a Unicode character value up to 16


bits.
 short − Stores an integer value upto 16 bits.

 int − Stores an integer value upto 32 bits.

 long − Stores an integer value upto 64 bits.

 float − Stores a floating point value upto 32bits.


66
 double − Stores a floating point value up to 64 bits.
 Converting one primitive datatype into another
is known as type conversion in Java.
 You can cast the primitive datatypes in two ways
namely, Widening and, Narrowing.
 Widening − Converting a lower datatype to a
higher datatype is known as widening.

Prepared by GSK
 In this case the casting/conversion is done
automatically therefore, it is known as implicit type
casting.
 In this case both datatypes should be compatible with
each other.

67
public class WideningExample
{
public static void main(String args[])
{
int i=20;

Prepared by GSK
float f=i; // Implicit Type Conversion
System.out.println(f);
}
}

Output:
20.0

68
NARROWING
 Narrowing − Converting a higher datatype to a
lower datatype is known as narrowing.
 In this case the casting/conversion is not done
automatically, you need to convert explicitly using

Prepared by GSK
the cast operator “( )” explicitly.
 Therefore, it is known as explicit type casting.

69
public class NarrowingTypeCasting
{
public static void main(String []args)
{
double a = 30.256;

Prepared by GSK
int b = (int)a; // Explicit Type Conversion
System.out.println(b);
}
}

Output:
30

70
OBJECT ORIENTED PROGRAMMING
CONCEPTS

Prepared by GSK
71
ABSTRACTION

 Abstraction in Java refers to hiding the


implementation details of a code and providing

Prepared by GSK
only the necessary information to the user.

 It provides the ability to simplify complex systems


by ignoring irrelevant details and reducing
complexity.

 Java provides many in-built abstractions and few


tools to create our own. 72
Prepared by GSK
73
ENCAPSULATION

 It is a mechanism that binds together the data and


methods that manipulate that data, and keeps

Prepared by GSK
both safe from outside interference and misuse.

 In encapsulation, the variables of a class can be


accessed only through the methods of their current
class.

74
Prepared by GSK
75
Prepared by GSK
76
Prepared by GSK
77
Example:
Inheritance: Real-Time example

Prepared by GSK
78
POLYMORPHISM

 Polymorphism in Java is the ability of an object


to take on multiple forms.

Prepared by GSK
 This concept is achieved through method
overriding or method overloading, allowing an
object to respond to different types of input or
behave in different ways.

79
Prepared by GSK
80
Prepared by GSK
81
Note: Java doesn’t support operator overloading except +
What are Classes and Objects?
Classes and objects are the two main aspects of object-
oriented programming.
Look at the following illustration to see the difference

Prepared by GSK
between class and objects:

82
Prepared by GSK
So, a class is a template for objects, and an
object is an instance of a class.

When the individual objects are created, they


inherit all the variables and methods from the
class. 83
JAVA CLASS
 It can be defined as a template that describe
the behaviors and states of a particular
entity.

Prepared by GSK
A class defines new data type. Once defined
this new type can be used to create object of
that type.
 Object is an instance of class. You may also
call it as physical existence of a logical
template class.
84
JAVA CLASS C ONTD..

 In Java, to declare a class class keyword is


used. A class contain both data and

Prepared by GSK
methods that operate on that data.

 The data or variables defined within a class are


called instance variables and the code that
operates on this data is known as methods.

 Thus, the instance variables and methods are


known as class members. 85
JAVA OBJECT

 Object is an instance of a class while class is a blueprint


of an object. An object represents the class and consists
of properties and behavior.

Prepared by GSK
 Properties refer to the fields declared with in class and
behavior represents to the methods available in the class.
 In real world, we can understand object as a cell phone
that has its properties like: name, cost, color etc and
behavior like calling, chatting etc.
 So we can say that object is a real world entity. Some real
world objects are: ball, fan, car etc. 86
Prepared by GSK
87
EXAMPLE: OBJECT CREATION

Prepared by GSK
Student std = new Student();

Here, std is an object that represents the class Student during


runtime.
The new keyword creates an actual physical copy of the object
and assign it to the std variable. It will have physical existence
88
and get memory in heap area. The new operator dynamically
allocates memory for an object.
Output:
Name: Ramesh
Roll Number: 253
Age: 25

Prepared by GSK
89
METHODS IN JAVA

 Method in Java is similar to a function defined


in other programming languages.

Prepared by GSK
 Method describes behavior of an object.
A method is a collection of statements that are
grouped together to perform an operation.
 For example, if we have a class Human, then
this class should have methods like eating(),
walking(), talking() etc, which describes the
behavior of the object. 90
METHODS IN JAVA CONTD..

 Used to achieve the reusability of code. We


write a method once and use it many times.

Prepared by GSK
 We do not require to write code again and again.

 The method is executed only when we call or


invoke it.

91
METHOD HEADER

Prepared by GSK
Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter list.
92
NAMING A METHOD

 While defining a method, remember that the


method name must start with a lowercase letter.

Prepared by GSK
 In the multi-word method name, the first letter of
each word must be in uppercase except the first
word. For example:

 Single-word method name: sum()

 Multi-word method name: areaOfCircle(),


stringComparision()
93
Declaring method is similar to function.
Syntax to declare the method in Java.

Prepared by GSK
return-type refers to the type of value returned
by the method.
methodName is a valid meaningful name that
represent name of a method.
parameter-list represents list of parameters
accepted by this method.
94
Method may have an optional return statement
that is used to return value to the caller function.
WHAT ARE THE TYPES OF METHODS IN
JAVA?

 Methods in Java can be broadly classified into


two types:

Prepared by GSK
 Predefined

 User-defined

95
PREDEFINED METHODS

 As the name gives it, predefined methods in Java


are the ones that the Java class libraries already

Prepared by GSK
define.

 This means that they can be called and used


anywhere in our program without defining them.

 There are numerous predefined methods, such as


length(), sqrt(), max(), and print(), and each of them
is defined inside their respective classes.
96
Predefined Methods Contd..

Prepared by GSK
Output:
The Square root is 5.0

97
USER-DEFINED METHODS
 Custom methods defined by the user are known as
user-defined methods. (Ex: subNumbers)

Prepared by GSK
98
Output: Out come is: 35
PARAMETER PASSING TECHNIQUES
 Parameter passing is the mechanism of transferring
data between methods.

Prepared by GSK
 There is only call by value in java, not call by
reference.
 If we pass value(s) while calling a method, it is
known as call by value.
 The changes being done in the called method
(ex : sum) , is not affected in the calling method
(ex: main( )). 99
Output:before change 50 after change 50
Output:
public class Swap
In called method x= 20
{
In called method y= 10
public static void swap(int x, int y)
After Swapping x = 10
{
After Swapping y = 20
int temp = x;
x = y;
y = temp;

Prepared by GSK
System.out.println(“In called method= " + x);
System.out.println(" In called method = " + y);
}
public static void main(String[] args)
{
int x = 10;
int y = 20;
swap(x, y);
System.out.println(" After Swapping = " + x);
System.out.println(“After Swapping= " + y);
}
} 100

Example Program to implement Call by Value


RECURSION IN JAVA
 Recursion in java is a process in which a method calls itself
continuously. When it reached basic condition it stops
the execution.

Prepared by GSK
 A method in java that calls itself is called recursive method.
 It makes the code compact but complex to understand.

Syntax:
returntype methodname(parmeter_list )
{
//code to be executed
methodname(); //calling same method
} 101
Prepared by GSK
Working of Recursion

102
JAVA RECURSION EXAMPLE 1: INFINITE TIMES

class RecursionExample1
{
static void p()

Prepared by GSK
{
System.out.println("hello");
p( );
}

static void main(String[] args)


{
Output:
p( ); hello
} hello
} ... 103
java.lang.StackOverflowError
JAVA RECURSION EXAMPLE 2: FINITE TIMES
public class RecursionExample2 Output:
{
static int count=0; hello 1
static void p() hello 2

Prepared by GSK
{ hello 3
count++; hello 4
hello 5
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args)
{
p();
}
104
}
Java Program to find Factorial of a number using Recursion

class Factorial
{

static int factorial( int n )


{
if (n != 0)

Prepared by GSK
return n * factorial(n-1); // recursive call
else
return 1;
}

public static void main(String[] args)


{
int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
Output:
105
Factorial of 4 is: 24
Working of Factorial Program
Factorial (6)

Prepared by GSK
106

You might also like