0% found this document useful (0 votes)
11 views95 pages

UNIT 1 Introduction To Java Class and Objects

Uploaded by

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

UNIT 1 Introduction To Java Class and Objects

Uploaded by

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

UNIT 1 class Simple{

Introduction to Java: Basics of Java public static void main(String args[]){


programming, Data types, Variables, Operators, System.out.println("Hello Java");
Control structures including selection, Looping,
Java methods, Overloading, Math class, Arrays in }
java.
}
Objects and Classes: Basics of objects and
classes in java, Constructors, Finalizer, Visibility Application
modifiers, Methods and objects, Inbuilt classes like
String, Character, String Buffer, File, this According to Sun, 3 billion devices run Java. There are
reference. many devices where Java is currently used. Some of them
are as follows:

What is Java? 1. Desktop Applications such as acrobat reader, media


player, antivirus, etc.
Java is a programming language and a platform. Java is 2. Web Applications such as irctc.co.in, javatpoint.com,
a high level, robust, object-oriented and secure etc.
programming language. 3. Enterprise Applications such as banking applications.
4. Mobile
Java was developed by Sun Microsystems (which is now the 5. Embedded System
subsidiary of Oracle) in the year 1995. James Gosling is 6. Smart Card
known as the father of Java. Before Java, its name was Oak. 7. Robotics
Since Oak was already a registered company, so James 8. Games, etc.
Gosling and his team changed the name from Oak to Java.
Types of Java Applications
Platform: Any hardware or software environment in which
a program runs, is known as a platform. Since Java has a
There are mainly 4 types of applications that can be
runtime environment (JRE) and API, it is called a platform.
created using Java programming:

Java Example 1) Standalone Application

Simple.java

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 1
Standalone applications are also known as desktop It is a Java programming platform. It includes Java
applications or window-based applications. These are programming APIs such as java.lang, java.io, java.net,
traditional software that we need to install on every java.util, java.sql, java.math etc. It includes core topics like
machine. Examples of standalone application are Media OOPs, String, Regex, Exception, Inner classes,
player, antivirus, etc. AWT and Swing are used in Java for Multithreading, I/O Stream, Networking, AWT, Swing,
creating standalone applications. Reflection, Collection, etc.

2) Web Application 2) Java EE (Java Enterprise Edition)

An application that runs on the server side and creates a It is an enterprise platform that is mainly used to develop
dynamic page is called a web application. web and enterprise applications. It is built on top of the
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. Java SE platform. It includes topics like Servlet, JSP, Web
technologies are used for creating web applications in Java. Services, EJB, JPA, etc.

3) Enterprise Application 3) Java ME (Java Micro Edition)

An application that is distributed in nature, such as banking It is a micro platform that is dedicated to mobile
applications, etc. is called an enterprise application. It has applications.
advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise 4) JavaFX
applications.
It is used to develop rich internet applications. It uses a
4) Mobile Application lightweight user interface API.

An application which is created for mobile devices is called


a mobile application. Currently, Android and Java ME are
Features of Java
used for creating mobile applications.
The primary objective of Java programming language
creation was to make it portable, simple and secure
Java Platforms / Editions programming language. Apart from this, there are also
some excellent features which play an important role in the
There are 4 platforms or editions of Java: popularity of this language. The features of Java are also
known as Java buzzwords.
1) Java SE (Java Standard Edition)
A list of the most important features of the Java language is
given below.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 2
1. Simple Object-oriented programming (OOPs) is a methodology that
2. Object-Oriented simplifies software development and maintenance by
3. Portable providing some rules.
4. Platform independent
5. Secured Basic concepts of OOPs are:
6. Robust
7. Architecture neutral 1. Object
8. Interpreted 2. Class
9. High Performance
3. Inheritance
10. Multithreaded
11. Distributed 4. Polymorphism
12. Dynamic 5. Abstraction
6. Encapsulation
Simple
Platform Independent
Java is very easy to learn, and its syntax is simple, clean
and easy to understand. According to Sun Microsystem,
Java language is a simple programming language because:

 Java syntax is based on C++ (so easier for


programmers to learn it after C++).
 Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator
overloading, etc.
 There is no need to remove unreferenced objects
because there is an Automatic Garbage Collection in Java.

Object-Oriented
Java is an object-oriented programming language. Java is platform independent because it is different from
Everything in Java is an object. Object-oriented means we other languages like C, C++, etc. which are compiled into
organize our software as a combination of different types platform specific machines while Java is a write once, run
of objects that incorporate both data and behavior. anywhere language. A platform is the hardware or software
environment in which a program runs.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 3
There are two types of platforms software-based and Java language provides these securities by default. Some
hardware-based. Java provides a software-based platform. security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.
The Java platform differs from most other platforms in the
sense that it is a software-based platform that runs on top Robust
of other hardware-based platforms. It has two components:
The English mining of Robust is strong. Java is robust
1. Runtime Environment
because:
2. API(Application Programming Interface)
 It uses strong memory management.
Java code can be executed on multiple platforms, for  There is a lack of pointers that avoids security problems.
example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java  Java provides automatic garbage collection which runs on
code is compiled by the compiler and converted into the Java Virtual Machine to get rid of objects which are not being
bytecode. This bytecode is a platform-independent code used by a Java application anymore.
because it can be run on multiple platforms, i.e., Write  There are exception handling and the type checking
Once and Run Anywhere (WORA). mechanism in Java. All these points make Java robust.

Secured Architecture-neutral
Java is best known for its security. With Java, we can Java is architecture neutral because there are no
develop virus-free systems. Java is secured because: implementation dependent features, for example, the size
of primitive types is fixed.
 No explicit pointer
 Java Programs run inside a virtual machine sandbox In C programming, int data type occupies 2 bytes of
 Classloader: Classloader in Java is a part of the Java memory for 32-bit architecture and 4 bytes of memory for
Runtime Environment (JRE) which is used to load Java 64-bit architecture. However, it occupies 4 bytes of
classes into the Java Virtual Machine dynamically. It adds memory for both 32 and 64-bit architectures in Java.
security by separating the package for the classes of the
local file system from those that are imported from Portable
network sources.
 Bytecode Verifier: It checks the code fragments for Java is portable because it facilitates you to carry the Java
illegal code that can violate access rights to objects. bytecode to any platform. It doesn't require any
 Security Manager: It determines what resources a implementation.
class can access such as reading and writing to the local
disk.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 4
High-performance It also supports functions from its native languages, i.e., C
and C++.
Java is faster than other traditional interpreted
programming languages because Java bytecode is "close" Java supports dynamic compilation and automatic memory
to native code. It is still a little bit slower than a compiled management (garbage collection).
language (e.g., C++). Java is an interpreted language that
is why it is slower than compiled languages, e.g., C, C++, First Java Program | Hello World
etc.
Example
Distributed o Create the Java program
o Compile and run the Java program
Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java
makes us able to access files by calling the methods from
any machine on the internet.
Creating Hello World Example
Let's create the hello java program:

class Simple{
Multi-threaded
public static void main(String args[]){
A thread is like a separate program, executing
concurrently. We can write Java programs that deal with System.out.println("Hello Java");
many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy }
memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web }
applications, etc.
Save the above file as Simple.java.

To compile: javac Simple.java


Dynamic To execute: java Simple

Java is a dynamic language. It supports the dynamic Output:


loading of classes. It means classes are loaded on demand.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 5
Hello Java  String[] args or String args[] is used for command
line argument. We will discuss it in coming section.
Compilation Flow:  System.out.println() is used to print statement.
Here, System is a class, out is an object of the PrintStream
When we compile Java program using javac tool, the Java class, println() is a method of the PrintStream class. We will
compiler converts the source code into byte code. discuss the internal working
of System.out.println() statement in the coming section.

Java Variables
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. There are three


types of variables in java: local, instance and static.
Parameters used in First Java
Program There are two types of data types in Java: primitive and
non-primitive.
The meaning of class, public, static, void, main, String[],
System.out.println().

 class keyword is used to declare a class in Java. Variable


 public keyword is an access modifier that represents
visibility. It means it is visible to all. A variable is the name of a reserved area allocated in
 static is a keyword. If we declare any method as memory. In other words, it is a name of the memory
static, it is known as the static method. The core location. It is a combination of "vary + able" which means
advantage of the static method is that there is no need to its value can be changed.
create an object to invoke the static method. The main()
method is executed by the JVM, so it doesn't require int data=50;//Here data is variable
creating an object to invoke the main() method. So, it
saves memory.
 void is the return type of the method. It means it Types of Variables
doesn't return any value.
 main represents the starting point of the program. There are three types of variables in Java:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 6
1. local variable {
2. instance variable
3. static variable static int m=100;//static variable

1) Local Variable void method()

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 int n=90;//local variable
aware that the variable exists.
}
A local variable cannot be defined with "static" keyword.
public static void main(String args[])
2) Instance Variable
{
A variable declared inside the class but outside the body of
the method, is called an instance variable. It is not int data=50;//instance variable
declared as static.
}
It is called an instance variable because its value is
instance-specific and is not shared among instances. }//end of class

3) Static variable Java Variable Example: Add Two


A variable that is declared as static is called a static Numbers
variable. It cannot be local. You can create a single copy of
the static variable and share it among all the instances of public class Simple{
the class. Memory allocation for static variables happens
only once when the class is loaded in the memory. public static void main(String[] args){

int a=10;
Example to understand the types of
variables in java int b=10;

public class A int c=a+b;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 7
System.out.println(c);
Java Variable Example:
} Narrowing (Typecasting)
} public class Simple{

Output: public static void main(String[] args){

20 float f=10.5f;

Java Variable Example: Widening //int a=f;//Compile time error

public class Simple{ int a=(int)f;

public static void main(String[] args){ System.out.println(f);

int a=10; System.out.println(a);

float f=a; }}

System.out.println(a); Output:

System.out.println(f); 10.5

10
}}

Output: Java Variable Example: Overflow


10 class Simple{

10.0 public static void main(String[] args){

//Overflow

int a=130;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 8
byte b=(byte)a; 20

System.out.println(a); Data Types in Java


System.out.println(b);
Data types specify the different sizes and values that can
be stored in the variable. There are two types of data types
}}
in Java:
Output: 1. Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.
130 2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
-126

Java Primitive Data Types


Java Variable Example: Adding
Lower Type In Java language, primitive data types are the building
blocks of data manipulation. These are the most basic data
types available in Java language.
class Simple{
Java is a statically-typed programming language. It means,
public static void main(String[] args){
all variables must be declared before its use. That is why we
need to declare variable's type and name.
byte a=10;
There are 8 types of primitive data types:
byte b=10;
 boolean data type
//byte c=a+b;//Compile Time Error: because a+b=20 will b  byte data type
e int  char data type
 short data type
byte c=(byte)(a+b);  int data type
 long data type
System.out.println(c);  float data type
 double data type
}}

Output:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 9
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:

1. 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
Data Type Default Value Default size lies between -128 to 127 (inclusive). Its minimum value is -
128 and maximum value is 127. Its default value is 0.
boolean false 1 bit
The byte data type is used to save memory in large arrays
char '\u0000' 2 byte where the memory savings is most required. It saves space
because a byte is 4 times smaller than an integer. It can
byte 0 1 byte also be used in place of "int" data type.

short 0 2 byte Example:

1. byte a = 10, byte b = -20


int 0 4 byte

long 0L 8 byte Short Data Type


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

Boolean Data Type


Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 10
The short data type can also be used to save memory just 1. long a = 100000L, long b = -200000L
like byte data type. A short data type is 2 times smaller
than an integer. Float Data Type
Example:
The float data type is a single-precision 32-bit IEEE 754
floating point.Its value range is unlimited. It is
1. short s = 10000, short r = -5000
recommended to use a float (instead of double) if you need
to save memory in large arrays of floating point numbers.
int Data Type The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
The int data type is a 32-bit signed two's complement
integer. Its value-range lies between - 2,147,483,648 (- Example:
2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 1. float f1 = 234.5f
2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type


Double Data Type
for integral values unless if there is no problem about
memory. The double data type is a double-precision 64-bit IEEE 754
floating point. Its value range is unlimited. The double data
Example: type is generally used for decimal values just like float. The
double data type also should never be used for precise
1. int a = 100000, int b = -200000 values, such as currency. Its default value is 0.0d.

Example:
Long Data Type
1. double d1 = 12.3
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).
Char Data Type
Its minimum value is - 9,223,372,036,854,775,808and
maximum value is 9,223,372,036,854,775,807. Its default The char data type is a single 16-bit Unicode character. Its
value is 0. The long data type is used when you need a value-range lies between '\u0000' (or 0) to '\uffff' (or
range of values more than those provided by int. 65,535 inclusive).The char data type is used to store
characters.
Example:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 11
Example:
Unary postfix expr++ expr--
1. char letterA = 'A' prefix ++expr --expr +expr -
expr ~ !
Why char uses 2 byte in java and what
is \u0000 ? Arithmetic multiplicative */%

additive +-
It is because java uses Unicode system not ASCII code
system. The \u0000 is the lowest range of Unicode system.
Shift shift << >> >>>
To get detail explanation about Unicode visit next page.
Relational comparison < > <= >= instanceof
Operators in Java
equality == !=
Operator in Java is a symbol that is used to perform Bitwise bitwise AND &
operations. For example: +, -, *, / etc.
bitwise ^
There are many types of operators in Java which are given exclusive OR
below:
bitwise |
 Unary Operator, inclusive OR
 Arithmetic Operator,
 Shift Operator, Logical logical AND &&
 Relational Operator,
 Bitwise Operator, logical OR ||
 Logical Operator,
 Ternary Operator and Ternary ternary ?:
 Assignment Operator.
Assignment assignment = += -= *= /= %= &=
^= |= <<= >>= >>>=
Java Operator Precedence
Java Unary Operator
Operator Category Precedence
Type The Java unary operators require only one operand. Unary
operators are used to perform various operations i.e.:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 12
 incrementing/decrementing a value by one 8. }}
 negating an expression
 inverting the value of a boolean Output:

22
Java Unary Operator Example: ++ and
-- 21

1. public class OperatorExample{ Java Unary Operator Example: ~ and !


2. public static void main(String args[]){
3. int x=10; 1. public class OperatorExample{
4. System.out.println(x++);//10 (11) 2. public static void main(String args[]){
5. System.out.println(++x);//12 3. int a=10;
6. System.out.println(x--);//12 (11) 4. int b=-10;
7. System.out.println(--x);//10 5. boolean c=true;
8. }} 6. boolean d=false;
7. System.out.println(~a);//-
11 (minus of total positive value which starts from 0)
Output: 8. System.out.println(~b);//9 (positive of total minus, positiv
e starts from 0)
10
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
12
11. }}
12
Output:
10
-11

Java Unary Operator Example 2: ++ and 9


--
false
1. public class OperatorExample{
true
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 13
Java Arithmetic Operators 4. }}

Java arithmetic operators are used to perform addition, Output:


subtraction, multiplication, and division. They act as basic
21
mathematical operations.
Java Left Shift Operator
Java Arithmetic Operator Example
The Java left shift operator << is used to shift all of the bits
1. public class OperatorExample{
in a value to the left side of a specified number of times.
2. public static void main(String args[]){
3. int a=10;
4. int b=5; Java Left Shift Operator Example
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5 1. public class OperatorExample{
7. System.out.println(a*b);//50 2. public static void main(String args[]){
8. System.out.println(a/b);//2 3. System.out.println(10<<2);//10*2^2=10*4=40
9. System.out.println(a%b);//0 4. System.out.println(10<<3);//10*2^3=10*8=80
10. }} 5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
Output: 7. }}

15 Output:
5 40

50 80

2 80

0 240

Java Arithmetic Operator Example: Java Right Shift Operator


Expression
The Java right shift operator >> is used to move the value
1. public class OperatorExample{ of the left operand to right by the number of bits specified
2. public static void main(String args[]){ by the right operand.
3. System.out.println(10*10/5+3-1*4/2);

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 14
Java Right Shift Operator Example -5

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

2 1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
Java Shift Operator Example: >> vs 4. int b=5;
>>> 5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
1. public class OperatorExample{ 7. System.out.println(a<b&a<c);//false & true = false
2. public static void main(String args[]){ 8. }}
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2); Output:
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) t false
o0
7. System.out.println(-20>>2); false
8. System.out.println(-20>>>2);
9. }} Java AND Operator Example: Logical &&
Output: vs Bitwise &
5 1. public class OperatorExample{
2. public static void main(String args[]){
5 3. int a=10;
4. int b=5;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 15
5. int c=20; 10. System.out.println(a);//10 because second condition is not
6. System.out.println(a<b&&a++<c);//false && true = false checked
7. System.out.println(a);//10 because second condition is not 11. System.out.println(a>b|a++<c);//true | true = true
checked 12. System.out.println(a);//11 because second condition is che
8. System.out.println(a<b&a++<c);//false && true = false cked
9. System.out.println(a);//11 because second condition is che 13. }}
cked
10. }} Output:

Output: true

false true

10 true

false 10

11 true

Java OR Operator Example: Logical || 11

and Bitwise | Java Ternary Operator


The logical || operator doesn't check the second condition if
Java Ternary operator is used as one line replacement for
the first condition is true. It checks the second condition
if-then-else statement and used a lot in Java programming.
only if the first one is false.
It is the only conditional operator which takes three
operands.
The bitwise | operator always checks both conditions
whether first condition is true or false.
Java Ternary Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){ 1. public class OperatorExample{
3. int a=10; 2. public static void main(String args[]){
4. int b=5; 3. int a=2;
5. int c=20; 4. int b=5;
6. System.out.println(a>b||a<c);//true || true = true 5. int min=(a<b)?a:b;
7. System.out.println(a>b|a<c);//true | true = true 6. System.out.println(min);
8. //|| vs | 7. }}
9. System.out.println(a>b||a++<c);//true || true = true

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 16
Output: 8. a*=2;//9*2
9. System.out.println(a);
2 10. a/=2;//18/2
11. System.out.println(a);
12. }}
Java Assignment Operator
Output:
Java assignment operator is one of the most common
operators. It is used to assign the value on its right to the 13
operand on its left.
9
Java Assignment Operator Example
18
1. public class OperatorExample{
9
2. public static void main(String args[]){
3. int a=10;
4. int b=20; Java Assignment Operator Example:
5. a+=4;//a=a+4 (a=10+4) Adding short
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b); 1. public class OperatorExample{
9. }} 2. public static void main(String args[]){
3. short a=10;
4. short b=10;
Output: 5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
14
7. System.out.println(a);
8. }}
16

Output:
Java Assignment Operator Example
Compile time error
1. public class OperatorExample{
2. public static void main(String[] args){ After type cast:
3. int a=10;
4. a+=3;//10+3 1. public class OperatorExample{
5. System.out.println(a); 2. public static void main(String args[]){
6. a-=4;//13-4 3. short a=10;
7. System.out.println(a); 4. short b=10;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 17
5. a=(short)(a+b);//20 which is int now converted to short catch: Java catch keyword is used to catch the exceptions
6. System.out.println(a); generated by try statements. It must be used after the try block
7. }} only.

Output: char: Java char keyword is used to declare a variable that can
hold unsigned 16-bit Unicode characters
20
class: Java class keyword is used to declare a class.
Java Keywords continue: Java continue keyword is used to continue the loop. It
continues the current flow of the program and skips the
Java keywords are also known as reserved words. remaining code at the specified condition.
Keywords are particular words that act as a key to a code.
These are predefined words by Java so they cannot be used default: Java default keyword is used to specify the default
as a variable or object name or class name. block of code in a switch statement.

do: Java do keyword is used in the control statement to declare


List of Java Keywords a loop. It can iterate a part of the program several times.

A list of Java keywords or reserved words are given below: double: Java double keyword is used to declare a variable that
can hold 64-bit floating-point number.
abstract: Java abstract keyword is used to declare an abstract
class. An abstract class can provide the implementation of the else: Java else keyword is used to indicate the alternative
interface. It can have abstract and non-abstract methods. branches in an if statement.

boolean: Java boolean keyword is used to declare a variable as enum: Java enum keyword is used to define a fixed set of
a boolean type. It can hold True and False values only. constants. Enum constructors are always private or default.

break: Java break keyword is used to break the loop or switch extends: Java extends keyword is used to indicate that a class
statement. It breaks the current flow of the program at specified is derived from another class or interface.
conditions.
final: Java final keyword is used to indicate that a variable holds
byte: Java byte keyword is used to declare a variable that can a constant value. It is used with a variable. It is used to restrict
hold 8-bit data values. the user from updating the value of the variable.

case: Java case keyword is used with the switch statements to finally: Java finally keyword indicates a block of code in a try-
mark blocks of text. catch structure. This block is always executed whether an
exception is handled or not.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 18
float: Java float keyword is used to declare a variable that can package: Java package keyword is used to declare a Java
hold a 32-bit floating-point number. package that includes the classes.

for: Java for keyword is used to start a for loop. It is used to private: Java private keyword is an access modifier. It is used to
execute a set of instructions/functions repeatedly when some indicate that a method or variable may be accessed only in the
condition becomes true. If the number of iteration is fixed, it is class in which it is declared.
recommended to use for loop.
protected: Java protected keyword is an access modifier. It can
if: Java if keyword tests the condition. It executes the if block if be accessible within the package and outside the package but
the condition is true. through inheritance only. It can't be applied with the class.

implements: Java implements keyword is used to implement an public: Java public keyword is an access modifier. It is used to
interface. indicate that an item is accessible anywhere. It has the widest
scope among all other modifiers.
import: Java import keyword makes classes and interfaces
available and accessible to the current source code. return: Java return keyword is used to return from a method
when its execution is complete.
instanceof: Java instanceof keyword is used to test whether the
object is an instance of the specified class or implements an short: Java short keyword is used to declare a variable that can
interface. hold a 16-bit integer.

int: Java int keyword is used to declare a variable that can hold static: Java static keyword is used to indicate that a variable or
a 32-bit signed integer. method is a class method. The static keyword in Java is mainly
used for memory management.
interface: Java interface keyword is used to declare an
interface. It can have only abstract methods. strictfp: Java strictfp is used to restrict the floating-point
calculations to ensure portability.
long: Java long keyword is used to declare a variable that can
hold a 64-bit integer. super: Java super keyword is a reference variable that is used
to refer to parent class objects. It can be used to invoke the
native: Java native keyword is used to specify that a method is immediate parent class method.
implemented in native code using JNI (Java Native Interface).
switch: The Java switch keyword contains a switch statement
new: Java new keyword is used to create new objects. that executes code based on test value. The switch statement
tests the equality of a variable against multiple values.
null: Java null keyword is used to indicate that a reference does
not refer to anything. It removes the garbage value. synchronized: Java synchronized keyword is used to specify
the critical sections or methods in multithreaded code.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 19
this: Java this keyword can be used to refer the current object in Java provides three types of control flow statements.
a method or constructor.
1. Decision Making statements
throw: The Java throw keyword is used to explicitly throw an o if statements
exception. The throw keyword is mainly used to throw custom o switch statement
exceptions. It is followed by an instance. 2. Loop statements
o do while loop
throws: The Java throws keyword is used to declare an o while loop
exception. Checked exceptions can be propagated with throws. o for loop
o for-each loop
transient: Java transient keyword is used in serialization. If you 3. Jump statements
define any data member as transient, it will not be serialized. o break statement
o continue statement
try: Java try keyword is used to start a block of code that will be
tested for exceptions. The try block must be followed by either
catch or finally block.
Decision-Making statements:

void: Java void keyword is used to specify that a method does As the name suggests, decision-making statements decide
not have a return value. which statement to execute and when. Decision-making
statements evaluate the Boolean expression and control
volatile: Java volatile keyword is used to indicate that a variable the program flow depending upon the result of the
may change asynchronously. condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
while: Java while keyword is used to start a while loop. This loop
iterates a part of the program several times. If the number of
iteration is not fixed, it is recommended to use the while loop.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition.
Java Control Statements | Control The control of the program is diverted depending upon the
Flow in Java specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four
Java compiler executes the code from top to bottom. The types of if-statements given below.
statements in the code are executed according to the order
1. Simple if statement
in which they appear. However, Java provides statements
2. if-else statement
that can be used to control the flow of Java code. Such 3. if-else-if ladder
statements are called control flow statements. It is one of 4. Nested if-statement
the fundamental features of Java, which provides a smooth
flow of program.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 20
Let's understand the if-statements one by one. 2) if-else statement

1) Simple if statement: The if-else statement is an extension to the if-statement,


which uses another block of code, i.e., else block. The else
It is the most basic statement among all control flow block is executed if the condition of the if-block is
statements in Java. It evaluates a Boolean expression and evaluated as false.
enables the program to enter a block of code if the
expression evaluates to true. Syntax:

Syntax of if statement is given below. 1. if(condition) {


2. statement 1; //executes when condition is true
1. if(condition) { 3. }
2. statement 1; //executes when condition is true 4. else{
3. } 5. statement 2; //executes when condition is false
6. }
Consider the following example in which we have used
the if statement in the java code. Consider the following example.

Student.java Student.java

Student.java 1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
1. public class Student {
4. int y = 12;
2. public static void main(String[] args) {
5. if(x+y < 10) {
3. int x = 10;
6. System.out.println("x + y is less than 10");
4. int y = 12;
7. } else {
5. if(x+y > 20) {
8. System.out.println("x + y is greater than 20");
6. System.out.println("x + y is greater than 20");
9. }
7. }
10. }
8. }
11. }
9. }
Output:
Output:
x + y is greater than 20
x + y is greater than 20

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 21
3) if-else-if ladder: 14. }

The if-else-if statement contains the if-statement followed Output:


by multiple else-if statements. In other words, we can say
that it is the chain of if-else statements that create a Delhi
decision tree where the program may enter in the block of
code where the condition is true. We can also define an 4. Nested if-statement
else statement at the end of the chain.
In nested if-statements, the if statement can contain
Syntax of if-else-if statement is given below. a if or if-else statement inside another if or else-if
statement.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true Syntax of Nested if-statement is given below.
3. }
4. else if(condition 2) { 1. if(condition 1) {
5. statement 2; //executes when condition 2 is true 2. statement 1; //executes when condition 1 is true
6. } 3. if(condition 2) {
7. else { 4. statement 2; //executes when condition 2 is true
8. statement 2; //executes when all the conditions are false 5. }
9. } 6. else{
7. statement 2; //executes when condition 2 is false
Consider the following example. 8. }
9. }
Student.java
Consider the following example.
1. public class Student {
2. public static void main(String[] args) { Student.java
3. String city = "Delhi";
4. if(city == "Meerut") { 1. public class Student {
5. System.out.println("city is meerut"); 2. public static void main(String[] args) {
6. }else if (city == "Noida") { 3. String address = "Delhi, India";
7. System.out.println("city is noida"); 4.
8. }else if(city == "Agra") { 5. if(address.endsWith("India")) {
9. System.out.println("city is agra"); 6. if(address.contains("Meerut")) {
10. }else { 7. System.out.println("Your city is Meerut");
11. System.out.println(city); 8. }else if(address.contains("Noida")) {
12. } 9. System.out.println("Your city is Noida");
13. } 10. }else {

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 22
11. System.out.println(address.split(",")[0]); 1. switch (expression){
12. } 2. case value1:
13. }else { 3. statement1;
14. System.out.println("You are not living in India"); 4. break;
15. } 5. .
16. } 6. .
17. } 7. .
8. case valueN:
Output: 9. statementN;
10. break;
Delhi 11. default:
12. default statement;
13. }
Switch Statement:
Consider the following example to understand the flow of
In Java, Switch statements are similar to if-else-if the switch statement.
statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based Student.java
on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It 1. public class Student implements Cloneable {
also enhances the readability of the program. 2. public static void main(String[] args) {
3. int num = 2;
Points to be noted about switch statement: 4. switch (num){
5. case 0:
o The case variables can be int, short, byte, char, or 6. System.out.println("number is 0");
enumeration. String type is also supported since version 7 of 7. break;
Java 8. case 1:
o Cases cannot be duplicate 9. System.out.println("number is 1");
o Default statement is executed when any of the case 10. break;
doesn't match the value of expression. It is optional. 11. default:
o Break statement terminates the switch block when the 12. System.out.println(num);
condition is satisfied. 13. }
It is optional, if not used, next case is executed. 14. }
o While using switch statements, we must notice that the 15. }
case expression will be of the same type as the variable.
However, it will also be a constant value. Output:

The syntax to use the switch statement is given below. 2

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 23
While using switch statements, we must notice that the The flow chart for the for-loop is given below.
case expression will be of the same type as the variable.
However, it will also be a constant value. The switch
permits only int, string, and Enum type variables to be
used.

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

In Java, we have three types of loops that execute similarly. Consider the following example to understand the proper
However, there are differences in their syntax and functioning of the for loop in java.
condition checking time.
Calculation.java
1. for loop
2. while loop 1. public class Calculattion {
3. do-while loop 2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
Let's understand the loop statements one by one. 4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
Java for loop 7. }
8. System.out.println("The sum of first 10 natural numbers is
In Java, for loop is similar to C and C++. It enables us to " + sum);
initialize the loop variable, check the condition, and 9. }
increment/decrement in a single line of code. We use the 10. }
for loop only when we exactly know the number of times,
we want to execute the block of code. Output:

1. for(initialization, condition, increment/decrement) { The sum of first 10 natural numbers is 55


2. //block of statements
3. }

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 24
Java for-each loop Python

JavaScript
Java provides an enhanced for loop to traverse the data
structures like array or collection. In the for-each loop, we
don't need to update the loop variable. The syntax to use Java while loop
the for-each loop in java is given below.
The while loop is also used to iterate over the number of
1. for(data_type var : array_name/collection_name){ statements multiple times. However, if we don't know the
2. //statements number of iterations in advance, it is recommended to use
3. } a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop
Consider the following example to understand the statement in while loop.
functioning of the for-each loop in Java.
It is also known as the entry-controlled loop since the
Calculation.java condition is checked at the start of the loop. If the condition
is true, then the loop body will be executed; otherwise, the
1. public class Calculation { statements after the loop will be executed.
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub The syntax of the while loop is given below.
4. String[] names = {"Java","C","C+
+","Python","JavaScript"}; 1. while(condition){
5. System.out.println("Printing the content of the array name 2. //looping statements
s:\n"); 3. }
6. for(String name:names) {
7. System.out.println(name);
The flow chart for the while loop is given in the following
8. }
9. }
image.
10. }

Output:

Printing the content of the array names:

Java

C++

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 25
0

10

Java do-while loop


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

Calculation .java It is also known as the exit-controlled loop since the


condition is not checked in advance. The syntax of the do-
1. public class Calculation { while loop is given below.
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub 1. do
4. int i = 0; 2. {
5. System.out.println("Printing the list of first 10 even numbe 3. //statements
rs \n"); 4. } while (condition);
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2; The flow chart of the do-while loop is given in the following
9. } image.
10. }
11. }

Output:

Printing the list of first 10 even numbers

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 26
Printing the list of first 10 even numbers

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
Consider the following example to understand the of the program. There are two types of jump statements in
functioning of the do-while loop in Java. Java, i.e., break and continue.

Calculation.java Java break statement


1. public class Calculation {
As the name suggests, the break statement is used to
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
break the current flow of the program and transfer the
4. int i = 0; control to the next statement outside a loop or switch
5. System.out.println("Printing the list of first 10 even numbe statement. However, it breaks only the inner loop in the
rs \n"); case of the nested loop.
6. do {
7. System.out.println(i); The break statement cannot be used independently in the
8. i = i + 2; Java program, i.e., it can only be written inside the loop or
9. }while(i<=10); switch statement.
10. }
11. } The break statement example with for loop
Output:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 27
Consider the following example in which we have used the 1. public class Calculation {
break statement with the for loop. 2.
3. public static void main(String[] args) {
BreakExample.java 4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
1. public class BreakExample {
7. b:
2.
8. for(int j = 0; j<=15;j++) {
3. public static void main(String[] args) {
9. c:
4. // TODO Auto-generated method stub
10. for (int k = 0; k<=20; k++) {
5. for(int i = 0; i<= 10; i++) {
11. System.out.println(k);
6. System.out.println(i);
12. if(k==5) {
7. if(i==6) {
13. break a;
8. break;
14. }
9. }
15. }
10. }
16. }
11. }
17.
12. }
18. }
19. }
Output: 20.
21.
0 22. }
1
Output:
2
0
3
1
4
2
5
3
6
4

break statement example with labeled for loop 5

Calculation.java

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 28
Java continue statement 5

1
Unlike break statement, the continue statement doesn't
break the loop, whereas, it skips the specific part of the 2
loop and jumps to the next iteration of the loop
immediately. 3

Consider the following example to understand the 5


functioning of the continue statement in Java.
2
1. public class ContinueExample {
2. 3
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub 5
5.
6.
7.
for(int i = 0; i<= 2; i++) {
Java If-else Statement
8. for (int j = i; j<=5; j++) {
9. The Java if statement is used to test the condition. It
10. if(j == 4) { checks boolean condition: true or false. There are various
11. continue; types of if statement in Java.
12. }
13. System.out.println(j); o if statement
14. } o if-else statement
15. } o if-else-if ladder
16. } o nested if statement
17.
18. }
Java if Statement
Output:
The Java if statement tests the condition. It executes the if
0 block if condition is true.

1 Syntax:
2
1. if(condition){
2. //code to be executed
3
3. }

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 29
The Java if-else statement also tests the condition. It
executes the if block if condition is true otherwise else
block is executed.

Syntax:

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

Example:

1. //Java Program to demonstate the use of if statement.


2. public class IfExample {
3. public static void main(String[] args) {
4. //defining an 'age' variable
5. int age=20;
6. //checking the age
7. if(age>18){
8. System.out.print("Age is greater than 18");
9. }
10. }
11. }
Example:
Output:
1. //A Java Program to demonstrate the use of if-else statem
Age is greater than 18 ent.
2. //It is a program of odd and even number.
Java if-else Statement 3. public class IfElseExample {

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 30
4. public static void main(String[] args) {
5. //defining a variable Using Ternary Operator
6. int number=13;
7. //Check if the number is divisible by 2 or not We can also use ternary operator (? :) to perform the task
8. if(number%2==0){ of if...else statement. It is a shorthand way to check the
9. System.out.println("even number"); condition. If the condition is true, the result of ? is returned.
10. }else{ But, if the condition is false, the result of : is returned.
11. System.out.println("odd number");
12. } Example:
13. }
14. }
1. public class IfElseTernaryExample {
2. public static void main(String[] args) {
Output: 3. int number=13;
4. //Using ternary operator
odd number 5. String output=(number%2==0)?"even number":"odd n
umber";
Leap Year Example: 6. System.out.println(output);
7. }
A year is leap, if it is divisible by 4 and 400. But, not by 8. }
100.
Output:
1. public class LeapYearExample {
2. public static void main(String[] args) { odd number
3. int year=2020;
4. if(((year % 4 ==0) && (year % 100 !=0)) || (year % 40
0==0)){ Java if-else-if ladder Statement
5. System.out.println("LEAP YEAR");
6. } The if-else-if ladder statement executes one condition from
7. else{ multiple statements.
8. System.out.println("COMMON YEAR");
9. } Syntax:
10. }
11. } 1. if(condition1){
2. //code to be executed if condition1 is true
Output: 3. }else if(condition2){
4. //code to be executed if condition2 is true
LEAP YEAR 5. }
6. else if(condition3){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 31
7. //code to be executed if condition3 is true 11. System.out.println("D grade");
8. } 12. }
9. ... 13. else if(marks>=60 && marks<70){
10. else{ 14. System.out.println("C grade");
11. //code to be executed if all the conditions are false 15. }
12. } 16. else if(marks>=70 && marks<80){
17. System.out.println("B grade");
18. }
19. else if(marks>=80 && marks<90){
20. System.out.println("A grade");
21. }else if(marks>=90 && marks<100){
22. System.out.println("A+ grade");
23. }else{
24. System.out.println("Invalid!");
25. }
26. }
27. }

Output:

C grade

Program to check POSITIVE, NEGATIVE or ZERO:

1. public class PositiveNegativeExample {


2. public static void main(String[] args) {
Example: 3. int number=-13;
4. if(number>0){
5. System.out.println("POSITIVE");
1. //Java Program to demonstrate the use of If else-if ladder.
6. }else if(number<0){
2. //It is a program of grading system for fail, D grade, C grad
7. System.out.println("NEGATIVE");
e, B grade, A grade and A+.
8. }else{
3. public class IfElseIfExample {
9. System.out.println("ZERO");
4. public static void main(String[] args) {
10. }
5. int marks=65;
11. }
6.
12. }
7. if(marks<50){
8. System.out.println("fail");
9. } Output:
10. else if(marks>=50 && marks<60){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 32
NEGATIVE 1. //Java Program to demonstrate the use of Nested If Statem
ent.
2. public class JavaNestedIfExample {
Java Nested if statement 3. public static void main(String[] args) {
4. //Creating two variables for age and weight
The nested if statement represents the if block within 5. int age=20;
another if block. Here, the inner if block condition executes 6. int weight=80;
only when outer if block condition is true. 7. //applying condition on age and weight
8. if(age>=18){
Syntax: 9. if(weight>50){
10. System.out.println("You are eligible to donate bloo
1. if(condition){ d");
2. //code to be executed 11. }
3. if(condition){ 12. }
4. //code to be executed 13. }}
5. }
6. } Output:

You are eligible to donate blood

Java Switch Statement


The Java switch statement executes one statement from
multiple conditions. It is like if-else-if ladder statement. The
switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int,
and Long. Since Java 7, you can use strings in the switch
statement.

In other words, the switch statement tests the equality of a


variable against multiple values.

Points to Remember
o There can be one or N number of case values for a switch
Example: expression.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 33
o The case value must be of switch expression type only.
The case value must be literal or constant. It doesn't
allow variables.
o The case values must be unique. In case of duplicate
value, it renders compile-time error.
o The Java switch expression must be of byte, short, int,
long (with its Wrapper type), enums and string.
o Each case statement can have a break statement which is
optional. When control reaches to the break statement, it jumps
the control after the switch expression. If a break statement is
not found, it executes the next case.
o The case value can have a default label which is optional.

Syntax:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Example:
Flowchart of Switch Statement
SwitchExample.java

1. public class SwitchExample {


2. public static void main(String[] args) {
3. //Declaring a variable for switch expression
4. int number=20;
5. //Switch expression
6. switch(number){
7. //Case statements
8. case 10: System.out.println("10");

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 34
9. break; 14. }
10. case 20: System.out.println("20"); 15. }
11. break;
12. case 30: System.out.println("30"); Output:
13. break;
14. //Default case statement 20
15. default:System.out.println("Not in 10, 20 or 30");
16. } 30
17. }
18. } Not in 10, 20 or 30

Output:
Java Switch Statement with String
20
Java allows us to use strings in switch expression since Java
SE 7. The case statement should be string literal.
Java Switch Statement is fall-through
Example:
The Java switch statement is fall-through. It means it
executes all statements after the first match if a break SwitchStringExample.java
statement is not present.
1. //Java Program to demonstrate the use of Java Switch
Example: 2. //statement with String
3. public class SwitchStringExample {
SwitchExample2.java 4. public static void main(String[] args) {
5. //Declaring String variable
1. //Java Switch Example where we are omitting the 6. String levelString="Expert";
2. //break statement 7. int level=0;
3. public class SwitchExample2 { 8. //Using String in Switch expression
4. public static void main(String[] args) { 9. switch(levelString){
5. int number=20; 10. //Using String Literal in Switch case
6. //switch expression with int value 11. case "Beginner": level=1;
7. switch(number){ 12. break;
8. //switch cases without break statements 13. case "Intermediate": level=2;
9. case 10: System.out.println("10"); 14. break;
10. case 20: System.out.println("20"); 15. case "Expert": level=3;
11. case 30: System.out.println("30"); 16. break;
12. default:System.out.println("Not in 10, 20 or 30"); 17. default: level=0;
13. } 18. break;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 35
19. } 19. case 'E':
20. System.out.println("Your Level is: "+level); 20. System.out.println("Micro processors, Logic
21. } switching theory");
22. } 21. break;
22. case 'M':
Output: 23. System.out.println("Drawing, Manufacturin
g Machines");
Your Level is: 3 24. break;
25. }
26. break;
Java Nested Switch Statement 27. case 3:
28. switch( branch )
We can use switch statement inside other switch statement 29. {
in Java. It is known as nested switch statement. 30. case 'C':
31. System.out.println("Computer Organization
, MultiMedia");
Example:
32. break;
33. case 'E':
NestedSwitchExample.java 34. System.out.println("Fundamentals of Logic
Design, Microelectronics");
1. //Java Program to demonstrate the use of Java Nested Swit 35. break;
ch 36. case 'M':
2. public class NestedSwitchExample { 37. System.out.println("Internal Combustion E
3. public static void main(String args[]) ngines, Mechanical Vibration");
4. { 38. break;
5. //C - CSE, E - ECE, M - Mechanical 39. }
6. char branch = 'C'; 40. break;
7. int collegeYear = 4; 41. case 4:
8. switch( collegeYear ) 42. switch( branch )
9. { 43. {
10. case 1: 44. case 'C':
11. System.out.println("English, Maths, Science"); 45. System.out.println("Data Communication a
12. break; nd Networks, MultiMedia");
13. case 2: 46. break;
14. switch( branch ) 47. case 'E':
15. { 48. System.out.println("Embedded System, Im
16. case 'C': age Processing");
17. System.out.println("Operating System, Jav 49. break;
a, Data Structure"); 50. case 'M':
18. break;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 36
51. System.out.println("Production Technology 12. case Sun:
, Thermal Engineering"); 13. System.out.println("Sunday");
52. break; 14. break;
53. } 15. case Mon:
54. break; 16. System.out.println("Monday");
55. } 17. break;
56. } 18. case Tue:
57. } 19. System.out.println("Tuesday");
20. break;
Output: 21. case Wed:
22. System.out.println("Wednesday");
Data Communication and Networks, MultiMedia 23. break;
24. case Thu:
25. System.out.println("Thursday");
Java Enum in Switch Statement 26. break;
27. case Fri:
Java allows us to use enum in switch statement. Java enum 28. System.out.println("Friday");
is a class that represent the group of constants. 29. break;
(immutable such as final variables). We use the keyword 30. case Sat:
31. System.out.println("Saturday");
enum and put the constants in curly braces separated by
32. break;
comma. 33. }
34. }
Example: 35. }
36. }
JavaSwitchEnumExample.java
Output:
1. //Java Program to demonstrate the use of Enum
2. //in switch statement Sunday
3. public class JavaSwitchEnumExample {
4. public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sa Monday
t }
5. public static void main(String args[]) Twesday
6. {
7. Day[] DayNow = Day.values(); Wednesday
8. for (Day Now : DayNow)
9. { Thursday
10. switch (Now)
11. { Friday

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 37
Saturday You are eligible for vote.

Java Wrapper in Switch Statement Loops in Java


Java allows us to use four wrapper classes: Byte, Short, The Java for loop is used to iterate a part of the program
Integer and Long in switch statement. several times. If the number of iteration is fixed, it is
recommended to use for loop.
Example:
There are three types of for loops in Java.
WrapperInSwitchCaseExample.java

1. //Java Program to demonstrate the use of Wrapper class


2. //in switch statement o Simple for Loop
3. public class WrapperInSwitchCaseExample { o For-each or Enhanced for Loop
4. public static void main(String args[]) o Labeled for Loop
5. {
6. Integer age = 18;
7. switch (age) Java Simple for Loop
8. {
9. case (16): A simple for loop is the same as C/C++. We can initialize
10. System.out.println("You are under 18."); the variable, check condition and increment/decrement
11. break; value. It consists of four parts:
12. case (18):
13. System.out.println("You are eligible for vote."
1. Initialization: It is the initial condition which is executed
);
once when the loop starts. Here, we can initialize the variable, or
14. break;
we can use an already initialized variable. It is an optional
15. case (65):
condition.
16. System.out.println("You are senior citizen.");
2. Condition: It is the second condition which is executed
17. break;
each time to test the condition of the loop. It continues
18. default:
execution until the condition is false. It must return boolean
19. System.out.println("Please give the valid age.
value either true or false. It is an optional condition.
");
3. Increment/Decrement: It increments or decrements the
20. break;
variable value. It is an optional condition.
21. }
4. Statement: The statement of the loop is executed each
22. }
time until the second condition is false.
23. }
Syntax:
Output:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 38
1. for(initialization; condition; increment/decrement){ Output:
2. //statement or code to be executed
3. } 1

Flowchart: 2

10

Java Nested for Loop


Example:
If we have a for loop inside the another loop, it is known as
ForExample.java nested for loop. The inner loop executes completely
whenever outer loop executes.
1. //Java Program to demonstrate the example of for loop
2. //which prints table of 1
Example:
3. public class ForExample {
4. public static void main(String[] args) {
5. //Code of Java for loop NestedForExample.java
6. for(int i=1;i<=10;i++){
7. System.out.println(i); 1. public class NestedForExample {
8. } 2. public static void main(String[] args) {
9. } 3. //loop of i
10. } 4. for(int i=1;i<=3;i++){
5. //loop of j
6. for(int j=1;j<=3;j++){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 39
7. System.out.println(i+" "+j); 10. }
8. }//end of i
9. }//end of j Output:
10. }
11. } *

Output: **

11 ***

12 ****

13 *****

21 Pyramid Example 2:
22
PyramidExample2.java
23
1. public class PyramidExample2 {
2. public static void main(String[] args) {
31
3. int term=6;
4. for(int i=1;i<=term;i++){
32
5. for(int j=term;j>=i;j--){
6. System.out.print("* ");
33
7. }
8. System.out.println();//new line
Pyramid Example 1: 9. }
10. }
PyramidExample.java 11. }

1. public class PyramidExample { Output:


2. public static void main(String[] args) {
3. for(int i=1;i<=5;i++){ ******
4. for(int j=1;j<=i;j++){
5. System.out.print("* "); *****
6. }
7. System.out.println();//new line ****
8. }
9. } ***

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 40
** 12

* 23

Java for-each Loop 44

56
The for-each loop is used to traverse array or collection in
Java. It is easier to use than simple for loop because we 78
don't need to increment value and use subscript notation.
Java Labeled For Loop
It works on the basis of elements and not the index. It
returns element one by one in the defined variable.
We can have a name of each Java for loop. To do so, we
use label before the for loop. It is useful while using the
Syntax:
nested for loop as we can break/continue specific for loop.
1. for(data_type variable : array_name){
2. //code to be executed Note: The break and continue keywords breaks or continues
3. } the innermost for loop respectively.

Example: Syntax:

1. labelname:
ForEachExample.java
2. for(initialization; condition; increment/decrement){
3. //code to be executed
1. //Java For-each loop example which prints the
4. }
2. //elements of the array
3. public class ForEachExample {
4. public static void main(String[] args) { Example:
5. //Declaring an array
6. int arr[]={12,23,44,56,78}; LabeledForExample.java
7. //Printing array using for-each loop
8. for(int i:arr){ 1. //A Java program to demonstrate the use of labeled for loo
9. System.out.println(i); p
10. } 2. public class LabeledForExample {
11. } 3. public static void main(String[] args) {
12. } 4. //Using Label for outer and for loop
5. aa:
Output: 6. for(int i=1;i<=3;i++){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 41
7. bb: 14. }
8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){ Output:
10. break aa;
11. } 11
12. System.out.println(i+" "+j);
13. } 12
14. }
15. } 13
16. }
21
Output:
31
11
32
12
33
13

21 Java Infinitive for Loop


If you use break bb;, it will break inner loop only which is If you use two semicolons ;; in the for loop, it will be
the default behaviour of any loop. infinitive for loop.

LabeledForExample2.java Syntax:

1. public class LabeledForExample2 { 1. for(;;){


2. public static void main(String[] args) { 2. //code to be executed
3. aa: 3. }
4. for(int i=1;i<=3;i++){
5. bb: Example:
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){ ForExample.java
8. break bb;
9. } 1. //Java program to demonstrate the use of infinite for loop
10. System.out.println(i+" "+j); 2. //which prints an statement
11. } 3. public class ForExample {
12. } 4. public static void main(String[] args) {
13. }

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 42
5. //Using no condition in for loop
programs programs at
6. for(;;){
repeatedly least once
7. System.out.println("infinitive loop");
on the basis and the
8. }
of given further
9. }
boolean execution
10. }
condition. depends
upon the
Output: given
boolean
infinitive loop condition.
infinitive loop When to If the number of If the number If the number
use iteration is fixed, of iteration is of iteration is
infinitive loop it is not fixed, it is not fixed and
recommended to recommende you must
infinitive loop use for loop. d to use have to
while loop. execute the
infinitive loop loop at least
once, it is
ctrl+c recommende
d to use the
Now, you need to press ctrl+c to exit from the program. do-while
loop.
Java for Loop vs while Loop vs do- Syntax for(init;condition;i while(conditi do{
while Loop ncr/decr){
// code to be
on){
//code to be
//code to be
executed
executed executed }while(condit
Compa for loop while do-while } } ion);
rison loop loop Example //for loop //while loop //do-while
for(int int i=1; loop
Introductio The Java for loop The Java The Java do i=1;i<=10;i++){ while(i<=10) int i=1;
n is a control flow while loop is while loop is System.out.printl { do{
statement that a control flow a control flow n(i); System.out.p System.out.p
iterates a part of statement statement } rintln(i); rintln(i);
the programs mul that that i++; i++;
tiple times. executes a executes a } }while(i<=10
part of the part of the

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 43
);
2. Update expression: Every time the loop body is
executed, this expression increments or decrements loop
Syntax for for(;;){ while(true){ do{ variable.
infinitive //code to be //code to be //code to be
loop executed executed executed Example:
} } }while(true);
i++;

Java While Loop Flowchart of Java While Loop

The Java while loop is used to iterate a part of Here, the important thing about while loop is that,
the program repeatedly until the specified Boolean sometimes it may not even execute. If the condition to be
condition is true. As soon as the Boolean condition tested results into false, the loop body is skipped and first
becomes false, the loop automatically stops. statement after the while loop will be executed.

The while loop is considered as a repeating if statement. If


the number of iteration is not fixed, it is recommended to
use the while loop.

Syntax:

1. while (condition){
2. //code to be executed
3. I ncrement / decrement statement
4. }

The different parts of do-while loop:

1. Condition: It is an expression which is tested. If the


condition is true, the loop body is executed and control Example:
goes to update expression. When the condition becomes
false, we exit the while loop. In the below example, we print integer values from 1 to 10.
Unlike the for loop, we separately need to initialize and
Example: increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
i <=100

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 44
WhileExample.java Syntax:

1. public class WhileExample { 1. while(true){


2. public static void main(String[] args) { 2. //code to be executed
3. int i=1; 3. }
4. while(i<=10){
5. System.out.println(i); Example:
6. i++;
7. } WhileExample2.java
8. }
9. }
1. public class WhileExample2 {
2. public static void main(String[] args) {
Output: 3. // setting the infinite while loop by passing true to the con
dition
1 4. while(true){
5. System.out.println("infinitive while loop");
2 6. }
7. }
3 8. }

4
Output:
5
infinitive while loop
6
infinitive while loop
7
infinitive while loop
8
infinitive while loop
9
infinitive while loop
10
ctrl+c

Java Infinitive While Loop In the above code, we need to enter Ctrl + C command to
terminate the infinite loop.
If you pass true in the while loop, it will be infinitive while
loop.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 45
Java do-while Loop Example:

i++;
The Java do-while loop is used to iterate a part of the
program repeatedly, until the specified condition is true. If Note: The do block is executed at least once, even if the
the number of iteration is not fixed and you must have to condition is false.
execute the loop at least once, it is recommended to use a
do-while loop. Flowchart of do-while loop:

Java do-while loop is called an exit control loop.


Therefore, unlike while loop and for loop, 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:

1. do{
2. //code to be executed / loop body
3. //update statement
4. }while (condition);

The different parts of do-while loop: Example:


1. Condition: It is an expression which is tested. If the In the below example, we print integer values from 1 to 10.
condition is true, the loop body is executed and control Unlike the for loop, we separately need to initialize and
goes to update expression. As soon as the condition increment the variable used in the condition (here, i).
becomes false, loop breaks automatically. Otherwise, the loop will execute infinitely.
Example: DoWhileExample.java
i <=100 1. public class DoWhileExample {
2. public static void main(String[] args) {
2. Update expression: Every time the loop body is 3. int i=1;
executed, the this expression increments or decrements 4. do{
loop variable. 5. System.out.println(i);
6. i++;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 46
7. }while(i<=10); DoWhileExample2.java
8. }
9. } 1. public class DoWhileExample2 {
2. public static void main(String[] args) {
Output: 3. do{
4. System.out.println("infinitive do while loop");
1 5. }while(true);
6. }
2 7. }

3 Output:
4 infinitive do while loop

5 infinitive do while loop

6 infinitive do while loop

7 ctrl+c

8
In the above code, we need to enter Ctrl + C command to
9
terminate the infinite loop.

10 Java Break Statement


Java Infinitive do-while Loop When a break statement is encountered inside a loop, the
loop is immediately terminated and the program control
If you pass true in the do-while loop, it will be infinitive do- resumes at the next statement following the loop.
while loop.
The Java break statement is used to break loop
Syntax: or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it
1. do{ breaks only inner loop.
2. //code to be executed
3. }while(true); We can use Java break statement in all types of loops such
as for loop, while loop and do-while loop.
Example:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 47
Syntax: 13. }
14. }
1. jump-statement;
2. break; Output:

Flowchart of Break Statement 1

Java Break Statement with Inner


Loop
It breaks inner loop only if you use break statement inside
the inner loop.
Java Break Statement with Loop
Example:
Example:
BreakExample2.java
BreakExample.java
1. //Java Program to illustrate the use of break statement
1. //Java Program to demonstrate the use of break statement 2. //inside an inner loop
3. public class BreakExample2 {
2. //inside the for loop. 4. public static void main(String[] args) {
3. public class BreakExample { 5. //outer loop
4. public static void main(String[] args) { 6. for(int i=1;i<=3;i++){
5. //using for loop 7. //inner loop
6. for(int i=1;i<=10;i++){ 8. for(int j=1;j<=3;j++){
7. if(i==5){ 9. if(i==2&&j==2){
8. //breaking the loop 10. //using break statement inside the inner
9. break; loop
10. } 11. break;
11. System.out.println(i); 12. }
12. } 13. System.out.println(i+" "+j);

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 48
14. } 6. for(int i=1;i<=3;i++){
15. } 7. bb:
16. } 8. for(int j=1;j<=3;j++){
17. } 9. if(i==2&&j==2){
10. //using break statement with label
Output: 11. break aa;
12. }
11 13. System.out.println(i+" "+j);
14. }
12 15. }
16. }
13 17. }

21 Output:

31 11

32 12

33 13

21
Java Break Statement with Labeled
For Loop Java Break Statement in while loop
We can use break statement with a label. The feature is Example:
introduced since JDK 1.5. So, we can break any loop in Java
now whether it is outer or inner loop. BreakWhileExample.java

Example: 1. //Java Program to demonstrate the use of break statement

BreakExample3.java 2. //inside the while loop.


3. public class BreakWhileExample {
1. //Java Program to illustrate the use of continue statement 4. public static void main(String[] args) {
2. //with label inside an inner loop to break outer loop 5. //while loop
3. public class BreakExample3 { 6. int i=1;
4. public static void main(String[] args) { 7. while(i<=10){
5. aa: 8. if(i==5){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 49
9. //using break statement 10. //using break statement
10. i++; 11. i++;
11. break;//it will break the loop 12. break;//it will break the loop
12. } 13. }
13. System.out.println(i); 14. System.out.println(i);
14. i++; 15. i++;
15. } 16. }while(i<=10);
16. } 17. }
17. } 18. }

Output: Output:

1 1

2 2

3 3

4 4

Java Break Statement in do-while Java Break Statement with Switch


loop To understand the example of break with switch statement,
please visit here: Java Switch Statement.
Example:

BreakDoWhileExample.java Java Continue Statement


1. //Java Program to demonstrate the use of break statement The continue statement is used in loop control structure
when you need to jump to the next iteration of the loop
2. //inside the Java do-while loop.
3. public class BreakDoWhileExample {
immediately. It can be used with for loop or while loop.
4. public static void main(String[] args) {
5. //declaring variable The Java continue statement is used to continue the loop. It
6. int i=1; continues the current flow of the program and skips the
7. //do-while loop remaining code at the specified condition. In case of an
8. do{ inner loop, it continues the inner loop only.
9. if(i==5){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 50
We can use Java continue statement in all types of loops 6
such as for loop, while loop and do-while loop.
7
Syntax:
8
1. jump-statement;
9
2. continue;
10
Java Continue Statement Example
As you can see in the above output, 5 is not printed on the
ContinueExample.java console. It is because the loop is continued when it reaches
to 5.
1. //Java Program to demonstrate the use of continue statem
ent
2. //inside the for loop.
Java Continue Statement with Inner
3. public class ContinueExample { Loop
4. public static void main(String[] args) {
5. //for loop
It continues inner loop only if you use the continue
6. for(int i=1;i<=10;i++){
7. if(i==5){
statement inside the inner loop.
8. //using continue statement
9. continue;//it will skip the rest statement ContinueExample2.java
10. }
11. System.out.println(i); 1. //Java Program to illustrate the use of continue statement
12. } 2. //inside an inner loop
13. } 3. public class ContinueExample2 {
14. } 4. public static void main(String[] args) {
5. //outer loop
Output: 6. for(int i=1;i<=3;i++){
7. //inner loop
1 8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){
2 10. //using continue statement inside inner l
oop
3 11. continue;
12. }
4 13. System.out.println(i+" "+j);
14. }

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 51
15. } 5. aa:
16. } 6. for(int i=1;i<=3;i++){
17. } 7. bb:
8. for(int j=1;j<=3;j++){
Output: 9. if(i==2&&j==2){
10. //using continue statement with label
11 11. continue aa;
12. }
12 13. System.out.println(i+" "+j);
14. }
13 15. }
16. }
21 17. }

23 Output:

31 11

32 12

33 13

21
Java Continue Statement with
Labelled For Loop 31

32
We can use continue statement with a label. This feature is
introduced since JDK 1.5. So, we can continue any loop in 33
Java now whether it is outer loop or inner.

Example: Java Continue Statement in while


loop
ContinueExample3.java
ContinueWhileExample.java
1. //Java Program to illustrate the use of continue statement
2. //with label inside an inner loop to continue outer loop
1. //Java Program to demonstrate the use of continue statem
3. public class ContinueExample3 {
ent
4. public static void main(String[] args) {

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 52
2. //inside the while loop.
3. public class ContinueWhileExample { Java Continue Statement in do-while
4.
5.
public static void main(String[] args) {
//while loop
Loop
6. int i=1;
7. while(i<=10){ ContinueDoWhileExample.java
8. if(i==5){
9. //using continue statement 1. //Java Program to demonstrate the use of continue statem
10. i++; ent
11. continue;//it will skip the rest statement 2. //inside the Java do-while loop.
12. } 3. public class ContinueDoWhileExample {
13. System.out.println(i); 4. public static void main(String[] args) {
14. i++; 5. //declaring variable
15. } 6. int i=1;
16. } 7. //do-while loop
17. } 8. do{
9. if(i==5){
10. //using continue statement
Output:
11. i++;
12. continue;//it will skip the rest statement
1
13. }
14. System.out.println(i);
2
15. i++;
16. }while(i<=10);
3
17. }
18. }
4

6 Output:

7 1

8 2

9 3

10 4

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 53
8 Single line comments starts with two forward slashes (//).
Any text in front of // is not executed by Java.
9
Syntax:
10
1. //This is single line comment
Java Comments Let's use single line comment in a Java program.
The Java comments are the statements in a program that
are not executed by the compiler and interpreter. CommentExample1.java

1. public class CommentExample1 {


Why do we use comments in a code? 2. public static void main(String[] args) {
3. int i=10; // i is a variable with value 10
o Comments are used to make the program more readable 4. System.out.println(i); //printing the variable i
by adding the details of the code. 5. }
o It makes easy to maintain the code and to find the errors 6. }
easily.
o The comments can be used to provide information or Output:
explanation about the variable, method, class, or any statement.
o It can also be used to prevent the execution of program 10
code while testing the alternative code.
2) Java Multi Line Comment
Types of Java Comments
The multi-line comment is used to comment multiple lines
There are three types of comments in Java. of code. It can be used to explain a complex code snippet
or to comment multiple lines of code at a time (as it will be
1. Single Line Comment difficult to use single-line comments there).
2. Multi Line Comment
3. Documentation Comment Multi-line comments are placed between /* and */. Any text
between /* and */ is not executed by Java.
1) Java Single Line Comment
Syntax:
The single-line comment is used to comment only one line
1. /*
of the code. It is the widely used and easiest way of 2. This
commenting the statements. 3. is

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 54
4. multi line To create documentation API, we need to use the javadoc
5. comment tool. The documentation comments are placed between
6. */ /** and */.

Let's use multi-line comment in a Java program. Syntax:

CommentExample2.java /**

1. public class CommentExample2 { *


2. public static void main(String[] args) {
3. /* Let's declare and *We can use various tags to depict the parameter
4. print variable in java. */
5. int i=10; *or heading or author name
6. System.out.println(i);
7. /* float j = 5.9;
*We can also use HTML tags
8. float k = 4.4;
9. System.out.println( j + k ); */
*
10. }
11. }
*/
Output:
javadoc tags
10
Some of the commonly used tags in documentation
Note: Usually // is used for short comments and /* */ is used comments:
for longer comments.

3) Java Documentation Comment Tag Syntax Description

Documentation comments are usually used to write large {@docRo {@docRoot} to depict relative path to root
programs for a project or software application as it helps to ot} directory of generated
create documentation API. These APIs are needed for document from any page.
reference, i.e., which classes, methods, arguments, etc.,
@author @author name To add the author of the class.
are used in the code.
- text

@code {@code text} To show the text in code font

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 55
15. */
without interpreting it as html
16.
markup or nested javadoc tag.
17. public class Calculate{
18. /**
@version @version To specify "Version" subheading
19. * This method calculates the summation of two integer
version-text and version-text when -version
s.
option is used.
20. * @param input1 This is the first parameter to sum() m
ethod
@since @since release To add "Since" heading with
21. * @param input2 This is the second parameter to the s
since text to generated
um() method.
documentation.
22. * @return int This returns the addition of input1 and in
put2
@param @param To add a parameter with given
23. */
parameter- name and description to
24. public int sum(int input1, int input2){
name 'Parameters' section.
25. return input1 + input2;
description
26. }
27. /**
@return @return Required for every method that
28. * This is the main method uses of sum() method.
description returns something (except void)
29. * @param args Unused
30. * @see IOException
Let's use the Javadoc tag in a Java program. 31. */
32. public static void main(String[] args) {
Calculate.java 33. Calculate obj = new Calculate();
34. int result = obj.sum(40, 20);
35.
1. import java.io.*;
36. System.out.println("Addition of numbers: " + result);
2.
37. }
3. /**
38. }
4. * <h2> Calculation of numbers </h2>
5. * This program implements an application
6.
7.
* to perform operation such as addition of numbers
* and print the result
Method in Java
8. * <p>
9. * <b>Note:</b> Comments make the code readable and In general, a method is a way to perform some task.
Similarly, the method in Java is a collection of instructions
10. * easy to understand. that performs a specific task. It provides the reusability of
11. * code. We can also easily modify code using methods. In
12. * @author Anurati this section, we will learn what is a method in Java,
13. * @version 16.0 types of methods, method declaration, and how to
14. * @since 2021-07-06 call a method in Java.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 56
What is a method in Java? Method Signature: Every method has a method
signature. It is a part of the method declaration. It includes
the method name and parameter list.
A method is a block of code or collection of statements or
a set of code grouped together to perform a certain task or Access Specifier: Access specifier or modifier is the
operation. It is used to achieve the reusability of code. access type of the method. It specifies the visibility of the
We write a method once and use it many times. We do not method. Java provides four types of access specifier:
require to write code again and again. It also provides
the easy modification and readability of code, just by o Public: The method is accessible by all classes when we
adding or removing a chunk of code. The method is use public specifier in our application.
executed only when we call or invoke it. o Private: When we use a private access specifier, the
method is accessible only in the classes in which it is defined.
The most important method in Java is the main() method. o Protected: When we use protected access specifier, the
If you want to read more about the main() method, method is accessible within the same package or subclasses in a
different package.
Default: When we do not use any access specifier in the
Method Declaration o
method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
The method declaration provides information about
method attributes, such as visibility, return-type, name, Return Type: Return type is a data type that the method
and arguments. It has six components that are known returns. It may have a primitive data type, object,
as method header, as we have shown in the following collection, void, etc. If the method does not return
figure. anything, we use void keyword.

Method Name: It is a unique name that is used to define


the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a


comma and enclosed in the pair of parentheses. It contains
the data type and variable name. If the method has no
parameter, left the parentheses blank.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 57
Method Body: It is a part of the method declaration. It methods just by calling them in the program at any point.
contains all the actions to be performed. It is enclosed Some pre-defined methods are length(), equals(),
within the pair of curly braces. compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes
Naming a Method related to the corresponding method runs in the
background that is already stored in the library.
While defining a method, remember that the method name Each and every predefined method is defined inside a
must be a verb and start with a lowercase letter. If the class. Such as print() method is defined in
method name has more than two words, the first name the java.io.PrintStream class. It prints the statement that
must be a verb followed by adjective or noun. In the multi- we write inside the method. For example, print("Java"), it
word method name, the first letter of each word must be prints Java on the console.
in uppercase except the first word. For example:
Let's see an example of the predefined method.
Single-word method name: sum(), area()
Demo.java
Multi-word method name: areaOfCircle(),
stringComparision() 1. public class Demo
2. {
It is also possible that a method has the same name as 3. public static void main(String[] args)
another method name in the same class, it is known 4. {
as method overloading. 5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max
(9,7));
Types of Method 7. }
8. }
There are two types of methods in Java:
Output:
o Predefined Method
o User-defined Method The maximum number is: 9

Predefined Method In the above example, we have used three predefined


methods main(), print(), and max(). We have used these
In Java, predefined methods are the method that is already methods directly without declaration because they are
defined in the Java class libraries is known as predefined predefined. The print() method is a method
methods. It is also known as the standard library of PrintStream class that prints the result on the console.
method or built-in method. We can directly use these

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 58
The max() method is a method of the Math class that User-defined Method
returns the greater of two numbers.
The method written by the user or programmer is known
We can also see the method signature of any predefined as a user-defined method. These methods are modified
method by using the link https://docs.oracle.com/. When according to the requirement.
we go through the link and see the max() method
signature, we find the following: How to Create a User-defined Method

Let's create a user defined method that checks the number


is even or odd. First, we will define the method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

We have defined the above method named findevenodd().


It has a parameter num of type int. The method does not
return any value that's why we have used void. The
In the above method signature, we see that the method method body contains the steps to check the number is
signature has access specifier public, non-access even or odd. If the number is even, it prints the number is
modifier static, return type int, method even, else prints the number is odd.
name max(), parameter list (int a, int b). In the above
example, instead of defining the method, we have just How to Call or Invoke a User-defined Method
invoked the method. This is the advantage of a predefined
method. It makes programming less complicated. Once we have defined a method, it should be called. The
calling of a method in a program is simple. When we call or
Similarly, we can also see the method signature of the invoke a user-defined method, the program control transfer
print() method. to the called method.

1. import java.util.Scanner;
2. public class EvenOdd

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 59
3. { 19. System.out.println(num+" is even");
4. public static void main (String args[]) 20. else
5. { 21. System.out.println(num+" is odd");
6. //creating Scanner class object 22. }
7. Scanner scan=new Scanner(System.in); 23. }
8. System.out.print("Enter the number: ");
9. //reading value from the user Output 1:
10. int num=scan.nextInt();
11. //method calling Enter the number: 12
12. findEvenOdd(num);
13. } 12 is even

In the above code snippet, as soon as the compiler reaches Output 2:


at line findEvenOdd(num), the control transfer to the
method and gives the output accordingly. Enter the number: 99

Let's combine both snippets of codes in a single program 99 is odd


and execute it.
Let's see another program that return a value to the calling
EvenOdd.java method.

1. import java.util.Scanner; In the following program, we have defined a method


2. public class EvenOdd named add() that sum up the two numbers. It has two
3. { parameters n1 and n2 of integer type. The values of n1 and
4. public static void main (String args[]) n2 correspond to the value of a and b, respectively.
5. { Therefore, the method adds the value of a and b and store
6. //creating Scanner class object it in the variable s and returns the sum.
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
Addition.java
10. int num=scan.nextInt();
11. //method calling 1. public class Addition
12. findEvenOdd(num); 2. {
13. } 3. public static void main(String[] args)
14. //user defined method 4. {
15. public static void findEvenOdd(int num) 5. int a = 19;
16. { 6. int b = 5;
17. //method body 7. //method calling
18. if(num%2==0) 8. int c = add(a, b); //a and b are actual parameters

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 60
9. System.out.println("The sum of a and b is= " + c); 3. public static void main(String[] args)
10. } 4. {
11. //user defined method 5. show();
12. public static int add(int n1, int n2) //n1 and n2 are for 6. }
mal parameters 7. static void show()
13. { 8. {
14. int s; 9. System.out.println("It is an example of static method.");
15. s=n1+n2; 10. }
16. return s; //returning the sum 11. }
17. }
18. } Output:

Output: It is an example of a static method.

The sum of a and b is= 24


Instance Method
Static Method The method of the class is known as an instance method.
It is a non-static method defined in the class. Before
A method that has static keyword is known as static calling or invoking the instance method, it is necessary to
method. In other words, a method that belongs to a class create an object of its class. Let's see an example of an
rather than an instance of a class is known as a static instance method.
method. We can also create a static method by using the
keyword static before the method name. InstanceMethodExample.java

The main advantage of a static method is that we can call 1. public class InstanceMethodExample
it without creating an object. It can access static data 2. {
members and also change the value of it. It is used to 3. public static void main(String [] args)
create an instance method. It is invoked by using the class 4. {
name. The best example of a static method is 5. //Creating an object of the class
the main() method. 6. InstanceMethodExample obj = new InstanceMethodExam
ple();
7. //invoking instance method
Example of static method 8. System.out.println("The sum is: "+obj.add(12, 13));
9. }
Display.java 10. int s;
11. //user-defined method because we have not used static ke
1. public class Display yword
2. { 12. public int add(int a, int b)

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 61
13. { Example
14. s = a+b;
15. //returning the sum 1. public void setRoll(int roll)
16. return s; 2. {
17. } 3. this.roll = roll;
18. } 4. }

Output: Example of accessor and mutator method


The sum is: 25
Student.java
There are two types of instance method: 1. public class Student
2. {
o Accessor Method 3. private int roll;
o Mutator Method 4. private String name;
5. public int getRoll() //accessor method
Accessor Method: The method(s) that reads the instance 6. {
variable(s) is known as the accessor method. We can easily 7. return roll;
identify it because the method is prefixed with the 8. }
word get. It is also known as getters. It returns the value 9. public void setRoll(int roll) //mutator method
of the private field. It is used to get the value of the private 10. {
field. 11. this.roll = roll;
12. }
13. public String getName()
Example 14. {
15. return name;
1. public int getId() 16. }
2. { 17. public void setName(String name)
3. return Id; 18. {
4. } 19. this.name = name;
20. }
Mutator Method: The method(s) read the instance 21. public void display()
variable(s) and also modify the values. We can easily 22. {
identify it because the method is prefixed with the 23. System.out.println("Roll no.: "+roll);
word set. It is also known as setters or modifiers. It does 24. System.out.println("Student name: "+name);
not return anything. It accepts a parameter of the same 25. }
data type that depends on the field. It is used to set the 26. }
value of the private field.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 62
Abstract Method Output:

Abstract method...
The method that does not has method body is known as
abstract method. In other words, without an
implementation is known as abstract method. It always Factory method
declares in the abstract class. It means the class itself
must be abstract if it has abstract method. To create an It is a method that returns an object to the class to which it
abstract method, we use the keyword abstract. belongs. All static methods are factory methods. For
example, NumberFormat obj =
Syntax NumberFormat.getNumberInstance();

1. abstract void method_name();


Method Overloading in Java
Example of abstract method
If a class has multiple methods having same name but
Demo.java different in parameters, it is known as Method
Overloading.
1. abstract class Demo //abstract class
2. { If we have to perform only one operation, having same
3. //abstract method declaration name of the methods increases the readability of
4. abstract void display(); the program.
5. }
6. public class MyClass extends Demo Suppose you have to perform addition of the given
7. { numbers but there can be any number of arguments, if you
8. //method impelmentation
write the method such as a(int,int) for two parameters, and
9. void display()
10. { b(int,int,int) for three parameters then it may be difficult
11. System.out.println("Abstract method?"); for you as well as other programmers to understand the
12. } behavior of the method because its name differs.
13. public static void main(String args[])
14. { So, we perform method overloading to figure out the
15. //creating object of abstract class program quickly.
16. Demo obj = new MyClass();
17. //invoking abstract method
18. obj.display();
Advantage of method overloading
19. }
20. } Method overloading increases the readability of the
program.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 63
Different ways to overload the method

There are two ways to overload the method in java 2) Method Overloading: changing data
1. By changing number of arguments type of arguments
2. By changing the data type
In this example, we have created two methods that differs
In Java, Method Overloading is not possible by changing the in data type. The first add method receives two integer
return type of the method only. arguments and second add method receives two double
arguments.
1) Method Overloading: changing no.
1. class Adder{
of arguments 2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
In this example, we have created two methods, first add() 4. }
method performs addition of two numbers and second add 5. class TestOverloading2{
method performs addition of three numbers. 6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
In this example, we are creating static methods so that we
9. }}
don't need to create instance for calling methods.

1.
2.
class Adder{
static int add(int a,int b){return a+b;}
Java Math class
3. static int add(int a,int b,int c){return a+b+c;}
4. } Java Math class provides several methods to work on math
5. class TestOverloading1{ calculations like min(), max(), avg(), sin(), cos(), tan(),
6. public static void main(String[] args){ round(), ceil(), floor(), abs() etc.
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11)); Unlike some of the StrictMath class numeric methods, all
9. }} implementations of the equivalent function of Math class
can't define to return the bit-for-bit same results. This
The Program Output: relaxation permits implementation with better-performance
where strict reproducibility is not required.
22
If the size is int or long and the results overflow the range
33
of value, the methods

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 64
addExact(), subtractExact(), multiplyExact(), a number.
and toIntExact() throw an ArithmeticException.
Math.pow() It returns the value of first argument
For other arithmetic operations like increment, decrement, raised to the power to second
divide, absolute value, and negation overflow occur only argument.
with a specific minimum or maximum value. It should be
checked against the maximum and minimum value as Math.signum() It is used to find the sign of a given
appropriate. value.

Math.ceil() It is used to find the smallest integer


Java Math Methods value that is greater than or equal to
the argument or mathematical integer.
The java.lang.Math class contains various methods for
performing basic numeric operations such as the logarithm, Math.copySign() It is used to find the Absolute value of
cube root, and trigonometric functions etc. The various first argument along with sign specified
in second argument.
java math methods are as follows:
Math.nextAfter() It is used to return the floating-point
Basic Math methods number adjacent to the first argument
in the direction of the second argument.

Method Description Math.nextUp() It returns the floating-point value


adjacent to d in the direction of positive
infinity.
Math.abs() It will return the Absolute value of the
given value. Math.nextDown() It returns the floating-point value
adjacent to d in the direction of
Math.max() It returns the Largest of two values. negative infinity.
Math.min() It is used to return the Smallest of two Math.floor() It is used to find the largest integer
values. value which is less than or equal to the
argument and is equal to the
Math.round() It is used to round of the decimal mathematical integer of a double value.
numbers to the nearest value.
Math.floorDiv() It is used to find the largest integer
Math.sqrt() It is used to return the square root of value that is less than or equal to the
a number. algebraic quotient.
Math.cbrt() It is used to return the cube root of

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 65
Math.random() It returns a double value with a positive Math.decrementExa It is used to return the argument
sign, greater than or equal to 0.0 and ct() decremented by one, throwing an
less than 1.0. exception if the result overflows an int
or long.
Math.rint() It returns the double value that is
closest to the given argument and equal Math.negateExact() It is used to return the negation of the
to mathematical integer. argument, throwing an exception if the
result overflows an int or long.
Math.hypot() It returns sqrt(x2 +y2) without
intermediate overflow or underflow. Math.toIntExact() It returns the value of
the long argument, throwing an
Math.ulp() It returns the size of an ulp of the exception if the value overflows an int.
argument.

Math.getExponent() It is used to return the unbiased Logarithmic Math Methods


exponent used in the representation of
a value.
Method Description
Math.IEEEremainde It is used to calculate the remainder
r() operation on two arguments as
prescribed by the IEEE 754 standard Math.log() It returns the natural logarithm of
and returns value. a double value.

Math.addExact() It is used to return the sum of its Math.log10( It is used to return the base 10 logarithm of
arguments, throwing an exception if the ) a double value.
result overflows an int or long.
Math.log1p( It returns the natural logarithm of the sum of
Math.subtractExact( It returns the difference of the ) the argument and 1.
) arguments, throwing an exception if the
result overflows an int. Math.exp() It returns E raised to the power of
a double value, where E is Euler's number and it
Math.multiplyExact( It is used to return the product of the is approximately equal to 2.71828.
) arguments, throwing an exception if the
result overflows an int or long. Math.expm It is used to calculate the power of E and
1() subtract one from it.
Math.incrementExa It returns the argument incremented by
ct() one, throwing an exception if the result
overflows an int. Trigonometric Math Methods

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 66
Metho Description Angular Math Methods
d
Method Description
Math.sin() It is used to return the trigonometric Sine value of
a Given double value.
Math.toDegre It is used to convert the specified Radians
Math.cos( It is used to return the trigonometric Cosine value es angle to equivalent angle measured in
) of a Given double value. Degrees.

Math.tan( It is used to return the trigonometric Tangent Math.toRadia It is used to convert the specified Degrees
) value of a Given double value. ns angle to equivalent angle measured in
Radians.
Math.asin It is used to return the trigonometric Arc Sine
() value of a Given double value
Java Arrays
Math.acos It is used to return the trigonometric Arc Cosine
() value of a Given double value.
Normally, an array is a collection of similar type of
Math.atan It is used to return the trigonometric Arc Tangent
elements which has contiguous memory location.
() value of a Given double value.
Java array is an object which contains elements of a
similar data type. Additionally, the elements of an array are
Hyperbolic Math Methods 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.
Method Description
Array in Java is index-based, the first element of the array
Math.sinh() is value
It is used to return the trigonometric Hyperbolic Cosine storedof at the 0th
a Given index, 2nd element is stored on 1st
double
value. index and so on.

Math.cosh( Unlike
It is used to return the trigonometric Hyperbolic Sine value C/C++,
of a Given we can
double get the length of the array using the
value.
) length member. In C/C++, we need to use the sizeof
operator.
Math.tanh( It is used to return the trigonometric Hyperbolic Tangent value of a Given double
) value. 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

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 67
primitive values or objects in an array in Java. Like C/C++, o Multidimensional Array
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++.
Single Dimensional Array in Java
Syntax to Declare an Array in Java

1. dataType[] arr; (or)


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

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];
Advantages
o Code Optimization: It makes the code optimized, we Example of Java Array
can retrieve or sort the data efficiently.
o Random access: We can get any data located at an Let's see the simple example of java array, where we are
index position. going to declare, instantiate, initialize and traverse an
array.
Disadvantages
1. //Java Program to illustrate how to declare, instantiate, init
ialize
o Size Limit: We can store only the fixed size of elements
2. //and traverse the Java array.
in the array. It doesn't grow its size at runtime. To solve this 3. class Testarray{
problem, collection framework is used in Java which grows 4. public static void main(String args[]){
automatically. 5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
Types of Array in java 9.
10.
a[3]=40;
a[4]=50;
11. //traversing array
There are two types of array. 12. for(int i=0;i<a.length;i++)//length is the property of arra
y
o Single Dimensional Array 13. System.out.println(a[i]);

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 68
14. }} 8. System.out.println(a[i]);
9. }}
Output:
Output:
10
33
20
3
70
4
40
5
50

For-each Loop for Java Array


We can also print the Java array using for-each loop. The
Declaration, Instantiation and Java for-each loop prints the array elements one by one. It
Initialization of Java Array holds an array element in a variable, then executes the
body of the loop.
We can declare, instantiate and initialize the java array
The syntax of the for-each loop is given below:
together by:
1. for(data_type variable:array){
1. int a[]={33,3,4,5};//declaration, instantiation and initializ 2. //body of the loop
ation 3. }

Let's see the simple example to print this array. Let us see the example of print the elements of Java array
using the for-each loop.
1. //Java Program to illustrate the use of declaration, instanti
ation
1. //Java Program to print the array elements using for-each l
2. //and initialization of Java array in a single line
oop
3. class Testarray1{
2. class Testarray1{
4. public static void main(String args[]){
3. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initializ
4. int arr[]={33,3,4,5};
ation
5. //printing array using for-each loop
6. //printing array
6. for(int i:arr)
7. for(int i=0;i<a.length;i++)//length is the property of arra
7. System.out.println(i);
y

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 69
8. }} 15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
Output: 17. }}

33 Output:

3 3

4
Anonymous Array in Java
5
Java supports the feature of an anonymous array, so you
don't need to declare the array while passing an array to
the method.
Passing Array to a Method in Java 1. //Java Program to demonstrate the way of passing an ano
nymous array
We can pass the java array to method so that we can reuse 2. //to method.
the same logic on any array. 3. public class TestAnonymousArray{
4. //creating a method which receives an array as a paramet
Let's see the simple example to get the minimum number er
of an array using a method. 5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
1. //Java Program to demonstrate the way of passing an arra
8. }
y
9.
2. //to method.
10. public static void main(String args[]){
3. class Testarray2{
11. printArray(new int[]{10,22,44,66});//passing anonymous
4. //creating a method which receives an array as a paramet
array to method
er
12. }}
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++) Output:
8. if(min>arr[i])
9. min=arr[i]; 10
10.
11. System.out.println(min); 22
12. }
13. 44
14. public static void main(String args[]){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 70
66 negative, equal to the array size or greater than the array
size while traversing the array.
Returning Array from the Method 1. //Java Program to demonstrate the case of
2. //ArrayIndexOutOfBoundsException in a Java Array.
We can also return an array from the method in Java. 3. public class TestArrayException{
4. public static void main(String args[]){
1. //Java Program to return an array from the method 5. int arr[]={50,60,70,80};
2. class TestReturnArray{ 6. for(int i=0;i<=arr.length;i++){
3. //creating method which returns an array 7. System.out.println(arr[i]);
4. static int[] get(){ 8. }
5. return new int[]{10,30,50,90,60}; 9. }}
6. }
7.
Output:
8. public static void main(String args[]){
9. //calling method which returns an array
Exception in thread "main"
10. int arr[]=get(); java.lang.ArrayIndexOutOfBoundsException: 4
11. //printing the values of an array
12. for(int i=0;i<arr.length;i++) at TestArrayException.main(TestArrayException.java:5)
13. System.out.println(arr[i]);
14. }} 50

Output: 60

10 70

30 80

50

90
Multidimensional Array in Java
60
In such case, data is stored in row and column based index
ArrayIndexOutOfBoundsException (also known as matrix form).

The Java Virtual Machine (JVM) throws an Syntax to Declare Multidimensional Array in Java
ArrayIndexOutOfBoundsException if length of the array in

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 71
1. dataType[][] arrayRefVar; (or) 9. System.out.print(arr[i][j]+" ");
2. dataType [][]arrayRefVar; (or) 10. }
3. dataType arrayRefVar[][]; (or) 11. System.out.println();
4. dataType []arrayRefVar[]; 12. }
13. }}
Example to instantiate Multidimensional Array in
Java Output:

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

Example to initialize Multidimensional Array in Java 245

445
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3; Jagged Array in Java
4. arr[1][0]=4;
5. arr[1][1]=5;
If we are creating odd number of columns in a 2D array, it
6. arr[1][2]=6;
7. arr[2][0]=7; is known as a jagged array. In other words, it is an array of
8. arr[2][1]=8; arrays with different number of columns.
9. arr[2][2]=9;
1. //Java Program to illustrate the jagged array
2. class TestJaggedArray{
Example of Multidimensional Java 3. public static void main(String[] args){
Array 4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
Let's see the simple example to declare, instantiate,
7. arr[1] = new int[4];
initialize and print the 2Dimensional array.
8. arr[2] = new int[2];
9. //initializing a jagged array
1. //Java Program to illustrate the use of multidimensional arr 10. int count = 0;
ay 11. for (int i=0; i<arr.length; i++)
2. class Testarray3{ 12. for(int j=0; j<arr[i].length; j++)
3. public static void main(String args[]){ 13. arr[i][j] = count++;
4. //declaring and initializing 2D array 14.
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 15. //printing the data of a jagged array
6. //printing 2D array 16. for (int i=0; i<arr.length; i++){
7. for(int i=0;i<3;i++){ 17. for (int j=0; j<arr[i].length; j++){
8. for(int j=0;j<3;j++){ 18. System.out.print(arr[i][j]+" ");

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 72
19. }
20. System.out.println();//new line Copying a Java Array
21. }
22. } We can copy an array to another by the arraycopy()
23. } method of System class.

Output: Syntax of arraycopy method

012 1. public static void arraycopy(


2. Object src, int srcPos,Object dest, int destPos, int length
3456 3. )

78
Example of Copying an Array in Java
1. //Java Program to copy a source array into a destination ar
ray in Java
What is the class name of Java array? 2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
In Java, an array is an object. For array object, a proxy 4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
class is created whose name can be obtained by
6. 'i', 'n', 'a', 't', 'e', 'd' };
getClass().getName() method on the object. 7. //declaring a destination array
8. char[] copyTo = new char[7];
1. //Java Program to get the class name of array in Java 9. //copying array using System.arraycopy() method
2. class Testarray4{ 10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
3. public static void main(String args[]){ 11. //printing the destination array
4. //declaration and initialization of array 12. System.out.println(String.valueOf(copyTo));
5. int arr[]={4,4,5}; 13. }
6. //getting the class name of Java array 14. }
7. Class c=arr.getClass();
8. String name=c.getName();
An entity that has state and behavior is known as an object
9. //printing the class name of Java array
10. System.out.println(name);
e.g., chair, bike, marker, pen, table, car, etc. It can be
11. physical or logical (tangible and intangible). The example
12. }} of an intangible object is the banking system.

Output: An object has three characteristics:

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

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 73
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.

For Example, Pen is an object. Its name is Reynolds; color


is white, known as its state. It is used to write, so writing is
its behavior.

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.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 74
The class in Java Syntax to declare a class:

1. class <class_name>{
A class is a group of objects which have common 2. field;
properties. It is a template or blueprint from which objects 3. method;
are created. It is a logical entity. It can't be physical. 4. }

A class in Java can contain:

 Fields
 Methods Instance variable in Java
 Constructors
 Blocks A variable which is created inside the class but outside the
 Nested class and interface method is known as an instance variable. Instance variable
doesn't get memory at compile time. It gets memory at
runtime when an object or instance is created. That is why
it is known as an instance variable.

Method in Java
In Java, a method is like a function which is used to expose
the behavior of an object.

Advantage of Method
o Code Reusability
o Code Optimization

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 75
15. }
new keyword in Java
Output:
The new keyword is used to allocate memory at runtime.
All objects get memory in Heap memory area. 0

null

Object and Class Example: main Object and Class Example: main
within the class outside the class
In this example, we have created a Student class which has In real time development, we create classes and use it
two data members id and name. We are creating the object from another class. It is a better approach than previous
of the Student class by new keyword and printing the one. Let's see a simple example, where we are having
object's value. main() method in another class.

Here, we are creating a main() method inside the class. We can have multiple classes in different Java files or single
Java file. If you define multiple classes in a single Java
File: Student.java source file, it is a good idea to save the file name with the
class name which has main() method.
1. //Java Program to illustrate how to define a class and fields
File: TestStudent1.java
2. //Defining a Student class.
3. class Student{ 1. //Java Program to demonstrate having the main method in
4. //defining fields
5. int id;//field or data member or instance variable 2. //another class
6. String name; 3. //Creating Student class.
7. //creating main method inside the Student class 4. class Student{
8. public static void main(String args[]){ 5. int id;
9. //Creating an object or instance 6. String name;
10. Student s1=new Student();//creating an object of Studen 7. }
t 8. //Creating another class TestStudent1 which contains the
11. //Printing values of the object main method
12. System.out.println(s1.id);//accessing member through ref 9. class TestStudent1{
erence variable 10. public static void main(String args[]){
13. System.out.println(s1.name); 11. Student s1=new Student();
14. } 12. System.out.println(s1.id);

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 76
13. System.out.println(s1.name); 10. System.out.println(s1.id+" "+s1.name);//printing membe
14. } rs with a white space
15. } 11. }
12. }
Output:
Output:
0
101 Sonoo
null
We can also create multiple objects and store information
3 Ways to initialize object in it through reference variable.

File: TestStudent3.java
There are 3 ways to initialize object in Java.
1. class Student{
1. By reference variable 2. int id;
2. By method 3. String name;
3. By constructor 4. }
5. class TestStudent3{
1) Object and Class Example: 6. public static void main(String args[]){
7. //Creating objects
Initialization through reference 8. Student s1=new Student();
9. Student s2=new Student();
Initializing an object means storing data into the object. 10. //Initializing objects
Let's see a simple example where we are going to initialize 11. s1.id=101;
the object through a reference variable. 12. s1.name="Sonoo";
13. s2.id=102;
File: TestStudent2.java 14. s2.name="Amit";
15. //Printing data
1. class Student{ 16. System.out.println(s1.id+" "+s1.name);
2. int id; 17. System.out.println(s2.id+" "+s2.name);
3. String name; 18. }
4. } 19. }
5. class TestStudent2{
6. public static void main(String args[]){ Output:
7. Student s1=new Student();
8. s1.id=101; 101 Sonoo
9. s1.name="Sonoo";
102 Amit

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 77
2) Object and Class Example:
Initialization through method
In this example, we are creating the two objects of Student
class and initializing the value to these objects by invoking
the insertRecord method. Here, we are displaying the state
(data) of the objects by invoking the displayInformation()
method.

File: TestStudent4.java

1. class Student{
2. int rollno; As you can see in the above figure, object gets the memory
3. String name;
in heap memory area. The reference variable refers to the
4. void insertRecord(int r, String n){
5. rollno=r; object allocated in the heap memory area. Here, s1 and s2
6. name=n; both are reference variables that refer to the objects
7. } allocated in memory.
8. void displayInformation(){System.out.println(rollno+"
"+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
3) Object and Class Example:
12. Student s1=new Student(); Initialization through a constructor
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation(); Object and Class Example: Employee
18. }
19. } Let's see an example where we are maintaining records of
employees.
Output:
File: TestEmployee.java
111 Karan
1. class Employee{
222 Aryan 2. int id;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 78
3. String name; 1. class Rectangle{
4. float salary; 2. int length;
5. void insert(int i, String n, float s) { 3. int width;
6. id=i; 4. void insert(int l, int w){
7. name=n; 5. length=l;
8. salary=s; 6. width=w;
9. } 7. }
10. void display(){System.out.println(id+" "+name+" 8. void calculateArea(){System.out.println(length*width);}
"+salary);} 9. }
11. } 10. class TestRectangle1{
12. public class TestEmployee { 11. public static void main(String args[]){
13. public static void main(String[] args) { 12. Rectangle r1=new Rectangle();
14. Employee e1=new Employee(); 13. Rectangle r2=new Rectangle();
15. Employee e2=new Employee(); 14. r1.insert(11,5);
16. Employee e3=new Employee(); 15. r2.insert(3,15);
17. e1.insert(101,"ajeet",45000); 16. r1.calculateArea();
18. e2.insert(102,"irfan",25000); 17. r2.calculateArea();
19. e3.insert(103,"nakul",55000); 18. }
20. e1.display(); 19. }
21. e2.display();
22. e3.display(); Output:
23. }
24. } 55

Output: 45

101 ajeet 45000.0


What are the different ways to create
102 irfan 25000.0
an object in Java?
103 nakul 55000.0
There are many ways to create an object in java. They are:
Object and Class Example: Rectangle o By new keyword
o By newInstance() method
There is given another example that maintains the records o By clone() method
of Rectangle class. o By deserialization
o By factory method etc.
File: TestRectangle1.java

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 79
We will learn these ways to create object later. Output:

Anonymous object Factorial is 120

Anonymous simply means nameless. An object which has Creating multiple objects by one
no reference is known as an anonymous object. It can be type only
used at the time of object creation only.
We can create multiple objects by one type only as we do
If you have to use an object only once, an anonymous in case of primitives.
object is a good approach. For example:
Initialization of primitive variables:
1. new Calculation();//anonymous object
1. int a=10, b=20;
Calling method through a reference:
Initialization of refernce variables:
1. Calculation c=new Calculation();
2. c.fact(5);
1. Rectangle r1=new Rectangle(), r2=new Rectangle();//
creating two objects
Calling method through an anonymous object
Let's see the example:
1. new Calculation().fact(5);
1. //Java Program to illustrate the use of Rectangle class whic
Let's see the full example of an anonymous object in Java. h
2. //has length and width data members
1. class Calculation{ 3. class Rectangle{
2. void fact(int n){ 4. int length;
3. int fact=1; 5. int width;
4. for(int i=1;i<=n;i++){ 6. void insert(int l,int w){
5. fact=fact*i; 7. length=l;
6. } 8. width=w;
7. System.out.println("factorial is "+fact); 9. }
8. } 10. void calculateArea(){System.out.println(length*width);}
9. public static void main(String args[]){ 11. }
10. new Calculation().fact(5);//calling method with anonymou 12. class TestRectangle2{
s object 13. public static void main(String args[]){
11. } 14. Rectangle r1=new Rectangle(),r2=new Rectangle();//
12. } creating two objects

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 80
15. r1.insert(11,5); creates a default constructor if your class doesn't have
16. r2.insert(3,15); any.
17. r1.calculateArea();
18. r2.calculateArea();
19. } Rules for creating Java constructor
20. }
There are two rules defined for the constructor.
Output:
1. Constructor name must be the same as its class name
55 2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
45 synchronized

Note: We can use access modifiers while declaring a


Constructors in Java constructor. It controls the object creation. In other words, we
can have private, protected, public or default constructor in
In Java, a constructor is a block of codes similar to the Java.
method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the Types of Java constructors
object is allocated in the memory.
There are two types of constructors in Java:
It is a special type of method which is used to initialize the
object. 1. Default constructor (no-arg constructor)
2. Parameterized constructor
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.

There are two types of constructors in Java: no-arg


constructor, and parameterized constructor.

Note: It is called constructor because it constructs the


values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 81
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }

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.
Java Default Constructor
A constructor is called "Default Constructor" when it
Example of parameterized constructor
doesn't have any parameter.
In this example, we have created the constructor of
Student class that have two parameters. We can have any
The default constructor is used to provide the default
number of parameters in the constructor.
values to the object like 0, null, etc., depending on the
type.
1. //Java Program to demonstrate the use of the parame
terized constructor.
Syntax of default constructor: 2. class Student4{
3. int id;
1. <class_name>(){}
4. String name;
5. //creating a parameterized constructor
Example of default constructor 6. Student4(int i,String n){
7. id = i;
1. //Java Program to create and call a default constructor 8. name = n;
2. class Bike1{ 9. }
3. //creating a default constructor 10. //method to display the values

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 82
11. void display(){System.out.println(id+" "+name);} 3. int id;
12. 4. String name;
13. public static void main(String args[]){ 5. int age;
14. //creating objects and passing values 6. //creating two arg constructor
15. Student4 s1 = new Student4(111,"Karan"); 7. Student5(int i,String n){
16. Student4 s2 = new Student4(222,"Aryan"); 8. id = i;
17. //calling method to display the values of object 9. name = n;
18. s1.display(); 10. }
19. s2.display(); 11. //creating three arg constructor
20. } 12. Student5(int i,String n,int a){
21. } 13. id = i;
14. name = n;
Output 15. age=a;
16. }
111 Karan 17. void display(){System.out.println(id+" "+name+"
"+age);}
222 Aryan 18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
Constructor Overloading in Java 22.
23.
s1.display();
s2.display();
24. }
In Java, a constructor is just like a method but without 25. }
return type. It can also be overloaded like Java methods.
26. Output:
27. 111 Karan 0
Constructor overloading in Java is a technique of having
28. 222 Aryan 25
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 Difference between constructor and
the number of parameters in the list and their types.
method in Java
Example of Constructor Overloading There are many differences between constructors and
methods. They are given below.
1. //Java program to overload constructors
2. class Student5{

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 83
Java Constructor Java Method

A constructor is used to initialize A method is used to


the state of an object. expose the behavior
of an object.

A constructor must not have a A method must have


return type. a return type.

The constructor is invoked The method is


implicitly. invoked explicitly.

The Java compiler provides a The method is not


default constructor if you don't provided by the
have any constructor in a class. compiler in any case.

The constructor name must be The method name


same as the class name. may or may not be
same as the class
name.

Java String
In Java, string is basically an object that represents
sequence of char values. An array of characters works
same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform


operations on strings such as compare(), concat(), equals(),

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 84
split(), length(), replace(), compareTo(), intern(),
substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence in
terfaces.

The Java String is immutable which means it cannot be


changed. Whenever we change any string, a new instance
is created. For mutable strings, you can use StringBuffer
and StringBuilder classes.

We will discuss immutable string later. Let's first


understand what String in Java is and how to create the
CharSequence Interface String object.

The CharSequence interface is used to represent the What is String in Java?


sequence of characters.
String, StringBuffer and StringBuilder classes implement it. Generally, String is a sequence of characters. But in Java,
It means, we can create strings in Java by using these string is an object that represents a sequence of
three classes. characters. The java.lang.String class is used to create a
string object.

How to create a string object?


There are two ways to create String object:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 85
1. By string literal "Welcome" in the pool, it will not create a new object but
2. By new keyword will return the reference to the same instance.

1) String Literal Note: String objects are stored in a special memory area
known as the "string constant pool".
Java String literal is created by using double quotes. For
Example: Why Java uses the concept of String
literal?
1. String s="welcome";
To make Java more memory efficient (because no new
Each time you create a string literal, the JVM checks the objects are created if it exists already in the string constant
"string constant pool" first. If the string already exists in pool).
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: 2) By new keyword
1. String s1="Welcome"; 1. String s=new String("Welcome");//creates two objects an
2. String s2="Welcome";//It doesn't create a new instance d one reference variable

In such case, JVM will create a new string object in normal


(non-pool) heap memory, and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer
to the object in a heap (non-pool).

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
In the above example, only one object will be created. 5. String s2=new String(ch);//converting char array to string
Firstly, JVM will not find any string object with the value
6. String s3=new String("example");//creating Java string by
"Welcome" in string constant pool that is why it will create
new keyword
a new object. After that it will find the string with the value

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 86
7. System.out.println(s1);
8. System.out.println(s2); format(Locale l, String string with given locale.
9. System.out.println(s3); format, Object... args)
10. }}
5 String substring(int It returns substring for
Output: beginIndex) given begin index.

java 6 String substring(int It returns substring for


beginIndex, int given begin index and
strings endIndex) end index.

example 7 boolean It returns true or false


contains(CharSequence after matching the
The above code, converts a char array into s) sequence of char value.
a String object. And displays the String objects s1, s2,
and s3 on console using println() method. 8 static String It returns a joined string.
join(CharSequence
delimiter,
Java String class methods CharSequence...
elements)
The java.lang.String class provides many useful methods to
perform operations on sequence of char values. 9 static String It returns a joined string.
join(CharSequence
delimiter, Iterable<?
No Method Description
extends
.
CharSequence>
elements)
1 char charAt(int index) It returns char value for
the particular index 10 boolean equals(Object It checks the equality of
another) string with the given
2 int length() It returns string length object.
3 static String It returns a formatted 11 boolean isEmpty() It checks if string is
format(String format, string. empty.
Object... args)
12 String concat(String str) It concatenates the
4 static String It returns formatted specified string.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 87
13 String replace(char old, It replaces all 23 String toLowerCase() It returns a string in
char new) occurrences of the lowercase.
specified char value.
24 String It returns a string in
14 String It replaces all toLowerCase(Locale l) lowercase using
replace(CharSequence occurrences of the specified locale.
old, CharSequence new) specified CharSequence.
25 String toUpperCase() It returns a string in
15 static String It compares another uppercase.
equalsIgnoreCase(String string. It doesn't check
another) case. 26 String It returns a string in
toUpperCase(Locale l) uppercase using
16 String[] split(String It returns a split string specified locale.
regex) matching regex.
27 String trim() It removes beginning
17 String[] split(String It returns a split string and ending spaces of
regex, int limit) matching regex and this string.
limit.
28 static String valueOf(int It converts given type
18 String intern() It returns an interned value) into string. It is an
string. overloaded method.

19 int indexOf(int ch) It returns the specified


char value index. Java StringBuffer Class
20 int indexOf(int ch, int It returns the specified
fromIndex) char value index Java StringBuffer class is used to create mutable
starting with given (modifiable) String objects. The StringBuffer class in Java is
index. the same as String class except it is mutable i.e. it can be
changed.
21 int indexOf(String It returns the specified
substring) substring index. Note: Java StringBuffer class is thread-safe i.e. multiple
threads cannot access it simultaneously. So it is safe and will
22 int indexOf(String It returns the specified result in an order.
substring, int substring index starting
fromIndex) with given index.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 88
Important Constructors of synchroniz String s) specified string with this
ed string at the specified
StringBuffer Class StringBuffe position. The insert() method
r is overloaded like insert(int,
char), insert(int, boolean),
Constructo Description insert(int, int), insert(int,
r float), insert(int, double) etc.

StringBuffer() It creates an empty String buffer with the public replace(int It is used to replace the string
initial capacity of 16. synchroniz startIndex, int from specified startIndex and
ed endIndex, endIndex.
StringBuffer(Stri It creates a String buffer with the specified StringBuffe String str)
ng str) string.. r

StringBuffer(int It creates an empty String buffer with the public delete(int It is used to delete the string
capacity) specified capacity as length. synchroniz startIndex, int from specified startIndex and
ed endIndex) endIndex.
StringBuffe
r
Important methods of
StringBuffer class public
synchroniz
reverse() is used to reverse the string.

ed
StringBuffe
Modifie Method Description r
r and
Type public int capacity() It is used to return the current
capacity.
public append(String It is used to append the
synchroniz s) specified string with this public void ensureCapacity( It is used to ensure the
ed string. The append() method int capacity at least equal to the
StringBuffe is overloaded like minimumCapaci given minimum.
r append(char), ty)
append(boolean), append(int),
append(float), append(double) public char charAt(int It is used to return the
etc. index) character at the specified
position.
public insert(int offset, It is used to insert the

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 89
public int length() It is used to return the length 2) StringBuffer insert() Method
of the string i.e. total number
of characters. The insert() method inserts the given String with this string
at the given position.
public substring(int It is used to return the
String beginIndex) substring from the specified StringBufferExample2.java
beginIndex.
1. class StringBufferExample2{
public substring(int It is used to return the
2. public static void main(String args[]){
String beginIndex, int substring from the specified
3. StringBuffer sb=new StringBuffer("Hello ");
endIndex) beginIndex and endIndex.
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
What is a mutable String? 7. }

A String that can be modified or changed is known as Output:


mutable String. StringBuffer and StringBuilder classes are
used for creating mutable strings. HJavaello

1) StringBuffer Class append() Method 3) StringBuffer replace() Method


The append() method concatenates the given argument The replace() method replaces the given String from the
with this String. specified beginIndex and endIndex.

StringBufferExample.java StringBufferExample3.java

1. class StringBufferExample{ 1. class StringBufferExample3{


2. public static void main(String args[]){ 2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello "); 3. StringBuffer sb=new StringBuffer("Hello");
4. sb.append("Java");//now original string is changed 4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints Hello Java 5. System.out.println(sb);//prints HJavalo
6. } 6. }
7. } 7. }

Output: Output:

Hello Java HJavalo

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 90
4) StringBuffer delete() Method 6) StringBuffer capacity() Method
The delete() method of the StringBuffer class deletes the The capacity() method of the StringBuffer class returns the
String from the specified beginIndex to endIndex. current capacity of the buffer. The default capacity of the
buffer is 16. If the number of character increases from its
StringBufferExample4.java current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is
1. class StringBufferExample4{ 16, it will be (16*2)+2=34.
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello"); StringBufferExample6.java
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo 1. class StringBufferExample6{
6. } 2. public static void main(String args[]){
7. } 3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
Output: 5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
Hlo 7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34
5) StringBuffer reverse() Method 9. i.e (oldcapacity*2)+2
10. }
11. }
The reverse() method of the StringBuilder class reverses
the current String.
Output:
StringBufferExample5.java 16

1. class StringBufferExample5{ 16
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello"); 34
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. } 7) StringBuffer ensureCapacity()
7. } method
Output: The ensureCapacity() method of the StringBuffer class
ensures that the given capacity is the minimum to the
olleH
current capacity. If it is greater than the current capacity, it

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 91
increases the capacity by (oldcapacity*2)+2. For example
if your current capacity is 16, it will be (16*2)+2=34. Java File Class
StringBufferExample7.java The File class is an abstract representation of file and
directory pathname. A pathname can be either absolute or
1. class StringBufferExample7{ relative.
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer(); The File class have several methods for working with
4. System.out.println(sb.capacity());//default 16 directories and files such as creating new directories or
5. sb.append("Hello"); files, deleting and renaming directories or files, listing the
6. System.out.println(sb.capacity());//now 16
contents of a directory etc.
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (
oldcapacity*2)+2 Fields
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2 Modifi Typ Field Description
12. System.out.println(sb.capacity());//now 70 er e
13. }
14. }
static String pathSeparator It is system-
dependent path-
Output: separator character,
represented as
16 a string for
convenience.
16
static char pathSeparatorC It is system-
34 har dependent path-
separator character.
34
static String separator It is system-
70 dependent default
name-separator
character,
represented as a
string for
convenience.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 92
static char separatorChar It is system- suffix) directory, using the given
dependent default prefix and suffix to generate
name-separator its name.
character.
boolean createNewFile() It atomically creates a new,
empty file named by this
Constructors abstract pathname if and
only if a file with this name
does not yet exist.
Constructor Description
boolean canWrite() It tests whether the
File(File parent, It creates a new File instance from a application can modify the
String child) parent abstract pathname and a child file denoted by this abstract
pathname string. pathname.String[]

File(String It creates a new File instance by boolean canExecute() It tests whether the
pathname) converting the given pathname string into application can execute the
an abstract pathname. file denoted by this abstract
pathname.
File(String parent, It creates a new File instance from a
String child) parent pathname string and a child boolean canRead() It tests whether the
pathname string. application can read the file
denoted by this abstract
File(URI uri) It creates a new File instance by pathname.
converting the given file: URI into an
abstract pathname. boolean isAbsolute() It tests whether this
abstract pathname is
absolute.
Useful Methods
boolean isDirectory() It tests whether the file
denoted by this abstract
pathname is a directory.
Modifie Method Description
r and boolean isFile() It tests whether the file
Type denoted by this abstract
pathname is a normal file.
static File createTempFile(St It creates an empty file in
ring prefix, String the default temporary-file String getName() It returns the name of the

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 93
file or directory denoted by
this abstract pathname.
this keyword in Java
String getParent() It returns the pathname There can be a lot of usage of Java this keyword. In Java,
string of this abstract this is a reference variable that refers to the current
pathname's parent, or null if object.
this pathname does not
name a parent directory.

Path toPath() It returns a java.nio.file.Path


object constructed from the
this abstract path.

URI toURI() It constructs a file: URI that


represents this abstract
pathname.

File[] listFiles() It returns an array of


abstract pathnames
denoting the files in the Usage of Java this keyword
directory denoted by this
abstract pathname Here is given the 6 usage of java this keyword.
long getFreeSpace() It returns the number of
1. this can be used to refer current class instance variable.
unallocated bytes in the
2. this can be used to invoke current class method
partition named by this
(implicitly)
abstract path name.
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
String[] list(FilenameFilter It returns an array of strings
5. this can be passed as argument in the constructor call.
filter) naming the files and
6. this can be used to return the current class instance from
directories in the directory
the method.
denoted by this abstract
pathname that satisfy the
specified filter. Suggestion: If you are beginner to java, lookup only three
usages of this keyword.
boolean mkdir() It creates the directory
named by this abstract
pathname.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 94
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+"
"+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}

-* * * * * * * *-

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

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword


by the example given below:

1. class Student{
2. int rollno;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 95

You might also like