0% found this document useful (0 votes)
12 views25 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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views25 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 PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT 1 class Simple{ Standalone applications are also known as desktop applications or It is a Java programming platform.

alone applications are also known as desktop applications or It is a Java programming platform. It includes Java programming
window-based applications. These are traditional software that we APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math
public static void main(String args[]){ need to install on every machine. Examples of standalone etc. It includes core topics like OOPs, String, Regex, Exception, Inner
Introduction to Java: Basics of Java programming, Data
application are Media player, antivirus, etc. AWT and Swing are used classes, Multithreading, I/O Stream, Networking, AWT, Swing,
types, Variables, Operators, Control structures including System.out.println("Hello Java"); in Java for creating standalone applications. Reflection, Collection, etc.
selection, Looping, Java methods, Overloading, Math
class, Arrays in java. } 2) Web Application 2) Java EE (Java Enterprise Edition)

Objects and Classes: Basics of objects and classes in java, } An application that runs on the server side and creates a dynamic It is an enterprise platform that is mainly used to develop web and
Constructors, Finalizer, Visibility modifiers, Methods and page is called a web application. enterprise applications. It is built on top of the Java SE platform. It
objects, Inbuilt classes like String, Character, String Buffer, Application Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
technologies are used for creating web applications in Java.
File, this reference.
According to Sun, 3 billion devices run Java. There are many devices 3) Java ME (Java Micro Edition)
where Java is currently used. Some of them are as follows: 3) Enterprise Application
What is Java? It is a micro platform that is dedicated to mobile applications.
1. Desktop Applications such as acrobat reader, media player, An application that is distributed in nature, such as banking
Java is a programming language and a platform. Java is a high antivirus, etc. applications, etc. is called an enterprise application. It has 4) JavaFX
level, robust, object-oriented and secure programming language. 2. Web Applications such as irctc.co.in, javatpoint.com, etc. advantages like high-level security, load balancing, and clustering.
3. Enterprise Applications such as banking applications. In Java, EJB is used for creating enterprise applications. It is used to develop rich internet applications. It uses a lightweight
Java was developed by Sun Microsystems (which is now the 4. Mobile user interface API.
subsidiary of Oracle) in the year 1995. James Gosling is known as the 5. Embedded System 4) Mobile Application
father of Java. Before Java, its name was Oak. Since Oak was already 6. Smart Card Features of Java
a registered company, so James Gosling and his team changed the 7. Robotics An application which is created for mobile devices is called a mobile
name from Oak to Java. 8. Games, etc. application. Currently, Android and Java ME are used for creating The primary objective of Java programming language creation was
mobile applications. to make it portable, simple and secure programming language. Apart
Platform: Any hardware or software environment in which a
Types of Java Applications from this, there are also some excellent features which play an
program runs, is known as a platform. Since Java has a runtime Java Platforms / Editions important role in the popularity of this language. The features of Java
environment (JRE) and API, it is called a platform. are also known as Java buzzwords.
There are mainly 4 types of applications that can be created using
Java programming: There are 4 platforms or editions of Java:
Java Example A list of the most important features of the Java language is given
1) Standalone Application 1) Java SE (Java Standard Edition) below.
Simple.java

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 1 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 platform is the hardware or software environment in which a program • Bytecode Verifier: It checks the code fragments for illegal
2. Object-Oriented simplifies software development and maintenance by providing runs. code that can violate access rights to objects.
3. Portable some rules. • Security Manager: It determines what resources a class can
4. Platform independent There are two types of platforms software-based and hardware- access such as reading and writing to the local disk.
5. Secured Basic concepts of OOPs are: based. Java provides a software-based platform.
6. Robust Java language provides these securities by default. Some security can
7. Architecture neutral 1. Object The Java platform differs from most other platforms in the sense that also be provided by an application developer explicitly through SSL,
8. Interpreted 2. Class it is a software-based platform that runs on top of other hardware- JAAS, Cryptography, etc.
9. High Performance based platforms. It has two components:
3. Inheritance
10. Multithreaded
4. Polymorphism Robust
1. Runtime Environment
11. Distributed
5. Abstraction 2. API(Application Programming Interface)
The English mining of Robust is strong. Java is robust because:
12. Dynamic
6. Encapsulation
Java code can be executed on multiple platforms, for example,
• It uses strong memory management.
Simple Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by
Platform Independent • There is a lack of pointers that avoids security problems.
the compiler and converted into bytecode. This bytecode is a • Java provides automatic garbage collection which runs on the Java
Java is very easy to learn, and its syntax is simple, clean and easy to platform-independent code because it can be run on multiple Virtual Machine to get rid of objects which are not being used by a Java
understand. According to Sun Microsystem, Java language is a simple platforms, i.e., Write Once and Run Anywhere (WORA). application anymore.
programming language because: • There are exception handling and the type checking mechanism in

• Java syntax is based on C++ (so easier for programmers to


Secured Java. All these points make Java robust.

learn it after C++).


Java is best known for its security. With Java, we can develop virus- Architecture-neutral
• Java has removed many complicated and rarely-used features,
free systems. Java is secured because:
for example, explicit pointers, operator overloading, etc.
Java is architecture neutral because there are no implementation
• There is no need to remove unreferenced objects because • No explicit pointer dependent features, for example, the size of primitive types is fixed.
there is an Automatic Garbage Collection in Java. • Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime In C programming, int data type occupies 2 bytes of memory for 32-
Object-Oriented Environment (JRE) which is used to load Java classes into the Java bit architecture and 4 bytes of memory for 64-bit architecture.
Java is platform independent because it is different from other Virtual Machine dynamically. It adds security by separating the However, it occupies 4 bytes of memory for both 32 and 64-bit
Java is an object-oriented programming language. Everything in Java languages like C, C++, etc. which are compiled into platform specific package for the classes of the local file system from those that are architectures in Java.
is an object. Object-oriented means we organize our software as a machines while Java is a write once, run anywhere language. A imported from network sources.
combination of different types of objects that incorporate both data
and behavior.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 3 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 4
Portable Dynamic To execute: java Simple require creating an object to invoke the main() method. So, it saves
memory.
Java is portable because it facilitates you to carry the Java bytecode Java is a dynamic language. It supports the dynamic loading of Output: • void is the return type of the method. It means it doesn't
to any platform. It doesn't require any implementation. classes. It means classes are loaded on demand. It also supports return any value.
functions from its native languages, i.e., C and C++. Hello Java • main represents the starting point of the program.
• String[] args or String args[] is used for command line
High-performance
Java supports dynamic compilation and automatic memory Compilation Flow: argument. We will discuss it in coming section.
Java is faster than other traditional interpreted programming management (garbage collection). • System.out.println() is used to print statement. Here, System
When we compile Java program using javac tool, the Java compiler is a class, out is an object of the PrintStream class, println() is a
languages because Java bytecode is "close" to native code. It is still a
converts the source code into byte code. method of the PrintStream class. We will discuss the internal working
little bit slower than a compiled language (e.g., C++). Java is an First Java Program | Hello World Example
interpreted language that is why it is slower than compiled of System.out.println() statement in the coming section.
languages, e.g., C, C++, etc. o Create the Java program
o Compile and run the Java program Java Variables
Distributed
A variable is a container which holds the value while the Java
Java is distributed because it facilitates users to create distributed program is executed. A variable is assigned with a data type.
applications in Java. RMI and EJB are used for creating distributed Creating Hello World Example
applications. This feature of Java makes us able to access files by Variable is a name of memory location. There are three types of
Let's create the hello java program: variables in java: local, instance and static.
calling the methods from any machine on the internet. Parameters used in First Java Program
class Simple{ There are two types of data types in Java: primitive and non-primitive.
The meaning of class, public, static, void, main, String[],
public static void main(String args[]){ System.out.println().
Multi-threaded
System.out.println("Hello Java"); • class keyword is used to declare a class in Java.
A thread is like a separate program, executing concurrently. We can • public keyword is an access modifier that represents visibility. Variable
write Java programs that deal with many tasks at once by defining } It means it is visible to all.
multiple threads. The main advantage of multi-threading is that it • static is a keyword. If we declare any method as static, it is A variable is the name of a reserved area allocated in memory. In
doesn't occupy memory for each thread. It shares a common memory } other words, it is a name of the memory location. It is a combination
known as the static method. The core advantage of the static method
area. Threads are important for multi-media, Web applications, etc. is that there is no need to create an object to invoke the static of "vary + able" which means its value can be changed.
Save the above file as Simple.java.
method. The main() method is executed by the JVM, so it doesn't
int data=50;//Here data is variable
To compile: javac Simple.java

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

Example to understand the types of variables public static void main(String[] args){ Output:
Types of Variables
in java int a=10; 10
There are three types of variables in Java:
public class A int b=10; 10.0
1. local variable
2. instance variable { int c=a+b;
3. static variable Java Variable Example: Narrowing
static int m=100;//static variable System.out.println(c); (Typecasting)
1) Local Variable
void method() } public class Simple{
A variable declared inside the body of the method is called local
variable. You can use this variable only within that method and the { } public static void main(String[] args){
other methods in the class aren't even aware that the variable exists.
int n=90;//local variable Output: float f=10.5f;
A local variable cannot be defined with "static" keyword.
} 20 //int a=f;//Compile time error
2) Instance Variable
public static void main(String args[])
Java Variable Example: Widening int a=(int)f;
A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static. {
public class Simple{ System.out.println(f);

It is called an instance variable because its value is instance-specific int data=50;//instance variable
public static void main(String[] args){ System.out.println(a);
and is not shared among instances.
}
int a=10; }}
3) Static variable
}//end of class
float f=a; Output:
A variable that is declared as static is called a static variable. It cannot
be local. You can create a single copy of the static variable and share Java Variable Example: Add Two System.out.println(a); 10.5
it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Numbers System.out.println(f); 10

public class Simple{


}}

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 7 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 8
byte b=10; Java is a statically-typed programming language. It means,
Java Variable Example: Overflow all variables must be declared before its use. That is why we need to
char '\u0000' 2 byte
//byte c=a+b;//Compile Time Error: because a+b=20 will be int declare variable's type and name.
class Simple{ byte 0 1 byte
byte c=(byte)(a+b); There are 8 types of primitive data types:
public static void main(String[] args){ short 0 2 byte
System.out.println(c); • boolean data type
//Overflow int 0 4 byte
• byte data type
}} • char data type
int a=130; long 0L 8 byte
• short data type
Output: • int data type
byte b=(byte)a;
• long data type float 0.0f 4 byte
20 • float data type
System.out.println(a);
• double data type double 0.0d 8 byte
System.out.println(b); Data Types in Java
}} Data types specify the different sizes and values that can be stored in
Boolean Data Type
the variable. There are two types of data types in Java:
The Boolean data type is used to store only two possible values: true
Output:
and false. This data type is used for simple flags that track true/false
1. Primitive data types: The primitive data types include boolean,
130 char, byte, short, int, long, float and double. conditions.
2. Non-primitive data types: The non-primitive data types
-126 include Classes, Interfaces, and Arrays. The Boolean data type specifies one bit of information, but its "size"
can't be defined precisely.

Java Variable Example: Adding Lower Java Primitive Data Types Example:
Type In Java language, primitive data types are the building blocks of data 1. Boolean one = false
manipulation. These are the most basic data types available in Java
class Simple{ language.
Data Type Default Value Default size Byte Data Type
public static void main(String[] args){
boolean false 1 bit The byte data type is an example of primitive data type. It isan 8-bit
byte a=10; signed two's complement integer. Its value-range lies between -128

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

to 127 (inclusive). Its minimum value is -128 and maximum value is The int data type is generally used as a default data type for integral
127. Its default value is 0. values unless if there is no problem about memory.
Double Data Type Operators in Java
The double data type is a double-precision 64-bit IEEE 754 floating Operator in Java is a symbol that is used to perform operations. For
The byte data type is used to save memory in large arrays where the Example:
point. Its value range is unlimited. The double data type is generally example: +, -, *, / etc.
memory savings is most required. It saves space because a byte is 4
1. int a = 100000, int b = -200000 used for decimal values just like float. The double data type also
times smaller than an integer. It can also be used in place of "int" data
should never be used for precise values, such as currency. Its default There are many types of operators in Java which are given below:
type.
value is 0.0d.
Long Data Type • Unary Operator,
Example:
Example: • Arithmetic Operator,
The long data type is a 64-bit two's complement integer. Its value-
1. byte a = 10, byte b = -20 • Shift Operator,
range lies between -9,223,372,036,854,775,808(-2^63) to 1. double d1 = 12.3 • Relational Operator,
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is
• Bitwise Operator,
Short Data Type - 9,223,372,036,854,775,808and maximum value is

9,223,372,036,854,775,807. Its default value is 0. The long data type
Char Data Type Logical Operator,
• Ternary Operator and
The short data type is a 16-bit signed two's complement integer. Its is used when you need a range of values more than those provided
The char data type is a single 16-bit Unicode character. Its value- • Assignment Operator.
value-range lies between -32,768 to 32,767 (inclusive). Its minimum by int.
value is -32,768 and maximum value is 32,767. Its default value is 0. range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The
Example: char data type is used to store characters. Java Operator Precedence
The short data type can also be used to save memory just like byte
data type. A short data type is 2 times smaller than an integer. 1. long a = 100000L, long b = -200000L Example:
Operator Category Precedence
Example: 1. char letterA = 'A' Type
Float Data Type
1. short s = 10000, short r = -5000 Why char uses 2 byte in java and what is \u0000 Unary postfix expr++ expr--
The float data type is a single-precision 32-bit IEEE 754 floating
point.Its value range is unlimited. It is recommended to use a float ? prefix ++expr --expr +expr -expr ~ !
int Data Type (instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for It is because java uses Unicode system not ASCII code system. The Arithmetic multiplicative */%
The int data type is a 32-bit signed two's complement integer. Its precise values, such as currency. Its default value is 0.0F. \u0000 is the lowest range of Unicode system. To get detail
value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 explanation about Unicode visit next page. additive +-
(2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and Example:
maximum value is 2,147,483,647. Its default value is 0. Shift shift << >> >>>
1. float f1 = 234.5f

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 11 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 12
22
Relational comparison < > <= >= instanceof Java Unary Operator Example: ++ and -- Java Arithmetic Operators
21
equality == != 1. public class OperatorExample{ Java arithmetic operators are used to perform addition, subtraction,
2. public static void main(String args[]){ multiplication, and division. They act as basic mathematical
Bitwise bitwise AND & Java Unary Operator Example: ~ and !
3. int x=10; operations.
4. System.out.println(x++);//10 (11) 1. public class OperatorExample{
bitwise exclusive ^
OR
5. System.out.println(++x);//12 2. public static void main(String args[]){ Java Arithmetic Operator Example
6. System.out.println(x--);//12 (11) 3. int a=10;
bitwise inclusive | 7. System.out.println(--x);//10 4. int b=-10; 1. public class OperatorExample{
8. }} 5. boolean c=true; 2. public static void main(String args[]){
OR
6. boolean d=false; 3. int a=10;
Output: 7. System.out.println(~a);//- 4. int b=5;
Logical logical AND &&
11 (minus of total positive value which starts from 0) 5. System.out.println(a+b);//15
logical OR || 10 8. System.out.println(~b);//9 (positive of total minus, positive starts fr 6. System.out.println(a-b);//5
om 0) 7. System.out.println(a*b);//50
Ternary ternary ?: 12 9. System.out.println(!c);//false (opposite of boolean value) 8. System.out.println(a/b);//2
10. System.out.println(!d);//true 9. System.out.println(a%b);//0
12 11. }} 10. }}
Assignment assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>= 10
Output: Output:

Java Unary Operator Java Unary Operator Example 2: ++ and -- -11 15

1. public class OperatorExample{ 9 5


The Java unary operators require only one operand. Unary operators
are used to perform various operations i.e.: 2. public static void main(String args[]){
false 50
3. int a=10;
• incrementing/decrementing a value by one 4. int b=10;
true 2
5. System.out.println(a++ + ++a);//10+12=22
• negating an expression
6. System.out.println(b++ + b++);//10+11=21
• inverting the value of a boolean 0
7.
8. }}
Java Arithmetic Operator Example: Expression
Output:
1. public class OperatorExample{

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

2. public static void main(String args[]){ Java Right Shift Operator Output: Java AND Operator Example: Logical && vs
3. System.out.println(10*10/5+3-1*4/2);
4. }} 5 Bitwise &
The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand. 5 1. public class OperatorExample{
Output:
2. public static void main(String args[]){
21 Java Right Shift Operator Example -5 3. int a=10;
4. int b=5;
1073741819
Java Left Shift Operator 1. public OperatorExample{ 5. int c=20;
2. public static void main(String args[]){ 6. System.out.println(a<b&&a++<c);//false && true = false
The Java left shift operator << is used to shift all of the bits in a value 3. System.out.println(10>>2);//10/2^2=10/4=2 Java AND Operator Example: Logical && and 7. System.out.println(a);//10 because second condition is not checked
4. System.out.println(20>>2);//20/2^2=20/4=5 Bitwise &
to the left side of a specified number of times.
5. System.out.println(20>>3);//20/2^3=20/8=2 8. System.out.println(a<b&a++<c);//false && true = false
6. }} 9. System.out.println(a);//11 because second condition is checked
Java Left Shift Operator Example The logical && operator doesn't check the second condition if the
10. }}
first condition is false. It checks the second condition only if the first
Output:
1. public class OperatorExample{ one is true. Output:
2. public static void main(String args[]){ 2
3. System.out.println(10<<2);//10*2^2=10*4=40 The bitwise & operator always checks both conditions whether first false
4. System.out.println(10<<3);//10*2^3=10*8=80 5 condition is true or false.
5. System.out.println(20<<2);//20*2^2=20*4=80 10
6. System.out.println(15<<4);//15*2^4=15*16=240 2 1. public class OperatorExample{
7. }} 2. public static void main(String args[]){ false

Java Shift Operator Example: >> vs >>> 3. int a=10;


11
Output: 4. int b=5;
5. int c=20;
1. public class OperatorExample{
40 2. public static void main(String args[]){
6. System.out.println(a<b&&a<c);//false && true = false Java OR Operator Example: Logical || and
7. System.out.println(a<b&a<c);//false & true = false
80
3. //For positive number, >> and >>> works same
8. }}
Bitwise |
4. System.out.println(20>>2);
5. System.out.println(20>>>2); The logical || operator doesn't check the second condition if the first
80 Output:
6. //For negative number, >>> changes parity bit (MSB) to 0 condition is true. It checks the second condition only if the first one
7. System.out.println(-20>>2);
240 false is false.
8. System.out.println(-20>>>2);
9. }}
false

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 15 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 16
The bitwise | operator always checks both conditions whether first Java Ternary Operator 6. b-=4;//b=b-4 (b=20-4) Java Assignment Operator Example: Adding
condition is true or false. 7. System.out.println(a);
8. System.out.println(b); short
Java Ternary operator is used as one line replacement for if-then-else
1. public class OperatorExample{ 9. }}
statement and used a lot in Java programming. It is the only 1. public class OperatorExample{
2. public static void main(String args[]){
conditional operator which takes three operands. Output: 2. public static void main(String args[]){
3. int a=10;
4. int b=5; 3. short a=10;
5. int c=20; Java Ternary Operator Example 14 4. short b=10;
6. System.out.println(a>b||a<c);//true || true = true 5. //a+=b;//a=a+b internally so fine
7. System.out.println(a>b|a<c);//true | true = true 1. public class OperatorExample{ 16 6. a=a+b;//Compile time error because 10+10=20 now int
8. //|| vs | 2. public static void main(String args[]){ 7. System.out.println(a);
9. System.out.println(a>b||a++<c);//true || true = true 3. int a=2; Java Assignment Operator Example 8. }}
10. System.out.println(a);//10 because second condition is not checked 4. int b=5;
5. int min=(a<b)?a:b; 1. public class OperatorExample{ Output:
11. System.out.println(a>b|a++<c);//true | true = true 6. System.out.println(min); 2. public static void main(String[] args){
12. System.out.println(a);//11 because second condition is checked 7. }} Compile time error
3. int a=10;
13. }} 4. a+=3;//10+3
Output: 5. System.out.println(a); After type cast:
Output: 6. a-=4;//13-4
2 7. System.out.println(a); 1. public class OperatorExample{
true 8. a*=2;//9*2 2. public static void main(String args[]){
3. short a=10;
Java Assignment Operator 9. System.out.println(a);
4. short b=10;
true 10. a/=2;//18/2
11. System.out.println(a); 5. a=(short)(a+b);//20 which is int now converted to short
true Java assignment operator is one of the most common operators. It is 6. System.out.println(a);
used to assign the value on its right to the operand on its left. 12. }}
7. }}
10
Output:
Java Assignment Operator Example Output:
true
13
1. public class OperatorExample{ 20
11
2. public static void main(String args[]){ 9
3. int a=10;
4. int b=20; 18
5. a+=4;//a=a+4 (a=10+4)
9

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

class: Java class keyword is used to declare a class. for: Java for keyword is used to start a for loop. It is used to execute a set private: Java private keyword is an access modifier. It is used to indicate
Java Keywords of instructions/functions repeatedly when some condition becomes true. If that a method or variable may be accessed only in the class in which it is
continue: Java continue keyword is used to continue the loop. It continues the number of iteration is fixed, it is recommended to use for loop. declared.
Java keywords are also known as reserved words. Keywords are the current flow of the program and skips the remaining code at the
particular words that act as a key to a code. These are predefined specified condition. if: Java if keyword tests the condition. It executes the if block if the protected: Java protected keyword is an access modifier. It can be
words by Java so they cannot be used as a variable or object name condition is true. accessible within the package and outside the package but through
or class name. default: Java default keyword is used to specify the default block of code inheritance only. It can't be applied with the class.
in a switch statement. implements: Java implements keyword is used to implement an interface.
public: Java public keyword is an access modifier. It is used to indicate that
List of Java Keywords do: Java do keyword is used in the control statement to declare a loop. It import: Java import keyword makes classes and interfaces available and an item is accessible anywhere. It has the widest scope among all other
can iterate a part of the program several times. accessible to the current source code. modifiers.
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- instanceof: Java instanceof keyword is used to test whether the object is return: Java return keyword is used to return from a method when its
abstract: Java abstract keyword is used to declare an abstract class. An bit floating-point number. an instance of the specified class or implements an interface. execution is complete.
abstract class can provide the implementation of the interface. It can have
abstract and non-abstract methods. else: Java else keyword is used to indicate the alternative branches in an if int: Java int keyword is used to declare a variable that can hold a 32-bit short: Java short keyword is used to declare a variable that can hold a 16-
statement. signed integer. bit integer.
boolean: Java boolean keyword is used to declare a variable as a boolean
type. It can hold True and False values only. enum: Java enum keyword is used to define a fixed set of constants. Enum interface: Java interface keyword is used to declare an interface. It can have static: Java static keyword is used to indicate that a variable or method is a
constructors are always private or default. only abstract methods. class method. The static keyword in Java is mainly used for memory
break: Java break keyword is used to break the loop or switch statement. It management.
breaks the current flow of the program at specified conditions. extends: Java extends keyword is used to indicate that a class is derived long: Java long keyword is used to declare a variable that can hold a 64-bit
from another class or interface. integer. strictfp: Java strictfp is used to restrict the floating-point calculations to
byte: Java byte keyword is used to declare a variable that can hold 8-bit ensure portability.
data values. final: Java final keyword is used to indicate that a variable holds a constant native: Java native keyword is used to specify that a method is
value. It is used with a variable. It is used to restrict the user from updating implemented in native code using JNI (Java Native Interface). super: Java super keyword is a reference variable that is used to refer to
case: Java case keyword is used with the switch statements to mark blocks the value of the variable. parent class objects. It can be used to invoke the immediate parent class
of text. new: Java new keyword is used to create new objects. method.
finally: Java finally keyword indicates a block of code in a try-catch
catch: Java catch keyword is used to catch the exceptions generated by try structure. This block is always executed whether an exception is handled or null: Java null keyword is used to indicate that a reference does not refer switch: The Java switch keyword contains a switch statement that executes
statements. It must be used after the try block only. not. to anything. It removes the garbage value. code based on test value. The switch statement tests the equality of a
variable against multiple values.
char: Java char keyword is used to declare a variable that can hold unsigned float: Java float keyword is used to declare a variable that can hold a 32-bit package: Java package keyword is used to declare a Java package that
16-bit Unicode characters floating-point number. includes the classes. 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 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 20
this: Java this keyword can be used to refer the current object in a method It is one of the fundamental features of Java, which provides a smooth 1. Simple if statement 9. }
or constructor. flow of program. 2. if-else statement
3. if-else-if ladder Output:
throw: The Java throw keyword is used to explicitly throw an exception. The Java provides three types of control flow statements. 4. Nested if-statement
throw keyword is mainly used to throw custom exceptions. It is followed by x + y is greater than 20
an instance. 1. Decision Making statements Let's understand the if-statements one by one.
o if statements 2) if-else statement
throws: The Java throws keyword is used to declare an exception. Checked o switch statement 1) Simple if statement:
exceptions can be propagated with throws. 2. Loop statements The if-else statement is an extension to the if-statement, which uses
o do while loop It is the most basic statement among all control flow statements in another block of code, i.e., else block. The else block is executed if
transient: Java transient keyword is used in serialization. If you define any while loop
o Java. It evaluates a Boolean expression and enables the program to the condition of the if-block is evaluated as false.
data member as transient, it will not be serialized. o for loop enter a block of code if the expression evaluates to true.
o for-each loop Syntax:
try: Java try keyword is used to start a block of code that will be tested for 3. Jump statements
exceptions. The try block must be followed by either catch or finally block.
Syntax of if statement is given below.
o break statement 1. if(condition) {
o continue statement 1. if(condition) { 2. statement 1; //executes when condition is true
void: Java void keyword is used to specify that a method does not have a
2. statement 1; //executes when condition is true 3. }
return value.
Decision-Making statements: 3. } 4. else{
5. statement 2; //executes when condition is false
volatile: Java volatile keyword is used to indicate that a variable may
As the name suggests, decision-making statements decide which Consider the following example in which we have used 6. }
change asynchronously.
statement to execute and when. Decision-making statements the if statement in the java code.
while: Java while keyword is used to start a while loop. This loop iterates a
Consider the following example.
evaluate the Boolean expression and control the program flow
part of the program several times. If the number of iteration is not fixed, it depending upon the result of the condition provided. There are two Student.java
is recommended to use the while loop. Student.java
types of decision-making statements in Java, i.e., If statement and
Student.java
switch statement. 1. public class Student {
Java Control Statements | Control Flow in 1. public class Student { 2. public static void main(String[] args) {
Java 1) If Statement: 2. public static void main(String[] args) { 3. int x = 10;
3. int x = 10; 4. int y = 12;
In Java, the "if" statement is used to evaluate a condition. The control 4. int y = 12; 5. if(x+y < 10) {
Java compiler executes the code from top to bottom. The statements 6. System.out.println("x + y is less than 10");
of the program is diverted depending upon the specific condition. 5. if(x+y > 20) {
in the code are executed according to the order in which they appear. 7. } else {
The condition of the If statement gives a Boolean value, either true 6. System.out.println("x + y is greater than 20");
However, Java provides statements that can be used to control the 8. System.out.println("x + y is greater than 20");
or false. In Java, there are four types of if-statements given below. 7. }
flow of Java code. Such statements are called control flow statements. 8. } 9. }

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

10. } 4. if(city == "Meerut") { Student.java o The case variables can be int, short, byte, char, or enumeration.
11. } 5. System.out.println("city is meerut"); String type is also supported since version 7 of Java
6. }else if (city == "Noida") { 1. public class Student { o Cases cannot be duplicate
Output: 7. System.out.println("city is noida"); 2. public static void main(String[] args) { o Default statement is executed when any of the case doesn't match
8. }else if(city == "Agra") { 3. String address = "Delhi, India"; the value of expression. It is optional.
x + y is greater than 20 9. System.out.println("city is agra"); 4. o Break statement terminates the switch block when the condition is
10. }else { 5. if(address.endsWith("India")) { satisfied.
3) if-else-if ladder: 11. System.out.println(city); 6. if(address.contains("Meerut")) { It is optional, if not used, next case is executed.
12. } 7. System.out.println("Your city is Meerut"); o While using switch statements, we must notice that the case
The if-else-if statement contains the if-statement followed by 13. } 8. }else if(address.contains("Noida")) { expression will be of the same type as the variable. However, it will also be
multiple else-if statements. In other words, we can say that it is the 14. } 9. System.out.println("Your city is Noida"); a constant value.
chain of if-else statements that create a decision tree where the 10. }else {
program may enter in the block of code where the condition is true. Output: 11. System.out.println(address.split(",")[0]); The syntax to use the switch statement is given below.
12. }
We can also define an else statement at the end of the chain.
Delhi 13. }else { 1. switch (expression){
14. System.out.println("You are not living in India"); 2. case value1:
Syntax of if-else-if statement is given below.
4. Nested if-statement 15. } 3. statement1;
16. } 4. break;
1. if(condition 1) {
In nested if-statements, the if statement can contain a if or if- 17. } 5. .
2. statement 1; //executes when condition 1 is true
else statement inside another if or else-if statement. 6. .
3. }
Output: 7. .
4. else if(condition 2) {
Syntax of Nested if-statement is given below. 8. case valueN:
5. statement 2; //executes when condition 2 is true
Delhi 9. statementN;
6. }
1. if(condition 1) { 10. break;
7. else {
2. statement 1; //executes when condition 1 is true Switch Statement: 11. default:
8. statement 2; //executes when all the conditions are false
3. if(condition 2) { 12. default statement;
9. }
4. statement 2; //executes when condition 2 is true 13. }
In Java, Switch statements are similar to if-else-if statements. The
Consider the following example. 5. } switch statement contains multiple blocks of code called cases and a
6. else{ Consider the following example to understand the flow of the switch
single case is executed based on the variable which is being switched.
7. statement 2; //executes when condition 2 is false statement.
Student.java The switch statement is easier to use instead of if-else-if statements.
8. }
It also enhances the readability of the program. Student.java
1. public class Student { 9. }
2. public static void main(String[] args) { Points to be noted about switch statement:
3. String city = "Delhi"; Consider the following example. 1. public class Student implements Cloneable {

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 23 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 24
2. public static void main(String[] args) { In Java, we have three types of loops that execute similarly. However, Consider the following example to understand the proper Calculation.java
3. int num = 2; there are differences in their syntax and condition checking time. functioning of the for loop in java.
4. switch (num){ 1. public class Calculation {
5. case 0: 1. for loop Calculation.java 2. public static void main(String[] args) {
6. System.out.println("number is 0"); 2. while loop 3. // TODO Auto-generated method stub
7. break; 3. do-while loop 1. public class Calculattion { 4. String[] names = {"Java","C","C++","Python","JavaScript"};
8. case 1: 2. public static void main(String[] args) { 5. System.out.println("Printing the content of the array names:\n");
9. System.out.println("number is 1"); Let's understand the loop statements one by one. 3. // TODO Auto-generated method stub 6. for(String name:names) {
10. break; 4. int sum = 0; 7. System.out.println(name);
11. default: 5. for(int j = 1; j<=10; j++) { 8. }
12. System.out.println(num);
Java for loop 9. }
6. sum = sum + j;
13. } 7. } 10. }
14. } In Java, for loop is similar to C and C++. It enables us to initialize the
8. System.out.println("The sum of first 10 natural numbers is " + sum)
15. } loop variable, check the condition, and increment/decrement in a Output:
;
single line of code. We use the for loop only when we exactly know 9. }
Output: the number of times, we want to execute the block of code. 10. } Printing the content of the array names:

2 1. for(initialization, condition, increment/decrement) { Output: Java


2. //block of statements
While using switch statements, we must notice that the case 3. } C
The sum of first 10 natural numbers is 55
expression will be of the same type as the variable. However, it will
The flow chart for the for-loop is given below. C++
also be a constant value. The switch permits only int, string, and Enum Java for-each loop
type variables to be used. Python
Java provides an enhanced for loop to traverse the data structures
Loop Statements like array or collection. In the for-each loop, we don't need to update JavaScript

the loop variable. The syntax to use the for-each loop in java is given
In programming, sometimes we need to execute the block of code below. Java while loop
repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated 1. for(data_type var : array_name/collection_name){ The while loop is also used to iterate over the number of statements
order. The execution of the set of instructions depends upon a 2. //statements multiple times. However, if we don't know the number of iterations
particular condition. 3. } in advance, it is recommended to use a while loop. Unlike for loop,
the initialization and increment/decrement doesn't take place inside
Consider the following example to understand the functioning of the the loop statement in while loop.
for-each loop in Java.

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

It is also known as the entry-controlled loop since the condition is 3. // TODO Auto-generated method stub It is also known as the exit-controlled loop since the condition is not 3. // TODO Auto-generated method stub
checked at the start of the loop. If the condition is true, then the loop 4. int i = 0; checked in advance. The syntax of the do-while loop is given below. 4. int i = 0;
body will be executed; otherwise, the statements after the loop will 5. System.out.println("Printing the list of first 10 even numbers \n"); 5. System.out.println("Printing the list of first 10 even numbers \n");
be executed. 1. do
6. while(i<=10) { 2. { 6. do {
7. System.out.println(i); 3. //statements 7. System.out.println(i);
The syntax of the while loop is given below.
8. i = i + 2; 4. } while (condition); 8. i = i + 2;
1. while(condition){ 9. } 9. }while(i<=10);
2. //looping statements 10. } The flow chart of the do-while loop is given in the following image. 10. }
3. } 11. } 11. }

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

Printing the list of first 10 even numbers Printing the list of first 10 even numbers

0 0

2 2

4 4

6 6

8 8

10 10

Java do-while loop Jump Statements


Consider the following example to understand the functioning of the
Consider the following example. The do-while loop checks the condition at the end of the loop after do-while loop in Java. Jump statements are used to transfer the control of the program to
executing the loop statements. When the number of iteration is not the specific statements. In other words, jump statements transfer the
Calculation .java known and we have to execute the loop at least once, we can use do- Calculation.java execution control to the other part of the program. There are two
while loop. types of jump statements in Java, i.e., break and continue.
1. public class Calculation { 1. public class Calculation {
2. public static void main(String[] args) { 2. public static void main(String[] args) {

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 27 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 28
0 18. } 7.
Java break statement
19. } 8. for (int j = i; j<=5; j++) {
1 20. 9.
As the name suggests, the break statement is used to break the
21. 10. if(j == 4) {
current flow of the program and transfer the control to the next 2 22. } 11. continue;
statement outside a loop or switch statement. However, it breaks only 12. }
the inner loop in the case of the nested loop. 3
Output: 13. System.out.println(j);
14. }
4
The break statement cannot be used independently in the Java 0 15. }
program, i.e., it can only be written inside the loop or switch 5 16. }
statement. 1 17.
6 18. }
2
The break statement example with for loop
break statement example with labeled for loop Output:
3
Consider the following example in which we have used the break
statement with the for loop. Calculation.java 0
4

1
BreakExample.java 1. public class Calculation { 5
2.
2
1. public class BreakExample { 3. public static void main(String[] args) {
Java continue statement
2. 4. // TODO Auto-generated method stub 3
3. public static void main(String[] args) { 5. a:
Unlike break statement, the continue statement doesn't break the
4. // TODO Auto-generated method stub 6. for(int i = 0; i<= 10; i++) { 5
7. b:
loop, whereas, it skips the specific part of the loop and jumps to the
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i); 8. for(int j = 0; j<=15;j++) { next iteration of the loop immediately. 1
7. if(i==6) { 9. c:
8. break; 10. for (int k = 0; k<=20; k++) { Consider the following example to understand the functioning of the 2
9. } 11. System.out.println(k); continue statement in Java.
10. } 12. if(k==5) { 3
11. } 13. break a; 1. public class ContinueExample {
12. } 14. } 2. 5
15. } 3. public static void main(String[] args) {
4. // TODO Auto-generated method stub 2
Output: 16. }
17. 5.
3
6. for(int i = 0; i<= 2; i++) {

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

5 2. //It is a program of odd and even number.


Java if-else Statement 3. public class IfElseExample {
4. public static void main(String[] args) {
Java If-else Statement The Java if-else statement also tests the condition. It executes the if 5. //defining a variable
block if condition is true otherwise else block is executed. 6. int number=13;
The Java if statement is used to test the condition. It 7. //Check if the number is divisible by 2 or not
checks boolean condition: true or false. There are various types of if Syntax: 8. if(number%2==0){
statement in Java. 9. System.out.println("even number");
1. if(condition){ 10. }else{
o if statement 2. //code if condition is true 11. System.out.println("odd number");
o if-else statement 3. }else{ 12. }
o if-else-if ladder 4. //code if condition is false 13. }
o nested if statement 5. } 14. }

Output:
Java if Statement
odd number
The Java if statement tests the condition. It executes the if block if
condition is true. Example:
Leap Year Example:
1. //Java Program to demonstate the use of if statement.
Syntax: A year is leap, if it is divisible by 4 and 400. But, not by 100.
2. public class IfExample {
3. public static void main(String[] args) {
1. if(condition){ 1. public class LeapYearExample {
4. //defining an 'age' variable
2. //code to be executed 2. public static void main(String[] args) {
5. int age=20;
3. } 3. int year=2020;
6. //checking the age
7. if(age>18){ 4. if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
8. System.out.print("Age is greater than 18"); 5. System.out.println("LEAP YEAR");
9. } 6. }
10. } 7. else{
11. } 8. System.out.println("COMMON YEAR");
9. }
10. }
Output:
Example: 11. }
Age is greater than 18
1. //A Java Program to demonstrate the use of if-else statement.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 31 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 32
Output: 1. if(condition1){ 2. //It is a program of grading system for fail, D grade, C grade, B gra 2. public static void main(String[] args) {
2. //code to be executed if condition1 is true de, A grade and A+. 3. int number=-13;
LEAP YEAR 3. }else if(condition2){ 3. public class IfElseIfExample { 4. if(number>0){
4. //code to be executed if condition2 is true 4. public static void main(String[] args) { 5. System.out.println("POSITIVE");
5. } 5. int marks=65; 6. }else if(number<0){
Using Ternary Operator 6. else if(condition3){ 6. 7. System.out.println("NEGATIVE");
7. //code to be executed if condition3 is true 7. if(marks<50){ 8. }else{
We can also use ternary operator (? :) to perform the task of if...else 8. } 8. System.out.println("fail"); 9. System.out.println("ZERO");
statement. It is a shorthand way to check the condition. If the 9. ... 9. } 10. }
condition is true, the result of ? is returned. But, if the condition is 10. else{ 10. else if(marks>=50 && marks<60){ 11. }
false, the result of : is returned. 11. //code to be executed if all the conditions are false 11. System.out.println("D grade"); 12. }
12. } 12. }
Example: 13. else if(marks>=60 && marks<70){ Output:
14. System.out.println("C grade");
1. public class IfElseTernaryExample { 15. } NEGATIVE
2. public static void main(String[] args) { 16. else if(marks>=70 && marks<80){
3. int number=13; 17. System.out.println("B grade");
4. //Using ternary operator 18. }
Java Nested if statement
5. String output=(number%2==0)?"even number":"odd number"; 19. else if(marks>=80 && marks<90){
The nested if statement represents the if block within another if block.
20. System.out.println("A grade");
6. System.out.println(output); 21. }else if(marks>=90 && marks<100){ Here, the inner if block condition executes only when outer if block
7. } 22. System.out.println("A+ grade"); condition is true.
8. } 23. }else{
24. System.out.println("Invalid!"); Syntax:
Output: 25. }
26. } 1. if(condition){
odd number 27. } 2. //code to be executed
3. if(condition){
Output: 4. //code to be executed
Java if-else-if ladder Statement 5. }
C grade 6. }
The if-else-if ladder statement executes one condition from multiple Example:
statements. Program to check POSITIVE, NEGATIVE or ZERO:
1. //Java Program to demonstrate the use of If else-if ladder.

Syntax: 1. public class PositiveNegativeExample {

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

You are eligible to donate blood 4. break; //optional Example:


5. case value2:
6. //code to be executed; SwitchExample.java
Java Switch Statement 7. break; //optional
8. ...... 1. public class SwitchExample {
The Java switch statement executes one statement from multiple 9. 2. public static void main(String[] args) {
conditions. It is like if-else-if ladder statement. The switch statement 10. default: 3. //Declaring a variable for switch expression
works with byte, short, int, long, enum types, String and some 11. code to be executed if all cases are not matched; 4. int number=20;
wrapper types like Byte, Short, Int, and Long. Since Java 7, you can 12. } 5. //Switch expression
use strings in the switch statement. 6. switch(number){
Flowchart of Switch Statement 7. //Case statements
In other words, the switch statement tests the equality of a variable 8. case 10: System.out.println("10");
against multiple values. 9. break;
10. case 20: System.out.println("20");
11. break;
Points to Remember 12. case 30: System.out.println("30");
13. break;
Example: o There can be one or N number of case values for a switch expression. 14. //Default case statement
o The case value must be of switch expression type only. The case 15. default:System.out.println("Not in 10, 20 or 30");
1. //Java Program to demonstrate the use of Nested If Statement. value must be literal or constant. It doesn't allow variables. 16. }
2. public class JavaNestedIfExample { o The case values must be unique. In case of duplicate value, it renders 17. }
3. public static void main(String[] args) { compile-time error. 18. }
4. //Creating two variables for age and weight o The Java switch expression must be of byte, short, int, long (with its
5. int age=20; Wrapper type), enums and string. Output:
6. int weight=80; o Each case statement can have a break statement which is optional.
7. //applying condition on age and weight When control reaches to the break statement, it jumps the control after the 20
8. if(age>=18){ switch expression. If a break statement is not found, it executes the next
9. if(weight>50){ case.
10. System.out.println("You are eligible to donate blood"); o The case value can have a default label which is optional. Java Switch Statement is fall-through
11. }
12. } Syntax: The Java switch statement is fall-through. It means it executes all
13. }} statements after the first match if a break statement is not present.
1. switch(expression){
Output: 2. case value1: Example:
3. //code to be executed;

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 35 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 36
SwitchExample2.java 1. //Java Program to demonstrate the use of Java Switch NestedSwitchExample.java 30. case 'C':
2. //statement with String 31. System.out.println("Computer Organization, MultiM
1. //Java Switch Example where we are omitting the 3. public class SwitchStringExample { 1. //Java Program to demonstrate the use of Java Nested Switch edia");
2. //break statement 4. public static void main(String[] args) { 2. public class NestedSwitchExample { 32. break;
3. public class SwitchExample2 { 5. //Declaring String variable 3. public static void main(String args[]) 33. case 'E':
4. public static void main(String[] args) { 6. String levelString="Expert"; 4. { 34. System.out.println("Fundamentals of Logic Design,
5. int number=20; 7. int level=0; 5. //C - CSE, E - ECE, M - Mechanical Microelectronics");
6. //switch expression with int value 8. //Using String in Switch expression 6. char branch = 'C'; 35. break;
7. switch(number){ 9. switch(levelString){ 7. int collegeYear = 4; 36. case 'M':
8. //switch cases without break statements 10. //Using String Literal in Switch case 8. switch( collegeYear ) 37. System.out.println("Internal Combustion Engines, M
9. case 10: System.out.println("10"); 11. case "Beginner": level=1; 9. { echanical Vibration");
10. case 20: System.out.println("20"); 12. break; 10. case 1: 38. break;
11. case 30: System.out.println("30"); 13. case "Intermediate": level=2; 11. System.out.println("English, Maths, Science"); 39. }
12. default:System.out.println("Not in 10, 20 or 30"); 14. break; 12. break; 40. break;
13. } 15. case "Expert": level=3; 13. case 2: 41. case 4:
14. } 16. break; 14. switch( branch ) 42. switch( branch )
15. } 17. default: level=0; 15. { 43. {
18. break; 16. case 'C': 44. case 'C':
Output: 19. } 17. System.out.println("Operating System, Java, Data St 45. System.out.println("Data Communication and Netw
20. System.out.println("Your Level is: "+level); ructure"); orks, MultiMedia");
20 21. } 18. break; 46. break;
22. } 19. case 'E': 47. case 'E':
30 20. System.out.println("Micro processors, Logic switchin 48. System.out.println("Embedded System, Image Proce
Output: g theory"); ssing");
Not in 10, 20 or 30 21. break; 49. break;
Your Level is: 3 22. case 'M': 50. case 'M':
Java Switch Statement with String 23. System.out.println("Drawing, Manufacturing Machin 51. System.out.println("Production Technology, Therma
l Engineering");
Java Nested Switch Statement es");
24. break; 52. break;
Java allows us to use strings in switch expression since Java SE 7. The
25. } 53. }
case statement should be string literal. We can use switch statement inside other switch statement in Java. It
26. break; 54. break;
is known as nested switch statement. 27. case 3: 55. }
Example:
28. switch( branch ) 56. }
Example: 29. { 57. }
SwitchStringExample.java

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

Output: 19. System.out.println("Tuesday"); You are eligible for vote.


20. break;
Java Wrapper in Switch Statement
Data Communication and Networks, MultiMedia 21. case Wed:
22. System.out.println("Wednesday"); Java allows us to use four wrapper classes: Byte, Short, Integer and Loops in Java
23. break; Long in switch statement.
Java Enum in Switch Statement 24. case Thu: The Java for loop is used to iterate a part of the program several
25. System.out.println("Thursday"); Example: times. If the number of iteration is fixed, it is recommended to use
Java allows us to use enum in switch statement. Java enum is a class 26. break; for loop.
that represent the group of constants. (immutable such as final 27. case Fri: WrapperInSwitchCaseExample.java
variables). We use the keyword enum and put the constants in curly 28. System.out.println("Friday"); There are three types of for loops in Java.
braces separated by comma. 29. break; 1. //Java Program to demonstrate the use of Wrapper class
30. case Sat: 2. //in switch statement
Example: 31. System.out.println("Saturday"); 3. public class WrapperInSwitchCaseExample {
32. break; 4. public static void main(String args[]) o Simple for Loop
JavaSwitchEnumExample.java 33. } 5. { o For-each or Enhanced for Loop
34. } 6. Integer age = 18; o Labeled for Loop
1. //Java Program to demonstrate the use of Enum 35. } 7. switch (age)
2. //in switch statement 36. } 8. {
3. public class JavaSwitchEnumExample { 9. case (16):
Java Simple for Loop
4. public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat } Output: 10. System.out.println("You are under 18.");
11. break; A simple for loop is the same as C/C++. We can initialize the variable,
5. public static void main(String args[])
6. { Sunday 12. case (18): check condition and increment/decrement value. It consists of four
7. Day[] DayNow = Day.values(); 13. System.out.println("You are eligible for vote."); parts:
8. for (Day Now : DayNow) Monday 14. break;
9. { 15. case (65): 1. Initialization: It is the initial condition which is executed once when
Twesday 16. System.out.println("You are senior citizen."); the loop starts. Here, we can initialize the variable, or we can use an already
10. switch (Now)
11. { 17. break; initialized variable. It is an optional condition.
Wednesday 2. Condition: It is the second condition which is executed each time
12. case Sun: 18. default:
13. System.out.println("Sunday"); 19. System.out.println("Please give the valid age."); to test the condition of the loop. It continues execution until the condition
Thursday
14. break; 20. break; is false. It must return boolean value either true or false. It is an optional
15. case Mon: 21. } condition.
Friday
16. System.out.println("Monday"); 22. } 3. Increment/Decrement: It increments or decrements the variable
17. break; Saturday 23. } value. It is an optional condition.
18. case Tue: 4. Statement: The statement of the loop is executed each time until
Output: the second condition is false.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 39 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 40
Syntax: 8. } 1. public class NestedForExample { 1. public class PyramidExample {
9. } 2. public static void main(String[] args) { 2. public static void main(String[] args) {
1. for(initialization; condition; increment/decrement){ 10. } 3. //loop of i 3. for(int i=1;i<=5;i++){
2. //statement or code to be executed 4. for(int i=1;i<=3;i++){ 4. for(int j=1;j<=i;j++){
3. } Output: 5. //loop of j 5. System.out.print("* ");
6. for(int j=1;j<=3;j++){ 6. }
Flowchart: 1 7. System.out.println(i+" "+j); 7. System.out.println();//new line
8. }//end of i 8. }
2 9. }//end of j 9. }
10. } 10. }
3 11. }
Output:
4
Output:
*
5
11
**
6
12
***
7
13
****
8
21
*****
9
22
10 Pyramid Example 2:
Example: 23
PyramidExample2.java
ForExample.java Java Nested for Loop 31

1. public class PyramidExample2 {


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

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

9. } ForEachExample.java Note: The break and continue keywords breaks or continues the 12
10. } innermost for loop respectively.
11. } 1. //Java For-each loop example which prints the 13
2. //elements of the array Syntax:
21
Output: 3. public class ForEachExample {
4. public static void main(String[] args) { 1. labelname:
****** 5. //Declaring an array If you use break bb;, it will break inner loop only which is the default
2. for(initialization; condition; increment/decrement){
6. int arr[]={12,23,44,56,78}; 3. //code to be executed behaviour of any loop.
***** 7. //Printing array using for-each loop 4. }
8. for(int i:arr){ LabeledForExample2.java
****
9. System.out.println(i); Example:
10. } 1. public class LabeledForExample2 {
*** 2. public static void main(String[] args) {
11. } LabeledForExample.java
12. } 3. aa:
**
1. //A Java program to demonstrate the use of labeled for loop 4. for(int i=1;i<=3;i++){
Output: 2. public class LabeledForExample { 5. bb:
*
3. public static void main(String[] args) { 6. for(int j=1;j<=3;j++){
12 4. //Using Label for outer and for loop 7. if(i==2&&j==2){
Java for-each Loop 5. aa: 8. break bb;
23 6. for(int i=1;i<=3;i++){ 9. }
The for-each loop is used to traverse array or collection in Java. It is 7. bb: 10. System.out.println(i+" "+j);
44 11. }
easier to use than simple for loop because we don't need to 8. for(int j=1;j<=3;j++){
increment value and use subscript notation. 9. if(i==2&&j==2){ 12. }
56 13. }
10. break aa;
14. }
It works on the basis of elements and not the index. It returns element 78 11. }
one by one in the defined variable. 12. System.out.println(i+" "+j);
13. } Output:
Syntax:
Java Labeled For Loop 14. }
11
15. }
1. for(data_type variable : array_name){ We can have a name of each Java for loop. To do so, we use label 16. }
12
2. //code to be executed before the for loop. It is useful while using the nested for loop as we
3. } can break/continue specific for loop. Output: 13

Example: 11 21

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 43 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 44
31 infinitive loop
When to use If the number of If the number If the number Java While Loop
32 infinitive loop iteration is fixed, it is of iteration is of iteration is
recommended to not fixed, it is not fixed and
The Java while loop is used to iterate a part of
33 infinitive loop use for loop. recommended you must have
the program repeatedly until the specified Boolean condition is true.
to use while to execute the
infinitive loop loop. loop at least As soon as the Boolean condition becomes false, the loop
Java Infinitive for Loop once, it is automatically stops.
ctrl+c recommended
If you use two semicolons ;; in the for loop, it will be infinitive for loop. to use the do- The while loop is considered as a repeating if statement. If the
Now, you need to press ctrl+c to exit from the program. while loop. number of iteration is not fixed, it is recommended to use the
Syntax: while loop.
Syntax for(init;condition;inc while(condition do{
1. for(;;){
Java for Loop vs while Loop vs do-while r/decr){ ){ //code to be Syntax:
2. //code to be executed Loop // code to be
executed
//code to be
executed
executed
}while(conditio
3. } 1. while (condition){
} } n); 2. //code to be executed
Example: Compari for loop while loop do-while 3. I ncrement / decrement statement
Example //for loop //while loop //do-while loop 4. }
son loop for(int int i=1; int i=1;
ForExample.java
i=1;i<=10;i++){ while(i<=10){ do{ The different parts of do-while loop:
Introduction The Java for loop is a The Java while The Java do System.out.println(i); System.out.prin System.out.prin
1. //Java program to demonstrate the use of infinite for loop control flow loop is a while loop is a
2. //which prints an statement } tln(i); tln(i); 1. Condition: It is an expression which is tested. If the condition is
statement that control flow control flow i++; i++;
3. public class ForExample { iterates a part of statement that statement that true, the loop body is executed and control goes to update
4. public static void main(String[] args) { } }while(i<=10);
the programs multip executes a part executes a part expression. When the condition becomes false, we exit the while
5. //Using no condition in for loop le times. of the of the loop.
Syntax for for(;;){ while(true){ do{
6. for(;;){ programs programs at infinitive //code to be //code to be //code to be
7. System.out.println("infinitive loop"); repeatedly on least once and Example:
loop executed executed executed
8. } the basis of the further } } }while(true);
9. } given boolean execution i <=100
10. } condition. depends upon
the given 2. Update expression: Every time the loop body is executed, this
Output: boolean expression increments or decrements loop variable.
condition.
infinitive loop

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

Example: 1. public class WhileExample { Syntax:


2. public static void main(String[] args) { Java do-while Loop
i++; 3. int i=1; 1. while(true){
4. while(i<=10){ 2. //code to be executed The Java do-while loop is used to iterate a part of the program
Flowchart of Java While Loop 5. System.out.println(i); 3. } repeatedly, until the specified condition is true. If the number of
6. i++; iteration is not fixed and you must have to execute the loop at least
Here, the important thing about while loop is that, sometimes it may 7. } Example: once, it is recommended to use a do-while loop.
not even execute. If the condition to be tested results into false, the 8. }
9. } WhileExample2.java Java do-while loop is called an exit control loop. Therefore, unlike
loop body is skipped and first statement after the while loop will be
executed. while loop and for loop, the do-while check the condition at the end
Output: 1. public class WhileExample2 { of loop body. The Java do-while loop is executed at least once
2. public static void main(String[] args) {
1
because condition is checked after loop body.
3. // setting the infinite while loop by passing true to the condition
4. while(true){
2 Syntax:
5. System.out.println("infinitive while loop");
6. }
3 1. do{
7. }
2. //code to be executed / loop body
8. }
4 3. //update statement
4. }while (condition);
5 Output:
The different parts of do-while loop:
6 infinitive while loop

infinitive while loop 1. Condition: It is an expression which is tested. If the condition is


7
true, the loop body is executed and control goes to update
Example: 8 infinitive while loop expression. As soon as the condition becomes false, loop breaks
automatically.
In the below example, we print integer values from 1 to 10. Unlike 9 infinitive while loop
the for loop, we separately need to initialize and increment the Example:
10 infinitive while loop
variable used in the condition (here, i). Otherwise, the loop will
execute infinitely. ctrl+c
i <=100
Java Infinitive While Loop
WhileExample.java In the above code, we need to enter Ctrl + C command to terminate 2. Update expression: Every time the loop body is executed, the this
If you pass true in the while loop, it will be infinitive while loop. the infinite loop. expression increments or decrements loop variable.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 47 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 48
Example: 5. System.out.println(i); 1. do{ The Java break statement is used to break loop or switch statement.
6. i++; 2. //code to be executed It breaks the current flow of the program at specified condition. In
i++; 7. }while(i<=10); 3. }while(true); case of inner loop, it breaks only inner loop.
8. }
Note: The do block is executed at least once, even if the condition is 9. } Example: We can use Java break statement in all types of loops such as for
false. loop, while loop and do-while loop.
Output: DoWhileExample2.java
Flowchart of do-while loop: Syntax:
1 1. public class DoWhileExample2 {
2. public static void main(String[] args) { 1. jump-statement;
2
3. do{ 2. break;
4. System.out.println("infinitive do while loop");
3
5. }while(true);
Flowchart of Break Statement
4 6. }
7. }
5
Output:
6
infinitive do while loop
7
infinitive do while loop
8
Example: infinitive do while loop
9
In the below example, we print integer values from 1 to 10. Unlike ctrl+c
the for loop, we separately need to initialize and increment the 10
variable used in the condition (here, i). Otherwise, the loop will In the above code, we need to enter Ctrl + C command to terminate Java Break Statement with Loop
execute infinitely. Java Infinitive do-while Loop the infinite loop.
Example:
DoWhileExample.java If you pass true in the do-while loop, it will be infinitive do-while Java Break Statement BreakExample.java
loop.
1. public class DoWhileExample {
2. public static void main(String[] args) { When a break statement is encountered inside a loop, the loop is 1. //Java Program to demonstrate the use of break statement
Syntax: immediately terminated and the program control resumes at the next 2. //inside the for loop.
3. int i=1;
4. do{ statement following the loop. 3. public class BreakExample {

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

4. public static void main(String[] args) { 4. public static void main(String[] args) { We can use break statement with a label. The feature is introduced
5. //using for loop 5. //outer loop since JDK 1.5. So, we can break any loop in Java now whether it is
Java Break Statement in while loop
6. for(int i=1;i<=10;i++){ 6. for(int i=1;i<=3;i++){ outer or inner loop.
7. if(i==5){ 7. //inner loop Example:
8. //breaking the loop 8. for(int j=1;j<=3;j++){ Example:
9. break; 9. if(i==2&&j==2){ BreakWhileExample.java
10. } 10. //using break statement inside the inner loop BreakExample3.java
11. System.out.println(i); 11. break; 1. //Java Program to demonstrate the use of break statement
12. } 12. } 2. //inside the while loop.
1. //Java Program to illustrate the use of continue statement
13. } 13. System.out.println(i+" "+j); 3. public class BreakWhileExample {
2. //with label inside an inner loop to break outer loop
14. } 14. } 4. public static void main(String[] args) {
3. public class BreakExample3 {
15. } 5. //while loop
4. public static void main(String[] args) {
Output: 16. } 6. int i=1;
5. aa:
17. } 7. while(i<=10){
6. for(int i=1;i<=3;i++){
1 8. if(i==5){
7. bb:
Output: 9. //using break statement
8. for(int j=1;j<=3;j++){
2 10. i++;
9. if(i==2&&j==2){
11 11. break;//it will break the loop
3 10. //using break statement with label
12. }
11. break aa;
12 13. System.out.println(i);
4 12. }
14. i++;
13 13. System.out.println(i+" "+j);
15. }
14. }
Java Break Statement with Inner Loop 21 15. }
16. }
17. }
16. }
It breaks inner loop only if you use break statement inside the inner 31 17. }
Output:
loop.
32 Output: 1
Example:
33 11 2
BreakExample2.java
12
Java Break Statement with Labeled For 3
1. //Java Program to illustrate the use of break statement
2. //inside an inner loop Loop 13 4
3. public class BreakExample2 {
21

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 51 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 52
4. public static void main(String[] args) {
Java Break Statement in do-while loop Java Break Statement with Switch 5. //for loop
Java Continue Statement with Inner Loop
6. for(int i=1;i<=10;i++){
Example: To understand the example of break with switch statement, please 7. if(i==5){ It continues inner loop only if you use the continue statement inside
visit here: Java Switch Statement. 8. //using continue statement the inner loop.
BreakDoWhileExample.java 9. continue;//it will skip the rest statement
10. } ContinueExample2.java
1. //Java Program to demonstrate the use of break statement Java Continue Statement 11. System.out.println(i);
2. //inside the Java do-while loop. 12. } 1. //Java Program to illustrate the use of continue statement
3. public class BreakDoWhileExample { The continue statement is used in loop control structure when you 13. } 2. //inside an inner loop
4. public static void main(String[] args) { need to jump to the next iteration of the loop immediately. It can be 14. } 3. public class ContinueExample2 {
5. //declaring variable used with for loop or while loop. 4. public static void main(String[] args) {
6. int i=1; Output: 5. //outer loop
7. //do-while loop The Java continue statement is used to continue the loop. It continues 6. for(int i=1;i<=3;i++){
8. do{ 1 7. //inner loop
the current flow of the program and skips the remaining code at the
9. if(i==5){ 8. for(int j=1;j<=3;j++){
specified condition. In case of an inner loop, it continues the inner
10. //using break statement 2 9. if(i==2&&j==2){
loop only.
11. i++; 10. //using continue statement inside inner loop
12. break;//it will break the loop 3 11. continue;
13. }
We can use Java continue statement in all types of loops such as for
12. }
14. System.out.println(i); loop, while loop and do-while loop. 4 13. System.out.println(i+" "+j);
15. i++; 14. }
Syntax: 6
16. }while(i<=10); 15. }
17. } 16. }
1. jump-statement; 7
18. } 17. }
2. continue;
8
Output: Output:

1
Java Continue Statement Example 9
11
10
2
ContinueExample.java
12

1. //Java Program to demonstrate the use of continue statement As you can see in the above output, 5 is not printed on the console.
3 13
2. //inside the for loop. It is because the loop is continued when it reaches to 5.
4 3. public class ContinueExample { 21

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

23 15. } 12. } 5. //declaring variable


16. } 13. System.out.println(i); 6. int i=1;
31 17. } 14. i++; 7. //do-while loop
15. } 8. do{
32
Output: 16. } 9. if(i==5){
17. } 10. //using continue statement
33
11 11. i++;
Output: 12. continue;//it will skip the rest statement
Java Continue Statement with Labelled For 12 13. }
1 14. System.out.println(i);
Loop 13 15. i++;
2 16. }while(i<=10);
21
We can use continue statement with a label. This feature is 17. }
3
introduced since JDK 1.5. So, we can continue any loop in Java now 31
18. }
whether it is outer loop or inner. 4
32 Output:
Example: 6
33 1
ContinueExample3.java 7
2

1. //Java Program to illustrate the use of continue statement


Java Continue Statement in while loop 8
3
2. //with label inside an inner loop to continue outer loop
3. public class ContinueExample3 {
ContinueWhileExample.java 9
4
4. public static void main(String[] args) {
1. //Java Program to demonstrate the use of continue statement 10
5. aa: 6
2. //inside the while loop.
6. for(int i=1;i<=3;i++){
3. public class ContinueWhileExample {
7. bb:
4. public static void main(String[] args) {
Java Continue Statement in do-while Loop 7
8. for(int j=1;j<=3;j++){
5. //while loop 8
9. if(i==2&&j==2){ ContinueDoWhileExample.java
6. int i=1;
10. //using continue statement with label
7. while(i<=10){ 9
11. continue aa; 1. //Java Program to demonstrate the use of continue statement
8. if(i==5){
12. } 2. //inside the Java do-while loop.
9. //using continue statement 10
13. System.out.println(i+" "+j); 3. public class ContinueDoWhileExample {
10. i++;
14. } 4. public static void main(String[] args) {
11. continue;//it will skip the rest statement

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 55 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 56
Syntax: 4. multi line To create documentation API, we need to use the javadoc tool. The
Java Comments 5. comment documentation comments are placed between /** and */.
1. //This is single line comment 6. */
The Java comments are the statements in a program that are not Syntax:
executed by the compiler and interpreter. Let's use single line comment in a Java program. Let's use multi-line comment in a Java program.
/**
CommentExample1.java CommentExample2.java
Why do we use comments in a code? *
1. public class CommentExample1 { 1. public class CommentExample2 {
o Comments are used to make the program more readable by adding 2. public static void main(String[] args) { 2. public static void main(String[] args) { *We can use various tags to depict the parameter
the details of the code. 3. int i=10; // i is a variable with value 10 3. /* Let's declare and
o It makes easy to maintain the code and to find the errors easily. 4. System.out.println(i); //printing the variable i 4. print variable in java. */ *or heading or author name
o The comments can be used to provide information or explanation 5. } 5. int i=10;
about the variable, method, class, or any statement. 6. } 6. System.out.println(i); *We can also use HTML tags
o It can also be used to prevent the execution of program code while 7. /* float j = 5.9;
testing the alternative code. Output: 8. float k = 4.4; *
9. System.out.println( j + k ); */
Types of Java Comments 10 10. } */
11. }
There are three types of comments in Java. 2) Java Multi Line Comment
Output:
javadoc tags
1. Single Line Comment The multi-line comment is used to comment multiple lines of code. Some of the commonly used tags in documentation comments:
10
2. Multi Line Comment It can be used to explain a complex code snippet or to comment
3. Documentation Comment multiple lines of code at a time (as it will be difficult to use single-line Note: Usually // is used for short comments and /* */ is used for longer
comments there). Tag Syntax Description
comments.
1) Java Single Line Comment
Multi-line comments are placed between /* and */. Any text between {@docRoot} {@docRoot} to depict relative path to root
/* and */ is not executed by Java.
3) Java Documentation Comment directory of generated document
The single-line comment is used to comment only one line of the
from any page.
code. It is the widely used and easiest way of commenting the
Documentation comments are usually used to write large programs
statements. Syntax:
for a project or software application as it helps to create @author @author name - To add the author of the class.
documentation API. These APIs are needed for reference, i.e., which text
Single line comments starts with two forward slashes (//). Any text in 1. /*
2. This classes, methods, arguments, etc., are used in the code.
front of // is not executed by Java.
3. is

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

13. * @version 16.0 modify code using methods. In this section, we will learn what is a
@code {@code text} To show the text in code font without
14. * @since 2021-07-06 method in Java, types of methods, method declaration, and how
interpreting it as html markup or
15. */ to call a method in Java.
nested javadoc tag.
16.
@version @version To specify "Version" subheading and 17. public class Calculate{
version-text version-text when -version option is 18. /** What is a method in Java?
used. 19. * This method calculates the summation of two integers.
20. * @param input1 This is the first parameter to sum() method A method is a block of code or collection of statements or a set of
@since @since release To add "Since" heading with since text 21. * @param input2 This is the second parameter to the sum() met code grouped together to perform a certain task or operation. It is
to generated documentation. hod. used to achieve the reusability of code. We write a method once and
22. * @return int This returns the addition of input1 and input2 use it many times. We do not require to write code again and again.
@param @param To add a parameter with given name 23. */ It also provides the easy modification and readability of code, just
parameter-name and description to 'Parameters' 24. public int sum(int input1, int input2){ Method Signature: Every method has a method signature. It is a part
by adding or removing a chunk of code. The method is executed only
description section. 25. return input1 + input2; of the method declaration. It includes the method
when we call or invoke it.
26. } name and parameter list.
@return @return Required for every method that 27. /**
description returns something (except void) The most important method in Java is the main() method. If you
28. * This is the main method uses of sum() method. Access Specifier: Access specifier or modifier is the access type of
29. * @param args Unused want to read more about the main() method,
the method. It specifies the visibility of the method. Java
30. * @see IOException
Let's use the Javadoc tag in a Java program. provides four types of access specifier:
31. */ Method Declaration
32. public static void main(String[] args) {
Calculate.java o Public: The method is accessible by all classes when we use public
33. Calculate obj = new Calculate(); The method declaration provides information about method specifier in our application.
34. int result = obj.sum(40, 20); attributes, such as visibility, return-type, name, and arguments. It has
1. import java.io.*; o Private: When we use a private access specifier, the method is
35. six components that are known as method header, as we have
2. accessible only in the classes in which it is defined.
36. System.out.println("Addition of numbers: " + result);
3. /** shown in the following figure. o Protected: When we use protected access specifier, the method is
37. }
4. * <h2> Calculation of numbers </h2> accessible within the same package or subclasses in a different package.
38. }
5. * This program implements an application o Default: When we do not use any access specifier in the method
6. * to perform operation such as addition of numbers declaration, Java uses default access specifier by default. It is visible only
7. * and print the result Method in Java from the same package only.
8. * <p>
9. * <b>Note:</b> Comments make the code readable and Return Type: Return type is a data type that the method returns. It
In general, a method is a way to perform some task. Similarly,
10. * easy to understand. may have a primitive data type, object, collection, void, etc. If the
the method in Java is a collection of instructions that performs a
11. * method does not return anything, we use void keyword.
12. * @author Anurati specific task. It provides the reusability of code. We can also easily

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 59 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 60
Method Name: It is a unique name that is used to define the name There are two types of methods in Java: 8. } In the above method signature, we see that the method signature
of a method. It must be corresponding to the functionality of the has access specifier public, non-access modifier static, return
method. Suppose, if we are creating a method for subtraction of two o Predefined Method Output: type int, method name max(), parameter list (int a, int b). In the
numbers, the method name must be subtraction(). A method is o User-defined Method above example, instead of defining the method, we have just invoked
The maximum number is: 9
invoked by its name. the method. This is the advantage of a predefined method. It makes
Predefined Method programming less complicated.
In the above example, we have used three predefined
Parameter List: It is the list of parameters separated by a comma
methods main(), print(), and max(). We have used these methods
and enclosed in the pair of parentheses. It contains the data type and In Java, predefined methods are the method that is already defined Similarly, we can also see the method signature of the print() method.
directly without declaration because they are predefined. The print()
variable name. If the method has no parameter, left the parentheses in the Java class libraries is known as predefined methods. It is also
method is a method of PrintStream class that prints the result on
blank. known as the standard library method or built-in method. We can User-defined Method
the console. The max() method is a method of the Math class that
directly use these methods just by calling them in the program at any
Method Body: It is a part of the method declaration. It contains all returns the greater of two numbers.
point. Some pre-defined methods are length(), equals(), The method written by the user or programmer is known as a user-
the actions to be performed. It is enclosed within the pair of curly compareTo(), sqrt(), etc. When we call any of the predefined defined method. These methods are modified according to the
We can also see the method signature of any predefined method by
braces. methods in our program, a series of codes related to the requirement.
using the link https://docs.oracle.com/. When we go through the link
corresponding method runs in the background that is already stored
and see the max() method signature, we find the following:
Naming a Method in the library. How to Create a User-defined Method

Each and every predefined method is defined inside a class. Such Let's create a user defined method that checks the number is even or
While defining a method, remember that the method name must be
as print() method is defined in the java.io.PrintStream class. It odd. First, we will define the method.
a verb and start with a lowercase letter. If the method name has
prints the statement that we write inside the method. For
more than two words, the first name must be a verb followed by
example, print("Java"), it prints Java on the console. 1. //user defined method
adjective or noun. In the multi-word method name, the first letter of
2. public static void findEvenOdd(int num)
each word must be in uppercase except the first word. For example: 3. {
Let's see an example of the predefined method.
4. //method body
Single-word method name: sum(), area() 5. if(num%2==0)
Demo.java
6. System.out.println(num+" is even");
Multi-word method name: areaOfCircle(), stringComparision() 7. else
1. public class Demo
2. { 8. System.out.println(num+" is odd");
It is also possible that a method has the same name as another 3. public static void main(String[] args) 9. }
method name in the same class, it is known as method overloading. 4. {
5. // using the max() method of Math class We have defined the above method named findevenodd(). It has a
Types of Method 6. System.out.print("The maximum number is: " + Math.max(9,7)); parameter num of type int. The method does not return any value
7. } that's why we have used void. The method body contains the steps

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

to check the number is even or odd. If the number is even, it prints 3. { In the following program, we have defined a method Static Method
the number is even, else prints the number is odd. 4. public static void main (String args[]) named add() that sum up the two numbers. It has two parameters
5. { n1 and n2 of integer type. The values of n1 and n2 correspond to the A method that has static keyword is known as static method. In other
How to Call or Invoke a User-defined Method 6. //creating Scanner class object value of a and b, respectively. Therefore, the method adds the value words, a method that belongs to a class rather than an instance of a
7. Scanner scan=new Scanner(System.in);
of a and b and store it in the variable s and returns the sum. class is known as a static method. We can also create a static method
Once we have defined a method, it should be called. The calling of a 8. System.out.print("Enter the number: ");
9. //reading value from user by using the keyword static before the method name.
method in a program is simple. When we call or invoke a user- Addition.java
10. int num=scan.nextInt();
defined method, the program control transfer to the called method. The main advantage of a static method is that we can call it without
11. //method calling
1. public class Addition
12. findEvenOdd(num); creating an object. It can access static data members and also change
1. import java.util.Scanner; 2. {
13. } the value of it. It is used to create an instance method. It is invoked
2. public class EvenOdd 3. public static void main(String[] args)
14. //user defined method by using the class name. The best example of a static method is
3. { 4. {
15. public static void findEvenOdd(int num) the main() method.
4. public static void main (String args[]) 5. int a = 19;
16. {
5. { 6. int b = 5;
17. //method body Example of static method
6. //creating Scanner class object 7. //method calling
18. if(num%2==0)
7. Scanner scan=new Scanner(System.in); 8. int c = add(a, b); //a and b are actual parameters
19. System.out.println(num+" is even"); Display.java
8. System.out.print("Enter the number: "); 9. System.out.println("The sum of a and b is= " + c);
20. else
9. //reading value from the user 10. }
21. System.out.println(num+" is odd"); 1. public class Display
10. int num=scan.nextInt(); 11. //user defined method
22. } 2. {
11. //method calling 12. public static int add(int n1, int n2) //n1 and n2 are formal param
23. } 3. public static void main(String[] args)
12. findEvenOdd(num); eters
13. } 13. { 4. {
Output 1: 5. show();
14. int s;
In the above code snippet, as soon as the compiler reaches at 15. s=n1+n2; 6. }
Enter the number: 12
line findEvenOdd(num), the control transfer to the method and 16. return s; //returning the sum 7. static void show()
17. } 8. {
gives the output accordingly. 12 is even
18. } 9. System.out.println("It is an example of static method.");
10. }
Let's combine both snippets of codes in a single program and Output 2:
Output: 11. }
execute it.
Enter the number: 99
The sum of a and b is= 24 Output:
EvenOdd.java
99 is odd
It is an example of a static method.
1. import java.util.Scanner;
2. public class EvenOdd Let's see another program that return a value to the calling method.

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 63 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 64
Instance Method o Accessor Method 1. public class Student Syntax
o Mutator Method 2. {
3. private int roll; 1. abstract void method_name();
The method of the class is known as an instance method. It is a non-
Accessor Method: The method(s) that reads the instance variable(s) 4. private String name;
static method defined in the class. Before calling or invoking the
is known as the accessor method. We can easily identify it because 5. public int getRoll() //accessor method Example of abstract method
instance method, it is necessary to create an object of its class. Let's 6. {
the method is prefixed with the word get. It is also known as getters.
see an example of an instance method. 7. return roll;
It returns the value of the private field. It is used to get the value of Demo.java
8. }
the private field.
InstanceMethodExample.java 9. public void setRoll(int roll) //mutator method 1. abstract class Demo //abstract class
10. { 2. {
1. public class InstanceMethodExample Example
11. this.roll = roll; 3. //abstract method declaration
2. { 12. }
1. public int getId() 4. abstract void display();
3. public static void main(String [] args) 13. public String getName()
2. { 5. }
4. { 14. {
3. return Id; 6. public class MyClass extends Demo
5. //Creating an object of the class 15. return name;
4. } 7. {
6. InstanceMethodExample obj = new InstanceMethodExample(); 16. } 8. //method impelmentation
7. //invoking instance method 17. public void setName(String name)
Mutator Method: The method(s) read the instance variable(s) and 9. void display()
8. System.out.println("The sum is: "+obj.add(12, 13)); 18. {
also modify the values. We can easily identify it because the method 10. {
9. } 19. this.name = name; 11. System.out.println("Abstract method?");
10. int s; is prefixed with the word set. It is also known as setters or modifiers. 20. } 12. }
11. //user-defined method because we have not used static keyword It does not return anything. It accepts a parameter of the same data 21. public void display() 13. public static void main(String args[])
12. public int add(int a, int b) type that depends on the field. It is used to set the value of the private 22. { 14. {
13. { field. 23. System.out.println("Roll no.: "+roll); 15. //creating object of abstract class
14. s = a+b; 24. System.out.println("Student name: "+name); 16. Demo obj = new MyClass();
15. //returning the sum Example 25. } 17. //invoking abstract method
16. return s; 26. } 18. obj.display();
17. } 1. public void setRoll(int roll) 19. }
18. } 2. {
Abstract Method 20. }
3. this.roll = roll;
Output: 4. } Output:
The method that does not has method body is known as abstract
The sum is: 25 method. In other words, without an implementation is known as
Example of accessor and mutator method Abstract method...
abstract method. It always declares in the abstract class. It means
There are two types of instance method: Student.java the class itself must be abstract if it has abstract method. To create
an abstract method, we use the keyword abstract.

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

Factory method 1. By changing number of arguments If the size is int or long and the results overflow the range of value,
2. By changing the data type the methods addExact(), subtractExact(), multiplyExact(),
It is a method that returns an object to the class to which it belongs. 2) Method Overloading: changing data type of and toIntExact() throw an ArithmeticException.
In Java, Method Overloading is not possible by changing the return type
All static methods are factory methods. For arguments
of the method only. For other arithmetic operations like increment, decrement, divide,
example, NumberFormat obj =
NumberFormat.getNumberInstance(); absolute value, and negation overflow occur only with a specific
In this example, we have created two methods that differs in data
1) Method Overloading: changing no. of minimum or maximum value. It should be checked against the
type. The first add method receives two integer arguments and
arguments maximum and minimum value as appropriate.
Method Overloading in Java second add method receives two double arguments.

In this example, we have created two methods, first add() method 1. class Adder{ Java Math Methods
If a class has multiple methods having same name but different in performs addition of two numbers and second add method performs 2. static int add(int a, int b){return a+b;}
parameters, it is known as Method Overloading. addition of three numbers. 3. static double add(double a, double b){return a+b;} The java.lang.Math class contains various methods for performing
4. } basic numeric operations such as the logarithm, cube root, and
If we have to perform only one operation, having same name of the In this example, we are creating static methods so that we don't need 5. class TestOverloading2{ trigonometric functions etc. The various java math methods are as
methods increases the readability of the program. to create instance for calling methods. 6. public static void main(String[] args){
follows:
7. System.out.println(Adder.add(11,11));
Suppose you have to perform addition of the given numbers but 1. class Adder{ 8. System.out.println(Adder.add(12.3,12.6));
there can be any number of arguments, if you write the method such 2. static int add(int a,int b){return a+b;} 9. }} Basic Math methods
as a(int,int) for two parameters, and b(int,int,int) for three parameters 3. static int add(int a,int b,int c){return a+b+c;}
4. }
then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs. 5. class TestOverloading1{
Java Math class Method Description
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11)); Java Math class provides several methods to work on math Math.abs() It will return the Absolute value of the given
So, we perform method overloading to figure out the program
8. System.out.println(Adder.add(11,11,11)); calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), value.
quickly.
9. }} floor(), abs() etc.
Math.max() It returns the Largest of two values.
Advantage of method overloading The Program Output: Unlike some of the StrictMath class numeric methods, all
Math.min() It is used to return the Smallest of two values.
implementations of the equivalent function of Math class can't define
Method overloading increases the readability of the program. 22 to return the bit-for-bit same results. This relaxation permits Math.round() It is used to round of the decimal numbers to
implementation with better-performance where strict reproducibility the nearest value.
Different ways to overload the method 33
is not required.
There are two ways to overload the method in java

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 67 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 68
Math.sqrt() It is used to return the square root of Math.random() It returns a double value with a positive sign, Math.decrementExact() It is used to return the argument decremented Method Description
a number. greater than or equal to 0.0 and less than 1.0. by one, throwing an exception if the result
overflows an int or long.
Math.sin() It is used to return the trigonometric Sine value of a Given
Math.cbrt() It is used to return the cube root of a number. Math.rint() It returns the double value that is closest to the
double value.
given argument and equal to mathematical Math.negateExact() It is used to return the negation of the
Math.pow() It returns the value of first argument raised to integer. argument, throwing an exception if the result
Math.cos() It is used to return the trigonometric Cosine value of a
the power to second argument. overflows an int or long.
Given double value.
Math.hypot() It returns sqrt(x2 +y2) without intermediate
Math.signum() It is used to find the sign of a given value. overflow or underflow. Math.toIntExact() It returns the value of the long argument,
Math.tan() It is used to return the trigonometric Tangent value of a
throwing an exception if the value overflows
Math.ceil() It is used to find the smallest integer value that Given double value.
Math.ulp() It returns the size of an ulp of the argument. an int.
is greater than or equal to the argument or
Math.asin() It is used to return the trigonometric Arc Sine value of a
mathematical integer. Math.getExponent() It is used to return the unbiased exponent used
Given double value
Math.copySign() It is used to find the Absolute value of first
in the representation of a value. Logarithmic Math Methods
Math.acos() It is used to return the trigonometric Arc Cosine value of a
argument along with sign specified in second Math.IEEEremainder() It is used to calculate the remainder operation
Given double value.
argument. on two arguments as prescribed by the IEEE Method Description
754 standard and returns value.
Math.atan() It is used to return the trigonometric Arc Tangent value of
Math.nextAfter() It is used to return the floating-point number
Math.log() It returns the natural logarithm of a double value. a Given double value.
adjacent to the first argument in the direction Math.addExact() It is used to return the sum of its arguments,
of the second argument. throwing an exception if the result overflows
Math.log10() It is used to return the base 10 logarithm of
an int or long.
Math.nextUp() It returns the floating-point value adjacent
a double value. Hyperbolic Math Methods
to d in the direction of positive infinity. Math.subtractExact() It returns the difference of the arguments,
Math.log1p() It returns the natural logarithm of the sum of the
throwing an exception if the result overflows
argument and 1. Method Description
Math.nextDown() It returns the floating-point value adjacent an int.
to d in the direction of negative infinity.
Math.exp() It returns E raised to the power of a double value, where
Math.multiplyExact() It is used to return the product of the Math.sinh() It is used to return the trigonometric Hyperbolic Cosine value of
E is Euler's number and it is approximately equal to
Math.floor() It is used to find the largest integer value which arguments, throwing an exception if the result
2.71828. Math.cosh() It is used to return the trigonometric Hyperbolic Sine value of a
is less than or equal to the argument and is overflows an int or long.
equal to the mathematical integer of a double
Math.expm1() It is used to calculate the power of E and subtract one Math.tanh() It is used to return the trigonometric Hyperbolic Tangent value o
value. Math.incrementExact() It returns the argument incremented by one,
from it.
throwing an exception if the result overflows
Math.floorDiv() It is used to find the largest integer value that an int.
is less than or equal to the algebraic quotient. Angular Math Methods
Trigonometric Math Methods
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 69 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 70

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


Method Description not available in C/C++.
Single Dimensional Array in Java
20
Math.toDegrees It is used to convert the specified Radians angle to Syntax to Declare an Array in Java
equivalent angle measured in Degrees. 70
1. dataType[] arr; (or)
Math.toRadians It is used to convert the specified Degrees angle to 2. dataType []arr; (or) 40
equivalent angle measured in Radians. 3. dataType arr[];
50

Instantiation of an Array in Java


Java Arrays
Advantages 1. arrayRefVar=new datatype[size];

Normally, an array is a collection of similar type of elements which Declaration, Instantiation and Initialization
has contiguous memory location.
o Code Optimization: It makes the code optimized, we can retrieve Example of Java Array of Java Array
or sort the data efficiently.
o Random access: We can get any data located at an index position. Let's see the simple example of java array, where we are going to
Java array is an object which contains elements of a similar data We can declare, instantiate and initialize the java array together by:
type. Additionally, the elements of an array are stored in a contiguous declare, instantiate, initialize and traverse an array.
memory location. It is a data structure where we store similar Disadvantages
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
elements. We can store only a fixed set of elements in a Java array. 1. //Java Program to illustrate how to declare, instantiate, initialize
o Size Limit: We can store only the fixed size of elements in the array. 2. //and traverse the Java array.
Let's see the simple example to print this array.
It doesn't grow its size at runtime. To solve this problem, collection 3. class Testarray{
Array in Java is index-based, the first element of the array is stored at
framework is used in Java which grows automatically. 4. public static void main(String args[]){
the 0th index, 2nd element is stored on 1st index and so on. 1. //Java Program to illustrate the use of declaration, instantiation
5. int a[]=new int[5];//declaration and instantiation
2. //and initialization of Java array in a single line
6. a[0]=10;//initialization
Unlike C/C++, we can get the length of the array using the length 3. class Testarray1{
7. a[1]=20;
member. In C/C++, we need to use the sizeof operator. 4. public static void main(String args[]){
8. a[2]=70;
Types of Array in java 9. a[3]=40;
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
In Java, array is an object of a dynamically generated class. Java array 6. //printing array
10. a[4]=50;
inherits the Object class, and implements the Serializable as well as There are two types of array. 7. for(int i=0;i<a.length;i++)//length is the property of array
11. //traversing array
8. System.out.println(a[i]);
Cloneable interfaces. We can store primitive values or objects in an 12. for(int i=0;i<a.length;i++)//length is the property of array
o Single Dimensional Array 9. }}
array in Java. Like C/C++, we can also create single dimentional or 13. System.out.println(a[i]);
o Multidimensional Array
multidimentional arrays in Java. 14. }}
Output:
Output: 33

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 71 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 72
3 3 Output:
Returning Array from the Method
4 4 3
We can also return an array from the method in Java.
5 5
Anonymous Array in Java 1. //Java Program to return an array from the method
2. class TestReturnArray{
For-each Loop for Java Array Java supports the feature of an anonymous array, so you don't need 3. //creating method which returns an array
Passing Array to a Method in Java to declare the array while passing an array to the method. 4. static int[] get(){
We can also print the Java array using for-each loop. The Java for- 5. return new int[]{10,30,50,90,60};
each loop prints the array elements one by one. It holds an array 1. //Java Program to demonstrate the way of passing an anonymous 6. }
element in a variable, then executes the body of the loop. We can pass the java array to method so that we can reuse the same
array 7.
logic on any array. 2. //to method. 8. public static void main(String args[]){
The syntax of the for-each loop is given below: 3. public class TestAnonymousArray{ 9. //calling method which returns an array
Let's see the simple example to get the minimum number of an array 4. //creating a method which receives an array as a parameter 10. int arr[]=get();
1. for(data_type variable:array){ using a method. 5. static void printArray(int arr[]){ 11. //printing the values of an array
2. //body of the loop 6. for(int i=0;i<arr.length;i++) 12. for(int i=0;i<arr.length;i++)
3. } 1. //Java Program to demonstrate the way of passing an array 7. System.out.println(arr[i]); 13. System.out.println(arr[i]);
2. //to method. 8. } 14. }}
Let us see the example of print the elements of Java array using the 3. class Testarray2{ 9.
for-each loop. 4. //creating a method which receives an array as a parameter 10. public static void main(String args[]){ Output:
5. static void min(int arr[]){ 11. printArray(new int[]{10,22,44,66});//passing anonymous array to m
1. //Java Program to print the array elements using for-each loop 6. int min=arr[0]; ethod 10
2. class Testarray1{ 7. for(int i=1;i<arr.length;i++) 12. }}
3. public static void main(String args[]){ 8. if(min>arr[i]) 30
4. int arr[]={33,3,4,5}; 9. min=arr[i]; Output:
5. //printing array using for-each loop 10. 50
6. for(int i:arr) 11. System.out.println(min); 10
12. } 90
7. System.out.println(i);
8. }} 13. 22
60
14. public static void main(String args[]){
Output: 15. int a[]={33,3,4,5};//declaring and initializing an array 44
16. min(a);//passing array to method
66
ArrayIndexOutOfBoundsException
33 17. }}

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

The Java Virtual Machine (JVM) throws an In such case, data is stored in row and column based index (also 4. //declaring and initializing 2D array 10. int count = 0;
ArrayIndexOutOfBoundsException if length of the array in negative, known as matrix form). 5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 11. for (int i=0; i<arr.length; i++)
equal to the array size or greater than the array size while traversing 6. //printing 2D array 12. for(int j=0; j<arr[i].length; j++)
the array. Syntax to Declare Multidimensional Array in Java 7. for(int i=0;i<3;i++){ 13. arr[i][j] = count++;
8. for(int j=0;j<3;j++){ 14.
1. //Java Program to demonstrate the case of 1. dataType[][] arrayRefVar; (or) 9. System.out.print(arr[i][j]+" "); 15. //printing the data of a jagged array
2. //ArrayIndexOutOfBoundsException in a Java Array. 2. dataType [][]arrayRefVar; (or) 10. } 16. for (int i=0; i<arr.length; i++){
3. public class TestArrayException{ 3. dataType arrayRefVar[][]; (or) 11. System.out.println(); 17. for (int j=0; j<arr[i].length; j++){
4. public static void main(String args[]){ 4. dataType []arrayRefVar[]; 12. } 18. System.out.print(arr[i][j]+" ");
5. int arr[]={50,60,70,80}; 13. }} 19. }
6. for(int i=0;i<=arr.length;i++){ Example to instantiate Multidimensional Array in Java 20. System.out.println();//new line
7. System.out.println(arr[i]); Output: 21. }
8. } 1. int[][] arr=new int[3][3];//3 row and 3 column 22. }
123 23. }
9. }}
Example to initialize Multidimensional Array in Java
245 Output:
Output:
1. arr[0][0]=1;
445 012
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 2. arr[0][1]=2;
3. arr[0][2]=3;
at TestArrayException.main(TestArrayException.java:5) 4. arr[1][0]=4; Jagged Array in Java 3456

5. arr[1][1]=5;
50 78
6. arr[1][2]=6; If we are creating odd number of columns in a 2D array, it is known
7. arr[2][0]=7; as a jagged array. In other words, it is an array of arrays with different
60
8. arr[2][1]=8; number of columns.
9. arr[2][2]=9;
70
1. //Java Program to illustrate the jagged array What is the class name of Java array?
80 Example of Multidimensional Java Array 2. class TestJaggedArray{
3. public static void main(String[] args){ In Java, an array is an object. For array object, a proxy class is created
Let's see the simple example to declare, instantiate, initialize and print 4. //declaring a 2D array with odd columns whose name can be obtained by getClass().getName() method on the
the 2Dimensional array. 5. int arr[][] = new int[3][]; object.
6. arr[0] = new int[3];
Multidimensional Array in Java 7. arr[1] = new int[4]; 1. //Java Program to get the class name of array in Java
1. //Java Program to illustrate the use of multidimensional array
2. class Testarray3{ 8. arr[2] = new int[2]; 2. class Testarray4{
3. public static void main(String args[]){ 9. //initializing a jagged array 3. public static void main(String args[]){

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 75 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 76
4. //declaration and initialization of array 6. 'i', 'n', 'a', 't', 'e', 'd' }; o An object is a runtime entity.
5. int arr[]={4,4,5}; 7. //declaring a destination array o The object is an entity which has state and behavior.
6. //getting the class name of Java array 8. char[] copyTo = new char[7]; o The object is an instance of a class.
7. Class c=arr.getClass(); 9. //copying array using System.arraycopy() method
8. String name=c.getName(); 10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
9. //printing the class name of Java array 11. //printing the destination array
10. System.out.println(name); 12. System.out.println(String.valueOf(copyTo));
11. 13. }
12. }} 14. }

Output: An entity that has state and behavior is known as an object e.g., chair,
bike, marker, pen, table, car, etc. It can be physical or logical (tangible
I and intangible). The example of an intangible object is the banking
system.
Copying a Java Array
An object has three characteristics:
We can copy an array to another by the arraycopy() method of
o State: represents the data (value) of an object.
System class.
o Behavior: represents the behavior (functionality) of an object such
as deposit, withdraw, etc.
Syntax of arraycopy method
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
1. public static void arraycopy(
internally by the JVM to identify each object uniquely.
2. Object src, int srcPos,Object dest, int destPos, int length
3. )
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.
Example of Copying an Array in Java
An object is an instance of a class. A class is a template or blueprint
1. //Java Program to copy a source array into a destination array in Ja
from which objects are created. So, an object is the instance(result)
va
of a class.
2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
Object Definitions:
4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
o An object is a real-world entity.

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

Syntax to declare a class: 15. }


The class in Java new keyword in Java
1. class <class_name>{ Output:
A class is a group of objects which have common properties. It is a The new keyword is used to allocate memory at runtime. All objects
2. field;
template or blueprint from which objects are created. It is a logical 3. method; get memory in Heap memory area. 0
entity. It can't be physical. 4. }
null
A class in Java can contain:
Object and Class Example: main within the Object and Class Example: main outside the
• Fields
• Methods Instance variable in Java class class
• Constructors
• Blocks A variable which is created inside the class but outside the method is In this example, we have created a Student class which has two data In real time development, we create classes and use it from another
• Nested class and interface known as an instance variable. Instance variable doesn't get memory members id and name. We are creating the object of the Student class. It is a better approach than previous one. Let's see a simple
at compile time. It gets memory at runtime when an object or class by new keyword and printing the object's value. example, where we are having main() method in another class.
instance is created. That is why it is known as an instance variable.
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 source file, it is a good
File: Student.java idea to save the file name with the class name which has main()
method.
Method in Java 1. //Java Program to illustrate how to define a class and fields
2. //Defining a Student class. File: TestStudent1.java
In Java, a method is like a function which is used to expose the 3. class Student{
behavior of an object. 4. //defining fields 1. //Java Program to demonstrate having the main method in
5. int id;//field or data member or instance variable 2. //another class
Advantage of Method 6. String name; 3. //Creating Student class.
7. //creating main method inside the Student class 4. class Student{
o Code Reusability 8. public static void main(String args[]){ 5. int id;
o Code Optimization 9. //Creating an object or instance 6. String name;
10. Student s1=new Student();//creating an object of Student 7. }
11. //Printing values of the object 8. //Creating another class TestStudent1 which contains the main me
12. System.out.println(s1.id);//accessing member through reference v thod
ariable 9. class TestStudent1{
13. System.out.println(s1.name); 10. public static void main(String args[]){
14. }

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 79 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 80
11. Student s1=new Student(); 5. class TestStudent2{ 17. System.out.println(s2.id+" "+s2.name); 15. s2.insertRecord(222,"Aryan");
12. System.out.println(s1.id); 6. public static void main(String args[]){ 18. } 16. s1.displayInformation();
13. System.out.println(s1.name); 7. Student s1=new Student(); 19. } 17. s2.displayInformation();
14. } 8. s1.id=101; 18. }
15. } 9. s1.name="Sonoo"; Output: 19. }
10. System.out.println(s1.id+" "+s1.name);//printing members with a
Output: white space 101 Sonoo Output:
11. }
0 12. } 102 Amit 111 Karan

null 222 Aryan


Output: 2) Object and Class Example: Initialization
through method
3 Ways to initialize object 101 Sonoo

We can also create multiple objects and store information in it In this example, we are creating the two objects of Student class and
There are 3 ways to initialize object in Java. initializing the value to these objects by invoking the insertRecord
through reference variable.
method. Here, we are displaying the state (data) of the objects by
1. By reference variable
File: TestStudent3.java invoking the displayInformation() method.
2. By method
3. By constructor
1. class Student{ File: TestStudent4.java
2. int id;
1) Object and Class Example: Initialization 3. String name; 1. class Student{
through reference 4. } 2. int rollno;
5. class TestStudent3{ 3. String name;
6. public static void main(String args[]){ 4. void insertRecord(int r, String n){ As you can see in the above figure, object gets the memory in heap
Initializing an object means storing data into the object. Let's see a
7. //Creating objects 5. rollno=r; memory area. The reference variable refers to the object allocated in
simple example where we are going to initialize the object through a
8. Student s1=new Student(); 6. name=n; the heap memory area. Here, s1 and s2 both are reference variables
reference variable. 9. Student s2=new Student(); 7. }
that refer to the objects allocated in memory.
10. //Initializing objects 8. void displayInformation(){System.out.println(rollno+" "+name);}
File: TestStudent2.java
11. s1.id=101; 9. }
12. s1.name="Sonoo"; 10. class TestStudent4{
1. class Student{
13. s2.id=102; 11. public static void main(String args[]){
2. int id;
14. s2.name="Amit"; 12. Student s1=new Student();
3. String name;
15. //Printing data 13. Student s2=new Student();
4. }
16. System.out.println(s1.id+" "+s1.name); 14. s1.insertRecord(111,"Karan");

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

23. } 17. r2.calculateArea(); 1. new Calculation();//anonymous object


3) Object and Class Example: Initialization
24. } 18. }
through a constructor 19. } Calling method through a reference:
Output:
Output: 1. Calculation c=new Calculation();
101 ajeet 45000.0 2. c.fact(5);
55
Object and Class Example: Employee 102 irfan 25000.0 Calling method through an anonymous object
45
Let's see an example where we are maintaining records of employees. 103 nakul 55000.0
1. new Calculation().fact(5);
File: TestEmployee.java What are the different ways to create an
Object and Class Example: Rectangle Let's see the full example of an anonymous object in Java.
1. class Employee{ object in Java?
There is given another example that maintains the records of 1. class Calculation{
2. int id;
Rectangle class. There are many ways to create an object in java. They are: 2. void fact(int n){
3. String name;
3. int fact=1;
4. float salary;
File: TestRectangle1.java o By new keyword 4. for(int i=1;i<=n;i++){
5. void insert(int i, String n, float s) {
o By newInstance() method 5. fact=fact*i;
6. id=i;
1. class Rectangle{ o By clone() method 6. }
7. name=n;
2. int length; o By deserialization 7. System.out.println("factorial is "+fact);
8. salary=s;
3. int width; o By factory method etc. 8. }
9. }
4. void insert(int l, int w){ 9. public static void main(String args[]){
10. void display(){System.out.println(id+" "+name+" "+salary);}
5. length=l; We will learn these ways to create object later. 10. new Calculation().fact(5);//calling method with anonymous object
11. }
12. public class TestEmployee { 6. width=w;
7. } 11. }
13.
14.
public static void main(String[] args) {
Employee e1=new Employee(); 8. void calculateArea(){System.out.println(length*width);}
Anonymous object 12. }
15. Employee e2=new Employee(); 9. }
10. class TestRectangle1{ Anonymous simply means nameless. An object which has no Output:
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000); 11. public static void main(String args[]){ reference is known as an anonymous object. It can be used at the
12. Rectangle r1=new Rectangle(); time of object creation only. Factorial is 120
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000); 13. Rectangle r2=new Rectangle();
20. e1.display(); 14. r1.insert(11,5); If you have to use an object only once, an anonymous object is a
21. e2.display(); 15. r2.insert(3,15); good approach. For example:
22. e3.display(); 16. r1.calculateArea();

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 83 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 84
16. r2.insert(3,15); a class. It is because java compiler creates a default constructor if your
Creating multiple objects by one type 17. r1.calculateArea(); class doesn't have any.
only 18. r2.calculateArea();
19. }
20. }
Rules for creating Java constructor
We can create multiple objects by one type only as we do in case of
primitives. There are two rules defined for the constructor.
Output:
Initialization of primitive variables: 55 1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
1. int a=10, b=20; 45 3. A Java constructor cannot be abstract, static, final, and synchronized

Initialization of refernce variables: Note: We can use access modifiers while declaring a constructor. It
Constructors in Java controls the object creation. In other words, we can have private,
1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two protected, public or default constructor in Java.
objects In Java, a constructor is a block of codes similar to the method. It is

Let's see the example:


called when an instance of the class is created. At the time of calling Types of Java constructors
constructor, memory for the object is allocated in the memory. Java Default Constructor
1. //Java Program to illustrate the use of Rectangle class which There are two types of constructors in Java:
It is a special type of method which is used to initialize the object. A constructor is called "Default Constructor" when it doesn't have any
2. //has length and width data members
3. class Rectangle{ 1. Default constructor (no-arg constructor) parameter.
Every time an object is created using the new() keyword, at least one 2. Parameterized constructor
4. int length;
5. int width; constructor is called. The default constructor is used to provide the default values to the
6. void insert(int l,int w){ object like 0, null, etc., depending on the type.
7. length=l; It calls a default constructor if there is no constructor available in the
8. width=w; class. In such case, Java compiler provides a default constructor by
Syntax of default constructor:
9. } default.
10. void calculateArea(){System.out.println(length*width);} 1. <class_name>(){}
11. } There are two types of constructors in Java: no-arg constructor, and
12. class TestRectangle2{ parameterized constructor.
13. public static void main(String args[]){
Example of default constructor
14. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two Note: It is called constructor because it constructs the values at the
objects 1. //Java Program to create and call a default constructor
time of object creation. It is not necessary to write a constructor for
15. r1.insert(11,5); 2. class Bike1{

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

3. //creating a default constructor 7. id = i; differentiated by the compiler by the number of parameters in the 27. 111 Karan 0
4. Bike1(){System.out.println("Bike is created");} 8. name = n; list and their types. 28. 222 Aryan 25
5. //main method 9. }
6. public static void main(String args[]){
7. //calling a default constructor
10. //method to display the values Example of Constructor Overloading Difference between constructor and
11. void display(){System.out.println(id+" "+name);}
8. Bike1 b=new Bike1();
12. 1. //Java program to overload constructors
method in Java
9. }
10. }
13. public static void main(String args[]){ 2. class Student5{
14. //creating objects and passing values There are many differences between constructors and methods. They
3. int id;
15. Student4 s1 = new Student4(111,"Karan"); are given below.
4. String name;
Java Parameterized Constructor 16. Student4 s2 = new Student4(222,"Aryan"); 5. int age;
17. //calling method to display the values of object 6. //creating two arg constructor Java Constructor Java Method
A constructor which has a specific number of parameters is called a 18. s1.display(); 7. Student5(int i,String n){
parameterized constructor. 19. s2.display(); 8. id = i; A constructor is used to initialize the A method is used to
20. } 9. name = n; state of an object. expose the behavior of an
Why use the parameterized constructor? 21. } 10. } object.
The parameterized constructor is used to provide different values to 11. //creating three arg constructor
Output A constructor must not have a return A method must have a
distinct objects. However, you can provide the same values also. 12. Student5(int i,String n,int a){
13. id = i; type. return type.
111 Karan
14. name = n;
Example of parameterized constructor 15. age=a;
The constructor is invoked implicitly. The method is invoked
222 Aryan
explicitly.
16. }
In this example, we have created the constructor of Student class that
17. void display(){System.out.println(id+" "+name+" "+age);} The Java compiler provides a default The method is not
have two parameters. We can have any number of parameters in the
18. constructor if you don't have any provided by the compiler
constructor.
Constructor Overloading in Java 19. public static void main(String args[]){ constructor in a class. in any case.
1. //Java Program to demonstrate the use of the parameterized 20. Student5 s1 = new Student5(111,"Karan");
constructor. 21. Student5 s2 = new Student5(222,"Aryan",25); The constructor name must be same The method name may or
In Java, a constructor is just like a method but without return type. It
2. class Student4{ 22. s1.display(); as the class name. may not be same as the
can also be overloaded like Java methods.
3. int id; 23. s2.display(); class name.
4. String name; Constructor overloading in Java is a technique of having more than 24. }
5. //creating a parameterized constructor one constructor with different parameter lists. They are arranged in a 25. }
6. Student4(int i,String n){ way that each constructor performs a different task. They are 26. Output:

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 87 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 88
Java String class provides a lot of methods to perform operations
on strings such as compare(), concat(), equals(), split(), length(),
1) String Literal
replace(), compareTo(), intern(), substring() etc.
Java String literal is created by using double quotes. For Example:
The java.lang.String class
1. String s="welcome";
implements Serializable, Comparable and CharSequence interfaces.
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference
to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool. For
example:

1. String s1="Welcome";
The Java String is immutable which means it cannot be changed. 2. String s2="Welcome";//It doesn't create a new instance
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 String object.
Java String
CharSequence Interface What is String in Java?
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example: The CharSequence interface is used to represent the sequence of Generally, String is a sequence of characters. But in Java, string is an
characters. String, StringBuffer and StringBuilder classes implement object that represents a sequence of characters. The java.lang.String
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'}; it. It means, we can create strings in Java by using these three classes. class is used to create a string object.
2. String s=new String(ch);

is same as: How to create a string object? In the above example, only one object will be created. Firstly, JVM will
not find any string object with the value "Welcome" in string constant
1. String s="javatpoint"; There are two ways to create String object: pool that is why it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new
1. By string literal
object but will return the reference to the same instance.
2. By new keyword

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

Note: String objects are stored in a special memory area known as the 10. }}
5 String substring(int It returns substring for given 14 String It replaces all occurrences of
"string constant pool".
Output: beginIndex) begin index. replace(CharSequence old, the specified CharSequence.
CharSequence new)
Why Java uses the concept of String literal? java 6 String substring(int It returns substring for given
beginIndex, int endIndex) begin index and end index. 15 static String It compares another string.
To make Java more memory efficient (because no new objects are strings equalsIgnoreCase(String It doesn't check case.
created if it exists already in the string constant pool). 7 boolean It returns true or false after another)
example contains(CharSequence s) matching the sequence of
2) By new keyword The above code, converts a char array into a String object. And
char value. 16 String[] split(String regex) It returns a split string
matching regex.
displays the String objects s1, s2, and s3 on console 8 static String It returns a joined string.
1. String s=new String("Welcome");//creates two objects and one ref
using println() method. join(CharSequence 17 String[] split(String regex, It returns a split string
erence variable
delimiter, CharSequence... int limit) matching regex and limit.
In such case, JVM will create a new string object in normal (non-pool) Java String class methods elements)
18 String intern() It returns an interned string.
heap memory, and the literal "Welcome" will be placed in the string
9 static String It returns a joined string.
constant pool. The variable s will refer to the object in a heap (non- The java.lang.String class provides many useful methods to perform 19 int indexOf(int ch) It returns the specified char
join(CharSequence
pool). operations on sequence of char values. value index.
delimiter, Iterable<?
extends CharSequence>
Java String Example No. Method Description elements)
20 int indexOf(int ch, int It returns the specified char
fromIndex) value index starting with
StringExample.java 10 boolean equals(Object It checks the equality of given index.
1 char charAt(int index) It returns char value for the
particular index another) string with the given object.
1. public class StringExample{ 21 int indexOf(String substring) It returns the specified
2. public static void main(String args[]){ 11 boolean isEmpty() It checks if string is empty. substring index.
2 int length() It returns string length
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'}; 12 String concat(String str) It concatenates the specified 22 int indexOf(String substring, It returns the specified
3 static String format(String It returns a formatted string.
5. String s2=new String(ch);//converting char array to string string. int fromIndex) substring index starting with
format, Object... args)
6. String s3=new String("example");//creating Java string by new key given index.
word 4 static String format(Locale l, It returns formatted string 13 String replace(char old, char It replaces all occurrences of
7. System.out.println(s1); new) the specified char value. 23 String toLowerCase() It returns a string in
String format, Object... args) with given locale.
8. System.out.println(s2); lowercase.
9. System.out.println(s3);

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 91 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 92
24 String toLowerCase(Locale l) It returns a string in Important Constructors of StringBuffer insert(int, char), insert(int, boolean), public String substring(int It is used to return the substring
lowercase using specified insert(int, int), insert(int, float), beginIndex, int from the specified beginIndex and
locale. Class insert(int, double) etc. endIndex) endIndex.

25 String toUpperCase() It returns a string in public replace(int It is used to replace the string from
uppercase.
Constructor Description synchronized startIndex, int specified startIndex and endIndex. What is a mutable String?
StringBuffer endIndex, String
StringBuffer() It creates an empty String buffer with the initial str)
26 String toUpperCase(Locale It returns a string in A String that can be modified or changed is known as mutable String.
capacity of 16.
l) uppercase using specified public delete(int It is used to delete the string from StringBuffer and StringBuilder classes are used for creating mutable
locale. StringBuffer(String It creates a String buffer with the specified string.. synchronized startIndex, int specified startIndex and endIndex. strings.
str) StringBuffer endIndex)
27 String trim() It removes beginning and 1) StringBuffer Class append() Method
ending spaces of this string. StringBuffer(int It creates an empty String buffer with the specified public reverse() is used to reverse the string.
capacity) capacity as length. synchronized The append() method concatenates the given argument with this
28 static String valueOf(int It converts given type into StringBuffer
String.
value) string. It is an overloaded
method. Important methods of StringBuffer class public int capacity() It is used to return the current
StringBufferExample.java
capacity.

1. class StringBufferExample{
Java StringBuffer Class Modifier Method Description public void ensureCapacity(int
minimumCapacity)
It is used to ensure the capacity at
least equal to the given minimum. 2. public static void main(String args[]){
and Type 3. StringBuffer sb=new StringBuffer("Hello ");
Java StringBuffer class is used to create mutable (modifiable) String public char charAt(int index) It is used to return the character at 4. sb.append("Java");//now original string is changed
public append(String s) It is used to append the specified the specified position. 5. System.out.println(sb);//prints Hello Java
objects. The StringBuffer class in Java is the same as String class
synchronized string with this string. The append() 6. }
except it is mutable i.e. it can be changed.
StringBuffer method is overloaded like public int length() It is used to return the length of the 7. }
append(char), append(boolean), string i.e. total number of
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot
append(int), append(float), characters. Output:
access it simultaneously. So it is safe and will result in an order.
append(double) etc.
public String substring(int It is used to return the substring Hello Java
public insert(int offset, It is used to insert the specified beginIndex) from the specified beginIndex.
synchronized String s) string with this string at the
StringBuffer specified position. The insert()
method is overloaded like

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

Output: 5. System.out.println(sb);//prints olleH 16


2) StringBuffer insert() Method
6. }
HJavalo 7. } 34
The insert() method inserts the given String with this string at the
given position.
4) StringBuffer delete() Method Output: 7) StringBuffer ensureCapacity() method
StringBufferExample2.java olleH
The delete() method of the StringBuffer class deletes the String from The ensureCapacity() method of the StringBuffer class ensures that
1. class StringBufferExample2{ the specified beginIndex to endIndex. the given capacity is the minimum to the current capacity. If it is
2. public static void main(String args[]){ 6) StringBuffer capacity() Method greater than the current capacity, it increases the capacity by
3. StringBuffer sb=new StringBuffer("Hello "); StringBufferExample4.java (oldcapacity*2)+2. For example if your current capacity is 16, it will be
4. sb.insert(1,"Java");//now original string is changed The capacity() method of the StringBuffer class returns the current (16*2)+2=34.
5. System.out.println(sb);//prints HJavaello 1. class StringBufferExample4{ capacity of the buffer. The default capacity of the buffer is 16. If the
6. } 2. public static void main(String args[]){ number of character increases from its current capacity, it increases StringBufferExample7.java
7. } 3. StringBuffer sb=new StringBuffer("Hello"); the capacity by (oldcapacity*2)+2. For example if your current
4. sb.delete(1,3); capacity is 16, it will be (16*2)+2=34. 1. class StringBufferExample7{
Output: 5. System.out.println(sb);//prints Hlo 2. public static void main(String args[]){
6. } StringBufferExample6.java 3. StringBuffer sb=new StringBuffer();
HJavaello 7. } 4. System.out.println(sb.capacity());//default 16
1. class StringBufferExample6{ 5. sb.append("Hello");
3) StringBuffer replace() Method Output: 2. public static void main(String args[]){ 6. System.out.println(sb.capacity());//now 16
3. StringBuffer sb=new StringBuffer(); 7. sb.append("java is my favourite language");
Hlo 4. System.out.println(sb.capacity());//default 16 8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacit
The replace() method replaces the given String from the specified
5. sb.append("Hello"); y*2)+2
beginIndex and endIndex.
5) StringBuffer reverse() Method 6. System.out.println(sb.capacity());//now 16 9. sb.ensureCapacity(10);//now no change
7. sb.append("java is my favourite language"); 10. System.out.println(sb.capacity());//now 34
StringBufferExample3.java
The reverse() method of the StringBuilder class reverses the current 8. System.out.println(sb.capacity());//now (16*2)+2=34 11. sb.ensureCapacity(50);//now (34*2)+2
String. 9. i.e (oldcapacity*2)+2 12. System.out.println(sb.capacity());//now 70
1. class StringBufferExample3{
10. } 13. }
2. public static void main(String args[]){
11. } 14. }
3. StringBuffer sb=new StringBuffer("Hello"); StringBufferExample5.java
4. sb.replace(1,3,"Java");
1. class StringBufferExample5{ Output: Output:
5. System.out.println(sb);//prints HJavalo
6. } 2. public static void main(String args[]){
16 16
7. } 3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();

Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 95 Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 96
16
character, represented as static File createTempFile(Strin It creates an empty file in the String getName() It returns the name of the file or
34 a string for convenience. g prefix, String suffix) default temporary-file directory, directory denoted by this
using the given prefix and suffix abstract pathname.
34 static char separatorChar It is system-dependent to generate its name.
default name-separator String getParent() It returns the pathname string of
70 character. boolean createNewFile() It atomically creates a new, this abstract pathname's parent,
empty file named by this or null if this pathname does not
abstract pathname if and only if name a parent directory.
Java File Class Constructors a file with this name does not yet
exist. Path toPath() It returns a java.nio.file.Path
object constructed from the this
The File class is an abstract representation of file and directory Constructor Description boolean canWrite() It tests whether the application abstract path.
pathname. A pathname can be either absolute or relative.
can modify the file denoted by
File(File parent, It creates a new File instance from a parent this abstract pathname.String[] URI toURI() It constructs a file: URI that
The File class have several methods for working with directories and String child) abstract pathname and a child pathname string. represents this abstract
files such as creating new directories or files, deleting and renaming boolean canExecute() It tests whether the application pathname.
directories or files, listing the contents of a directory etc. File(String It creates a new File instance by converting the can execute the file denoted by
pathname) given pathname string into an abstract this abstract pathname. File[] listFiles() It returns an array of abstract
Fields pathname. pathnames denoting the files in
boolean canRead() It tests whether the application the directory denoted by this
File(String parent, It creates a new File instance from a parent can read the file denoted by this abstract pathname
Modifier Type Field Description String child) pathname string and a child pathname string. abstract pathname.
long getFreeSpace() It returns the number of
File(URI uri) It creates a new File instance by converting the boolean isAbsolute() It tests whether this abstract unallocated bytes in the
static String pathSeparator It is system-dependent
given file: URI into an abstract pathname. pathname is absolute. partition named by this abstract
path-separator character,
path name.
represented as
boolean isDirectory() It tests whether the file denoted
a string for convenience. Useful Methods by this abstract pathname is a String[] list(FilenameFilter It returns an array of strings
directory. filter) naming the files and directories
static char pathSeparatorChar It is system-dependent
in the directory denoted by this
path-separator character. Modifier Method Description boolean isFile() It tests whether the file denoted abstract pathname that satisfy
static String separator It is system-dependent
and Type by this abstract pathname is a the specified filter.
normal file.
default name-separator

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

4. float fee;
boolean mkdir() It creates the directory named by
5. Student(int rollno,String name,float fee){
this abstract pathname.
6. rollno=rollno;
7. name=name;
8. fee=fee;
this keyword in Java 9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
There can be a lot of usage of Java this keyword. In Java, this is 11. }
a reference variable that refers to the current object. 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. }}

-* * * * * * * *-

Usage of Java this keyword 1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable.
Here is given the 6 usage of java this keyword.
If there is ambiguity between the instance variables and parameters,
1. this can be used to refer current class instance variable. this keyword resolves the problem of ambiguity.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor. Understanding the problem without this keyword
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call. Let's understand the problem if we don't use this keyword by the
6. this can be used to return the current class instance from the example given below:
method.
1. class Student{
Suggestion: If you are beginner to java, lookup only three usages of 2. int rollno;
this keyword. 3. String name;

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

You might also like