UNIT 1 Introduction To Java Class and Objects
UNIT 1 Introduction To Java Class and Objects
Simple.java
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 1
Standalone applications are also known as desktop It is a Java programming platform. It includes Java
applications or window-based applications. These are programming APIs such as java.lang, java.io, java.net,
traditional software that we need to install on every java.util, java.sql, java.math etc. It includes core topics like
machine. Examples of standalone application are Media OOPs, String, Regex, Exception, Inner classes,
player, antivirus, etc. AWT and Swing are used in Java for Multithreading, I/O Stream, Networking, AWT, Swing,
creating standalone applications. Reflection, Collection, etc.
An application that runs on the server side and creates a It is an enterprise platform that is mainly used to develop
dynamic page is called a web application. web and enterprise applications. It is built on top of the
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. Java SE platform. It includes topics like Servlet, JSP, Web
technologies are used for creating web applications in Java. Services, EJB, JPA, etc.
An application that is distributed in nature, such as banking It is a micro platform that is dedicated to mobile
applications, etc. is called an enterprise application. It has applications.
advantages like high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise 4) JavaFX
applications.
It is used to develop rich internet applications. It uses a
4) Mobile Application lightweight user interface API.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 2
1. Simple Object-oriented programming (OOPs) is a methodology that
2. Object-Oriented simplifies software development and maintenance by
3. Portable providing some rules.
4. Platform independent
5. Secured Basic concepts of OOPs are:
6. Robust
7. Architecture neutral 1. Object
8. Interpreted 2. Class
9. High Performance
3. Inheritance
10. Multithreaded
11. Distributed 4. Polymorphism
12. Dynamic 5. Abstraction
6. Encapsulation
Simple
Platform Independent
Java is very easy to learn, and its syntax is simple, clean
and easy to understand. According to Sun Microsystem,
Java language is a simple programming language because:
Object-Oriented
Java is an object-oriented programming language. Java is platform independent because it is different from
Everything in Java is an object. Object-oriented means we other languages like C, C++, etc. which are compiled into
organize our software as a combination of different types platform specific machines while Java is a write once, run
of objects that incorporate both data and behavior. anywhere language. A platform is the hardware or software
environment in which a program runs.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 3
There are two types of platforms software-based and Java language provides these securities by default. Some
hardware-based. Java provides a software-based platform. security can also be provided by an application developer
explicitly through SSL, JAAS, Cryptography, etc.
The Java platform differs from most other platforms in the
sense that it is a software-based platform that runs on top Robust
of other hardware-based platforms. It has two components:
The English mining of Robust is strong. Java is robust
1. Runtime Environment
because:
2. API(Application Programming Interface)
It uses strong memory management.
Java code can be executed on multiple platforms, for There is a lack of pointers that avoids security problems.
example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java Java provides automatic garbage collection which runs on
code is compiled by the compiler and converted into the Java Virtual Machine to get rid of objects which are not being
bytecode. This bytecode is a platform-independent code used by a Java application anymore.
because it can be run on multiple platforms, i.e., Write There are exception handling and the type checking
Once and Run Anywhere (WORA). mechanism in Java. All these points make Java robust.
Secured Architecture-neutral
Java is best known for its security. With Java, we can Java is architecture neutral because there are no
develop virus-free systems. Java is secured because: implementation dependent features, for example, the size
of primitive types is fixed.
No explicit pointer
Java Programs run inside a virtual machine sandbox In C programming, int data type occupies 2 bytes of
Classloader: Classloader in Java is a part of the Java memory for 32-bit architecture and 4 bytes of memory for
Runtime Environment (JRE) which is used to load Java 64-bit architecture. However, it occupies 4 bytes of
classes into the Java Virtual Machine dynamically. It adds memory for both 32 and 64-bit architectures in Java.
security by separating the package for the classes of the
local file system from those that are imported from Portable
network sources.
Bytecode Verifier: It checks the code fragments for Java is portable because it facilitates you to carry the Java
illegal code that can violate access rights to objects. bytecode to any platform. It doesn't require any
Security Manager: It determines what resources a implementation.
class can access such as reading and writing to the local
disk.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 4
High-performance It also supports functions from its native languages, i.e., C
and C++.
Java is faster than other traditional interpreted
programming languages because Java bytecode is "close" Java supports dynamic compilation and automatic memory
to native code. It is still a little bit slower than a compiled management (garbage collection).
language (e.g., C++). Java is an interpreted language that
is why it is slower than compiled languages, e.g., C, C++, First Java Program | Hello World
etc.
Example
Distributed o Create the Java program
o Compile and run the Java program
Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for
creating distributed applications. This feature of Java
makes us able to access files by calling the methods from
any machine on the internet.
Creating Hello World Example
Let's create the hello java program:
class Simple{
Multi-threaded
public static void main(String args[]){
A thread is like a separate program, executing
concurrently. We can write Java programs that deal with System.out.println("Hello Java");
many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy }
memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web }
applications, etc.
Save the above file as Simple.java.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 5
Hello Java String[] args or String args[] is used for command
line argument. We will discuss it in coming section.
Compilation Flow: System.out.println() is used to print statement.
Here, System is a class, out is an object of the PrintStream
When we compile Java program using javac tool, the Java class, println() is a method of the PrintStream class. We will
compiler converts the source code into byte code. discuss the internal working
of System.out.println() statement in the coming section.
Java Variables
A variable is a container which holds the value while
the Java program is executed. A variable is assigned with a
data type.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 6
1. local variable {
2. instance variable
3. static variable static int m=100;//static variable
int a=10;
Example to understand the types of
variables in java int b=10;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 7
System.out.println(c);
Java Variable Example:
} Narrowing (Typecasting)
} public class Simple{
20 float f=10.5f;
float f=a; }}
System.out.println(a); Output:
System.out.println(f); 10.5
10
}}
//Overflow
int a=130;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 8
byte b=(byte)a; 20
Output:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 9
The Boolean data type is used to store only two possible
values: true and false. This data type is used for simple
flags that track true/false conditions.
Example:
Example:
Long Data Type
1. double d1 = 12.3
The long data type is a 64-bit two's complement integer. Its
value-range lies between -9,223,372,036,854,775,808(-
2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Char Data Type
Its minimum value is - 9,223,372,036,854,775,808and
maximum value is 9,223,372,036,854,775,807. Its default The char data type is a single 16-bit Unicode character. Its
value is 0. The long data type is used when you need a value-range lies between '\u0000' (or 0) to '\uffff' (or
range of values more than those provided by int. 65,535 inclusive).The char data type is used to store
characters.
Example:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 11
Example:
Unary postfix expr++ expr--
1. char letterA = 'A' prefix ++expr --expr +expr -
expr ~ !
Why char uses 2 byte in java and what
is \u0000 ? Arithmetic multiplicative */%
additive +-
It is because java uses Unicode system not ASCII code
system. The \u0000 is the lowest range of Unicode system.
Shift shift << >> >>>
To get detail explanation about Unicode visit next page.
Relational comparison < > <= >= instanceof
Operators in Java
equality == !=
Operator in Java is a symbol that is used to perform Bitwise bitwise AND &
operations. For example: +, -, *, / etc.
bitwise ^
There are many types of operators in Java which are given exclusive OR
below:
bitwise |
Unary Operator, inclusive OR
Arithmetic Operator,
Shift Operator, Logical logical AND &&
Relational Operator,
Bitwise Operator, logical OR ||
Logical Operator,
Ternary Operator and Ternary ternary ?:
Assignment Operator.
Assignment assignment = += -= *= /= %= &=
^= |= <<= >>= >>>=
Java Operator Precedence
Java Unary Operator
Operator Category Precedence
Type The Java unary operators require only one operand. Unary
operators are used to perform various operations i.e.:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 12
incrementing/decrementing a value by one 8. }}
negating an expression
inverting the value of a boolean Output:
22
Java Unary Operator Example: ++ and
-- 21
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 13
Java Arithmetic Operators 4. }}
15 Output:
5 40
50 80
2 80
0 240
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 14
Java Right Shift Operator Example -5
1073741819
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2 Java AND Operator Example: Logical &&
4. System.out.println(20>>2);//20/2^2=20/4=5 and Bitwise &
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
The logical && operator doesn't check the second condition
if the first condition is false. It checks the second condition
Output: only if the first one is true.
2
The bitwise & operator always checks both conditions
5 whether first condition is true or false.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 15
5. int c=20; 10. System.out.println(a);//10 because second condition is not
6. System.out.println(a<b&&a++<c);//false && true = false checked
7. System.out.println(a);//10 because second condition is not 11. System.out.println(a>b|a++<c);//true | true = true
checked 12. System.out.println(a);//11 because second condition is che
8. System.out.println(a<b&a++<c);//false && true = false cked
9. System.out.println(a);//11 because second condition is che 13. }}
cked
10. }} Output:
Output: true
false true
10 true
false 10
11 true
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 16
Output: 8. a*=2;//9*2
9. System.out.println(a);
2 10. a/=2;//18/2
11. System.out.println(a);
12. }}
Java Assignment Operator
Output:
Java assignment operator is one of the most common
operators. It is used to assign the value on its right to the 13
operand on its left.
9
Java Assignment Operator Example
18
1. public class OperatorExample{
9
2. public static void main(String args[]){
3. int a=10;
4. int b=20; Java Assignment Operator Example:
5. a+=4;//a=a+4 (a=10+4) Adding short
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b); 1. public class OperatorExample{
9. }} 2. public static void main(String args[]){
3. short a=10;
4. short b=10;
Output: 5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
14
7. System.out.println(a);
8. }}
16
Output:
Java Assignment Operator Example
Compile time error
1. public class OperatorExample{
2. public static void main(String[] args){ After type cast:
3. int a=10;
4. a+=3;//10+3 1. public class OperatorExample{
5. System.out.println(a); 2. public static void main(String args[]){
6. a-=4;//13-4 3. short a=10;
7. System.out.println(a); 4. short b=10;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 17
5. a=(short)(a+b);//20 which is int now converted to short catch: Java catch keyword is used to catch the exceptions
6. System.out.println(a); generated by try statements. It must be used after the try block
7. }} only.
Output: char: Java char keyword is used to declare a variable that can
hold unsigned 16-bit Unicode characters
20
class: Java class keyword is used to declare a class.
Java Keywords continue: Java continue keyword is used to continue the loop. It
continues the current flow of the program and skips the
Java keywords are also known as reserved words. remaining code at the specified condition.
Keywords are particular words that act as a key to a code.
These are predefined words by Java so they cannot be used default: Java default keyword is used to specify the default
as a variable or object name or class name. block of code in a switch statement.
A list of Java keywords or reserved words are given below: double: Java double keyword is used to declare a variable that
can hold 64-bit floating-point number.
abstract: Java abstract keyword is used to declare an abstract
class. An abstract class can provide the implementation of the else: Java else keyword is used to indicate the alternative
interface. It can have abstract and non-abstract methods. branches in an if statement.
boolean: Java boolean keyword is used to declare a variable as enum: Java enum keyword is used to define a fixed set of
a boolean type. It can hold True and False values only. constants. Enum constructors are always private or default.
break: Java break keyword is used to break the loop or switch extends: Java extends keyword is used to indicate that a class
statement. It breaks the current flow of the program at specified is derived from another class or interface.
conditions.
final: Java final keyword is used to indicate that a variable holds
byte: Java byte keyword is used to declare a variable that can a constant value. It is used with a variable. It is used to restrict
hold 8-bit data values. the user from updating the value of the variable.
case: Java case keyword is used with the switch statements to finally: Java finally keyword indicates a block of code in a try-
mark blocks of text. catch structure. This block is always executed whether an
exception is handled or not.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 18
float: Java float keyword is used to declare a variable that can package: Java package keyword is used to declare a Java
hold a 32-bit floating-point number. package that includes the classes.
for: Java for keyword is used to start a for loop. It is used to private: Java private keyword is an access modifier. It is used to
execute a set of instructions/functions repeatedly when some indicate that a method or variable may be accessed only in the
condition becomes true. If the number of iteration is fixed, it is class in which it is declared.
recommended to use for loop.
protected: Java protected keyword is an access modifier. It can
if: Java if keyword tests the condition. It executes the if block if be accessible within the package and outside the package but
the condition is true. through inheritance only. It can't be applied with the class.
implements: Java implements keyword is used to implement an public: Java public keyword is an access modifier. It is used to
interface. indicate that an item is accessible anywhere. It has the widest
scope among all other modifiers.
import: Java import keyword makes classes and interfaces
available and accessible to the current source code. return: Java return keyword is used to return from a method
when its execution is complete.
instanceof: Java instanceof keyword is used to test whether the
object is an instance of the specified class or implements an short: Java short keyword is used to declare a variable that can
interface. hold a 16-bit integer.
int: Java int keyword is used to declare a variable that can hold static: Java static keyword is used to indicate that a variable or
a 32-bit signed integer. method is a class method. The static keyword in Java is mainly
used for memory management.
interface: Java interface keyword is used to declare an
interface. It can have only abstract methods. strictfp: Java strictfp is used to restrict the floating-point
calculations to ensure portability.
long: Java long keyword is used to declare a variable that can
hold a 64-bit integer. super: Java super keyword is a reference variable that is used
to refer to parent class objects. It can be used to invoke the
native: Java native keyword is used to specify that a method is immediate parent class method.
implemented in native code using JNI (Java Native Interface).
switch: The Java switch keyword contains a switch statement
new: Java new keyword is used to create new objects. that executes code based on test value. The switch statement
tests the equality of a variable against multiple values.
null: Java null keyword is used to indicate that a reference does
not refer to anything. It removes the garbage value. synchronized: Java synchronized keyword is used to specify
the critical sections or methods in multithreaded code.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 19
this: Java this keyword can be used to refer the current object in Java provides three types of control flow statements.
a method or constructor.
1. Decision Making statements
throw: The Java throw keyword is used to explicitly throw an o if statements
exception. The throw keyword is mainly used to throw custom o switch statement
exceptions. It is followed by an instance. 2. Loop statements
o do while loop
throws: The Java throws keyword is used to declare an o while loop
exception. Checked exceptions can be propagated with throws. o for loop
o for-each loop
transient: Java transient keyword is used in serialization. If you 3. Jump statements
define any data member as transient, it will not be serialized. o break statement
o continue statement
try: Java try keyword is used to start a block of code that will be
tested for exceptions. The try block must be followed by either
catch or finally block.
Decision-Making statements:
void: Java void keyword is used to specify that a method does As the name suggests, decision-making statements decide
not have a return value. which statement to execute and when. Decision-making
statements evaluate the Boolean expression and control
volatile: Java volatile keyword is used to indicate that a variable the program flow depending upon the result of the
may change asynchronously. condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
while: Java while keyword is used to start a while loop. This loop
iterates a part of the program several times. If the number of
iteration is not fixed, it is recommended to use the while loop.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition.
Java Control Statements | Control The control of the program is diverted depending upon the
Flow in Java specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four
Java compiler executes the code from top to bottom. The types of if-statements given below.
statements in the code are executed according to the order
1. Simple if statement
in which they appear. However, Java provides statements
2. if-else statement
that can be used to control the flow of Java code. Such 3. if-else-if ladder
statements are called control flow statements. It is one of 4. Nested if-statement
the fundamental features of Java, which provides a smooth
flow of program.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 20
Let's understand the if-statements one by one. 2) if-else statement
Student.java Student.java
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 21
3) if-else-if ladder: 14. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 22
11. System.out.println(address.split(",")[0]); 1. switch (expression){
12. } 2. case value1:
13. }else { 3. statement1;
14. System.out.println("You are not living in India"); 4. break;
15. } 5. .
16. } 6. .
17. } 7. .
8. case valueN:
Output: 9. statementN;
10. break;
Delhi 11. default:
12. default statement;
13. }
Switch Statement:
Consider the following example to understand the flow of
In Java, Switch statements are similar to if-else-if the switch statement.
statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based Student.java
on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It 1. public class Student implements Cloneable {
also enhances the readability of the program. 2. public static void main(String[] args) {
3. int num = 2;
Points to be noted about switch statement: 4. switch (num){
5. case 0:
o The case variables can be int, short, byte, char, or 6. System.out.println("number is 0");
enumeration. String type is also supported since version 7 of 7. break;
Java 8. case 1:
o Cases cannot be duplicate 9. System.out.println("number is 1");
o Default statement is executed when any of the case 10. break;
doesn't match the value of expression. It is optional. 11. default:
o Break statement terminates the switch block when the 12. System.out.println(num);
condition is satisfied. 13. }
It is optional, if not used, next case is executed. 14. }
o While using switch statements, we must notice that the 15. }
case expression will be of the same type as the variable.
However, it will also be a constant value. Output:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 23
While using switch statements, we must notice that the The flow chart for the for-loop is given below.
case expression will be of the same type as the variable.
However, it will also be a constant value. The switch
permits only int, string, and Enum type variables to be
used.
Loop Statements
In programming, sometimes we need to execute the block
of code repeatedly while some condition evaluates to true.
However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. Consider the following example to understand the proper
However, there are differences in their syntax and functioning of the for loop in java.
condition checking time.
Calculation.java
1. for loop
2. while loop 1. public class Calculattion {
3. do-while loop 2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
Let's understand the loop statements one by one. 4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
Java for loop 7. }
8. System.out.println("The sum of first 10 natural numbers is
In Java, for loop is similar to C and C++. It enables us to " + sum);
initialize the loop variable, check the condition, and 9. }
increment/decrement in a single line of code. We use the 10. }
for loop only when we exactly know the number of times,
we want to execute the block of code. Output:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 24
Java for-each loop Python
JavaScript
Java provides an enhanced for loop to traverse the data
structures like array or collection. In the for-each loop, we
don't need to update the loop variable. The syntax to use Java while loop
the for-each loop in java is given below.
The while loop is also used to iterate over the number of
1. for(data_type var : array_name/collection_name){ statements multiple times. However, if we don't know the
2. //statements number of iterations in advance, it is recommended to use
3. } a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop
Consider the following example to understand the statement in while loop.
functioning of the for-each loop in Java.
It is also known as the entry-controlled loop since the
Calculation.java condition is checked at the start of the loop. If the condition
is true, then the loop body will be executed; otherwise, the
1. public class Calculation { statements after the loop will be executed.
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub The syntax of the while loop is given below.
4. String[] names = {"Java","C","C+
+","Python","JavaScript"}; 1. while(condition){
5. System.out.println("Printing the content of the array name 2. //looping statements
s:\n"); 3. }
6. for(String name:names) {
7. System.out.println(name);
The flow chart for the while loop is given in the following
8. }
9. }
image.
10. }
Output:
Java
C++
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 25
0
10
Output:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 26
Printing the list of first 10 even numbers
10
Jump Statements
Jump statements are used to transfer the control of the
program to the specific statements. In other words, jump
statements transfer the execution control to the other part
Consider the following example to understand the of the program. There are two types of jump statements in
functioning of the do-while loop in Java. Java, i.e., break and continue.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 27
Consider the following example in which we have used the 1. public class Calculation {
break statement with the for loop. 2.
3. public static void main(String[] args) {
BreakExample.java 4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
1. public class BreakExample {
7. b:
2.
8. for(int j = 0; j<=15;j++) {
3. public static void main(String[] args) {
9. c:
4. // TODO Auto-generated method stub
10. for (int k = 0; k<=20; k++) {
5. for(int i = 0; i<= 10; i++) {
11. System.out.println(k);
6. System.out.println(i);
12. if(k==5) {
7. if(i==6) {
13. break a;
8. break;
14. }
9. }
15. }
10. }
16. }
11. }
17.
12. }
18. }
19. }
Output: 20.
21.
0 22. }
1
Output:
2
0
3
1
4
2
5
3
6
4
Calculation.java
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 28
Java continue statement 5
1
Unlike break statement, the continue statement doesn't
break the loop, whereas, it skips the specific part of the 2
loop and jumps to the next iteration of the loop
immediately. 3
1 Syntax:
2
1. if(condition){
2. //code to be executed
3
3. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 29
The Java if-else statement also tests the condition. It
executes the if block if condition is true otherwise else
block is executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
Example:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 30
4. public static void main(String[] args) {
5. //defining a variable Using Ternary Operator
6. int number=13;
7. //Check if the number is divisible by 2 or not We can also use ternary operator (? :) to perform the task
8. if(number%2==0){ of if...else statement. It is a shorthand way to check the
9. System.out.println("even number"); condition. If the condition is true, the result of ? is returned.
10. }else{ But, if the condition is false, the result of : is returned.
11. System.out.println("odd number");
12. } Example:
13. }
14. }
1. public class IfElseTernaryExample {
2. public static void main(String[] args) {
Output: 3. int number=13;
4. //Using ternary operator
odd number 5. String output=(number%2==0)?"even number":"odd n
umber";
Leap Year Example: 6. System.out.println(output);
7. }
A year is leap, if it is divisible by 4 and 400. But, not by 8. }
100.
Output:
1. public class LeapYearExample {
2. public static void main(String[] args) { odd number
3. int year=2020;
4. if(((year % 4 ==0) && (year % 100 !=0)) || (year % 40
0==0)){ Java if-else-if ladder Statement
5. System.out.println("LEAP YEAR");
6. } The if-else-if ladder statement executes one condition from
7. else{ multiple statements.
8. System.out.println("COMMON YEAR");
9. } Syntax:
10. }
11. } 1. if(condition1){
2. //code to be executed if condition1 is true
Output: 3. }else if(condition2){
4. //code to be executed if condition2 is true
LEAP YEAR 5. }
6. else if(condition3){
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 31
7. //code to be executed if condition3 is true 11. System.out.println("D grade");
8. } 12. }
9. ... 13. else if(marks>=60 && marks<70){
10. else{ 14. System.out.println("C grade");
11. //code to be executed if all the conditions are false 15. }
12. } 16. else if(marks>=70 && marks<80){
17. System.out.println("B grade");
18. }
19. else if(marks>=80 && marks<90){
20. System.out.println("A grade");
21. }else if(marks>=90 && marks<100){
22. System.out.println("A+ grade");
23. }else{
24. System.out.println("Invalid!");
25. }
26. }
27. }
Output:
C grade
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 32
NEGATIVE 1. //Java Program to demonstrate the use of Nested If Statem
ent.
2. public class JavaNestedIfExample {
Java Nested if statement 3. public static void main(String[] args) {
4. //Creating two variables for age and weight
The nested if statement represents the if block within 5. int age=20;
another if block. Here, the inner if block condition executes 6. int weight=80;
only when outer if block condition is true. 7. //applying condition on age and weight
8. if(age>=18){
Syntax: 9. if(weight>50){
10. System.out.println("You are eligible to donate bloo
1. if(condition){ d");
2. //code to be executed 11. }
3. if(condition){ 12. }
4. //code to be executed 13. }}
5. }
6. } Output:
Points to Remember
o There can be one or N number of case values for a switch
Example: expression.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 33
o The case value must be of switch expression type only.
The case value must be literal or constant. It doesn't
allow variables.
o The case values must be unique. In case of duplicate
value, it renders compile-time error.
o The Java switch expression must be of byte, short, int,
long (with its Wrapper type), enums and string.
o Each case statement can have a break statement which is
optional. When control reaches to the break statement, it jumps
the control after the switch expression. If a break statement is
not found, it executes the next case.
o The case value can have a default label which is optional.
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Example:
Flowchart of Switch Statement
SwitchExample.java
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 34
9. break; 14. }
10. case 20: System.out.println("20"); 15. }
11. break;
12. case 30: System.out.println("30"); Output:
13. break;
14. //Default case statement 20
15. default:System.out.println("Not in 10, 20 or 30");
16. } 30
17. }
18. } Not in 10, 20 or 30
Output:
Java Switch Statement with String
20
Java allows us to use strings in switch expression since Java
SE 7. The case statement should be string literal.
Java Switch Statement is fall-through
Example:
The Java switch statement is fall-through. It means it
executes all statements after the first match if a break SwitchStringExample.java
statement is not present.
1. //Java Program to demonstrate the use of Java Switch
Example: 2. //statement with String
3. public class SwitchStringExample {
SwitchExample2.java 4. public static void main(String[] args) {
5. //Declaring String variable
1. //Java Switch Example where we are omitting the 6. String levelString="Expert";
2. //break statement 7. int level=0;
3. public class SwitchExample2 { 8. //Using String in Switch expression
4. public static void main(String[] args) { 9. switch(levelString){
5. int number=20; 10. //Using String Literal in Switch case
6. //switch expression with int value 11. case "Beginner": level=1;
7. switch(number){ 12. break;
8. //switch cases without break statements 13. case "Intermediate": level=2;
9. case 10: System.out.println("10"); 14. break;
10. case 20: System.out.println("20"); 15. case "Expert": level=3;
11. case 30: System.out.println("30"); 16. break;
12. default:System.out.println("Not in 10, 20 or 30"); 17. default: level=0;
13. } 18. break;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 35
19. } 19. case 'E':
20. System.out.println("Your Level is: "+level); 20. System.out.println("Micro processors, Logic
21. } switching theory");
22. } 21. break;
22. case 'M':
Output: 23. System.out.println("Drawing, Manufacturin
g Machines");
Your Level is: 3 24. break;
25. }
26. break;
Java Nested Switch Statement 27. case 3:
28. switch( branch )
We can use switch statement inside other switch statement 29. {
in Java. It is known as nested switch statement. 30. case 'C':
31. System.out.println("Computer Organization
, MultiMedia");
Example:
32. break;
33. case 'E':
NestedSwitchExample.java 34. System.out.println("Fundamentals of Logic
Design, Microelectronics");
1. //Java Program to demonstrate the use of Java Nested Swit 35. break;
ch 36. case 'M':
2. public class NestedSwitchExample { 37. System.out.println("Internal Combustion E
3. public static void main(String args[]) ngines, Mechanical Vibration");
4. { 38. break;
5. //C - CSE, E - ECE, M - Mechanical 39. }
6. char branch = 'C'; 40. break;
7. int collegeYear = 4; 41. case 4:
8. switch( collegeYear ) 42. switch( branch )
9. { 43. {
10. case 1: 44. case 'C':
11. System.out.println("English, Maths, Science"); 45. System.out.println("Data Communication a
12. break; nd Networks, MultiMedia");
13. case 2: 46. break;
14. switch( branch ) 47. case 'E':
15. { 48. System.out.println("Embedded System, Im
16. case 'C': age Processing");
17. System.out.println("Operating System, Jav 49. break;
a, Data Structure"); 50. case 'M':
18. break;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 36
51. System.out.println("Production Technology 12. case Sun:
, Thermal Engineering"); 13. System.out.println("Sunday");
52. break; 14. break;
53. } 15. case Mon:
54. break; 16. System.out.println("Monday");
55. } 17. break;
56. } 18. case Tue:
57. } 19. System.out.println("Tuesday");
20. break;
Output: 21. case Wed:
22. System.out.println("Wednesday");
Data Communication and Networks, MultiMedia 23. break;
24. case Thu:
25. System.out.println("Thursday");
Java Enum in Switch Statement 26. break;
27. case Fri:
Java allows us to use enum in switch statement. Java enum 28. System.out.println("Friday");
is a class that represent the group of constants. 29. break;
(immutable such as final variables). We use the keyword 30. case Sat:
31. System.out.println("Saturday");
enum and put the constants in curly braces separated by
32. break;
comma. 33. }
34. }
Example: 35. }
36. }
JavaSwitchEnumExample.java
Output:
1. //Java Program to demonstrate the use of Enum
2. //in switch statement Sunday
3. public class JavaSwitchEnumExample {
4. public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sa Monday
t }
5. public static void main(String args[]) Twesday
6. {
7. Day[] DayNow = Day.values(); Wednesday
8. for (Day Now : DayNow)
9. { Thursday
10. switch (Now)
11. { Friday
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 37
Saturday You are eligible for vote.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 38
1. for(initialization; condition; increment/decrement){ Output:
2. //statement or code to be executed
3. } 1
Flowchart: 2
10
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 39
7. System.out.println(i+" "+j); 10. }
8. }//end of i
9. }//end of j Output:
10. }
11. } *
Output: **
11 ***
12 ****
13 *****
21 Pyramid Example 2:
22
PyramidExample2.java
23
1. public class PyramidExample2 {
2. public static void main(String[] args) {
31
3. int term=6;
4. for(int i=1;i<=term;i++){
32
5. for(int j=term;j>=i;j--){
6. System.out.print("* ");
33
7. }
8. System.out.println();//new line
Pyramid Example 1: 9. }
10. }
PyramidExample.java 11. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 40
** 12
* 23
56
The for-each loop is used to traverse array or collection in
Java. It is easier to use than simple for loop because we 78
don't need to increment value and use subscript notation.
Java Labeled For Loop
It works on the basis of elements and not the index. It
returns element one by one in the defined variable.
We can have a name of each Java for loop. To do so, we
use label before the for loop. It is useful while using the
Syntax:
nested for loop as we can break/continue specific for loop.
1. for(data_type variable : array_name){
2. //code to be executed Note: The break and continue keywords breaks or continues
3. } the innermost for loop respectively.
Example: Syntax:
1. labelname:
ForEachExample.java
2. for(initialization; condition; increment/decrement){
3. //code to be executed
1. //Java For-each loop example which prints the
4. }
2. //elements of the array
3. public class ForEachExample {
4. public static void main(String[] args) { Example:
5. //Declaring an array
6. int arr[]={12,23,44,56,78}; LabeledForExample.java
7. //Printing array using for-each loop
8. for(int i:arr){ 1. //A Java program to demonstrate the use of labeled for loo
9. System.out.println(i); p
10. } 2. public class LabeledForExample {
11. } 3. public static void main(String[] args) {
12. } 4. //Using Label for outer and for loop
5. aa:
Output: 6. for(int i=1;i<=3;i++){
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 41
7. bb: 14. }
8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){ Output:
10. break aa;
11. } 11
12. System.out.println(i+" "+j);
13. } 12
14. }
15. } 13
16. }
21
Output:
31
11
32
12
33
13
LabeledForExample2.java Syntax:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 42
5. //Using no condition in for loop
programs programs at
6. for(;;){
repeatedly least once
7. System.out.println("infinitive loop");
on the basis and the
8. }
of given further
9. }
boolean execution
10. }
condition. depends
upon the
Output: given
boolean
infinitive loop condition.
infinitive loop When to If the number of If the number If the number
use iteration is fixed, of iteration is of iteration is
infinitive loop it is not fixed, it is not fixed and
recommended to recommende you must
infinitive loop use for loop. d to use have to
while loop. execute the
infinitive loop loop at least
once, it is
ctrl+c recommende
d to use the
Now, you need to press ctrl+c to exit from the program. do-while
loop.
Java for Loop vs while Loop vs do- Syntax for(init;condition;i while(conditi do{
while Loop ncr/decr){
// code to be
on){
//code to be
//code to be
executed
executed executed }while(condit
Compa for loop while do-while } } ion);
rison loop loop Example //for loop //while loop //do-while
for(int int i=1; loop
Introductio The Java for loop The Java The Java do i=1;i<=10;i++){ while(i<=10) int i=1;
n is a control flow while loop is while loop is System.out.printl { do{
statement that a control flow a control flow n(i); System.out.p System.out.p
iterates a part of statement statement } rintln(i); rintln(i);
the programs mul that that i++; i++;
tiple times. executes a executes a } }while(i<=10
part of the part of the
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 43
);
2. Update expression: Every time the loop body is
executed, this expression increments or decrements loop
Syntax for for(;;){ while(true){ do{ variable.
infinitive //code to be //code to be //code to be
loop executed executed executed Example:
} } }while(true);
i++;
The Java while loop is used to iterate a part of Here, the important thing about while loop is that,
the program repeatedly until the specified Boolean sometimes it may not even execute. If the condition to be
condition is true. As soon as the Boolean condition tested results into false, the loop body is skipped and first
becomes false, the loop automatically stops. statement after the while loop will be executed.
Syntax:
1. while (condition){
2. //code to be executed
3. I ncrement / decrement statement
4. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 44
WhileExample.java Syntax:
4
Output:
5
infinitive while loop
6
infinitive while loop
7
infinitive while loop
8
infinitive while loop
9
infinitive while loop
10
ctrl+c
Java Infinitive While Loop In the above code, we need to enter Ctrl + C command to
terminate the infinite loop.
If you pass true in the while loop, it will be infinitive while
loop.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 45
Java do-while Loop Example:
i++;
The Java do-while loop is used to iterate a part of the
program repeatedly, until the specified condition is true. If Note: The do block is executed at least once, even if the
the number of iteration is not fixed and you must have to condition is false.
execute the loop at least once, it is recommended to use a
do-while loop. Flowchart of do-while loop:
Syntax:
1. do{
2. //code to be executed / loop body
3. //update statement
4. }while (condition);
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 46
7. }while(i<=10); DoWhileExample2.java
8. }
9. } 1. public class DoWhileExample2 {
2. public static void main(String[] args) {
Output: 3. do{
4. System.out.println("infinitive do while loop");
1 5. }while(true);
6. }
2 7. }
3 Output:
4 infinitive do while loop
7 ctrl+c
8
In the above code, we need to enter Ctrl + C command to
9
terminate the infinite loop.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 47
Syntax: 13. }
14. }
1. jump-statement;
2. break; Output:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 48
14. } 6. for(int i=1;i<=3;i++){
15. } 7. bb:
16. } 8. for(int j=1;j<=3;j++){
17. } 9. if(i==2&&j==2){
10. //using break statement with label
Output: 11. break aa;
12. }
11 13. System.out.println(i+" "+j);
14. }
12 15. }
16. }
13 17. }
21 Output:
31 11
32 12
33 13
21
Java Break Statement with Labeled
For Loop Java Break Statement in while loop
We can use break statement with a label. The feature is Example:
introduced since JDK 1.5. So, we can break any loop in Java
now whether it is outer or inner loop. BreakWhileExample.java
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 49
9. //using break statement 10. //using break statement
10. i++; 11. i++;
11. break;//it will break the loop 12. break;//it will break the loop
12. } 13. }
13. System.out.println(i); 14. System.out.println(i);
14. i++; 15. i++;
15. } 16. }while(i<=10);
16. } 17. }
17. } 18. }
Output: Output:
1 1
2 2
3 3
4 4
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 50
We can use Java continue statement in all types of loops 6
such as for loop, while loop and do-while loop.
7
Syntax:
8
1. jump-statement;
9
2. continue;
10
Java Continue Statement Example
As you can see in the above output, 5 is not printed on the
ContinueExample.java console. It is because the loop is continued when it reaches
to 5.
1. //Java Program to demonstrate the use of continue statem
ent
2. //inside the for loop.
Java Continue Statement with Inner
3. public class ContinueExample { Loop
4. public static void main(String[] args) {
5. //for loop
It continues inner loop only if you use the continue
6. for(int i=1;i<=10;i++){
7. if(i==5){
statement inside the inner loop.
8. //using continue statement
9. continue;//it will skip the rest statement ContinueExample2.java
10. }
11. System.out.println(i); 1. //Java Program to illustrate the use of continue statement
12. } 2. //inside an inner loop
13. } 3. public class ContinueExample2 {
14. } 4. public static void main(String[] args) {
5. //outer loop
Output: 6. for(int i=1;i<=3;i++){
7. //inner loop
1 8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){
2 10. //using continue statement inside inner l
oop
3 11. continue;
12. }
4 13. System.out.println(i+" "+j);
14. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 51
15. } 5. aa:
16. } 6. for(int i=1;i<=3;i++){
17. } 7. bb:
8. for(int j=1;j<=3;j++){
Output: 9. if(i==2&&j==2){
10. //using continue statement with label
11 11. continue aa;
12. }
12 13. System.out.println(i+" "+j);
14. }
13 15. }
16. }
21 17. }
23 Output:
31 11
32 12
33 13
21
Java Continue Statement with
Labelled For Loop 31
32
We can use continue statement with a label. This feature is
introduced since JDK 1.5. So, we can continue any loop in 33
Java now whether it is outer loop or inner.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 52
2. //inside the while loop.
3. public class ContinueWhileExample { Java Continue Statement in do-while
4.
5.
public static void main(String[] args) {
//while loop
Loop
6. int i=1;
7. while(i<=10){ ContinueDoWhileExample.java
8. if(i==5){
9. //using continue statement 1. //Java Program to demonstrate the use of continue statem
10. i++; ent
11. continue;//it will skip the rest statement 2. //inside the Java do-while loop.
12. } 3. public class ContinueDoWhileExample {
13. System.out.println(i); 4. public static void main(String[] args) {
14. i++; 5. //declaring variable
15. } 6. int i=1;
16. } 7. //do-while loop
17. } 8. do{
9. if(i==5){
10. //using continue statement
Output:
11. i++;
12. continue;//it will skip the rest statement
1
13. }
14. System.out.println(i);
2
15. i++;
16. }while(i<=10);
3
17. }
18. }
4
6 Output:
7 1
8 2
9 3
10 4
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 53
8 Single line comments starts with two forward slashes (//).
Any text in front of // is not executed by Java.
9
Syntax:
10
1. //This is single line comment
Java Comments Let's use single line comment in a Java program.
The Java comments are the statements in a program that
are not executed by the compiler and interpreter. CommentExample1.java
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 54
4. multi line To create documentation API, we need to use the javadoc
5. comment tool. The documentation comments are placed between
6. */ /** and */.
CommentExample2.java /**
Documentation comments are usually used to write large {@docRo {@docRoot} to depict relative path to root
programs for a project or software application as it helps to ot} directory of generated
create documentation API. These APIs are needed for document from any page.
reference, i.e., which classes, methods, arguments, etc.,
@author @author name To add the author of the class.
are used in the code.
- text
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 55
15. */
without interpreting it as html
16.
markup or nested javadoc tag.
17. public class Calculate{
18. /**
@version @version To specify "Version" subheading
19. * This method calculates the summation of two integer
version-text and version-text when -version
s.
option is used.
20. * @param input1 This is the first parameter to sum() m
ethod
@since @since release To add "Since" heading with
21. * @param input2 This is the second parameter to the s
since text to generated
um() method.
documentation.
22. * @return int This returns the addition of input1 and in
put2
@param @param To add a parameter with given
23. */
parameter- name and description to
24. public int sum(int input1, int input2){
name 'Parameters' section.
25. return input1 + input2;
description
26. }
27. /**
@return @return Required for every method that
28. * This is the main method uses of sum() method.
description returns something (except void)
29. * @param args Unused
30. * @see IOException
Let's use the Javadoc tag in a Java program. 31. */
32. public static void main(String[] args) {
Calculate.java 33. Calculate obj = new Calculate();
34. int result = obj.sum(40, 20);
35.
1. import java.io.*;
36. System.out.println("Addition of numbers: " + result);
2.
37. }
3. /**
38. }
4. * <h2> Calculation of numbers </h2>
5. * This program implements an application
6.
7.
* to perform operation such as addition of numbers
* and print the result
Method in Java
8. * <p>
9. * <b>Note:</b> Comments make the code readable and In general, a method is a way to perform some task.
Similarly, the method in Java is a collection of instructions
10. * easy to understand. that performs a specific task. It provides the reusability of
11. * code. We can also easily modify code using methods. In
12. * @author Anurati this section, we will learn what is a method in Java,
13. * @version 16.0 types of methods, method declaration, and how to
14. * @since 2021-07-06 call a method in Java.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 56
What is a method in Java? Method Signature: Every method has a method
signature. It is a part of the method declaration. It includes
the method name and parameter list.
A method is a block of code or collection of statements or
a set of code grouped together to perform a certain task or Access Specifier: Access specifier or modifier is the
operation. It is used to achieve the reusability of code. access type of the method. It specifies the visibility of the
We write a method once and use it many times. We do not method. Java provides four types of access specifier:
require to write code again and again. It also provides
the easy modification and readability of code, just by o Public: The method is accessible by all classes when we
adding or removing a chunk of code. The method is use public specifier in our application.
executed only when we call or invoke it. o Private: When we use a private access specifier, the
method is accessible only in the classes in which it is defined.
The most important method in Java is the main() method. o Protected: When we use protected access specifier, the
If you want to read more about the main() method, method is accessible within the same package or subclasses in a
different package.
Default: When we do not use any access specifier in the
Method Declaration o
method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
The method declaration provides information about
method attributes, such as visibility, return-type, name, Return Type: Return type is a data type that the method
and arguments. It has six components that are known returns. It may have a primitive data type, object,
as method header, as we have shown in the following collection, void, etc. If the method does not return
figure. anything, we use void keyword.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 57
Method Body: It is a part of the method declaration. It methods just by calling them in the program at any point.
contains all the actions to be performed. It is enclosed Some pre-defined methods are length(), equals(),
within the pair of curly braces. compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes
Naming a Method related to the corresponding method runs in the
background that is already stored in the library.
While defining a method, remember that the method name Each and every predefined method is defined inside a
must be a verb and start with a lowercase letter. If the class. Such as print() method is defined in
method name has more than two words, the first name the java.io.PrintStream class. It prints the statement that
must be a verb followed by adjective or noun. In the multi- we write inside the method. For example, print("Java"), it
word method name, the first letter of each word must be prints Java on the console.
in uppercase except the first word. For example:
Let's see an example of the predefined method.
Single-word method name: sum(), area()
Demo.java
Multi-word method name: areaOfCircle(),
stringComparision() 1. public class Demo
2. {
It is also possible that a method has the same name as 3. public static void main(String[] args)
another method name in the same class, it is known 4. {
as method overloading. 5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max
(9,7));
Types of Method 7. }
8. }
There are two types of methods in Java:
Output:
o Predefined Method
o User-defined Method The maximum number is: 9
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 58
The max() method is a method of the Math class that User-defined Method
returns the greater of two numbers.
The method written by the user or programmer is known
We can also see the method signature of any predefined as a user-defined method. These methods are modified
method by using the link https://docs.oracle.com/. When according to the requirement.
we go through the link and see the max() method
signature, we find the following: How to Create a User-defined Method
1. import java.util.Scanner;
2. public class EvenOdd
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 59
3. { 19. System.out.println(num+" is even");
4. public static void main (String args[]) 20. else
5. { 21. System.out.println(num+" is odd");
6. //creating Scanner class object 22. }
7. Scanner scan=new Scanner(System.in); 23. }
8. System.out.print("Enter the number: ");
9. //reading value from the user Output 1:
10. int num=scan.nextInt();
11. //method calling Enter the number: 12
12. findEvenOdd(num);
13. } 12 is even
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 60
9. System.out.println("The sum of a and b is= " + c); 3. public static void main(String[] args)
10. } 4. {
11. //user defined method 5. show();
12. public static int add(int n1, int n2) //n1 and n2 are for 6. }
mal parameters 7. static void show()
13. { 8. {
14. int s; 9. System.out.println("It is an example of static method.");
15. s=n1+n2; 10. }
16. return s; //returning the sum 11. }
17. }
18. } Output:
The main advantage of a static method is that we can call 1. public class InstanceMethodExample
it without creating an object. It can access static data 2. {
members and also change the value of it. It is used to 3. public static void main(String [] args)
create an instance method. It is invoked by using the class 4. {
name. The best example of a static method is 5. //Creating an object of the class
the main() method. 6. InstanceMethodExample obj = new InstanceMethodExam
ple();
7. //invoking instance method
Example of static method 8. System.out.println("The sum is: "+obj.add(12, 13));
9. }
Display.java 10. int s;
11. //user-defined method because we have not used static ke
1. public class Display yword
2. { 12. public int add(int a, int b)
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 61
13. { Example
14. s = a+b;
15. //returning the sum 1. public void setRoll(int roll)
16. return s; 2. {
17. } 3. this.roll = roll;
18. } 4. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 62
Abstract Method Output:
Abstract method...
The method that does not has method body is known as
abstract method. In other words, without an
implementation is known as abstract method. It always Factory method
declares in the abstract class. It means the class itself
must be abstract if it has abstract method. To create an It is a method that returns an object to the class to which it
abstract method, we use the keyword abstract. belongs. All static methods are factory methods. For
example, NumberFormat obj =
Syntax NumberFormat.getNumberInstance();
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 63
Different ways to overload the method
There are two ways to overload the method in java 2) Method Overloading: changing data
1. By changing number of arguments type of arguments
2. By changing the data type
In this example, we have created two methods that differs
In Java, Method Overloading is not possible by changing the in data type. The first add method receives two integer
return type of the method only. arguments and second add method receives two double
arguments.
1) Method Overloading: changing no.
1. class Adder{
of arguments 2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
In this example, we have created two methods, first add() 4. }
method performs addition of two numbers and second add 5. class TestOverloading2{
method performs addition of three numbers. 6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
In this example, we are creating static methods so that we
9. }}
don't need to create instance for calling methods.
1.
2.
class Adder{
static int add(int a,int b){return a+b;}
Java Math class
3. static int add(int a,int b,int c){return a+b+c;}
4. } Java Math class provides several methods to work on math
5. class TestOverloading1{ calculations like min(), max(), avg(), sin(), cos(), tan(),
6. public static void main(String[] args){ round(), ceil(), floor(), abs() etc.
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11)); Unlike some of the StrictMath class numeric methods, all
9. }} implementations of the equivalent function of Math class
can't define to return the bit-for-bit same results. This
The Program Output: relaxation permits implementation with better-performance
where strict reproducibility is not required.
22
If the size is int or long and the results overflow the range
33
of value, the methods
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 64
addExact(), subtractExact(), multiplyExact(), a number.
and toIntExact() throw an ArithmeticException.
Math.pow() It returns the value of first argument
For other arithmetic operations like increment, decrement, raised to the power to second
divide, absolute value, and negation overflow occur only argument.
with a specific minimum or maximum value. It should be
checked against the maximum and minimum value as Math.signum() It is used to find the sign of a given
appropriate. value.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 65
Math.random() It returns a double value with a positive Math.decrementExa It is used to return the argument
sign, greater than or equal to 0.0 and ct() decremented by one, throwing an
less than 1.0. exception if the result overflows an int
or long.
Math.rint() It returns the double value that is
closest to the given argument and equal Math.negateExact() It is used to return the negation of the
to mathematical integer. argument, throwing an exception if the
result overflows an int or long.
Math.hypot() It returns sqrt(x2 +y2) without
intermediate overflow or underflow. Math.toIntExact() It returns the value of
the long argument, throwing an
Math.ulp() It returns the size of an ulp of the exception if the value overflows an int.
argument.
Math.addExact() It is used to return the sum of its Math.log10( It is used to return the base 10 logarithm of
arguments, throwing an exception if the ) a double value.
result overflows an int or long.
Math.log1p( It returns the natural logarithm of the sum of
Math.subtractExact( It returns the difference of the ) the argument and 1.
) arguments, throwing an exception if the
result overflows an int. Math.exp() It returns E raised to the power of
a double value, where E is Euler's number and it
Math.multiplyExact( It is used to return the product of the is approximately equal to 2.71828.
) arguments, throwing an exception if the
result overflows an int or long. Math.expm It is used to calculate the power of E and
1() subtract one from it.
Math.incrementExa It returns the argument incremented by
ct() one, throwing an exception if the result
overflows an int. Trigonometric Math Methods
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 66
Metho Description Angular Math Methods
d
Method Description
Math.sin() It is used to return the trigonometric Sine value of
a Given double value.
Math.toDegre It is used to convert the specified Radians
Math.cos( It is used to return the trigonometric Cosine value es angle to equivalent angle measured in
) of a Given double value. Degrees.
Math.tan( It is used to return the trigonometric Tangent Math.toRadia It is used to convert the specified Degrees
) value of a Given double value. ns angle to equivalent angle measured in
Radians.
Math.asin It is used to return the trigonometric Arc Sine
() value of a Given double value
Java Arrays
Math.acos It is used to return the trigonometric Arc Cosine
() value of a Given double value.
Normally, an array is a collection of similar type of
Math.atan It is used to return the trigonometric Arc Tangent
elements which has contiguous memory location.
() value of a Given double value.
Java array is an object which contains elements of a
similar data type. Additionally, the elements of an array are
Hyperbolic Math Methods stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
Method Description
Array in Java is index-based, the first element of the array
Math.sinh() is value
It is used to return the trigonometric Hyperbolic Cosine storedof at the 0th
a Given index, 2nd element is stored on 1st
double
value. index and so on.
Math.cosh( Unlike
It is used to return the trigonometric Hyperbolic Sine value C/C++,
of a Given we can
double get the length of the array using the
value.
) length member. In C/C++, we need to use the sizeof
operator.
Math.tanh( It is used to return the trigonometric Hyperbolic Tangent value of a Given double
) value. In Java, array is an object of a dynamically generated class.
Java array inherits the Object class, and implements the
Serializable as well as Cloneable interfaces. We can store
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 67
primitive values or objects in an array in Java. Like C/C++, o Multidimensional Array
we can also create single dimentional or multidimentional
arrays in Java.
1. arrayRefVar=new datatype[size];
Advantages
o Code Optimization: It makes the code optimized, we Example of Java Array
can retrieve or sort the data efficiently.
o Random access: We can get any data located at an Let's see the simple example of java array, where we are
index position. going to declare, instantiate, initialize and traverse an
array.
Disadvantages
1. //Java Program to illustrate how to declare, instantiate, init
ialize
o Size Limit: We can store only the fixed size of elements
2. //and traverse the Java array.
in the array. It doesn't grow its size at runtime. To solve this 3. class Testarray{
problem, collection framework is used in Java which grows 4. public static void main(String args[]){
automatically. 5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
Types of Array in java 9.
10.
a[3]=40;
a[4]=50;
11. //traversing array
There are two types of array. 12. for(int i=0;i<a.length;i++)//length is the property of arra
y
o Single Dimensional Array 13. System.out.println(a[i]);
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 68
14. }} 8. System.out.println(a[i]);
9. }}
Output:
Output:
10
33
20
3
70
4
40
5
50
Let's see the simple example to print this array. Let us see the example of print the elements of Java array
using the for-each loop.
1. //Java Program to illustrate the use of declaration, instanti
ation
1. //Java Program to print the array elements using for-each l
2. //and initialization of Java array in a single line
oop
3. class Testarray1{
2. class Testarray1{
4. public static void main(String args[]){
3. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initializ
4. int arr[]={33,3,4,5};
ation
5. //printing array using for-each loop
6. //printing array
6. for(int i:arr)
7. for(int i=0;i<a.length;i++)//length is the property of arra
7. System.out.println(i);
y
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 69
8. }} 15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
Output: 17. }}
33 Output:
3 3
4
Anonymous Array in Java
5
Java supports the feature of an anonymous array, so you
don't need to declare the array while passing an array to
the method.
Passing Array to a Method in Java 1. //Java Program to demonstrate the way of passing an ano
nymous array
We can pass the java array to method so that we can reuse 2. //to method.
the same logic on any array. 3. public class TestAnonymousArray{
4. //creating a method which receives an array as a paramet
Let's see the simple example to get the minimum number er
of an array using a method. 5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
1. //Java Program to demonstrate the way of passing an arra
8. }
y
9.
2. //to method.
10. public static void main(String args[]){
3. class Testarray2{
11. printArray(new int[]{10,22,44,66});//passing anonymous
4. //creating a method which receives an array as a paramet
array to method
er
12. }}
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++) Output:
8. if(min>arr[i])
9. min=arr[i]; 10
10.
11. System.out.println(min); 22
12. }
13. 44
14. public static void main(String args[]){
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 70
66 negative, equal to the array size or greater than the array
size while traversing the array.
Returning Array from the Method 1. //Java Program to demonstrate the case of
2. //ArrayIndexOutOfBoundsException in a Java Array.
We can also return an array from the method in Java. 3. public class TestArrayException{
4. public static void main(String args[]){
1. //Java Program to return an array from the method 5. int arr[]={50,60,70,80};
2. class TestReturnArray{ 6. for(int i=0;i<=arr.length;i++){
3. //creating method which returns an array 7. System.out.println(arr[i]);
4. static int[] get(){ 8. }
5. return new int[]{10,30,50,90,60}; 9. }}
6. }
7.
Output:
8. public static void main(String args[]){
9. //calling method which returns an array
Exception in thread "main"
10. int arr[]=get(); java.lang.ArrayIndexOutOfBoundsException: 4
11. //printing the values of an array
12. for(int i=0;i<arr.length;i++) at TestArrayException.main(TestArrayException.java:5)
13. System.out.println(arr[i]);
14. }} 50
Output: 60
10 70
30 80
50
90
Multidimensional Array in Java
60
In such case, data is stored in row and column based index
ArrayIndexOutOfBoundsException (also known as matrix form).
The Java Virtual Machine (JVM) throws an Syntax to Declare Multidimensional Array in Java
ArrayIndexOutOfBoundsException if length of the array in
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 71
1. dataType[][] arrayRefVar; (or) 9. System.out.print(arr[i][j]+" ");
2. dataType [][]arrayRefVar; (or) 10. }
3. dataType arrayRefVar[][]; (or) 11. System.out.println();
4. dataType []arrayRefVar[]; 12. }
13. }}
Example to instantiate Multidimensional Array in
Java Output:
445
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3; Jagged Array in Java
4. arr[1][0]=4;
5. arr[1][1]=5;
If we are creating odd number of columns in a 2D array, it
6. arr[1][2]=6;
7. arr[2][0]=7; is known as a jagged array. In other words, it is an array of
8. arr[2][1]=8; arrays with different number of columns.
9. arr[2][2]=9;
1. //Java Program to illustrate the jagged array
2. class TestJaggedArray{
Example of Multidimensional Java 3. public static void main(String[] args){
Array 4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
Let's see the simple example to declare, instantiate,
7. arr[1] = new int[4];
initialize and print the 2Dimensional array.
8. arr[2] = new int[2];
9. //initializing a jagged array
1. //Java Program to illustrate the use of multidimensional arr 10. int count = 0;
ay 11. for (int i=0; i<arr.length; i++)
2. class Testarray3{ 12. for(int j=0; j<arr[i].length; j++)
3. public static void main(String args[]){ 13. arr[i][j] = count++;
4. //declaring and initializing 2D array 14.
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 15. //printing the data of a jagged array
6. //printing 2D array 16. for (int i=0; i<arr.length; i++){
7. for(int i=0;i<3;i++){ 17. for (int j=0; j<arr[i].length; j++){
8. for(int j=0;j<3;j++){ 18. System.out.print(arr[i][j]+" ");
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 72
19. }
20. System.out.println();//new line Copying a Java Array
21. }
22. } We can copy an array to another by the arraycopy()
23. } method of System class.
78
Example of Copying an Array in Java
1. //Java Program to copy a source array into a destination ar
ray in Java
What is the class name of Java array? 2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
In Java, an array is an object. For array object, a proxy 4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
class is created whose name can be obtained by
6. 'i', 'n', 'a', 't', 'e', 'd' };
getClass().getName() method on the object. 7. //declaring a destination array
8. char[] copyTo = new char[7];
1. //Java Program to get the class name of array in Java 9. //copying array using System.arraycopy() method
2. class Testarray4{ 10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
3. public static void main(String args[]){ 11. //printing the destination array
4. //declaration and initialization of array 12. System.out.println(String.valueOf(copyTo));
5. int arr[]={4,4,5}; 13. }
6. //getting the class name of Java array 14. }
7. Class c=arr.getClass();
8. String name=c.getName();
An entity that has state and behavior is known as an object
9. //printing the class name of Java array
10. System.out.println(name);
e.g., chair, bike, marker, pen, table, car, etc. It can be
11. physical or logical (tangible and intangible). The example
12. }} of an intangible object is the banking system.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 73
o Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a
unique ID. The value of the ID is not visible to the external user.
However, it is used internally by the JVM to identify each object
uniquely.
Object Definitions:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 74
The class in Java Syntax to declare a class:
1. class <class_name>{
A class is a group of objects which have common 2. field;
properties. It is a template or blueprint from which objects 3. method;
are created. It is a logical entity. It can't be physical. 4. }
Fields
Methods Instance variable in Java
Constructors
Blocks A variable which is created inside the class but outside the
Nested class and interface method is known as an instance variable. Instance variable
doesn't get memory at compile time. It gets memory at
runtime when an object or instance is created. That is why
it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose
the behavior of an object.
Advantage of Method
o Code Reusability
o Code Optimization
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 75
15. }
new keyword in Java
Output:
The new keyword is used to allocate memory at runtime.
All objects get memory in Heap memory area. 0
null
Object and Class Example: main Object and Class Example: main
within the class outside the class
In this example, we have created a Student class which has In real time development, we create classes and use it
two data members id and name. We are creating the object from another class. It is a better approach than previous
of the Student class by new keyword and printing the one. Let's see a simple example, where we are having
object's value. main() method in another class.
Here, we are creating a main() method inside the class. We can have multiple classes in different Java files or single
Java file. If you define multiple classes in a single Java
File: Student.java source file, it is a good idea to save the file name with the
class name which has main() method.
1. //Java Program to illustrate how to define a class and fields
File: TestStudent1.java
2. //Defining a Student class.
3. class Student{ 1. //Java Program to demonstrate having the main method in
4. //defining fields
5. int id;//field or data member or instance variable 2. //another class
6. String name; 3. //Creating Student class.
7. //creating main method inside the Student class 4. class Student{
8. public static void main(String args[]){ 5. int id;
9. //Creating an object or instance 6. String name;
10. Student s1=new Student();//creating an object of Studen 7. }
t 8. //Creating another class TestStudent1 which contains the
11. //Printing values of the object main method
12. System.out.println(s1.id);//accessing member through ref 9. class TestStudent1{
erence variable 10. public static void main(String args[]){
13. System.out.println(s1.name); 11. Student s1=new Student();
14. } 12. System.out.println(s1.id);
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 76
13. System.out.println(s1.name); 10. System.out.println(s1.id+" "+s1.name);//printing membe
14. } rs with a white space
15. } 11. }
12. }
Output:
Output:
0
101 Sonoo
null
We can also create multiple objects and store information
3 Ways to initialize object in it through reference variable.
File: TestStudent3.java
There are 3 ways to initialize object in Java.
1. class Student{
1. By reference variable 2. int id;
2. By method 3. String name;
3. By constructor 4. }
5. class TestStudent3{
1) Object and Class Example: 6. public static void main(String args[]){
7. //Creating objects
Initialization through reference 8. Student s1=new Student();
9. Student s2=new Student();
Initializing an object means storing data into the object. 10. //Initializing objects
Let's see a simple example where we are going to initialize 11. s1.id=101;
the object through a reference variable. 12. s1.name="Sonoo";
13. s2.id=102;
File: TestStudent2.java 14. s2.name="Amit";
15. //Printing data
1. class Student{ 16. System.out.println(s1.id+" "+s1.name);
2. int id; 17. System.out.println(s2.id+" "+s2.name);
3. String name; 18. }
4. } 19. }
5. class TestStudent2{
6. public static void main(String args[]){ Output:
7. Student s1=new Student();
8. s1.id=101; 101 Sonoo
9. s1.name="Sonoo";
102 Amit
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 77
2) Object and Class Example:
Initialization through method
In this example, we are creating the two objects of Student
class and initializing the value to these objects by invoking
the insertRecord method. Here, we are displaying the state
(data) of the objects by invoking the displayInformation()
method.
File: TestStudent4.java
1. class Student{
2. int rollno; As you can see in the above figure, object gets the memory
3. String name;
in heap memory area. The reference variable refers to the
4. void insertRecord(int r, String n){
5. rollno=r; object allocated in the heap memory area. Here, s1 and s2
6. name=n; both are reference variables that refer to the objects
7. } allocated in memory.
8. void displayInformation(){System.out.println(rollno+"
"+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
3) Object and Class Example:
12. Student s1=new Student(); Initialization through a constructor
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation(); Object and Class Example: Employee
18. }
19. } Let's see an example where we are maintaining records of
employees.
Output:
File: TestEmployee.java
111 Karan
1. class Employee{
222 Aryan 2. int id;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 78
3. String name; 1. class Rectangle{
4. float salary; 2. int length;
5. void insert(int i, String n, float s) { 3. int width;
6. id=i; 4. void insert(int l, int w){
7. name=n; 5. length=l;
8. salary=s; 6. width=w;
9. } 7. }
10. void display(){System.out.println(id+" "+name+" 8. void calculateArea(){System.out.println(length*width);}
"+salary);} 9. }
11. } 10. class TestRectangle1{
12. public class TestEmployee { 11. public static void main(String args[]){
13. public static void main(String[] args) { 12. Rectangle r1=new Rectangle();
14. Employee e1=new Employee(); 13. Rectangle r2=new Rectangle();
15. Employee e2=new Employee(); 14. r1.insert(11,5);
16. Employee e3=new Employee(); 15. r2.insert(3,15);
17. e1.insert(101,"ajeet",45000); 16. r1.calculateArea();
18. e2.insert(102,"irfan",25000); 17. r2.calculateArea();
19. e3.insert(103,"nakul",55000); 18. }
20. e1.display(); 19. }
21. e2.display();
22. e3.display(); Output:
23. }
24. } 55
Output: 45
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 79
We will learn these ways to create object later. Output:
Anonymous simply means nameless. An object which has Creating multiple objects by one
no reference is known as an anonymous object. It can be type only
used at the time of object creation only.
We can create multiple objects by one type only as we do
If you have to use an object only once, an anonymous in case of primitives.
object is a good approach. For example:
Initialization of primitive variables:
1. new Calculation();//anonymous object
1. int a=10, b=20;
Calling method through a reference:
Initialization of refernce variables:
1. Calculation c=new Calculation();
2. c.fact(5);
1. Rectangle r1=new Rectangle(), r2=new Rectangle();//
creating two objects
Calling method through an anonymous object
Let's see the example:
1. new Calculation().fact(5);
1. //Java Program to illustrate the use of Rectangle class whic
Let's see the full example of an anonymous object in Java. h
2. //has length and width data members
1. class Calculation{ 3. class Rectangle{
2. void fact(int n){ 4. int length;
3. int fact=1; 5. int width;
4. for(int i=1;i<=n;i++){ 6. void insert(int l,int w){
5. fact=fact*i; 7. length=l;
6. } 8. width=w;
7. System.out.println("factorial is "+fact); 9. }
8. } 10. void calculateArea(){System.out.println(length*width);}
9. public static void main(String args[]){ 11. }
10. new Calculation().fact(5);//calling method with anonymou 12. class TestRectangle2{
s object 13. public static void main(String args[]){
11. } 14. Rectangle r1=new Rectangle(),r2=new Rectangle();//
12. } creating two objects
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 80
15. r1.insert(11,5); creates a default constructor if your class doesn't have
16. r2.insert(3,15); any.
17. r1.calculateArea();
18. r2.calculateArea();
19. } Rules for creating Java constructor
20. }
There are two rules defined for the constructor.
Output:
1. Constructor name must be the same as its class name
55 2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and
45 synchronized
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 81
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 82
11. void display(){System.out.println(id+" "+name);} 3. int id;
12. 4. String name;
13. public static void main(String args[]){ 5. int age;
14. //creating objects and passing values 6. //creating two arg constructor
15. Student4 s1 = new Student4(111,"Karan"); 7. Student5(int i,String n){
16. Student4 s2 = new Student4(222,"Aryan"); 8. id = i;
17. //calling method to display the values of object 9. name = n;
18. s1.display(); 10. }
19. s2.display(); 11. //creating three arg constructor
20. } 12. Student5(int i,String n,int a){
21. } 13. id = i;
14. name = n;
Output 15. age=a;
16. }
111 Karan 17. void display(){System.out.println(id+" "+name+"
"+age);}
222 Aryan 18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
Constructor Overloading in Java 22.
23.
s1.display();
s2.display();
24. }
In Java, a constructor is just like a method but without 25. }
return type. It can also be overloaded like Java methods.
26. Output:
27. 111 Karan 0
Constructor overloading in Java is a technique of having
28. 222 Aryan 25
more than one constructor with different parameter lists.
They are arranged in a way that each constructor performs
a different task. They are differentiated by the compiler by Difference between constructor and
the number of parameters in the list and their types.
method in Java
Example of Constructor Overloading There are many differences between constructors and
methods. They are given below.
1. //Java program to overload constructors
2. class Student5{
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 83
Java Constructor Java Method
Java String
In Java, string is basically an object that represents
sequence of char values. An array of characters works
same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 84
split(), length(), replace(), compareTo(), intern(),
substring() etc.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 85
1. By string literal "Welcome" in the pool, it will not create a new object but
2. By new keyword will return the reference to the same instance.
1) String Literal Note: String objects are stored in a special memory area
known as the "string constant pool".
Java String literal is created by using double quotes. For
Example: Why Java uses the concept of String
literal?
1. String s="welcome";
To make Java more memory efficient (because no new
Each time you create a string literal, the JVM checks the objects are created if it exists already in the string constant
"string constant pool" first. If the string already exists in pool).
the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is
created and placed in the pool. For example: 2) By new keyword
1. String s1="Welcome"; 1. String s=new String("Welcome");//creates two objects an
2. String s2="Welcome";//It doesn't create a new instance d one reference variable
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 86
7. System.out.println(s1);
8. System.out.println(s2); format(Locale l, String string with given locale.
9. System.out.println(s3); format, Object... args)
10. }}
5 String substring(int It returns substring for
Output: beginIndex) given begin index.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 87
13 String replace(char old, It replaces all 23 String toLowerCase() It returns a string in
char new) occurrences of the lowercase.
specified char value.
24 String It returns a string in
14 String It replaces all toLowerCase(Locale l) lowercase using
replace(CharSequence occurrences of the specified locale.
old, CharSequence new) specified CharSequence.
25 String toUpperCase() It returns a string in
15 static String It compares another uppercase.
equalsIgnoreCase(String string. It doesn't check
another) case. 26 String It returns a string in
toUpperCase(Locale l) uppercase using
16 String[] split(String It returns a split string specified locale.
regex) matching regex.
27 String trim() It removes beginning
17 String[] split(String It returns a split string and ending spaces of
regex, int limit) matching regex and this string.
limit.
28 static String valueOf(int It converts given type
18 String intern() It returns an interned value) into string. It is an
string. overloaded method.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 88
Important Constructors of synchroniz String s) specified string with this
ed string at the specified
StringBuffer Class StringBuffe position. The insert() method
r is overloaded like insert(int,
char), insert(int, boolean),
Constructo Description insert(int, int), insert(int,
r float), insert(int, double) etc.
StringBuffer() It creates an empty String buffer with the public replace(int It is used to replace the string
initial capacity of 16. synchroniz startIndex, int from specified startIndex and
ed endIndex, endIndex.
StringBuffer(Stri It creates a String buffer with the specified StringBuffe String str)
ng str) string.. r
StringBuffer(int It creates an empty String buffer with the public delete(int It is used to delete the string
capacity) specified capacity as length. synchroniz startIndex, int from specified startIndex and
ed endIndex) endIndex.
StringBuffe
r
Important methods of
StringBuffer class public
synchroniz
reverse() is used to reverse the string.
ed
StringBuffe
Modifie Method Description r
r and
Type public int capacity() It is used to return the current
capacity.
public append(String It is used to append the
synchroniz s) specified string with this public void ensureCapacity( It is used to ensure the
ed string. The append() method int capacity at least equal to the
StringBuffe is overloaded like minimumCapaci given minimum.
r append(char), ty)
append(boolean), append(int),
append(float), append(double) public char charAt(int It is used to return the
etc. index) character at the specified
position.
public insert(int offset, It is used to insert the
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 89
public int length() It is used to return the length 2) StringBuffer insert() Method
of the string i.e. total number
of characters. The insert() method inserts the given String with this string
at the given position.
public substring(int It is used to return the
String beginIndex) substring from the specified StringBufferExample2.java
beginIndex.
1. class StringBufferExample2{
public substring(int It is used to return the
2. public static void main(String args[]){
String beginIndex, int substring from the specified
3. StringBuffer sb=new StringBuffer("Hello ");
endIndex) beginIndex and endIndex.
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
What is a mutable String? 7. }
StringBufferExample.java StringBufferExample3.java
Output: Output:
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 90
4) StringBuffer delete() Method 6) StringBuffer capacity() Method
The delete() method of the StringBuffer class deletes the The capacity() method of the StringBuffer class returns the
String from the specified beginIndex to endIndex. current capacity of the buffer. The default capacity of the
buffer is 16. If the number of character increases from its
StringBufferExample4.java current capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current capacity is
1. class StringBufferExample4{ 16, it will be (16*2)+2=34.
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello"); StringBufferExample6.java
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo 1. class StringBufferExample6{
6. } 2. public static void main(String args[]){
7. } 3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
Output: 5. sb.append("Hello");
6. System.out.println(sb.capacity());//now 16
Hlo 7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34
5) StringBuffer reverse() Method 9. i.e (oldcapacity*2)+2
10. }
11. }
The reverse() method of the StringBuilder class reverses
the current String.
Output:
StringBufferExample5.java 16
1. class StringBufferExample5{ 16
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello"); 34
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. } 7) StringBuffer ensureCapacity()
7. } method
Output: The ensureCapacity() method of the StringBuffer class
ensures that the given capacity is the minimum to the
olleH
current capacity. If it is greater than the current capacity, it
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 91
increases the capacity by (oldcapacity*2)+2. For example
if your current capacity is 16, it will be (16*2)+2=34. Java File Class
StringBufferExample7.java The File class is an abstract representation of file and
directory pathname. A pathname can be either absolute or
1. class StringBufferExample7{ relative.
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer(); The File class have several methods for working with
4. System.out.println(sb.capacity());//default 16 directories and files such as creating new directories or
5. sb.append("Hello"); files, deleting and renaming directories or files, listing the
6. System.out.println(sb.capacity());//now 16
contents of a directory etc.
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (
oldcapacity*2)+2 Fields
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2 Modifi Typ Field Description
12. System.out.println(sb.capacity());//now 70 er e
13. }
14. }
static String pathSeparator It is system-
dependent path-
Output: separator character,
represented as
16 a string for
convenience.
16
static char pathSeparatorC It is system-
34 har dependent path-
separator character.
34
static String separator It is system-
70 dependent default
name-separator
character,
represented as a
string for
convenience.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 92
static char separatorChar It is system- suffix) directory, using the given
dependent default prefix and suffix to generate
name-separator its name.
character.
boolean createNewFile() It atomically creates a new,
empty file named by this
Constructors abstract pathname if and
only if a file with this name
does not yet exist.
Constructor Description
boolean canWrite() It tests whether the
File(File parent, It creates a new File instance from a application can modify the
String child) parent abstract pathname and a child file denoted by this abstract
pathname string. pathname.String[]
File(String It creates a new File instance by boolean canExecute() It tests whether the
pathname) converting the given pathname string into application can execute the
an abstract pathname. file denoted by this abstract
pathname.
File(String parent, It creates a new File instance from a
String child) parent pathname string and a child boolean canRead() It tests whether the
pathname string. application can read the file
denoted by this abstract
File(URI uri) It creates a new File instance by pathname.
converting the given file: URI into an
abstract pathname. boolean isAbsolute() It tests whether this
abstract pathname is
absolute.
Useful Methods
boolean isDirectory() It tests whether the file
denoted by this abstract
pathname is a directory.
Modifie Method Description
r and boolean isFile() It tests whether the file
Type denoted by this abstract
pathname is a normal file.
static File createTempFile(St It creates an empty file in
ring prefix, String the default temporary-file String getName() It returns the name of the
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 93
file or directory denoted by
this abstract pathname.
this keyword in Java
String getParent() It returns the pathname There can be a lot of usage of Java this keyword. In Java,
string of this abstract this is a reference variable that refers to the current
pathname's parent, or null if object.
this pathname does not
name a parent directory.
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 94
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+"
"+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
-* * * * * * * *-
1. class Student{
2. int rollno;
Object Oriented Programming using JAVA Unit 1 - Notes Prepared By. KAMALAKAR HEGDE Page No | 95