JAVA –Unit2 PESIAMS,Shimoga
Java is a high-level, general-purpose, object-oriented, and secure programming language
developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally known as OAK. In
1995, Sun Microsystem changed the name to Java. In 2009, Sun Microsystem takeover by
Oracle Corporation.
Features of Java
o Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or re-
implemented in Java. For example, pointer and operator overloading are not used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It means it has some
data and behavior. A program must have at least one class and object.
o Robust: Java makes an effort to check error at run time and compile time. It uses a strong
memory management system called garbage collector. Exception handling and garbage
collection features make it strong.
o Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines the
access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.
o Portable: Java Byte code can be carried to any platform. No implementation-dependent
features. Everything related to storage is predefined, for example, the size of primitive
data types.
o High Performance: Java is an interpreted language. Java enables high performance with
the use of the Just-In-Time compiler.
Darshan P R, Asst. Professor Page 1
JAVA –Unit2 PESIAMS,Shimoga
o Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over the
internet. EJB and RMI are used to create a distributed system.
o Multi-threaded: Java also supports multi-threading. It means to handle more than one
job a time.
OOPs (Object Oriented Programming System)
Object-oriented programming is a way of solving a complex problem by breaking them into a
small sub-problem. An object is a real-world entity. It is easier to develop a program by using an
object. In OOPs, we create programs using class and object in a structured manner.
o Class: A class is a template or blueprint or prototype that defines data members and
methods of an object. An object is the instance of the class. We can define a class by
using the class keyword.
o Object: An object is a real-world entity that can be identified distinctly. For example, a
desk, a circle can be considered as objects. An object has a unique behavior, identity, and
state. Data fields with their current values represent the state of an object (also known as
its properties or attributes).
o Abstraction: An abstraction is a method of hiding irrelevant information from the user.
For example, the driver only knows how to drive a car; there is no need to know how
does the car run. We can make a class abstract by using the keyword abstract. In Java, we
use abstract class and interface to achieve abstraction.
o Encapsulation: An encapsulation is the process of binding data and functions into a
single unit. A class is an example of encapsulation. In Java, Java bean is a fully
encapsulated class.
o Inheritance: Inheritance is the mechanism in which one class acquire all the features of
another class. We can achieve inheritance by using the extends keyword. It facilitates the
reusability of the code.
o Polymorphism: The polymorphism is the ability to appear in many forms. In other
words, single action in different ways. For example, a boy in the classroom behaves like a
student, in house behaves like a son. There are two types of polymorphism: run time
polymorphism and compile-time polymorphism.
Advantage of OOPs over Procedure-oriented programming language
1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global
data can be accessed from anywhere.
3) OOPs provides the ability to simulate real-world event much moreeffectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.
Darshan P R, Asst. Professor Page 2
JAVA –Unit2 PESIAMS,Shimoga
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Darshan P R, Asst. Professor Page 3
JAVA –Unit2 PESIAMS,Shimoga
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example:byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example: int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
Darshan P R, Asst. Professor Page 4
JAVA –Unit2 PESIAMS,Shimoga
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.
Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
Java Variable Example: Narrowing (Typecasting)
public class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
Darshan P R, Asst. Professor Page 5
JAVA –Unit2 PESIAMS,Shimoga
int a=(int)f;
System.out.println(f);
System.out.println(a);
}} Output:
10.5
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Darshan P R, Asst. Professor Page 6
JAVA –Unit2 PESIAMS,Shimoga
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
o incrementing/decrementing a value by one
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}} Output:
22
21
Darshan P R, Asst. Professor Page 7
JAVA –Unit2 PESIAMS,Shimoga
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
5
50
2
0
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Darshan P R, Asst. Professor Page 8
JAVA –Unit2 PESIAMS,Shimoga
Output:
40
80
80
240
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
Darshan P R, Asst. Professor Page 9
JAVA –Unit2 PESIAMS,Shimoga
System.out.println(a<b&a<c);//false & true = false
}} Output:
false
false
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in
Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on
its right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
Darshan P R, Asst. Professor Page 10
JAVA –Unit2 PESIAMS,Shimoga
System.out.println(b);
}}
Output:
14
16
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
If Statement:
In Java, the "if" statement is used to evaluate a condition.
if-else statement:
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements.
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
Darshan P R, Asst. Professor Page 11
JAVA –Unit2 PESIAMS,Shimoga
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
} } }
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Darshan P R, Asst. Professor Page 12
JAVA –Unit2 PESIAMS,Shimoga
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
Java for-each loop
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 the for-each loop in
java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop.
while(condition){
//looping statements
}
Darshan P R, Asst. Professor Page 13
JAVA –Unit2 PESIAMS,Shimoga
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
do
{
//statements
} while (condition);
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} } } } Output:
0
1
2
3
4
5
6
Darshan P R, Asst. Professor Page 14
JAVA –Unit2 PESIAMS,Shimoga
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
} } } }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
Advantage of method overloading
Method overloading increases the readability of the program.
Darshan P R, Asst. Professor Page 15
JAVA –Unit2 PESIAMS,Shimoga
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int, long, float or double. The char datatype can be promoted
to int,long,float or double and so on.
Darshan P R, Asst. Professor Page 16
JAVA –Unit2 PESIAMS,Shimoga
Java Math class
Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.
public class JavaMathExample1
{ public static void main(String[] args)
{
double x = 28;
double y = 4;
// return the maximum of two numbers
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
// return the square root of y
System.out.println("Square root of y is: " + Math.sqrt(y));
//returns 28 power of 4 i.e. 28*28*28*28
System.out.println("Power of x and y is: " + Math.pow(x, y));
// return the logarithm of given value
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
// return the logarithm of given value when base is 10
System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));
// return the log of x + 1
System.out.println("log1p of x is: " +Math.log1p(x));
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
System.out.println("expm1 of a is: " +Math.expm1(x));
}
}
Darshan P R, Asst. Professor Page 17
JAVA –Unit2 PESIAMS,Shimoga
Output:
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12
expm1 of a is: 1.446257064290475E12
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Darshan P R, Asst. Professor Page 18
JAVA –Unit2 PESIAMS,Shimoga
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
Darshan P R, Asst. Professor Page 19
JAVA –Unit2 PESIAMS,Shimoga
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}}}
Output:
268
6 8 10
Darshan P R, Asst. Professor Page 20