0% found this document useful (0 votes)
2 views73 pages

Java Language

The document provides an overview of Object-Oriented Programming (OOP) and its core principles, including encapsulation, inheritance, abstraction, and polymorphism. It discusses the Java programming language, its features, and its importance in various industries, as well as the compilation and execution process of Java programs. Additionally, it covers variables, data types, and type casting in Java, detailing their definitions and usage.

Uploaded by

adars251
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)
2 views73 pages

Java Language

The document provides an overview of Object-Oriented Programming (OOP) and its core principles, including encapsulation, inheritance, abstraction, and polymorphism. It discusses the Java programming language, its features, and its importance in various industries, as well as the compilation and execution process of Java programs. Additionally, it covers variables, data types, and type casting in Java, detailing their definitions and usage.

Uploaded by

adars251
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/ 73

OOP-Unit-1 Notes

What is Object-Oriented Programming?


The word object-oriented is the combination of two words i.e. object and oriented. The
dictionary meaning of the object is an article or entity that exists in the real world. The meaning
of oriented is interested in a particular kind of thing or entity. In layman's terms, it is a
programming pattern that rounds around an object or entity are called object-oriented
programming.

Object-Oriented Programming or OOP refers to languages that use objects in programming.


Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.

It is the most popular programming model among developers. It is well suited for programs that
are large, complex, and actively updated or maintained. It simplifies software development and
maintenance by providing major concepts such as abstraction, inheritance, polymorphism,
and encapsulation. These core concepts support OOP.

Pillars of OOP

The major concepts that we have discussed above are known as pillars of OOP. There
are four pillars on which OOP rests.

o Abstraction

o Encapsulation

o Inheritance
o Polymorphism

Principles of object-oriented programming


These are the four main principles of the object-oriented programming paradigm. Understanding
them is essential to becoming a successful programmer.
1. Encapsulation

2. Inheritance

3. Abstraction
4. Polymorphism

Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into an entity.
It protects data and functions from outside interference and misuse. Therefore, it also provides
security. A class is the best example of encapsulation.

Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent class) into a
newly created class (child class). It is known as inheritance. It provides code reusability.
Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs.. Poly means many
and morphs means forms. It allows us to create methods with the same name but different
method signatures. It allows the developer to create clean, sensible, readable, and resilient code.

The above figure best describes the concepts of polymorphism. A person plays an employee role
in the office, father and husband role in the home.

What is Java?
Java is a programming language and a platform.. Java is a high level, robust, object-oriented
object
and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his tea
teamm changed the name from Oak to
Java.

Platform:: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Importance of Java
One of the essential reasonss for Java's popularity is the cross-platform
platform compatible and built-in
built
security. Java program can run on any machine with a Java Runtime Environment (JRE)
installed. Programs operate on various computers. Java is used by many banks, manufacturers,
insurance organizations, utilities, and retailers. It is the reason that major industries ruled by
Java.
In this section, we will discuss what makes Java so popular and what are the major industries
that uses Java programming language.

Features that Makes Java Popular

The following features make the Java programming language special and popular.

o Simple to use

o Built-in Security

o Open Source

o Robust API

o Strong community

o Excellent documentation

o Powerful set of Programming Tools

o Versatility

Features of Java
The primary objective of Java programming language creation was to make it 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.

A list of the most important features of the Java language is given below.
Java Industry Usage:
Java is used in almost all fields, be it financial, e-commerce, enterprise, mobile, distributed, or
big data applications.. For example, most of the financial software used by big players like
Citigroup, Barclays, etc. is Java--based. E-commerce giant Amazon uses Java-based
based applications
for its operations

Compilation and Running of a Java Program

1: Compilation

First, the source ‘.java’ file is passed through the compiler, which then encodes the source
code into a machine-independent
independent encoding, known as Bytecode. The content of each class
contained in the source file is stored in a separate ‘.class’ file.

2: Execution
The class files generated by the compiler are independent of the machine or the OS, which
allows them to be run on any system. To run, the main class file (the class that contains the
method main) is passed to the JVM and then goes through three main stages before the final
machine code is executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler

What is Java Bytecode?


Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a
.class file. With the help of java bytecode we achieve platform independence in java.

How does it works?


When we write a program in Java, firstly, the compiler compiles that program and a bytecode is
generated for that piece of code. When we wish to run this .class file on any other platform, we
can do so. After the first compilation, the bytecode generated is now run by the Java Virtual
Machine and not the processor in consideration. This essentially means that we only need to have
basic java installation on any platforms that we want to run our code on. Resources required to
run the bytecode are made available by theJava Virtual Machine, which calls the processor to
allocate the required resources. JVM's are stack-based so they stack implementation to read the
codes.

JDK
JDK is an acronym for Java Development Kit. 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:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. 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.

The implementation of JVM is also actively released by other companies besides Sun
Microsystems
JVM (Java Virtual Machine)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
OOP-Unit-2 Notes

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.

A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.

Variable is a name of memory location.

Types of Variables
There are three types of variables in Java:

o local variable

o instance variable

o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

A local variable cannot be defined with "static" keyword.

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.
Example to understand the types of variables in java
public class A
{
static int m=500;//static variable
void method()
{
int n=10;//local variable
}
public static void main(String args[])
{
int data=40;//instance variable
}
}//end of class

Variables Dynamic Initialization in Java

If any variable is not assigned with value at compile-time and assigned at run time is called
dynamic initialization of a variable. Basically, this is achieved through constructors, setter
methods, normal methods and builtin api methods which returns a value or object.

Scope and lifetime of variables in Java

Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is an instance
variable. The general scope of an instance variable is throughout the class except in static
methods. The lifetime of an instance variable is until the object stays in memory.

Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static is known
as a class variable. The general scope of a class variable is throughout the class and the lifetime
of a class variable is until the end of the program or as long as the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local variables
including the parameters in a method. Scope of a local variable is within the block in which it is
declared and the lifetime of a local variable is until the control leaves the block in which it is
declared.

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:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.

Example:

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.

Example:

short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

Example:

int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.

Example:

double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:

char letterA = 'A'

Type Conversion & Casting in Java


In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler and
manual conversion performed by the programmer.

Type casting
Convert a value from one data type to another data type is known as type casting.

Types of Type Casting

There are two types of type casting:


o Widening Type Casting

o Narrowing Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:

o Both data types must be compatible with each other.

o The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's
see an example.

WideningTypeCastingExample.java

public class WideningTypeCastingExample


{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
} }
In the above example, we have taken a variable x and converted it into a long type. After that, the
long type is converted into the float type.

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not
perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

Let's see an example of narrowing type casting.

In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into int
type.

NarrowingTypeCastingExample.java

public class NarrowingTypeCastingExample {


public static void main(String args[]) {
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i); }}
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:

o Unary Operator,

o Arithmetic Operator,

o Shift Operator,

o Relational Operator,

o Bitwise Operator,

o Logical Operator,

o Ternary Operator and

o Assignment Operator.

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

o incrementing/decrementing a value by one

o negating an expression

o inverting the value of a boolean

Java Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example


public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.

Java Right Shift Operator Example


public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in
Java programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on
its right to the operand on its left. (=, +=, -=, *=, /=, %= )
OOP-Unit-3 Notes

Java Control Statements


Java compiler executes the code from top to bottom. The statements in the
code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the
fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean
expression and control the program flow depending upon the result of the
condition provided. There are two types of decision-making statements in
Java, i.e., If statement and switch statement.

1) If Statement:
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.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of
code if the expression evaluates to true.

Syntax of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

Consider the following example in which we have used the if statement in the
java code.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another


block of code, i.e., else block. The else block is executed if the condition of the
if-block is evaluated as false.

Syntax:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
} } }
3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if


statements. In other words, we can say that it is the chain of if-else statements
that create a decision tree where the program may enter in the block of code
where the condition is true. We can also define an else statement at the end of
the chain.

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}

Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement


inside another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Program that finds greatest among three number

class Gr

public static void main(String args[])

int a=2,b=3,c=5;

if(a>b)

if(a>c)

System.out.println(“a is greatest”);

else

System.out.println(“c is greatest”);

else

if(b>c)

System.out.println(“b is greatest”);

else

System.out.println(“c is greatest”);

}
}

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.

for(initialization, condition, increment/decrement) {


//block of statements
}

The flow chart for the for-loop is given below.


Consider the following example to understand the proper functioning of the
for loop in java.

Calculation.java

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each
each loop, we don't need to upda
update
te the loop variable.
The syntax to use the for-each
each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Consider the following example to understand the functioning of the for-each
loop in Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}

Java while loop


The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while
loop.

It is also known as the entry-controlled loop since the condition is checked at


the start of the loop. If the condition is true, then the loop body will be
executed; otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

while(condition){
//looping statements
}

The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing
"Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing
the loop statements. When the number of iteration is not known and we have
to execute the loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked
in advance. The syntax of the do-while loop is given below.

do
{
//statements
} while (condition);

The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while
do
loop in Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing
"Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Jump Statements
Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the execution
control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.

Java break statement


As the name suggests, the break statement is used to break the current flow
of the program and transfer the control to the next statement outside a loop
or switch statement. However, it breaks only the inner loop in the case of the
nested loop.

The break statement cannot be used independently in the Java program, i.e., it
can only be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement
with the for loop.

BreakExample.java

public class BreakExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Java continue statement
Unlike break statement, the continue statement doesn't break the loop,
whereas, it skips the specific part of the loop and jumps to the next iteration
of the loop immediately.

Consider the following example to understand the functioning of the continue


statement in Java.

public class ContinueExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Some Important Programs

1. Write a program that takes 3 subject marks as an input, and print percentage.
Also print the grade according to following criteria
Percentage >=90 ----------- <=100
Print “A grade”
Percentage >=70 ----------- <90
Print “B grade”
Percentage >=40 ----------- <70
Print “C grade”
Otherwise
Print Fail

Solution:
import java.uti.*;
class Grade
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
float a,b,c,per;
System.out.println("Enter three subject marks");
a=sc.nextFloat();
b=sc.nextFloat();
c=sc.nextFloat();
per=(a+b+c)/3;
System.out.println("Percentage="+per);
if(per>=90 && per<=100)
System.out.println("A Grade");
if(per>=70 && per<90)
System.out.println("B Grade");
if(per>=40 && per<70)
System.out.println("C Grade");
else
System.out.println("Fail");
}
}

2. Write a program that checks whether a number is prime or not


import java.uti.*;
class Prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,f=0,i;
System.out.println("Enter Numer");
n=sc.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)
{
f=1;
break;
}
}
if(f==0)
System.out.println("Number is Prime");
else
System.out.println("Number is not Prime");
}
}
2. Write a program that checks whether a number is palindrome or not
Solution:

import java.uti.*;
class Prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,rev=0,t;
System.out.println("Enter Numer");
n=sc.nextInt();
t=n;
while(t!=0)
{
rev=rev*10+t%10;
t=t/10;
}
System.out.println("Reversed Number="+rev);
if(rev==n)
System.out.println("Number is Palindrome");
else
System.out.println(""Number is not Palindrome");

}
}
OOP-Unit-4-Notes
Java Arrays
Normally, an array is a collection of similar type of elements which has
contiguous memory location.

Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.

In Java, array is an object of a dynamically generated class. Java array inherits


the Object class, and implements the Serializable as well as Cloneable
interfaces. We can store primitive values or objects in an array in Java. Like
C/C++, we can also create single dimentional or multidimentional arrays in
Java.

Moreover, Java provides the feature of anonymous arrays which is not


available in C/C++.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

Single Dimensional Array in Java is basically a linear array that allows its user
to store multiple values of the same data type. It's a collection of data that
stores elements of the same type in a sequentially allocated space in memory.

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Example of Java Array


Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Declaration, Instantiation and Initialization of Java


Array
We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Programs based on One Dimensional Array


1. Write a program to calculate sum of array elements.
import java.util.*;
class SumofArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,i,sum=0;
System.out.println("Enter Array Size");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter Array Elements");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
sum=sum+a[i];
}
System.out.println("Sum="+sum);
}
}

2. Write a program to find minimum and maximum array elements.


import java.util.*;
class MinMaxArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,i;
System.out.println("Enter Array Size");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter Array Elements");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int min=a[0],max=a[0];
for(i=0;i<n;i++)
{
if(min>a[i]
min=a[i];
if(max<a[i]
max=a[i];
}
System.out.println("Min="+min);
System.out.println("Max="+max);
}
}

3. Write a program that searches (Linear) whether the element is present


in array or not.

import java.util.*;
class Search
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,I;
System.out.println("Enter Array Size");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter Array Elements");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int el,f=0;
System.out.println("Enter Element to be searched");
el=sc.nextInt();
for(i=0;i<n;i++)
{
if(el==a[i])
{
f=1;
break;
}
if(f==0)
System.out.println("Element not found");
else
System.out.println("Element found");
}
}

4. Write a program to sort the array

import java.util.*;
class Sort
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n,i,sum=0;
System.out.println("Enter Array Size");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter Array Elements");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int t,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=c;
}
}

}
System.out.println("Sorted Array ");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
Multi Dimensional Array in Java

To store tabular data we use multidimensional Array. In such case, data is


stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

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

Program to read and print 2-D Array Elements

import java.util.*;
class TwoDArray
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int r,c,i,j;
System.out.println("Enter row and column");
r=sc.nextInt();
c=sc.nextInt();
int a[][]=new int[r][c];
System.out.println("Enter Array Elements");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=sc.nextInt();
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(a[i][j]+" ");

}
System.out.println(" ");
}
}
}
OOP-Unit-5 Notes
What is a class in Java
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>{
field;
method;
}

What is an object in Java


An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Example:
class A
{
int s=2;
public static void main(String args[])
{
A a=new A(); //object creation
System.out.println(a.s)
}
}

Object and Class Example: Initialization through reference


Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference
variable.
class Student{

int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=10;
s1.name="Arshad";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}

Method in Java
A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to achieve
the reusability of code. We write a method once and use it many times. We
do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.

The most important method in Java is the main() method.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use these
methods just by calling them in the program at any point

User defined Method


Once we have defined a method, it should be called. The calling of a method
in a program is simple. When we call or invoke a user-defined method, the
program control transfer to the called method.

Example:
import java.util.*;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int n=scan.nextInt();
//method calling
checkEvenOdd(n);
}
//user defined method
public static void checkEvenOdd(int n)
{
//method body
if(n%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}

Parameter Passing/Call by value


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.

Example:

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

Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A
method in java that calls itself is called recursive method.
It makes the code compact but complex to understand.

Java Recursion Example: Factorial Number


Import java.util.*;
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println("Factorial=”+factorial(n));
}
}

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases
the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.


Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

Method Overloading:
// Java program to demonstrate working of method
// overloading in Java

public class Sum {

// Overloaded sum(). This sum takes two int parameters


public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Java constructor
In Java, a constructor is a block of codes similar to the method. It iscalled
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one
constructor is called.

It calls a default constructor if there is no constructor available in the


class. In such case, Java compiler provides a default constructor by
default.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any
parameter.
Syntax of default constructor:
<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will
be invoked at the time of object creation.
//Java Program to create and call a default constructor
class Car{
//creating a default constructor
Bike1(){System.out.println("Car is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Car();
}
}
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a
parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to


distinct objects. However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that
have two parameters. We can have any number of parameters in the
constructor.

//Java Program to demonstrate the use of the parameterized constructor


. class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(123,"Armaan");
Student4 s2 = new Student4(345,"Pradeep");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can
also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more than one


constructor with different parameter lists. They are arranged in a way
that each constructor performs a different task. They are differentiated
by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(123,"Armaan");
Student5 s2 = new Student5(345,"Pradeep",25);
s1.display();
s2.display();
} }

Access Control/Modifiers in Java


There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package and
outside the package.

this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.
this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.

Class Student{
1.int rollno;
2.String name;
3.float fee;
4.Student(int rollno,String name,float fee){
5.rollno=rollno; //this.rollno=rollno;
6.name=name; //this.name=name;
7.fee=fee;//this.fee=fee
8.}
9.void display(){System.out.println(rollno+" "+name+" "+fee);}
10.}
11.class TestThis1{
12.public static void main(String args[]){
13.Student s1=new Student(111,"ankit",5000f);
14.Student s2=new Student(112,"sumit",6000f);
15.s1.display();
16.s2.display();
17.}}

this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used
to reuse the constructor.

Class A{

A(){System.out.println("hello a");}

A(int x){
this();
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A(10);
}}
OUTPUT: hello a
10

Calling parameterized constructor from default constructor:

class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis{
public static void main(String args[]){
A a=new A();
}}

OUTPUT: 5
hello a

Java static keyword

The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time
of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).


Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="PIET";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(110,"Arshad");
Student s2 = new Student(222,"Mangesh");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

2) Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an
instance of a class.
o A static method can access static data member and can change the
value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "PIET";
//static method to change the value of static variable
static void change(){
college = "PIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword
can be used in many context. Final can be:

1. variable
2. method
3. class

1) Java final variable


If you make any variable as final, you cannot change the value of final
variable(It will be constant).

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //Compile time error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
2) Java final method
If you make any method as final, you cannot override it.

3) Java final class


If you make any class as final, you cannot extend it.

Java Inner Classes (Nested Classes)


Java inner class or nested class is a class that is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place to
be more readable and maintainable.

Additionally, it can access all the members of the outer class, including private
data members and methods.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

Advantage of Java inner classes


There are three advantages of inner classes in Java. They are as follows:

1. Nested classes represent a particular type of relationship that is it can


access all the members (data members and methods) of the outer
class, including private.
2. Nested classes are used to develop more readable and maintainable
code because it logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

Example:
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Garbage Collection

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words, it is a way to destroy the unused objects.

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.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;

2) By assigning a reference to another:


1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
1. New Employee();
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.

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 static void gc(){}

Example of garbage collection in java


1. public class TestGarbage1{
2. public void finalize(){
3. System.out.println("object is garbage collected");
4. }
5. public static void main(String args[]){
6. TestGarbage1 s1=new TestGarbage1();
7. TestGarbage1 s2=new TestGarbage1();
8. s1=null;
9. s2=null;
10. System.gc();
11. }
12. }

You might also like