Oops Module I Notes
Oops Module I Notes
Need for OOP paradigm: Object oriented paradigm is a significant methodology for the
development of any software. Most of the architecture styles or patterns such as pipe and filter, data
repository, and component-based can be implemented by using this paradigm.
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python,
etc.
Encapsulation:
Encapsulation is the process of combining data and code into a single unit (object / class). In OOP,
every object is associated with its data and code. In programming, data is defined as variables and
code is defined as methods. The java programming language uses the class concept to implement
encapsulation.
Inheritance:
Inheritance is the process of acquiring properties and behaviors from one object to another object or
one class to another class. In inheritance, we derive a new class from the existing class. Here, the
new class acquires the properties and behaviors from the existing class.
Polymorphism:
Polymorphism is the process of defining same method with different implementation. That means
creating multiple methods with different behaviors.
Abstraction:
Abstraction is hiding the internal details and showing only esential functionality. In the abstraction
concept, we do not show the actual implemention to the end user, instead we provide only esential
things. For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system works?
etc.
Coping with complexity: Coping with complexity in Object-Oriented Programming (OOP) is
crucial for writing maintainable, scalable, and understandable code. Complexity can arise from
various sources, including the structure of your classes and objects, interactions between objects,
and the overall design of your software. Here are some strategies to help you cope with complexity
in OOP:Encapsulation,Abstraction,Inheritance etc.
A way of viewing the world: is an idea to illustrate the object-oriented programming concept with
an example of a real-world situation.
Let us consider a situation, I am at my office and I wish to get food to my family members who are
at my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. Look at the following image.
To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and
pass a message containing my request. It is the responsibility of the agent (Zomato) to satisfy my
request. Here, the agent uses some method to do this. I do not need to know the method that the
agent has used to solve my request. This is usually hidden from me.
So, in object-oriented programming, problem-solving is the solution to our problem which requires
the help of many individuals in the community. We may describe agents and communities as
follows.
In our example, the online food delivery system is a community in which the agents are zomato and
set of hotels. Each hotel provides a variety of services that can be used by other members like
zomato, myself, and my family in the community.
Messages and Methods
To solve my problem, I started with a request to the agent zomato, which led to still more requestes
among the members of the community until my request has done. Here, the members of a
community interact with one another by making requests until the problem has satisfied.
In our example, I send a request to zomato with a message that contains food items, the quantity of
food, and the hotel details. The receiver uses a method to food get delivered to my home.
Responsibilities
In our example, my request for action indicates only the desired outcome (food delivered to my
family). The agent (zomato) free to use any technique that solves my problem. By discussing a
problem in terms of responsibilities increases the level of abstraction. This enables more
independence between the objects in solving complex problems.
In object-oriented programming, all objects are instances of a class. The method invoked by an
object in response to a message is decided by the class. All the objects of a class use the same
method in response to a similar message.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes (objects) of
a community. This graphical representation shows classes listed in a hierarchical tree-like structure.
In this more abstract class listed near the top of the tree, and more specific classes in the middle of
the tree, and the individuals listed near the bottom.
In the class hierarchy, both parent and child classes may have the same method which implemented
individually. Here, the implementation of the parent is overridden by the child. Or a class may
provide multiple definitions to a single method to work with different arguments (overloading).
The search for the method to invoke in response to a request (message) begins with the class of this
receiver. If no suitable method is found, the search is performed in the parent class of it. The search
continues up the parent class chain until either a suitable method is found or the parent class chain is
exhausted. If a suitable method is found, the method is executed. Otherwise, an error message is
issued.
Java is the most popular object-oriented programming language. Java has many advanced features,
a list of key features is known as Java Buzz Words. The java team has listed the following terms as
java buzz words.
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming concepts
are similar to C++. In a java programming language, many complicated features like pointers,
operator overloading, structures, unions, etc. have been removed. One of the most useful features is
the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept,
java provides a feature "applet" which can be embedded into a web application. The applet in java
does not allow access to other parts of the computer, which keeps away from harmful programs like
viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide variety
of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Robust
Java is more robust because the java code can be executed on a variety of environments, java has a
strong memory management mechanism (garbage collector), java is a strictly typed language, it has
a strong set of exception handling mechanism, and many more.
Java has invented to archive "write once; run anywhere, any time, forever". The java provides JVM
(Java Virtual Machine) to to archive architectural-neutral or platform-independent. The JVM allows
the java program created using one operating system can be executed on any other operating
system.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
Interpreted
High performance
Java provides high performance with the help of features like JVM, interpretation, and its
simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI), this
feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
• English words are used to denote variables, programming structures and commands, and
Structured Programming is supported by most 3GLs.
• Commonly known 3GLs are FORTRAN, BASIC, Pascal, JAVA and the C-family (C, C++, C#,
Objective-C) of languages. Also known as a high-level programming language.
class Simple{
System.out.println("Hello Java");
To compile:
javac Simple.java
To execute:
java Simple
The following three steps are used to create and execute a java program.
public keyword is an access modifier that represents visibility. It means it is visible to all.
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.
void is the return type of the method. It means it doesn't return any value.
String[] args or String args[] is used for command line argument. We will discuss it in coming
section.
System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class. We will discuss the internal
working of System.out.println() statement in the coming section.
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode
can be executed. It can also run those programs which are written in other languages and compiled
to Java bytecode.
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE : the Java Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK : The Java Development Kit (JDK) is a software development environment which is used to
develop Java applications and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
int data=50;
Types of Variables
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.
2) Instance Variable :A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static. It is called an instance variable because its
value is instance-specific and is not shared among instances.
3) Static variable : A variable that is declared as static is called a static variable. It cannot be local.
You can create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the memory.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Boolean Data Type: The Boolean data type is used to store only two possible values: true and
false.
Example: Boolean one = false
Byte Data Type :The byte data type is a primitive data type. Its value-range lies between -128 to
127
Example: byte a = 10;
Short Data Type: The short data type is a primitive data type. Its value-range lies between -32,768
to 32,767
Example : short s = 100;
Int Data Type: The int data type is a primitive data type.
Example: int a = 100;
Long Data Type: The long data type is a primitive data type.
Example: long a = 1000L;
Float Data Type
float data type :The long data type is a primitive data types, its stores floating point values
Example: float f1 = 234.5f ;
Double Data Type:The Double data type is a primitive data type.
Example: double d1 = 12.3 ;
Char Data Type: The char data type is a single 16-bit Unicode character.The char data type is used
to store characters.
Example : char letterA = 'A' ;
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.
Types of Array in java
Single Dimensional Array :
Syntax
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java : arrayRefVar=new datatype[size]
Example : int a[]={33,3,4,5};
Example :
class Test{
public static void main(String args[]){
int arr[]={33,3,4,5};
for(int i:arr)
System.out.println(i);
}}
Out put
33
3
4
5
Multidimensional Array
Syntax
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[]
Example to instantiate Multidimensional Array in Java
Operators in Java
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:
additive +-
equality != = =
bitwise exclusive ^
OR
bitwise inclusive |
OR
logical OR ||
Ternary ternary ?:
Simple if statement:If the condition is True, then the block of statements is executed and if it is
False, then the block of statements is ignored.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
Example
public class Example {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Out put
Age is greater than 18
if-else statement: If the condition is True, then the if block of statements is executed and if it is
False, then the else block of statements is executed.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Example
public class Example {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
} }
Out put
odd number
if-else-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if
statements.
Syntax:
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
}
Example
public class Example {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Out put
C grade
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:
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
}
}
Example
public class Example {
public static void main(String[] args) {
int age=20;
int weight=80;
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Out put
You are eligible to donate blood
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.
Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
• Break statement terminates the switch block when the condition is satisfied. It is optional, if not
used, next case is executed.
syntax :
switch (expression){
case value 1:
statement 1;
break;
.
.
case value N:
statement N;
break;
default:
default statement; }
Example
public class Example {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Out put
20
Loops in Java : The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.
The for loop: is used to execute a single statement or a block of statements repeatedly as long as
the given condition is TRUE.
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Example
public class Example {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
System.out.println(i);
}
}
}
Out put
1
2
3
Java Nested for Loop: If we have a for loop inside the another loop, it is known as nested for loop.
The inner loop executes completely whenever outer loop executes.
Syntax:
for(initialization; condition; increment/decrement){
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
}
Example
public class Pyramid {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Out put
*
**
***
Java for-each Loop: The for-each loop is used to traverse array or collection in Java. It is easier to
use than simple for loop because we don't need to increment value and use subscript notation.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example
public class Example {
public static void main(String[] args) {
int arr[]={12,23,44};
for(int i:arr){
System.out.println(i);
}
}
}
Out put
12
23
44
While Loop: The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. If the number of iteration is not fixed, it is recommended to use
the while loop.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
Example
public class Example {
public static void main(String[] args) {
int i=1;
while(i<=3){
System.out.println(i);
i++;
}
}
}
Out put
1
2
3
the do-while: check the condition at the end of loop body. The Java do-while loop is executed at
least once because condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
Example
public class Example {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=3);
}
}
Out put
1
2
3
Break Statement: When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
Syntax:
while (condition){
break;
}
Example
Syntax:
while (condition){
continue;
}
Out put
1
3
Java Comments : The Java comments are the statements in a program that are not executed by the
compiler and interpreter.
There are three types of comments in Java.
• Single Line Comment: //This is single line comment
• Multi Line Comment
/*
This
is
multi line
comment
*/
• Documentation Comment
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
class: The java class is a template of an object. The class defines the blueprint of an object.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
Example
class Student{
int id;
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Out put
0
Null
By reference variable
Example
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="mrec";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Out put
101
mrec
By method
Example
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
s1.insertRecord(111,"Karan");
s1.displayInformation();
}
}
Out put
111
Karan
By constructor
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
constructor : A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial values for
object attributes.
Every time an object is created using the new() keyword, at least one constructor is called.
if there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.
• Parameterized constructor
Default constructor : A constructor that has no parameters is known as default the constructor.
Example
class Defaultconst{
Defaultconst( ){System.out.println("Default constructor");}
public static void main(String args[]){
Defaultconst dc=new Defaultconst(); } }
out put
Default constructor
Example
class Student {
String name;
int id;
Student(String name, int id){
this.name = name;
this.id = id; } } class Test {
public static void main(String[] args){
Student std = new Student("avinash", 68);
System.out.println(“Student Name :" + std.name + " and student Id :" + std.id); }}
Out put
Student Name: Avinash
and student Id : 68
A method
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.
Use of the methods To reuse code: define the code once, and use it many times.
Types of Method
• Predefined Method
• User-defined Method
predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods ex length(), equals(), compareTo(), sqrt()
Example:
public class Demo {
public static void main(String[] args) {
System.out.print("The maximum number is: " + Math.max(9,7)); } }
Out put
9
• User-defined Method : The method written by the user or programmer is known as a user-
defined method.
Example without parameters
Out put
Jenny is 18
These return types required a return statement at the end of the method. A return keyword is used
for returning the resulted value.
Example
Out put
8
Access Specifier: Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member.
Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
Example
class A{
private int data=40;
private void msg(){System.out.println("Hello java");} }
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error obj.msg();
}}
Out put
Compile Time Error obj.msg();
Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you don't use any modifier, it is treated as default by default.
Example
package pack;
class A{
void msg(){
System.out.println("Hello");} }
package mypack;
import pack.*;
class B{
public static void main(String args[ ]){
A obj = new A();//Compile Time Error obj.msg();
}}
Protected: The access level of a protected modifier is within the package and outside the package
through child class.
Example
package pack;
public class A{
protected void msg(){
System.out.println(“Hello");
}}
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg(); } }
Out put
Hello
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.
Example
package pack;
public class A{
public void msg(){
System.out.println("Hello");} }
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); } }
Out put
Hello
this:this is a keyword which is used to refer current object of a class. we can it to refer any member
of the class. It means we can access any instance variable and method by using this keyword.
Example
class Demo{
int a=10;
void display( )
{
int a=200;
System.out.println("LOCAL VCARIABLE="+a);
System.out.println("INSTANCE VARIABLE="this.a);
}
public static void main(String args[]){
Demo obj=new Dem( );
obj.display( );
}
Out put
200
10
Garbage Collection: is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
• 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.
By nulling a reference:
Employee e=new Employee();
e=null;
By anonymous object:
new Employee();
Example
public class Student{
String name = “mahi”;
public void greet(){System.out.println(“hi:"+name);}
public void attend(){
System.out.println(“student attended");}
public static void main(String args[]){
new Student().greet();
new Student().attend() }
}
Out put
hi mahi
student attended
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:
Method Overloading.
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
Different ways to overload the method
• By changing number of arguments
• By changing the data type
Method Overloading: changing no. of arguments
Example
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){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Out put
22
33
Overloading constructor
Example
public class Student {
int id;
String name;
Student(){
System.out.println("this a default constructor"); }
Student(int i, String n){
id = i;
name = n;
System.out.println("this a Parameterized Constructor"); }
public static void main(String[] args) {
Student s = new Student();
Student student = new Student(10, "mahi");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name); } }
Out put
this a default constructor
this a Parameterized Constructor
Student Id : 10
Student Name: mahi
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
class Parent {
final void show() {}
}
class Child extends Parent {
void show() {}
}
The overriding method must have the same return type (or subtype)
From Java 5.0 onwards it is possible to have different return types for an overriding method in the
child class, but the child’s return type should be a sub-type of the parent’s return type
Example
class Parent {
public Object method(){
System.out.println("This is the method in parent");
return new Object(); }}
class Child extends Parent {
public String method(){
System.out.println(
"This is the method in Child ");
return "Hello, World!";}}
public class Test {
public static void main(String[] args){
SuperClass obj1 = new SuperClass(); obj1.method();
SubClass obj2 = new SubClass(); obj2.method(); }}
Overriding and Access Modifiers
The access modifier for an overriding method can allow more, but not less, access than the
overridden method.
Example
class Parent {
private void m1(){
System.out.println("From parent m1()”);}}
class Child extends Parent {
public void m1(){
System.out.println("From child m1()");}}
class Main {
public static void main(String[] args){
Child obj = new Child();
obj.m1();}}
Out put
From child m1()
polymorphism
The word polymorphism means having many forms.
• Compile-time Polymorphism/ static /Early Binding
• Runtime Polymorphism/Dynamic Binding/Late Binding
Recursion in Java
Recursion in java is a process in which a method calls itself continuously.
Syntax:
returntype methodname(){
methodname();//calling same method
}
Example
public class Example {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
class Operation{
int data=50;
class Operation2{
int data=50;
}
}
Out put
before change 50
after change 150
Example
class OuterClass {
class InnerClass {
void display(){
System.out.println(“inner class “);}}
public class Demo {
public static void main(String[] args)
{
OuterClass o= new OuterClass( );
OuterClass.InnerClass i= o.new InnerClass( )
// or OuterClass.InnerClass i= new OuterClass. new InnerClass( );
// or new OuterClass. new InnerClass( ) . display();
i.display();
}
}
Out put
inner class
Example
class OuterClass {
class InnerClass {
public void display(){
System.out.println(“inner class “);}}
public void view( ){
InnerClass i=new InnerClass( )
i.display();
}
public class Demo {
public static void main(String[] args)
{
OuterClass o= new OuterClass( );
i.view();
}
}
Out put
inner class
string: Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
Creating a String
There are two ways to create string in Java:
1. String literal
String s = “mrec”;
For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
string constant pool: String objects are stored in a special memory area known as the "string
constant pool”
Example :
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Out put
java
strings
example
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Immutable String:String references are used to store various attributes like username, password,
etc. In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.
Example
class Test{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Out put
Sachin
As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
Example
class Test{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects } }
Out put
Sachin Tendulkar
The String class valueOf() method coverts given type such as int, long, float, double, boolean, char
and char array into String.
Example
int a=10;
String s=String.valueOf(a);
System.out.println(s+10); // 1010
Example
String s="Sachin";
s.startsWith("Sa");//true
s.endsWith("n");//true
Example
public class Test{
public static void main(String args[])
{
String s="Sachin";
int a=10;
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
System.out.println(s.length());//6
s=String.valueOf(a);
System.out.println(s+10);//1010
String s1=s.replace("10"," Sachin ");
System.out.println(s1);// Sachin
System.out.println(s1.trim());//Sachin
}
}
Exception Handling: in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can
be caught and handled by the program. When an exception occurs within a method, it creates an
object. This object is called the exception object. It contains information about the exception, such
as the name and description of the exception and the state of the program when the exception
occurred.
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Difference between Error and Exception
Error: An Error indicates a serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch