Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views40 pages

Oops Module I Notes

The document provides an overview of Object-Oriented Programming (OOP), highlighting its core concepts such as encapsulation, inheritance, polymorphism, and abstraction, along with its significance in software development. It discusses the features and advantages of Java as a popular OOP language, including its simplicity, security, portability, and robustness. Additionally, it outlines the differences between Java, C, and Python, and explains the components of Java programming including variables, data types, and the execution process of a Java program.
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)
22 views40 pages

Oops Module I Notes

The document provides an overview of Object-Oriented Programming (OOP), highlighting its core concepts such as encapsulation, inheritance, polymorphism, and abstraction, along with its significance in software development. It discusses the features and advantages of Java as a popular OOP language, including its simplicity, security, portability, and robustness. Additionally, it outlines the differences between Java, C, and Python, and explains the components of Java programming including variables, data types, and the execution process of a Java program.
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/ 40

UNIT - I

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.

summary of OOP: OOP stands for Object-Oriented Programming. OOP is a programming


paradigm in which every program is follows the concept of object. In other words, OOP is a way of
writing programs based on the object concept.

The object-oriented programming paradigm has the following core concepts.

• 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.

Abstraction mechanisms : Abstraction is a process of hiding the implementation details and


showing only functionality to the user. Ex for example, sending SMS where you type the text and
send the message. You don't know the internal processing about the message delivery.

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.

Agents and Communities

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.

An object-oriented program is structured as a community of interacting agents, called objects.


Where each object provides a service (data and methods) that is used by other members of the
community.

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 object-oriented programming, every action is initiated by passing a message to an agent (object),


which is responsible for the action. The receiver is the object to whom the message was sent. In
response to the message, the receiver performs some method to carry out the request. Every
message may include any additional information as arguments.

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 object-oriented programming, behaviors of an object described in terms of 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.

Classes and Instances

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 object-oriented programming, classes can be organized into a hierarchical inheritance structure. A


child class inherits properties from the parent class that higher in the tree.

Method Binding, Overriding, and Exception

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 buzz words:

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

Java is said to be a pure object-oriented programming language. In java, everything is an object. It


supports all the features of the object-oriented programming paradigm. The primitive data types
java also implemented as objects using wrapper classes, but still, it allows primitive data types to
archive high-performance.

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.

Architecture-neutral (or) Platform Independent

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

Java enables the creation of cross-platform programs by compiling into an intermediate


representation called Java bytecode. The byte code is interpreted to any machine code so that it runs
on the native machine.

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).

The history of Java :

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.

5) JDK 1.0 was released on January 23, 1996.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.

Third generation (programming) language

• A third generation (programming) language (3GL) is a grouping of programming languages that


introduced significant enhancements to second generation languages, primarily intended to
make the programming language more programmer-friendly.

• 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.

Difference between C, JAVA and PYTHON


C JAVA PYTHON

Compiled Language, Platform- dependent Interpreted Programming


Platform- dependent Compiled Programming Language,
Language, Platform Platform independent
independent
Operator overloading is not Overloading of the operator is Overloading of the operator is
supported. not supported. supported
Multiple inheritance is not Java provides partial multiple Provides both single as well as
supported in C. inheritance multiple inheritance
Threads are not supported. Multithreading capability is Multithreading is supported.
built-in.
A small number of Many concepts, such as It comes with a large library set
libraries available. UI, are supported by the that allows it to be used for AI,
library. data science, and other
applications.

First Java Program

class Simple{

public static void main(String args[]){

System.out.println("Hello Java");

Save the above file as Simple.java.

To compile:

javac Simple.java

To execute:

java Simple

Execution Process of Java Program

The following three steps are used to create and execute a java program.

• Create a source code (.java file).

• Compile the source code using javac command.

• Run or execute .class file uisng java command.


Parameters used in First Java Program

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.

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.

main represents the starting point of the program.

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.

Difference between JDK, JRE, and JVM

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.

The JVM performs the following main tasks:

• 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:

• Standard Edition Java Platform

• Enterprise Edition Java Platform

• Micro Edition Java Platform

Variable: A variable is a named memory location used to store a data value.

Syntax: data_type variable_name;

int data=50;

Types of Variables

There are three types of variables in Java:

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 in Java

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.

Primitive data types:


Data Type Default Value Default size

boolean FALSE 1 bit

char \u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 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

int[][] arr=new int[3][3];//3 row and 3 column


Example
class Test{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Out put
123
245
445
Unicode System: Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
• ASCII (American Standard Code for Information Interchange) for the United States.
• ISO 8859-1 for Western European Language.
• KOI-8 for Russian.
• GB18030 and BIG-5 for chinese, and so on.

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:

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality != = =

Bitwise bitwise AND &

bitwise exclusive ^
OR
bitwise inclusive |
OR

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment += -= *= /= %= &= ^= |= <<=


>>= >>>=

Java Control Statements

Decision Making statements


• if statements
• switch statement
Loop statements
• do while loop
• while loop
• for loop
• for-each loop
Jump statements
• break statement
• continue statement
If Statement: In Java, 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.

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

public class BreakExample {


public static void main(String[] args) {
for(int i=1;i<=3;i++){
if(i==2){
break;
}
System.out.println(i);
}
}
}
Out put
1
2
Continue Statement : The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for loop or while loop.

Syntax:
while (condition){
continue;
}

public class ContinueExample {


public static void main(String[] args) {
for(int i=1;i<=3;i++){
if(i==2){
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}

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;
}

Creating an Object: In java, an object is an instance of a class. When an object of a class is


created, the class is said to be instantiated.
Syntax
<ClassName> <objectName> = new <ClassName>( );

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

There are 3 ways to initialize object in Java.

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);}

public static void main(String args[]){

Student s1 = new Student4(111,"Karan");


s1.display();
}
}
Out put
111
Karan

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.

There are two types of constructors in Java:

• Default constructor (no-arg constructor)

• 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

Parameterized constructor : A constructor that has parameters is known as parameterized


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

public class Main {


static void myMethod() {
System.out.println("I just got executed!”);}
public static void main(String[] args) {
myMethod(); }. }
Out put
I just got executed!

Example with parameters

public class Main {


static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age); }
public static void main(String[] args) {
myMethod("Jenny", 8); } }

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

public class Main {


static int myMethod(int x, int y) {
return x + y; }
public static void main(String[] args) {
System.out.println(myMethod(5, 3)); }. }

Out put
8
Access Specifier: Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member.

Types of Access Modifiers

• Default – No keyword required


• Private
• Protected
• Public

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.

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.
How can an object be unreferenced?
• By nulling the reference
• By assigning a reference to another
• By anonymous object etc.

By nulling a reference:
Employee e=new Employee();
e=null;

By assigning a reference to another:


Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;

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:

protected void finalize(){ }


gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
public class TestGarbage1{
public void finalize(){
System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}}
Out put
object is garbage collected
object is garbage collected

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

Method Overloading: changing data type of 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){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Out put
22
24.9

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
}

Types of inheritance in java


Single Inheritance Example
When a class inherits another class, it is known as a single inheritance.
class Animal{
}
class Dog extends Animal{
}

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. class Animal{
void eat(){
System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");} }
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");} }
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Out put
eating…
barking…
weeping..

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. class
Animal{
void eat(){
System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing...");} }
class TestInheritance{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
c.bark();//C.T.Error
}}

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Example
class A{
void msg(){
System.out.println("Hello");}
}
class B{
void msg(){
System.out.println("Welcome");} }
class C extends A,B{
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}}

Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

Usage of Java Method Overriding


• Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
• Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.

There must be an IS-A relationship (inheritance).


Example
class Galaxy{
void camera(){System.out.println(“12 MP ");}
}
class Edge extends Galaxy{
void camera(){
System.out.println(“ 20 MP “);}
public static void main(String args[]){
Edge obj = new Edge();
obj.camera();
}
}
Out put
20 MP

Rules for method overriding

Final methods can not be overridden


If we don’t want a method to be overridden, we declare it as final. Please see Using Final with
Inheritance.

class Parent {
final void show() {}
}
class Child extends Parent {
void show() {}
}

Static methods can not be overridden


Static Method Also known as class level method and it is declared using a static keyword, its copy
is shared by all the objects of a class.

Private methods can not be overridden


Private methods in Java are not visible to any other class

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

Compile-time Polymorphism/ static /Early Binding


When type of the object is determined at compiled time(by the compiler), it is known as static
binding. Ex overloading
If there is any private, final or static method in a class, there is static binding.

Runtime Polymorphism/Dynamic Binding/Late Binding


When type of the object is determined at run-time, it is known as dynamic binding. Ex overriding
Example
class Animal{
void eat(){
System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){
System.out.println("dog is eating...");}
public static void main(String args[]){
Animal b1= new Animal();
b1.eat();//animal is eating...
Dog b2= new Dog();
b2.eat();//dog is eating...
Animal a=new Dog();
a.eat(); // dog is eating...
}}
Out put
animal is eating...
dog is eating...
dog is eating...

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));
}

public static void main(String[] args) {


System.out.println("Factorial of 3 is: "+factorial(3));
}
}
Out put
Factorial of 3 is: 6

Working of above program:


factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6

Parameter passing(Call by Value)


There is only call by value in java, not call by reference. If we call a method passing a value, it is
known as call by value. The changes being done in the called method, is not affected in the calling
method.

class Operation{
int data=50;

void change(int data){


data=data+100;//changes will be in the local variable only
}

public static void main(String args[]){


Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data); } }
Out put
before change 50
after change 50

Example of call by value


In case of call by reference original value is changed if we made changes in the called method. If
we pass object in place of any primitive value, original value will be changed.

class Operation2{
int data=50;

void change(Operation2 op){


op.data=op.data+100;//changes will be in the instance variable
}

public static void main(String args[]){


Operation2 op=new Operation2();

System.out.println("before change "+op.data);


op.change(op);//passing object
System.out.println("after change "+op.data);

}
}
Out put
before change 50
after change 150

nested and inner classes


In Java, it is possible to define a class within another class, such classes are known as nested
classes.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}

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”;

2. Using new keyword


String s = new String (“mrec”);
• 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

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.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.


CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder classes implement it. It means, we can create strings in Java by using these three
classes.

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

String trim() method


The String class trim() method eliminates white spaces before and after the String.
Example
String s=" Sachin ";
s.trim();

String charAt() Method


The String class charAt() method returns a character at specified index.
Example
String s="Sachin";
s.charAt(0);//S

String length() Method


The String class length() method returns length of the specified String.
Example
String s="Sachin";
s.length();//6

String valueOf() Method

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

String replace() Method


The String class replace() method replaces all occurrence of first sequence of character with second
sequence of character.
Example
String s1="Java is a programming language.";
String replaceString=s1.replace(“Java","C ");//replaces all occurrences of "Java" to “C "

String startsWith() and endsWith() method


The method startsWith() checks whether the String starts with the letters passed as arguments and
endsWith() method checks whether the String ends with the letters passed as arguments.

Example
String s="Sachin";
s.startsWith("Sa");//true
s.endsWith("n");//true

String toUpperCase() and toLowerCase() method


The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Example
String s="Sachin";
s.toUpperCase();
s.toLowerCase();

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

You might also like