You are on page 1of 436

JAVA

What is Java?

❖ General-purpose, class-based, object-oriented programming language


Features of Java
❖ Simple
❖ Object-Oriented
❖ Portable
❖ Platform independent
❖ Robust
❖ Architecture neutral
❖ High Performance
❖ Multithreaded
❖ Distributed
Types of Java Applications

1) Standalone Application

2) Web Application

3) Enterprise Application

4) Mobile Application
Desktop GUI Applications

❖ We use APIs like AWT, Swing, JavaFX to build these applications.

❖ Examples of desktop GUI applications are Acrobat Reader,Media Player,


Antiviruses, etc.
Web-based Applications

❖ Java support for web development through Servlet, JSP, and Struts.

❖ Also known as a server-side programming language.

❖ frameworks Spring, Hibernate, Spring Boot, used for developing web-based


applications.

❖ LinkedIn, AliExpress, web.archive.org, IRCTC, etc. are the popular


websites that are written using Java programming language.
Enterprise Applications of Java

❖ Java EE (Java Enterprise Edition) is used to provide the tools to develop


large-scale,scalable, reliable, distributed and secured network applications
in enterprises.

❖ JavaEE is considered as the backbone for a variety of banking applications

❖ Companies like Naukri, Jabong, Google, Myntra, Flipkart, Trivago, ibibo,


TCS, Infosys, HCL, Wipro, Pinterest, eBay, etc use Java.
Mobile Applications

❖ Most of the android applications build using Java.

❖ Popular android app development IDE Android Studio also uses Java for
developing android applications.

❖ The most popular android applications Spotify and Twitter are developed
using Java
Gaming Applications

❖ Android games can be built with Java.

❖ Java supports jMonkeyEngine which is the most powerful open-source


3D-Engine and has the capacity to design 3-Dimensional games.

❖ some popular Frameworks and Libraries available for Game Development,


like - LibGDX and OpenGL.

❖ games developed in Java are Minecraft, Mission Impossible III, etc


Java Platforms / Editions
1) Java SE (Java Standard Edition)
2) Java EE (Java Enterprise Edition)

3) Java ME (Java Micro Edition)

4) JavaFX
Java Platform, Standard Edition (Java SE):

▪ Java SE’s API offers the Java programming language’s core functionality.

▪ Defines all the basis of type and object to high-level classes.

▪ Used for networking, security, database access, graphical user interface


(GUI) development.
Java Platform, Enterprise Edition (Java EE):
• Offers an API and runtime environment for developing and running highly
scalable, large-scale, and secure network applications.

Java Programming Language Platform, Micro Edition (Java ME):

• Offers an API and a small-footprint virtual machine running Java


programming language applications on small devices, like mobile phones.
Java FX:
Platform for developing rich internet applications using a lightweight user-
interface API.
Java Code Conventions
Code /Naming convention

• Is a rule to follow when we are naming identifiers such as class, package,


variable, constant, method, etc.

• But, it is not forced to follow.

• So, it is known as convention not rule.


Advantage of Code/Naming Conventions

• By using standard Java naming conventions, we make our code easier to read

for ourself and other programmers.

• Readability of Java program is very important.

• It indicates that less time is spent to figure out what the code does.
Classes and interfaces

• First letter should be uppercase.

• If the name is created from several words, the first letter of the inner words
should be capitalized (a "camelCase" format).

• Class names must be nouns: Cat, Exam, PrintReader.

• Interface names must be adjectives: Comparable, Iterable, Navigable.


Methods

• First letter must be lowercase, and then normal camelCase rules are used.

• Names should be verb-noun pairs: getName, doJob, setLastName.


Variables

• First letter must be lowercase, and then normal camelCase rules are used.

• It is recommended to use short, understandable names: firstName,

buttonHeight.
Constants

• Constants are created by declaring variables final and static.

• Names of the constants should have uppercase letters separated with

underscore characters: MAX_WEIGHT.


Java Bean Standards In Java
JavaBean Standards in Java
• If the property is not a boolean, the getter method’s prefix must be get. For
example, getSize()is a valid JavaBeans getter name for a property named
“size”.
• If the property is a boolean, the getter method’s prefix is either get or is. For
example, getStopped() or isStopped() are both valid JavaBeans names for a
boolean property.
• The setter method’s prefix must be set. For example, setSize() is the valid
JavaBean name for a property named size.
Examples of JavaBean Standards

• public void setMyValue(int v)

• public int getMyValue()

• public boolean isMyStatus()


Simple Java Program
class Simple

public static void main(String args[])

System.out.println("Hello Java");

} javac
To compile:
Simple.java
To execute: java Simple
Compilation Flow
Valid java main method signature

•public static void main(String[] args)


•public static void main(String []args)
•public static void main(String args[])
•public static void main(String... args)
•static public void main(String[] args)
•public static final void main(String[] args)
•final public static void main(String[] args)
Invalid java main method signature

• public void main(String[] args)

• static void main(String[] args)

• public void static main(String[] args)

• abstract public static void main(String[] args)


Can you save a java source file by other name than the
class name?

To compile: javac Simple.java


To execute: java Simple
Can you have multiple classes in a java source
file?
Java Variables
Java Variables

➢ Variable is a name of memory location.

➢ Is a combination of "vary + able" that means its value can be changed.

➢ There are three types of variables in java:

1. local variable

2. instance variable

3. static variable
1. Local Variable:
• Variable declared inside the body of the method.
• We can use this variable only within that method
• Cannot be defined with "static" keyword
2. Instance Variable
• Variable declared inside the class but outside the body of the method.
• It is not declared as static.
3. Static variable
• Variable which is declared as static is called static variable.
• It cannot be local
• Memory allocation for static variable happens only once when the class is
loaded in the memory
Example to understand the types of variables in java

class A
{
int data=50;
//instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
Java Variable Example: Widening
class Simple{

public static void main(String[] args)

int a=10;

float f=a;

System.out.println(a); OUTPUT:
System.out.println(f); 10
10.0
}}
Java Variable Example: Narrowing
class Simple {

public static void main(String[] args) {

float f=10.5f;

int a=f;

int a=(int)f;
OUTPUT:
System.out.println(f);

System.out.println(a); 10.5
10
}}
Data Types in Java
Integer
This group includes byte, short, int, long

byte :

• It is 1 byte(8-bits) integer data type.

• Value range from -128 to 127.

• Default value zero.

• example: byte b=10;

short :

• It is 2 bytes(16-bits) integer data type.

• Value range from -32768 to 32767.

• Default value zero.

• example: short s=11;


int :
• It is 4 bytes(32-bits) integer data type.
• Value range from -2147483648 to 2147483647.
• Default value zero.
• example: int i=10;

long :
• It is 8 bytes(64-bits) integer data type.
• Value range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
• Default value zero. example:
• long l=100012;
// byte type
byte b = 20;
System.out.println("b= "+b);

// short type
short s = 20;
System.out.println("s= "+s);

// int type
int i = 20;
System.out.println("i= "+i);

// long type
long l = 20;
System.out.println("l= "+l);
Floating-Point Number
This group includes float, double
float :
• It is 4 bytes(32-bits) float data type.
• Default value 0.0f.
• example: float ff=10.3f;

double :
• It is 8 bytes(64-bits) float data type.
• Default value 0.0d.
• example: double db=11.123;
Characters
• Data types used to store characters are char.

• Uses unicode to represent characters.

• Unicode defines a fully international character set that can represent all of the
characters found in all human languages like, latin, greek, arabic, and many
more.

• This data type is a single 16-bit(2bytes) unicode character and its value-ranges
between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).
• The \u in your example is for Unicode, we can store unicode characters that take
up to 16 bits, from \u0000 to \uFFFF.
public class Demo {
public static void main(String[] args)
{
char ch = 'S';
System.out.println(ch);

char ch2 = '&';


System.out.println(ch2);

char ch3 = '$'; Output:


System.out.println(ch3);
S
&
} } $
Boolean

• Is used to store two possible values i.e. true or false.

• Default value is false.

• Basically used for simple flags that track true/false conditions.


public class Demo {

public static void main(String[] args) {

boolean t = true;

System.out.println(t);

boolean f = false;

System.out.println(f);

} }
Type casting in java
Type Casting in Java

• Process of converting the value of one data type (int, float, double, etc.)
Into another data type is known as type casting.
There are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger


type size

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

• Narrowing Casting (manually) - converting a larger type to a smaller size


type

double -> float -> long -> int -> char -> short -> byte
Widening Casting
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i;
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
} Output:
Int value 100
Long value 100
} Float value 100.0
Narrowing Casting
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
Output:
System.out.println("Int value "+i); Double value 100.04
} } Long value 100
Int value 100
Example 2:
byte b;
int i = 257;
double d = 323.142;

System.out.println("Conversion of int to byte.");

// i % 256
b = (byte)i;

System.out.println("i = " + i + " b = " + b);


System.out.println(

// d % 256
b = (byte)d;

System.out.println("d = " + d + " b= " + b);


Output

Conversion of int to byte.

i = 257 b = 1

Conversion of double to byte.

d = 323.142 b= 67
Java int to char

public class IntToCharExample1{

public static void main(String args[])

int a=65;

char c=(char)a;

System.out.println(a);

}}
Output:
A
Convert char to int
char a = '5';

char b = 'c';

// convert char variables to int // ASCII value of characters is assigned

int num1 = a;

int num2 = b;

System.out.println(num1); // 53

System.out.println(num2); // 99
char to int using getNumericValue() method
char a = '5';
char b = '9';

// convert char variables to int // Use getNumericValue()


int num1 = Character.getNumericValue(a);
int num2 = Character.getNumericValue(b);

System.out.println(num1); // 5
System.out.println(num2); // 9
char to int using parseInt() method
char a = '5';

char b = '9';

// Use parseInt()

int num1 = Integer.parseInt(String.valueOf(a));

int num2 = Integer.parseInt(String.valueOf(b));

System.out.println(num1); // 5

System.out.println(num2); // 9
Tokens
Tokens

• Token as the smallest individual element.

• For example, we cannot create a sentence without using words;

• Similarly, we cannot create a program without using tokens.

• Tokens is the building block or the basic component for creating a program.
Keywords in Java
keywords
• keyword is a reserved word.

• We cannot use it as a variable name, constant name, etc.


Identifiers
Identifiers
• All Java variables must be identified with unique names.

• These unique names are called identifiers.

• Identifiers can be short names (like x and y) or more descriptive names


(age, sum, totalVolume).

• Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:
The general rules for naming variables are:

• Names can contain letters, digits, underscores, and dollar signs

• Names must begin with a letter

• Names should start with a lowercase letter and it cannot contain whitespace

• Names can also begin with $ and _ (but we will not use it)

• Names are case sensitive ("myVar" and "myvar" are different variables)

• Reserved words (like Java keywords, such as int or boolean) cannot be used
as names
valid identifiers in Java:
• TestVariable
• testvariable
• a
• i
• Test_Variable
• _testvariable
• $testvariable
• sum_of_array
• TESTVARIABLE
• jtp123
Invalid identifiers

• Test Variable ( We can not include a space in an identifier)

• 123java ( The identifier should not begin with numbers)

• java+J2EE ( The plus (+) symbol cannot be used)

• a-java ( Hyphen symbol is not allowed)

• java_&_J2EE ( ampersand symbol is not allowed)

• Java’J2EE (we can not use an apostrophe symbol in an identifier)


Difference Between Keyword and Identifier
Literals in java
What are Literals in Java?

• Have a constant value and a fixed data type and are often known as
constants in Java.

• Literals are assigned to a variable to provide a value to the variable.

• Example: int cost =340 ;


Types of Literals in Java
Integer Literals

• Integer literals are sequences of digits.

• 4 types of integer literals in Java:

1. binary (base 2)

2. decimal (base 10)

3. octal (base 8)

4. hexadecimal (base 16)


Decimal Integer:

• Integers having a base value of 10.

• Contains values between 0 to 9.

• Can be a positive value(+) or a negative value(-) but it cannot contain any


point in between them.

• Example: 1000, 1234, +78, -82, etc.


Octal Integer

• Integers having a base value of 8

• Contains values between 0 to 7.

• All octal numbers must start with a 0.

• Example: 012, 077,075, etc.

• int octal_int=077;
Hexadecimal Integer:
• Integers having a base value of 16.

• Containing values between 0 to 15.

• Contains both digits as well as characters.

• Digits range from 0 to 9 and the numbers 10 to 15 are replaced by characters a to f.

• Any integer starting with 0x or 0X is considered to be a hexadecimal integer.

• Example: 0xff, 0x2a, 0xf1f2, etc.

• int hexadec_int=0x1ff2;
Binary Integer

• Integers with a base value of 2.

• Contains only two digits 0 and 1.

• Start with a 0b indicating that it is a binary digit.

• Example: 0b100101, 0b1010101, etc.

• int binary_int=0b1010101;
Example
int decimal_int=1234;

int octal_int=077;

int hexadec_int=0x1ff2;

int binary_int=0b1010101;

System.out.println("This is a Decimal Literal: "+decimal_int);

System.out.println("This is an Octal Literal: "+octal_int);

System.out.println("This is a Hexa Decimal Literal: "+hexadec_int);

System.out.println("This is a Binary Literal: "+binary_int);


Output

This is a Decimal Literal: 1234

This is an Octal Literal: 63

This is a Hexa Decimal Literal: 8178

This is a Binary Literal: 85


Floating Point Literal

• Floating-point literals are values that contain a decimal point in between


them.

• Floating-point literals are generally double data type by default.

• We can assign them to float data types by adding an f at the end of the
value.

• Example: float val_float=1.7732f;


Few points to remember while declaring floating-
point literals are:

• If no suffix is present, the default data type is double.

• F or f suffix represents a floating data type.

• D or d suffix represents a double data type.


Few legal and illegal floating literals:

• 123.45 //Legal
• 122.32E5 //Legal
• 231.12F //Legal
• 1/4 // Illegal Symbol Used “/”
• 1.7.5 //Illegal, as two decimal points used.
• 1,234.56 // Illegal, as commas are not allowed
• 123.E4 //Illegal, as E cannot precede the point.
• 321E //Illegal, as the exponent part is incomplete.
Example

float val_float=1.7732f;

double val_double=1.7732d;

float val_exponent=123E4f;

System.out.println("This is a Floating Point Literal"+val_float);

System.out.println("This is a Decimal Literal"+val_double);

System.out.println("This is an Exponential Literal"+val_exponent);


Output

• This is a Floating Point Literal 1.7732

• This is a Decimal Literal 1.7732

• This is an Exponential Literal 1230000.0


Boolean Literal:

• Contains only two values true and false.

• Declared using the keyword boolean.

• It is a very useful literal to declare flag variables in different programs to


terminate a looping sequence.
Example

boolean flag1=true;

boolean flag2=false;

System.out.println("This is a boolean true flag variable "+flag1);

System.out.println("This is a boolean false flag variable "+flag2);


String Literal

• String is basically an array of characters.

• Anything written inside a double quote is a string “”.

• Example

String Company = “Atria”; //Valid String Literal

String Company = Atria; //Invalid as there is no double quote.


Example
String company=“Atria”;

String null_Literal=null;

System.out.println("This is a String Literal: "+company);

System.out.println("This is a null Literal: "+null_Literal);

Output:

This is a String Literal: Atria

This is a null Literal: null


Character Literal

• Character Literals in java are represented with a single quote.

• Example: char ch = 'a';


Char literal as Integral literal:

• we can specify char literal as integral literal, which represents the Unicode

value of the character, and that integral literal can be specified either in

Decimal, Octal, and Hexadecimal forms.

• But the allowed range is 0 to 65535.

• char ch = 062;
Unicode Representation:

• We can specify char literals in Unicode representation ‘\uxxxx’.

• Here xxxx represents 4 hexadecimal numbers.

• char ch = '\u0061’; // Here /u0061 represent a.


• A single character (b, t, n, f, r)

• An octal number between 000 and 377

• A u followed by four hexadecimal digits specifying a Unicode character


Example

char ch = 'a';
// It is an Integer literal with octal form
char b = 0789;
// Unicode representation
char c = '\u0061';

System.out.println(ch);
System.out.println(b);
System.out.println(c);
Output

• a

• error:Integer number too large

• a
OPERATORS IN JAVA
Operators in java

Operator in java is a symbol that is used to perform operations


Java Operator
Operator Type Category Precedence
postfix expr++ expr--
Unary
prefix ++expr --expr +expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:

Assignment assignment = += -= *= /= %=
Java Unary Operator
class OperatorExample{

public static void main(String args[]){

int x=10;

System.out.println(x++);
10
System.out.println(++x); 12
12
System.out.println(x--);
10
System.out.println(--x);

}}
SHIFT OPERATOR
Shift Operator

• Left Shift (<<)

• Right Shift (>>)


Left Shift Operator

• Left shift operator shifts all bits towards the left by a certain number of

specified bits.

• It is denoted by <<.
Java Left Shift Operator Example

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

}}
Right Shift Operator

• Right shift operator shifts all bits towards the right by a certain number of
specified bits.

• It is denoted by >>.

• When we shift any number to the right, the least significant bits (rightmost) are
discarded and the most significant position (leftmost) is filled with the sign bit.
Java Right Shift Operator Example

class OperatorExample{

public static void main(String args[]){

System.out.println(10>>2); //10/2^2=10/4=2

System.out.println(20>>2); //20/2^2=20/4=5

System.out.println(20>>3); //20/2^3=20/8=2

}}
Relation operators
Relation operators

• Used to test comparison between operands or values.

• Can be use to test whether two values are equal or not equal or less than or
greater than etc.

• Returns the Boolean results, i.e. true or false after the comparison
Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand


Example

int a, b;

a=40;

b=30;

System.out.println("a == b = " + (a == b) );

System.out.println("a != b = " + (a != b) );

System.out.println("a > b = " + (a > b) );

System.out.println("a < b = " + (a < b) );

System.out.println("b >= a = " + (b >= a) );

System.out.println("b <= a = " + (b <= a) );


Bitwise operators
Bitwise operators

• Bitwise operators are used to perform operations bit by bit.

• Java defines several bitwise operators that can be applied to the integer types
long, int, short, char and byte.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
truth table for bitwise &, | and ^

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise OR Operator

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25

00001100

| 00011001

____________

00011101 = 29 (In Decimal)


Program 1

class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

result = number1 | number2;


System.out.println(result); // prints 29
}
}
Bitwise AND Operator

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

// Bitwise AND Operation of 12 and 25

00001100

& 00011001

____________

00001000 = 8 (In Decimal)


Program

class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise AND between 12 and 25


result = number1 & number2;
System.out.println(result); // prints 8
}
}
Bitwise XOR Operator

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

// Bitwise XOR Operation of 12 and 25

00001100

^ 00011001

____________

00010101 = 21 (In Decimal)


Program

class Main {
public static void main(String[] args) {

int number1 = 12, number2 = 25, result;

// bitwise XOR between 12 and 25


result = number1 ^ number2;
System.out.println(result); // prints 21
}
}
Bitwise Complement Operator

• Bitwise complement operator is a unary operator (works with only one


operand).

• It is denoted by ~.

• It changes binary digits 1 to 0 and 0 to 1.


• The bitwise complement of any integer N is equal to - (N + 1).

For example,

• Consider an integer 35.

• As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36.


Program

class Main {
public static void main(String[] args) {

int number = 35, result;

// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
}
}
Logical Operators
Logical operators

• Logical operators are used to check whether an expression is true or false.

• They are used in decision making.


Operator Example Meaning

&& (Logical expression1 && true only if both expression1


AND) expression2 and expression2 are true

expression1 || true if either expression1 or


|| (Logical OR)
expression2 expression2 is true

true if expression is false and


! (Logical NOT) !expression
vice versa
class Main {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Ternary Operator

•The ternary operator (conditional operator) is shorthand for the if-then-


else statement.

variable = Expression ? expression1 : expression2

• If the Expression is true, expression1 is assigned to the variable.

• If the Expression is false, expression2 is assigned to the variable.


Example

int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result);
JAVA WRAPPER CLASSES

Description
Each of Java's eight primitive data types has a class dedicated to it. These are

known as wrapper classes, because they "wrap" the primitive data type into an

object of that class. The wrapper classes are part of the java.lang package, which is

imported by default into all Java programs.

The wrapper classes in java servers two primary purposes.

 To provide mechanism to ‘wrap’ primitive values in an object so that primitives

can do activities reserved for the objects like being added to ArrayList, Hashset,

HashMap etc. collection.

 To provide an assortment of utility functions for primitives like converting

primitive types to and from string objects, converting to various bases like

binary, octal or hexadecimal, or comparing various objects.

The following two statements illustrate the difference between a primitive data

type and an object of a wrapper class:

int x = 25;

Integer y = new Integer(33);


The first statement declares an int variable named x and initializes it with the value

25. The second statement instantiates an Integer object. The object is initialized

with the value 33 and a reference to the object is assigned to the object variable y.

Below table lists wrapper classes in Java API with constructor details.

Primitive Wrapper Class Constructor Argument

boolean Boolean boolean or String

byte Byte byte or String

char Character char

int Integer int or String

float Float float, double or String

double Double double or String

long Long long or String

short Short short or String


Below is wrapper class hierarchy as per Java API

As explain in above table all wrapper classes (except Character) take String as

argument constructor. Please note we might get NumberFormatException if we try

to assign invalid argument in constructor. For example to create Integer object we

can have following syntax.

Integer intObj = new Integer (25);

Integer intObj2 = new Integer ("25");

Here in we can provide any number as string argument but not the words etc.

Below statement will throw run time exception (NumberFormatException)

Integer intObj3 = new Integer ("Two");

The following discussion focuses on the Integer wrapperclass, but applies in a

general sense to all eight wrapper classes.


The most common methods of the Integer wrapper class are summarized in below

table. Similar methods for the other wrapper classes are found in the Java API

documentation.

Method Purpose

parseInt(s) returns a signed decimal integer value equivalent to string s

toString(i) returns a new String object representing the integer i

byteValue() returns the value of this Integer as a byte

doubleValue() returns the value of this Integer as an double

floatValue() returns the value of this Integer as a float

intValue() returns the value of this Integer as an int

shortValue() returns the value of this Integer as a short

longValue() returns the value of this Integer as a long

int compareTo(int i) Compares the numerical value of the invoking object with that of i.

Returns 0 if the values are equal. Returns a negative value if the

invoking object has a lower value. Returns a positive value if the

invoking object has a greater value.


static int compare(int num1, int Compares the values of num1 and num2. Returns 0 if the values are

num2) equal. Returns a negative value if num1 is less than num2. Returns a

positive value if num1 is greater than num2.

boolean equals(Object intObj) Returns true if the invoking Integer object is equivalent to intObj.

Otherwise, it returns false.

Let’s see java program which explain few wrapper classes methods.

1. package WrapperIntro;

2.

3.

4.

5. public class WrapperDemo {

6.

7.

8.

9. public static void main (String args[]){

10.

11. Integer intObj1 = new Integer (25);

12.

13. Integer intObj2 = new Integer ("25");

14.

15. Integer intObj3= new Integer (35);

16.
17. //compareTo demo

18.

19. System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(in

tObj2));

20.

21. System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(in

tObj3));

22.

23.

24.

25. //Equals demo

26.

27. System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2));

28.

29. System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3));

30.

31.

32.

33. Float f1 = new Float("2.25f");

34.

35. Float f2 = new Float("20.43f");

36.

37. Float f3 = new Float(2.25f);

38.

39. System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2));

40.
41. System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));

42.

43.

44.

45. //Addition of Integer with Float

46.

47. Float f = intObj1.floatValue() + f1;

48.

49. System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );

50.

51. }

52.

53.

54.

55. }

Output
valueOf (), toHexString(), toOctalString() and
toBinaryString() Methods:
This is another approach to create wrapper objects. We can convert from binary or

octal or hexadecimal before assigning value to wrapper object using two argument

constructor. Below program explains the method in details.

1. package WrapperIntro;

2.

3.

4.

5. public class ValueOfDemo {

6.

7.

8.

9. public static void main(String[] args) {

10.

11. Integer intWrapper = Integer.valueOf("12345");

12.

13. //Converting from binary to decimal

14.

15. Integer intWrapper2 = Integer.valueOf("11011", 2);

16.

17. //Converting from hexadecimal to decimal

18.

19. Integer intWrapper3 = Integer.valueOf("D", 16);


20.

21.

22.

23. System.out.println("Value of intWrapper Object: "+ intWrapper);

24.

25. System.out.println("Value of intWrapper2 Object: "+ intWrapper2);

26.

27. System.out.println("Value of intWrapper3 Object: "+ intWrapper3);

28.

29. System.out.println("Hex value of intWrapper: " + Integer.toHexString(intWrapper));

30.

31. System.out.println("Binary Value of intWrapper2: "+ Integer.toBinaryString(intWrapper2));

32.

33. }

34.

35. }

Output
Summary
 Each of primitive data types has dedicated class in java library.

 Wrapper class provides many methods while using collections like sorting,

searching etc.
control statements

If, If..else Statement in Java with Examples


When we need to execute a set of statements based on a condition then we need to use control flow
statements. For example, if a number is greater than zero then we want to print “Positive Number” but if it
is less than zero then we want to print “Negative Number”. In this case we have two print statements in the
program, but only one print statement executes at a time based on the input value. We will see how to write
such type of conditions in the java program using control statements.
In this tutorial, we will see four types of control statements that you can use in java programs based on the
requirement: In this tutorial we will cover following conditional statements:

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

If statement
If statement consists a condition, followed by statement or a set of statements as shown below:
if(condition){
Statement(s);
}
The statements gets executed only when the given condition is true. If the condition is false then the
statements inside if statement body are completely ignored.

Example of if statement
public class IfStatementExample {

public static void main(String args[]){


int num=70;
if( num < 100 ){
/* This println statement will only execute,
* if the above condition is true
*/
System.out.println("number is less than 100");
}
}
}
Output:
number is less than 100

Nested if statement in Java


When there is an if statement inside another if statement then it is called the nested if statement.
The structure of nested if looks like this:
if(condition_1) {
Statement1(s);

if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the conditions(
condition_1 and condition_2) are true.
Example of Nested if statement
public class NestedIfExample {

public static void main(String args[]){


int num=70;
if( num < 100 ){
System.out.println("number is less than 100");
if(num > 50){
System.out.println("number is greater than 50");
}
}
}
}
Output:
number is less than 100
number is greater than 50

If else statement in Java


This is how an if-else statement looks:
if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside “else” would
execute if the condition is false.

Example of if-else statement


public class IfElseExample {

public static void main(String args[]){


int num=120;
if( num < 50 ){
System.out.println("num is less than 50");
}
else {
System.out.println("num is greater than or equal 50");
}
}
}
Output:
num is greater than or equal 50

if-else-if Statement
if-else-if statement is used when we need to check multiple conditions. In this statement we have only one
“if” and one “else”, however we can have multiple “else if”. It is also known as if else if ladder. This is how
it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
Note: The most important point to note here is that in if-else-if statement, as soon as the condition is met, the
corresponding set of statements get executed, rest gets ignored. If none of the condition is met then the
statements inside “else” gets executed.

Example of if-else-if
public class IfElseIfExample {

public static void main(String args[]){


int num=1234;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");
}
}
}
Output:
Its a four digit number
Check out these related java examples:
1. Java Program to find the largest of three numbers using if..else..if
2. Java Program to check if number is positive or negative
3. Java Program to check if number is even or odd
Switch Case statement in Java with example
Switch case statement is used when we have number of options (or choices) and we may need to perform a
different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression)
{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}
Switch Case statement is mostly used with break statement even though it is optional. We will first see an
example without break statement and then we will discuss switch case with break
A Simple Switch Case Example
public class SwitchCaseExample1 {

public static void main(String args[]){


int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:
System.out.println("Case2: Value is: "+num);
case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}
Output:
Default: Value is: 2

Explanation: In switch I gave an expression, you can give variable also. I gave num+2, where num value is
2 and after addition the expression resulted 4. Since there is no case defined with value 4 the default case got
executed. This is why we should use default in switch case, so that if there is no catch that matches the
condition, the default block gets executed.
Switch Case Flow Diagram
First the variable, value or expression which is provided in the switch parenthesis is evaluated and then
based on the result, the corresponding case block is executed that matches the result.

Break statement in Switch Case


Break statement is optional in switch case but you would use it almost every time you deal with switch case.
Before we discuss about break statement, Let’s have a look at the example below where I am not using the
break statement:
public class SwitchCaseExample2 {

public static void main(String args[]){


int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
case 4:
System.out.println("Case4 ");
default:
System.out.println("Default ");
}
}
}
Output:
Case2
Case3
Case4
Default
In the above program, we have passed integer value 2 to the switch, so the control switched to the case 2,
however we don’t have break statement after the case 2 that caused the flow to pass to the subsequent cases
till the end. The solution to this problem is break statement
Break statements are used when you want your program-flow to come out of the switch body. Whenever a
break statement is encountered in the switch body, the execution flow would directly come out of the switch,
ignoring rest of the cases
Let’s take the same example but this time with break statement.
Example with break statement
public class SwitchCaseExample2 {

public static void main(String args[]){


int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
break;
case 2:
System.out.println("Case2 ");
break;
case 3:
System.out.println("Case3 ");
break;
case 4:
System.out.println("Case4 ");
break;
default:
System.out.println("Default ");
}
}
}
Output:
Case2
Now you can see that only case 2 had been executed, rest of the cases were ignored.

Why didn’t I use break statement after default?


The control would itself come out of the switch after default so I didn’t use it, however if you still want to
use the break after default then you can use it, there is no harm in doing that.

Few points about Switch Case


1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case
keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order
based on the requirement.
2) You can also use characters in switch case. for example –
public class SwitchCaseExample2 {

public static void main(String args[]){


char ch='b';
switch(ch)
{
case 'd':
System.out.println("Case1 ");
break;
case 'b':
System.out.println("Case2 ");
break;
case 'x':
System.out.println("Case3 ");
break;
case 'y':
System.out.println("Case4 ");
break;
default:
System.out.println("Default ");
}
}
}
3) The expression given inside switch should result in a constant value otherwise it would not be valid.
For example:

Valid expressions for switch:


switch(1+2+23)
switch(1*2+3%4)

Invalid switch expressions:


switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch statements inside another
switch. However nested switch statements should be avoided as it makes program more complex and less
readable.
Check out these related java programs:
1. Java Program to check whether a char is vowel or Consonant using Switch Case
2. Java Program to make a Simple Calculator using Switch Case

For loop in Java with example


Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java we
have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use “for loop”
in Java.
Syntax of for loop:
for(initialization; condition ; increment/decrement)
{
statement(s);
}

Flow of Execution of the for Loop


As a program executes, the interpreter always keeps track of which statement is about to be executed. We
call this the control flow, or the flow of execution of the program.

First step: In for loop, initialization happens first and only one time, which means that the initialization part
of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements
inside for loop body gets executed. Once the condition returns false, the statements in for loop does not
execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that
updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.

Example of Simple For loop


class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}
The output of this program is:
The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operation
Infinite for loop
The importance of Boolean expression and increment/decrement operation co-ordination:
class ForLoopExample2 {
public static void main(String args[]){
for(int i=1; i>=1; i++){
System.out.println("The value of i is: "+i);
}
}
}
This is an infinite loop as the condition would never return false. The initialization step is setting up the
value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the
Boolean expression: i>1) so it would never return false. This would eventually lead to the infinite loop
condition. Thus it is important to see the co-ordination between Boolean expression and
increment/decrement operation to determine whether the loop would terminate at some point of time or not.
Here is another example of infinite for loop:
// infinite loop
for ( ; ; ) {
// statement(s)
}

For loop example to iterate an array:


Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Output:
2
11
45
9

Enhanced For loop


Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.
Let’s take the same example that we have written above and rewrite it using enhanced for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
}
Output:
2
11
45
9
Note: In the above example, I have declared the num as int in the enhanced for loop. This will change
depending on the data type of array. For example, the enhanced for loop for string type would look like this:
String arr[]={"hi","hello","bye"};
for (String str : arr) {
System.out.println(str);
}
Check out these java programming examples related to for loop:
1. Java Program to find sum of natural numbers using for loop
2. Java Program to find factorial of a number using loops
3. Java Program to print Fibonacci Series using for loop

While loop in Java with examples


In the last tutorial, we discussed for loop. In this tutorial we will discuss while loop. As discussed in
previous tutorial, loops are used to execute a set of statements repeatedly until a particular condition is
satisfied.
Syntax of while loop
while(condition)
{
statement(s);
}
How while Loop works?
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute.
When condition returns false, the control comes out of loop and jumps to the next statement after while loop.
Note: The important point to note when using while loop is that we need to use increment or decrement
statement inside while loop so that the loop variable gets changed on each iteration, and at some point
condition returns false. This way we can end the execution of while loop otherwise the loop would execute
indefinitely.

Simple while loop example


class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2

Infinite while loop


class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
This loop would never end, its an infinite while loop. This is because condition is i>1 which would always
be true as we are incrementing the value of i inside while loop.
Here is another example of infinite while loop:
while (true){
statement(s);
}
Example: Iterating an array using while loop
Here we are iterating and displaying array elements using while loop.
class WhileLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
int i=0;
while(i<4){
System.out.println(arr[i]);
i++;
}
}
}
Output:
2
11
45
9
Check out these related programs:
1. Java Program to display Fibonacci Series using while loop
2. Java Program to find factorial using while loop
do-while loop in Java with example
In the last tutorial, we discussed while loop. In this tutorial we will discuss do-while loop in java. do-while
loop is similar to while loop, however there is a difference between them: In while loop, condition is
evaluated before the execution of loop’s body but in do-while loop condition is evaluated after the execution
of loop’s body.
Syntax of do-while loop:
do
{
statement(s);
} while(condition);
How do-while loop works?
First, the statements inside loop execute and then the condition gets evaluated, if the condition returns true
then the control gets transferred to the “do” else it jumps to the next statement after do-while.

do-while loop example


class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
Output:
10
9
8
7
6
5
4
3
2
Example: Iterating array using do-while loop
Here we have an integer array and we are iterating the array and displaying each element using do-while
loop.
class DoWhileLoopExample2 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}
}
Output:
2
11
45
9

Continue Statement in Java with example


Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly
jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body
for the current iteration. This is particularly useful when you want to continue the loop but do not want the
rest of the statements(after continue statement) in loop body to execute for that particular iteration.
Syntax:
continue word followed by semi colon.
continue;
Example: continue statement inside for loop
public class ContinueExample {

public static void main(String args[]){


for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}

System.out.print(j+" ");
}
}
}
Output:
012356
As you may have noticed, the value 4 is missing in the output, why? because when the value of variable j is
4, the program encountered a continue statement, which makes it to jump at the beginning of for loop for
next iteration, skipping the statements for current iteration (that’s the reason println didn’t execute when the
value of j was 4).
Flow Diagram of Continue Statement

Example: Use of continue in While loop


Same thing you can see here. We are iterating this loop from 10 to 0 for counter value and when the counter
value is 7 the loop skipped the print statement and started next iteration of the while loop.
public class ContinueExample2 {

public static void main(String args[]){


int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
System.out.print(counter+" ");
counter--;
}
}
}
Output:
10 9 8 6 5 4 3 2 1 0
Example of continue in do-While loop
public class ContinueExample3 {

public static void main(String args[]){


int j=0;
do
{
if (j==7)
{
j++;
continue;
}
System.out.print(j+ " ");
j++;
}while(j<10);

}
}
Output:
012345689

Break statement in Java with example


The break statement is usually used in following two scenarios:
a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered inside a
loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations. It is used
along with if statement, whenever used inside loop so that the loop gets terminated for a particular condition.
The important point to note here is that when a break statement is used inside a nested loop, then only the
inner loop gets terminated.
b) It is also used in switch case control. Generally all cases in switch case are followed by a break statement
so that whenever the program control jumps to a case, it doesn’t execute subsequent cases (see the example
below). As soon as a break is encountered in switch-case block, the control comes out of the switch-case
body.
Syntax of break statement:
“break” word followed by semi colon
break;

Example – Use of break in a while loop


In the example below, we have a while loop running from o to 100 but since we have a break statement that
only occurs when the loop value reaches 2, the loop gets terminated and the control gets passed to the next
statement in program after the loop body.
public class BreakExample1 {
public static void main(String args[]){
int num =0;
while(num<=100)
{
System.out.println("Value of variable is: "+num);
if (num==2)
{
break;
}
num++;
}
System.out.println("Out of while-loop");
}
}
Output:
Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop

Example – Use of break in a for loop


The same thing you can see here. As soon as the var value hits 99, the for loop gets terminated.
public class BreakExample2 {

public static void main(String args[]){


int var;
for (var =100; var>=10; var --)
{
System.out.println("var: "+var);
if (var==99)
{
break;
}
}
System.out.println("Out of for-loop");
}
}
Output:
var: 100
var: 99
Out of for-loop

Example – Use of break statement in switch-case


public class BreakExample3 {

public static void main(String args[]){


int num=2;

switch (num)
{
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}
}
}
Output:
Case 2
In this example, we have break statement after each Case block, this is because if we don’t have it then the
subsequent case block would also execute. The output of the same program without break would be Case 2
Case 3 Default.
Arrays and String
An array is a collection of similar type of elements which is stored in a contiguous
memory location.

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

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

One Dimensional Array :

A list of items can be given one variable name using only one subscript such a variable is called
a single-scripted or one –dimensional array.
Example
int a[]=new int[5];
for this array computer reserve five memory locations as

a[0] a[1] a[2] a[3] a[4]

The values assigned to the array elements, as follows:


a[0]=20
a[1]=40
a[2]=45
a[3]=100
a[4]=55

Creating Array:
Array must be declared and created in computer memory before they are used. Creation of array
involves three steps:
1. Declare the array
2. Create memory locations
3. Put values into the locations
Declaration of Arrays
Array in java may be declared in two forms.
Form1
Datatype Arrayname[ ];
Form2
Datatype[ ] Arrayname;
Example:
int number[ ];
floar percentage []
int[ ] count;
float[ ] average;

Creation of Arrays

After declaring the array, we need to create it in the memory.


Java allows us to create arrays using new operator only, as below :
Arrayname=new datatype[size];
Example:
number=new int[5];
average=new float[10];
these lines creates sufficient memory space for array number and average.
It is also possible to combine two steps – declaration and creation into one ,shown below :
int number [ ] = new int[5];

Initialization of Array: [ put values into array ]


Putting the values into the array is known as initialization . This is done using the array subscript
as shown below.
Arrayname [Subscript] = value;
Ex.
Number[0]=5;
Number[1]=40;
..
Number[4]=60;
We can also initialize array automatically in the same wayas the ordinary variable when they are
declared, as shown below:
Datatype arrayname[ ] = { list of values };
Values separated by commas and surrounded by curly braces.
Ex.
Int number[ ] = {10,20,50,100,55};
Program to demonstrate one dimensional array
class Testarray
{
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output:
33
3
4
5

Two Dimensional array

Two dimensional array requires two subscript one for Row and another for Column .Data in two
dimensional arrays are stored in tabular form (in row major order).
Declaration of 2D array:
int a[ ][ ];
a = new int [3][4];
or
int[][] a = new int[3][4];
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of
type int.
Initialization of 2D array :
Ex.
int a[ ][ ] = {1,2,3,4,5,6,7,8,9,10,11,12};
Or
int a[ ][ ] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };
or
int a[ ][ ] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12}
};

//Program to demonstrate two dimensional array


class 2darray
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
123
245
445
String Array

Strings represent a sequence of character.


Java String array is used to hold fixed number of Strings
Java String array is basically an array of objects.
There are two ways to declare string array – declaration without size and declare with size.
There are two ways to initialize string array – at the time of declaration, populating values after
declaration.
We can do different kind of processing on string array such as iteration, sorting, searching etc.
Java String Array Declaration

Below code shows different ways for string array declaration in java.
String[ ] strArray; //declare without size

String[ ] strArray1 = new String[3]; //declare with size


Note that we can also write string array as String strArray[] but above shows way is the standard
and recommended way. Also in the above code, strArray is null whereas strArray1 value
is [null, null, null].
Java String Array Initialization
Let’s look at different ways to initialize string array in java.
//inline initialization
String[ ] strArray1 = new String[] {"BMW","Ford","AUDI"};
String[] strArray2 = {"BMW","Ford","AUDI"};

//initialization after declaration


String[] strArray3 = new String[3];
strArray3[0] = "BMW";
strArray3[1] = "FORD";
strArray3[2] = "AUDI";

//Program to demonstrate string array


public class StringExample
{
public static void main(String args[])
{
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output:
java
strings
example

String Methods:

The String class has a set of built-in methods that you can use on strings.
Method Description Return Type

charAt() Returns the character at the specified index char


(position)

compareTo() Compares two strings lexicographically int

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of boolean


characters

equals() Compares two strings. Returns true if the boolean


strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the specified String


locale, format string, and arguments

getChars() Copies characters from a string to an array of void


chars

indexOf() Returns the position of the first found int


occurrence of specified characters in a string

isEmpty() Checks whether a string is empty or not boolean

lastIndexOf() Returns the position of the last found int


occurrence of specified characters in a string
length() Returns the length of a specified string int

replace() Searches a string for a specified value, and String


returns a new string where the specified values
are replaced

replaceFirst() Replaces the first occurrence of a substring that String


matches the given regular expression with the
given replacement

replaceAll() Replaces each substring of this string that String


matches the given regular expression with the
given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified boolean


characters

subSequence() Returns a new character sequence that is a CharSequence


subsequence of this sequence

substring() Extracts the characters from a string, beginning String


at a specified start position, and through the
specified number of character

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String


Ex.
1. String s1=”sachin”;
String s2 = s1.concat(“Tendulkar”);
System.out.println(s2);
Output:
Sachin Tendulkar
2. String s1=”HELLO”;
String s2 = s1.toLowerCase;
String s3 = s1.ChartAt(4);
System.out.println(s2);
System.out.println(s3);
Output:
hello
O
String Handling
• In Java, a string is a sequence of characters.
• Java implements strings as object of type String.
The String Constructors
 String s = new String( );
 default constructor
 create an empty string
 String s = new String(char chars[ ]);
 create a string initialized by an array of characters
 Example : char chars* + = ,‘a, ‘b’, ‘c’, ‘d’. ‘e’-;
String s = new String(chars);
 String s = new String(char chars[ ], int startIndex, int numChars);
 can specify a subrange of a character array as an initializer.
 startIndex specifies the index at which the subrange begins.
 numChars specifies the number of characters to use.
 Example : char chars* + = ,‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’-
String s = new String(chars, 2, 3);
-> initializes s with the characters ‘cde’
 String s = new String(String strObj);
 construct a String object that contains the same character sequence as another
String object using this constructor.
 Example: char c* + = ,‘J’, ‘A’, ‘V’, ‘A’-;
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
 String s = new String(byte asciiChars[ ]);
 Constructors that initialize a string when given a byte array.
 asciiChars specifies the array of bytes.
 String s = new String(byte asciiChars[ ],int startIndex, int numChars);
 Example: byte ascii[ ] = {65, 66,67,68,69,70};
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2,3);
System.out.println(s2);
Output:
ABCDEF
CDE
String Length
• The length of the string is the number of characters it contains.
• To obtain this value, call the length( ) method.
int length( )
Example
char chars* + = ,‘a’, ‘b’, ‘c’-;
String s = new String(chars);
System.out.println(s.length( ));
Special String Operations
• automatic creation of new string instances from string literals.
• concatenation of multiple String objects by use of the + operator.
• conversion of other data types to a String representation.
String Literals
• For each string literal in your program, Java automatically constructs a
String object.
Example: String str = “abc”
• String literals can be used to call methods directly as if it were an
object reference.
Example: System.out.println(“abc”.length( ));
String Concatenation
• Java does not allow operators to be applied to String objects.
• One exception is, the + operator, which concatenates two strings
producing a String object as the result.
• Example: String age = “9”;
String s = “He is” + age + “years old”;
System.out.println(s);
String Concatenation with other data types
• Strings can be concatenated with other types of data.
• Example: int age = 9;
String s = “He is” + age + “years old”;
System.out.println(s);
• Mixing other types of operations with String concatenation expressions
String s = “four:” +2+2;
System.out.println(s); // output: four:22
• If 2 and 2 has to be added, then use the parenthesis
String s = “four:” +(2+2);
System.out.println(s); // output: four:4
Character Extraction
• Many of the String methods employ an index into the String for their
operation.
• Like arrays, the String indexes begin at zero.
charAt( )
• To extract a single character from a String.
• General form
char charAt(int where)
where -> index of the character; value must be non-negative.
Example: char ch;
ch = “abc”.charAt(1); //assign the value “b” to ch
getChars( )
• To extract more than one character at a time.
• General form
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
sourceStart -> index of the beginning of the substring
sourceEnd -> index that is one past the end of the desired substring
(from sourceStart to sourceEnd – 1)
target[ ] -> array that receive the characters specified.
targetStart -> index within target at which the substring will be copied
• Example
class getCharsDemo
{
public static void main(String args[ ])
{
String s = “This is a Demo program”;
int start = 10, end =14;
char buf[ ] = new char[10];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
getBytes( )
• alternative to getChars( ) that stores the characters in an array of bytes.
• General form:
byte[ ] getBytes( )
toCharArray( )
• To convert all the characters in a String object into a character array,
the easy way is to call toCharArray( )
• General form:
char[ ] toCharArray( )
String Comparison
 equals( ) and equalsIgnoreCase( )
• To compare two strings for equality
boolean equals(String str)
• To perform a comparison that ignores case differences
boolean equalsIgnoreCase(String str)
str -> String object being compared with the invoking string object
returns -> true if the strings contain the same characters in the same
order.
• Example
class EqualsDemo {
public static void main(String args[ ]) {
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = “Hi”;
String s4 = “HELLO”;
System.out.println(s1.equals(s2);
System.out.println(s1.equals(s3);
System.out.println(s1.equals(s4);
System.out.println(s1.equalsIgnoreCase(s4);
}
}
 regionMatches( )
• compares a specific region inside a string with another specific region in another
string.
• General Forms:
boolean regionMatches(int startIndex, String str2, int str2StartIndex,
int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex, String str2,
int str2StartIndex, int numChars)
startIndex -> index at which the comparison will start at
within str1.
str2 -> string being compared.
str2StartIndex ->index at which the comparison will start at
within str2.
numChars -> length of the substring being compared.
ignoreCase -> if it is true, the case of the characters is ignored.
• Example
String s1 = “This is a test”;
String s2 = “This can be a TEST”;
int start = 10;
int start1 = 14;
int numChars = 4;
System.out.println(s1.regionMatches(start, s2,start1,numChars));
int pos =10;
int pos1 = 14;
System.out.println(s1.regionMatches(true, pos, s2,start1,numChars));
 startsWith( ) and endsWith( )
• startsWith( ) -> determines whether a given string begins with a
specified string
• endsWith( ) -> determines whether the given string ends with a
specified string
• General forms:
boolean startsWith(String str)
boolean endsWith(String str)
• Example
“Foobar”.endsWith(“bar”) -> true
“Foobar”.startsWith(“Foo”) -> true
• Another form of startsWith( )
boolean startsWith(String str, int startIndex)
startIndex -> index into the invoking object at which point, the
search will begin
“Foobar”.startsWith(“bar”, 3) -> true
 equals( )
• equals( ) method compares the characters inside a String object.
• Example
String s1 = “Hello”;
String s2 = new String(s1);
System.out.println(s1.equals(s2));

Output
true
 compareTo( )
• For sorting, we need to know which string is less than, equal to, or greater than the
next.
• A String is less than another if it comes before the other in dictionary order.
• A String is greater than another if it comes after the other in dictionary order.
• General form
int compareTo(String str)
str -> string being compared
Value Meaning
<0 Invoking string less than str
>0 Invoking string greater than str
= 0 Two strings are equal
• Example
• Now comes first because of the uppercase(uppercase has low value in ascii
set)
• If you want ignore the case while comparing, then call the method,
compareToIgnoreCase( )
GF
int compareToIgnoreCase(String str)
Searching Strings
• indexOf( ) -> searches for the first occurrence of a character or
substring.
• lastIndexOf( ) -> searches for the last occurrence of a character or
substring
• General forms
int indexOf(char ch)
int lastIndexOf(char ch)
int indexOf(String str)
int lastIndexOf(String str)
ch -> character being sought
str -> substring
• Specifying starting points for the search
int indexOf(char ch, int startIndex)
int latIndexOf(char ch, int startIndex)
startIndex -> index at which point the search begins
-> for index( ) search runs from startIndex to the end of
the string.
-> for lastIndexOf( ), search runs from startIndex to zero.
• Example
String s = “This is a test.This is too”;
System.out.println(s.indexOf(‘t’));
System.out.println(s.lastIndexOf(‘t’));
System.out.println(s.indexOf(“is”);
System.out.println(s.indexOf(‘s’,10));
System.out.println(s.lastIndexOf(“is”, 15));
Modifying a String
• String objects are immutable. To modify a string,
-> use one of the String methods given below
 subString( )
• To extract a sub string
• 2 forms
String subString(int startIndex)
-> from startIndex to end of the invoking string
String subString(int startIndex, int endIndex)
-> from startIndex to endIndex – 1
• Example
 concat( )
• To concatenate two strings
• General form
String concat(String str)
• Example
String s1 = “One”;
String s2 = s1.concat(“Two”);
System.out.println(s2);

Output
One Two
 replace( )
• Replaces all occurrences of one character in the invoking string with
another character.
• General form
String replace(char original, char replacement)
• Example
String s = “Hello”;
String s1 = s.replace(‘l’, ‘w’);
System.out.println(s1);
Output
Hewwo
 trim( )
• Returns a copy of the invoking string from which any leading and trailing
whitespace has been removed.
• General form
String trim( )
• Example
String s = “ Hello World “.trim( );
System.out.println(s);

Output
Hello World
 Changing the case of characters
• toLowerCase( ) -> converts all the characters in a String from uppercase
to lowercase
• toUpperCase( ) -> converts all the characters in a String from lowercase to
uppercase
• General forms
String toLowerCase( )
String toUpperCase( )
• Example
String s = “This is a test”;
String upper = s.toUpperCase( );
String lower = s.toLowerCase( );
System.out.println(upper);
System.out.println(lower);

Output
THIS IS A TEST
this is a test
Data Conversion using valueOf( )
• The valueOf( ) method converts data from its internal format into a
human readable form.
• static method
• General forms
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
• valueOf( ) is called when String representation of some other data
type is needed.
• Example
String s = “hello”;
int a = 10;
String abc = s.valueOf(a);
System.out.println(abc);
Output
10
Java classes/objects
Java objects
• Java is an object-oriented programming language.

• Everything in Java is associated with classes and objects.

• An object is any entity that has a state and behavior.

• For example: in real life, a car is an object.

• The car has attributes, such as weight and color, and methods, such as drive and
brake.
Java Class
• A class is a blueprint for the object.

• Before we create an object, we first need to define the class.

• We can think of the class as a sketch (prototype) of a house.

• It contains all the details about the floors, doors, windows, etc.

• Based on these descriptions we build the house.

• House is the object.


Java Class Syntax
class ClassName

// fields

// methods

• fields are used to store data

• methods are used to perform some operations


A class in Java can contain:

• Fields

• Methods

• Constructors

• Blocks

• Nested class and interface


• For bicycle object, we can create the class as:

class Bicycle {

// state or field
int gear = 5;

// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Objects
• An object is called an instance of a class.

• For example, suppose Bicycle is a class then MountainBicycle, SportsBicycle,


TouringBicycle, etc can be considered as objects of the class.
Creating an Object in Java
• Java Object Syntax: className variable_name = new className();

// for Bicycle class

• Bicycle sportsBicycle = new Bicycle();

• Bicycle touringBicycle = new Bicycle();


• className is the name of class that can be anything like: Bicycle that we declared
in the above example.

• variable_name is name of reference variable that is used to hold the reference of


created object.

• The new is a keyword which is used to allocate memory for the object.
Example: Creating a Class and its object
public class Student{

String name;
int rollno;
int age;

void info(){
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args) {
Student student = new Student();

// Accessing and property value


student.name = "Ramesh";
student.rollno = 253;
student.age = 25;

// Calling method
student.info();

} }
Output:
Name: Ramesh

Roll Number: 253

Age: 25
3 ways to initialize object
There are 3 ways to initialize object in Java.

• By reference variable

• By method

• By constructor
1) Object and Class Example: Initialization through reference

• Initializing an object means storing data into the object.


Example
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
} }
We can also create multiple objects and store information in it through reference
variable.

class Student{ s2.id=102;


int id; s2.name="Amit";
String name; System.out.println(s1.id+" "+s1.name);
} System.out.println(s2.id+" "+s2.name);
class TestStudent3{ }
public static void main(String args[]){ }
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
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.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
• Object gets the memory in heap memory area.
• The reference variable refers to the object allocated in the heap memory area.
• Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
Constructor
Constructors in Java

• Is called when an instance of the object is created.

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

Rules for creating Java constructor


• Constructor name must be the same as its class name

• A Constructor must have no explicit return type

• A Java constructor cannot be abstract, static, final


Types of Java constructors

1. Default constructor

2. User-Defined constructor
Java Default Constructor
• Default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
Example of default constructor that displays the
default values
class Student3{
int id;
String name;
void display()
{ System.out.println(id+“ "+name); }

public static void main(String args[])


{
Student3 s1=new Student3();
Student3 s2=new Student3(); Output:
s1.display(); 0 null
s2.display(); 0 null
} }
Java Parameterized Constructor

• A constructor which has a specific number of parameters

• Parameterized constructor is used to provide different values to the distinct


objects.
Example of parameterized constructor
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}

void display() { System.out.println(id+" "+name); }

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


111 Karan
222 Aryan
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
} }
Example of Constructor Overloading

class Student5{ void display()


int id; {
String name; System.out.println(id+" "+name+" "+age);
int age; }

Student5(int i,String n){ public static void main(String args[]){


id = i; Student5 s1 = new Student5(111,"Karan");
name = n; Student5 s2 = new Student5(222,"Aryan",25);
} s1.display();
s2.display();
Student5(int i,String n,int a){ }
id = i; }
name = n;
age=a; Output:
} 111 Karan 0
222 Aryan 25
Difference between constructor and method in
Java

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.


The Java compiler provides a default
The method is not provided by the compiler in
constructor if you don't have any constructor in
any case.
a class.

The constructor name must be same as the class The method name may or may not be same as
name. class name.
static keyword
static keyword

➢ Used for memory management mainly.

➢ A static method can be accessed without creating an object of the class first:
The static can be used with :

• Variable (also known as a class variable)

• Method (also known as a class method)

• Block

• Nested class
static variable

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

• Used to refer to the common property of all objects (which is not unique for
each object), for example, the company name of employees, college name of
students, etc.

• Gets memory only once in the class area at the time of class loading.
Advantages of static variable

• Memory efficient (i.e., it saves memory).


Java static method

• If we declare any method static keyword is known as static method.

• A static method belongs to the class rather than the object of a class.

• A static method can be invoked without the need for creating an instance of a
class.

• A static method can access static data member and can change the value of it.
class StaticTest {

// non-static method
int multiply(int a, int b){
return a * b;
}

// static method
static int add(int a, int b){
return a + b;
}
}

public class Main {

public static void main( String[] args ) {

// create an instance of the StaticTest class


StaticTest st = new StaticTest();

// call the nonstatic method


System.out.println(" 2 * 2 = " + st.multiply(2,2));

// call the static method


System.out.println(" 2 + 3 = " + StaticTest.add(2,3));
}
}
Java static block

• Is used to initialize the static data member.

• Is executed before the main method at the time of classloading.


Example

class A2{

static{

System.out.println("static block is invoked");

public static void main(String args[]){

System.out.println("Hello main");

}
Static class
• A class can be made static only if it is a nested class.

• Nested static class doesn’t need reference of Outer class

• A static class cannot access non-static members of the Outer


class
class JavaExample{
private static String str = “Cranberrys";

static class MyNestedClass{


public void disp() {
System.out.println(str);
}

}
public static void main(String args[])
{ JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
}
this keyword in java
this keyword

• this is a reference variable that refers to the current object.

• this keyword is to eliminate the confusion between class attributes and


parameters with the same name
Usage of Java this keyword

• this can be used to refer current class instance variable.

• this can be used to invoke current class method (implicitly)

• this() can be used to invoke current class constructor.


this: to refer current class instance variable

• this keyword can be used to refer current class instance variable.

• If there is ambiguity between the instance variables and parameters, this


keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
class Main {

int age;

Main(int age){

age = age;

public static void main(String[] args) {

Main obj = new Main(8);

System.out.println(“Age= " + obj.age);


Output:
}
Age = 0
}
Solution of the above problem by this keyword
class Main {

int age;

Main(int age){

this.age = age;

public static void main(String[] args) {

Main obj = new Main(8);

System.out.println(“Age= " + obj.age);

}
Output:
} Age = 8
this: to invoke current class method

• We may invoke the method of the current class by using the this keyword.

• If we don't use the this keyword, compiler automatically adds this keyword
while invoking the method.
class A{
void m() {System.out.println("hello m");}
void n(){
System.out.println("hello n");
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
Output:
a.n();
hello n
}} hello m
this() : to invoke current class constructor

• this() constructor call can be used to invoke the current class constructor.

• Used to reuse the constructor

• In other words, it is used for constructor chaining.


Calling default constructor from parameterized constructor:

class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
Output:
A a=new A(10);
hello a
}} 10
Calling parameterized constructor from default constructor:
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A(); Output:
5
} hello a
Encapsulation in Java with example
Encapsulation simply means binding object state(fields) and
behaviour(methods) together. If you are creating class, you are doing
encapsulation. In this guide we will see how to do encapsulation in java
program, if you are looking for a real-life example of encapsulation then refer
this guide: OOPs features explained using real-life examples.

For other OOPs topics such as inheritance and polymorphism, refer OOPs
concepts

Lets get back to the topic.

What is encapsulation?
The whole idea behind encapsulation is to hide the implementation details
from users. If a data member is private it means it can only be accessed
within the same class. No outside class can access private data member
(variable) of other class.

However if we setup public getter and setter methods to update (for


example void setSSN(int ssn))and read (for example int getSSN()) the private
data fields then the outside class can access those private data fields via
public methods.

This way data can only be accessed by public methods thus making the
private fields and their implementation hidden for outside classes. That’s why
encapsulation is known as data hiding. Lets see an example to understand
this concept better.

Example of Encapsulation in Java


How to implement encapsulation in java:
1) Make the instance variables private so that they cannot be accessed
directly from outside the class. You can only set and get values of these
variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the
fields.

class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;

//Getter and Setter methods


public int getEmpSSN(){
return ssn;
}

public String getEmpName(){


return empName;
}

public int getEmpAge(){


return empAge;
}

public void setEmpAge(int newValue){


empAge = newValue;
}

public void setEmpName(String newValue){


empName = newValue;
}

public void setEmpSSN(int newValue){


ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:

Employee Name: Mario


Employee SSN: 112233
Employee Age: 32
In above example all the three data members (or data fields) are
private(see: Access Modifiers in Java) which cannot be accessed directly.
These fields can be accessed via public methods only.
Fields empName, ssn and empAge are made hidden data fields using encapsulation
technique of OOPs.
Advantages of encapsulation
1. It improves maintainability and flexibility and re-usability: for e.g. In
the above code the implementation code of void setEmpName(String
name) and String getEmpName() can be changed at any point of time.
Since the implementation is purely hidden for outside classes they
would still be accessing the private field empName using the same
methods (setEmpName(String name) and getEmpName()). Hence the
code can be maintained at any point of time without breaking the
classes that uses the code. This improves the re-usability of the
underlying class.
2. The fields can be made read-only (If we don’t define setter
methods in the class) or write-only (If we don’t define the getter
methods in the class). For e.g. If we have a field(or variable) that
we don’t want to be changed so we simply define the variable as
private and instead of set and get both we just need to define the
get method for that variable. Since the set method is not present
there is no way an outside class can modify the value of that field.
3. User would not be knowing what is going on behind the scene.
They would only be knowing that to update a field call set method
and to read a field call get method but what these set and get
methods are doing is purely hidden from them.

Encapsulation is also known as “data Hiding“.


Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and felds of the parent class. Moreover, you can add
new methods and felds in your current class also.

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass


inherits the features. It is also called a base class or a parent class.

o Reusability: As the name specifes, reusability is a mechanism which


facilitates you to reuse the felds and methods of the existing class when you
create a new class. You can use the same felds and methods already defned
in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name

//methods and felds


}

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.

In the terminology of Java, a class which is inherited is called a parent or


superclass, and the new class is called child or subclass.

Java Inheritance Example

As displayed in the above fgure, Programmer is the subclass and Employee


is the superclass. The relationship between the two classes is Programmer
IS-A Employee. It means that Programmer is a type of Employee.

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;
public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

}
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the feld of own class
as well as of Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance.


For Example:
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the
single inheritance.

File: TestInheritance.java

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

}}

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As
you can see in the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a multilevel
inheritance.

File: TestInheritance2.java

class Animal{

void eat(){System.out.println("eating...");}

}
class Dog extends Animal{

void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat();

}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class Cat extends Animal{


void meow(){System.out.println("meowing...");}

class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in


java?
To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits
A and B classes. If A and B classes have the same method and you call it
from child class object, there will be ambiguity to call the method of A or B
class.

Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or diferent, there will be compile time error.

class A{

void msg(){System.out.println("Hello");}

class B{

void msg(){System.out.println("Welcome");}

}
class C extends A,B{//suppose if it were

public static void main(String args[]){

C obj=new C();

obj.msg();//Now which msg() method would be invoked?

}
Compile Time Error

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer
immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class


instance variable.
We can use super keyword to access the data member or feld of parent
class. It is used if parent class and child class have same felds.

class Animal{

String color="white";

class Dog extends Animal{

String color="black";

void printColor(){
System.out.println(color);//prints color of Dog class

System.out.println(super.color);//prints color of Animal class

class TestSuper1{

public static void main(String args[]){

Dog d=new Dog();

d.printColor();

}}

Output:

black
white

In the above example, Animal and Dog both classes have a common
property color. If we print color property, it will print the color of current class
by default. To access the parent property, we need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should
be used if subclass contains the same method as parent class. In other
words, it is used if method is overridden.

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void eat(){System.out.println("eating bread...");}

void bark(){System.out.println("barking...");}

void work(){

super.eat();

bark();

}
}

class TestSuper2{

public static void main(String args[]){

Dog d=new Dog();

d.work();

}}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we
call eat() method from Dog class, it will call the eat() method of Dog class by
default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor.
Let's see a simple example:

class Animal{

Animal(){System.out.println("animal is created");}

class Dog extends Animal{

Dog(){

super();

System.out.println("dog is created");

class TestSuper3{

public static void main(String args[]){

Dog d=new Dog();


}}

Output:

animal is created
dog is created

Final Keyword In Java


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

1. variable

2. method

3. class

The fnal keyword can be applied with the variables, a fnal variable that
have no value it is called blank fnal variable or uninitialized fnal variable. It
can be initialized in the constructor only. The blank fnal variable can be
static also which will be initialized in the static block only. We will have
detailed learning of these. Let's frst learn the basics of fnal keyword.

1) Java final variable


If you make any variable as fnal, you cannot change the value of fnal
variable(It will be constant).
Example of final variable
There is a fnal variable speedlimit, we are going to change the value of this
variable, but It can't be changed because fnal variable once assigned a
value can never be changed.

class Bike9{

final int speedlimit=90;//fnal variable

void run(){

speedlimit=400;

public static void main(String args[]){

Bike9 obj=new Bike9();

obj.run();

}//end of class
Output:Compile Time Error

2) Java final method


If you make any method as fnal, you cannot override it.

Example of final method


class Bike{

final void run(){System.out.println("running");}

class Honda extends Bike{

void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){

Honda honda= new Honda();

honda.run();

}
}
Output:Compile Time Error

3) Java final class


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

Example of final class


final class Bike{}

class Honda1 extends Bike{

void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){

Honda1 honda= new Honda1();

honda.run();

}
Output:Compile Time Erro

Q) Is final method inherited?


Ans) Yes, fnal method is inherited but you cannot override it. For Example:

class Bike{

final void run(){System.out.println("running...");}

class Honda2 extends Bike{

public static void main(String args[]){

new Honda2().run();

}
Output:running...
Q) What is blank or uninitialized final variable?
A fnal variable that is not initialized at the time of declaration is known as
blank fnal variable.

If you want to create a variable that is initialized at the time of creating


object and once initialized may not be changed, it is useful. For example PAN
CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


class Student{

int id;

String name;

final String PAN_CARD_NUMBER;

...

}
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

class Bike10{

final int speedlimit;//blank fnal variable

Bike10(){

speedlimit=70;

System.out.println(speedlimit);

public static void main(String args[]){

new Bike10();

}
Output: 70
static blank final variable
A static fnal variable that is not initialized at the time of declaration is known
as static blank fnal variable. It can be initialized only in static block.

Example of static blank final variable


class A{

static final int data;//static blank fnal variable

static{ data=50;}

public static void main(String args[]){

System.out.println(A.data);

Q) What is final parameter?

If you declare any parameter as fnal, you cannot change the value of it.

class Bike11{

int cube(final int n){

n=n+2;//can't be changed as n is fnal

n*n*n;

public static void main(String args[]){

Bike11 b=new Bike11();

b.cube(5);

}
Output: Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.

Uses of Java interface


There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

Declaring an interface
An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
interface interface_name
{
// declare constant fields
// declare methods that abstract
// by default.
}

Relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Example

interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello");
}
}
class MB
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
Output:
Hello
Interface Example:
In this example, the interface A has only one method. Its implementation is provided by
B and C classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used
by someone else. The implementation part is hidden by the user who uses the
interface.
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Display method in B class");
}
}
class C implements B
{
public void display()
{
System.out.println("display method in C class");
}
}
class MainClass
{
public static void main(String args[])
{
D obj=new D();
obj.draw();
}
}

Multiple inheritance by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

interface A
{
void display();
}
interface B
{
void show();
}
class C implements A,B
{
public void display()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class MainClass
{
public static void main(String args[])
{
C obj = new C();
obj.display();
obj.show();
}
}
Output:
Hello
Welcome

Interface inheritance
A class implements an interface, but one interface extends another interface.
interface A
{
void display();
}
interface B extends A
{
void show();
}
class C implements B
{
public void display()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
Class MainClass
{
public static void main(String args[])
{
C obj = new C();
obj.display();
obj.show();
}
}
Output:
Hello
Welcome

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.
Points to Remember
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of
the method.
Example
abstract class
{ }

Abstract Method
A method which is declared as abstract and does not have implementation is known as
an abstract method.
Example
abstract void display(); //no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely");
}
}
class Car
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
}
}
running safely

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare
the abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given
below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstract methods. 8, it can have default and statc methods also.

2) Abstract class doesn't support multple Interface supports multple inheritance.


inheritance.

3) Abstract class can have fnal, non-fnal, statc Interface has only statc and fnal variables.
and non-statc variables.

4) Abstract class can provide the Interface can't provide the implementaton of
implementaton of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single
action in difeeent ways. Polymorphism is derived from 2 Greek words: poly
and morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism


and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in
which a call to an overridden method is resolved at runtime rather than
compile-time.

In this process, an overridden method is called through the reference


variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.

Let's frst understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting. For example:

class A{}
class B extends A{}

A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface
type. For Example:

interface I{}

class A{}

class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A
Object

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendor. Splendor
class extends Bike class and overrides its run() method. We are calling the
run method by the reference variable of Parent class. Since it refers to the
subclass object and subclass method overrides the Parent class method, the
subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known


as runtime polymorphism.

class Bike{

void run(){System.out.println("running");}

class Splendor extends Bike{

void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){

Bike b = new Splendor();//upcasting


b.run();

Output:

running safely with 60km.

Java Runtime Polymorphism Example: Bank


Consider a scenario where Bank is a class that provides a method to get the
rate of interest. However, the rate of interest may difer according to banks.
For example, SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7%
rate of interest.

Note: This example is also given in method overriding but there was no upcasting.

class Bank{

float getRateOfInterest(){return 0;}

class SBI extends Bank{

float getRateOfInterest(){return 8.4f;}

}
class ICICI extends Bank{

float getRateOfInterest(){return 7.3f;}

class AXIS extends Bank{

float getRateOfInterest(){return 9.7f;}

class TestPolymorphism{

public static void main(String args[]){

Bank b;

b=new SBI();

System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());

b=new ICICI();

System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());

b=new AXIS();

System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape


class Shape{

void draw(){System.out.println("drawing...");}

class Rectangle extends Shape{

void draw(){System.out.println("drawing rectangle...");}

class Circle extends Shape{

void draw(){System.out.println("drawing circle...");}


}

class Triangle extends Shape{

void draw(){System.out.println("drawing triangle...");}

class TestPolymorphism2{

public static void main(String args[]){

Shape s;

s=new Rectangle();

s.draw();

s=new Circle();

s.draw();

s=new Triangle();

s.draw();

Output:

drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism Example: Animal


class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void eat(){System.out.println("eating bread...");}

class Cat extends Animal{

void eat(){System.out.println("eating rat...");}

class Lion extends Animal{


void eat(){System.out.println("eating meat...");}

class TestPolymorphism3{

public static void main(String[] args){

Animal a;

a=new Dog();

a.eat();

a=new Cat();

a.eat();

a=new Lion();

a.eat();

}}

Output:

eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime polymorphism
can't be achieved by data members.

In the example given below, both the classes have a data member
speedlimit. We are accessing the data member by the reference variable of
Parent class which refers to the subclass object. Since we are accessing the
data member which is not overridden, hence it will access the data member
of the Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.

class Bike{

int speedlimit=90;

class Honda3 extends Bike{


int speedlimit=150;

public static void main(String args[]){

Bike obj=new Honda3();

System.out.println(obj.speedlimit);//90

Output:

90

Java Runtime Polymorphism with Multilevel


Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel
inheritance.

class Animal{

void eat(){System.out.println("eating");}

class Dog extends Animal{

void eat(){System.out.println("eating fruits");}

class BabyDog extends Dog{

void eat(){System.out.println("drinking milk");}

public static void main(String args[]){

Animal a1,a2,a3;

a1=new Animal();

a2=new Dog();

a3=new BabyDog();

a1.eat();

a2.eat();

a3.eat();
}

Output:

eating
eating fruits
drinking Milk

Try for Output


class Animal{

void eat(){System.out.println("animal is eating...");}

class Dog extends Animal{

void eat(){System.out.println("dog is eating...");}

class BabyDog1 extends Dog{

public static void main(String args[]){

Animal a=new BabyDog1();

a.eat();

}}

Output:

Dog is eating

Since, BabyDog is not overriding the eat() method, so eat() method of Dog
class is invoked.

Static Binding and Dynamic Binding


Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).

2. Dynamic Binding (also known as Late Binding).

Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

int data=30;

Here data variable is a type of int.

2) References have a type


class Dog{

public static void main(String args[]){


Dog d1;//Here d1 is a type of Dog

}
3) Objects have a type
An object is an instance of particular java
class,but it is also an instance of its superclass.

class Animal{}

class Dog extends Animal{

public static void main(String args[]){

Dog d1=new Dog();

Here d1 is an instance of Dog class, but it is also


an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it
is known as static binding.

If there is any private, fnal or static method in a class, there is static binding.

Example of static binding


class Dog{

private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){

Dog d1=new Dog();

d1.eat();

}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic
binding.

Example of dynamic binding


class Animal{

void eat(){System.out.println("animal is eating...");}

class Dog extends Animal{

void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){

Animal a=new Dog();

a.eat();

}
Output:dog is eating...

In the above example object type cannot be


determined by the compiler, because the
instance of Dog is also an instance of Animal.So
compiler doesn't know its type, only its base
type.
Java Collection Framework
Chapter Topics

• Introduction to the Java collections Framework


• Lists
• Sets
• Maps
• The Collections Class

2
The Java Collection Framework

The Java Collections Framework is a library of


classes and interfaces for working with collections
of objects.

A collection is an object which can store other


objects, called elements. Collections provide
methods for adding and removing elements, and for
searching for a particular element within the
collection.

3
The Main Types of Collections

• Lists
• Sets
• Maps

4
Lists

Lists: List type collections assign an integer (called an


index) to each element stored.
Indices of elements are 0 for the element at the
beginning of the list, 1 for the next element, and so
on.
Lists permit duplicate elements, which are
distinguished by their position in the list.

5
Sets

Set: a collection with no notion of position within the


collection for stored elements. Sets do not permit
duplicate elements.

6
Maps

A map is a collection of pairs of objects:


1. A value: this is the object to be stored.
2. A key: this is another object associated with the value, and which can be
used to quickly find the value within the collection.
A map is really a set of keys, with each each key
having a value attached to it.
Maps do not allow duplicate keys.

7
Part of the JCF Hierarchy

8
9
The Collection Interface

• Lists and Sets are similar in many ways.


• The Collection Interface describes the operations that
are common to both.
• Maps are fundamentally different from Lists and Sets
and are described by a different interface.

10
Some Methods in the Collection Interface
Method Description
add(o : E) : boolean Adds an object o to the Collection. The method returns
true if o is successfully added to the collection, false
otherwise.
clear() : void Removes all elements from the collection.

contains(o : Object): Returns true if o is an element of the collection, false


boolean otherwise.
isEmpty() : boolean Returns true if there are no elements in the collection,
false otherwise.
iterator() : Iterator<E> Returns an object called an iterator that can be used to
examine all elements stored in the collection.
remove(o : Object) : Removes the object o from the collection and returns
boolean true if the operation is successful, false otherwise.
size() : int Returns the number of elements currently stored in the
collection.

11
AbstractCollection

The AbstractCollection class provides a skeleton


implementation for a Collection class by
implementing many of the methods of the
Collection interface.

Programmers can create a working collection class


by providing implementations for iterator(), size(),
and overriding add(o : Object).

12
Iterators

An iterator is an object that is associated with a


collection. The iterator provides methods for
fetching the elements of the collection, one at a
time, in some order.

Iterators have a method for removing from the


collection the last item fetched.

13
The Iterator Interface

Iterators implement the Iterator interface. This


interface specifies the following methods:
hasNext() : boolean
next() : E
remove() : void
The remove() method is optional, so not all
iterators have it.

14
Methods of the Iterator Interface

Method Description

hasNext() : boolean Returns true if there is at least one more element


from the collection that can be returned, false
otherwise.
next() : E Returns the next element from the collection.

remove() : void Removes from the collection the element


returned by the last call to next(). This method
can be called at least one time for each call to
next().

15
The List Interface

The List interface extends the Collection interface by


adding operations that are specific to the position-based,
index-oriented nature of a list.

16
List Interface Methods

The methods in the List interface describe


operations for adding elements and removing
elements from the list based on the index of the
element.
There are also methods for determining the index
of an element in the list when the value of an
element is known.

17
The List Interface Methods
add(index:int, el:E) : Adds the element el to the collection at the given index.
void Throws IndexOutOfBoundsException if index is negative,
or greater than the size of the list.
get(index:int):E Returns the element at the given index, or throws
IndexOutBoundsException if index is negative or greater
than or equal to the size of the list.
indexOf(o:Object):int Returns the least (first) index at which the object o is
found; returns -1 if o is not in the list.
lastIndexOf(o:Object):int Returns the greatest (last) index at which the object o is
found; returns -1 if o is not in the list.
listIterator():ListIterator< Returns an iterator specialized to work with List
E> collections.
remove(index:int):E Removes and returns the element at the given index;
throws IndexOutOfBoundsException if index is negative,
or greater than or equal to the size of the list.
set(index:int, el:E):E Replaces the element at index with the new element el.
18
AbstractList

This is an abstract class that provides a skeletal


implementation of a List collection.

It extends AbstractCollection and implements the


List interface.

It serves as the abstract superclass for the concrete


classes ArrayList and Vector.

19
ArrayList and Vector

ArrayList and Vector are array-based lists.


Internally, they use arrays to store their elements:
whenever the array gets full, a new, bigger array is
created, and the elements are copied to the new
array.

Vector has higher overhead than ArrayList because


Vector is synchronized to make it safe for use in
programs with multiple threads.

20
AbstractSequentialList and LinkedList

Array-based lists have high overhead when elements are


being inserted into the list, or removed from the list, at
positions that are not at the end of the list.

LinkedList is a concrete class that stores elements in a way


that eliminates the high overhead of adding to, and
removing from positions in the middle of the list.

LinkedList extends AbstractSequentialList, which in turn,


extends AbstractList.

21
Using the Concrete List Classes

• The concrete classes ArrayList, Vector, and LinkedList work in


similar ways, but have different performance characteristics.
• Because they all implement the List interface, you can use
List interface references to instantiate and refer to the
different concrete classes.
• Using a List interface instead of the concrete class reference
allows you to later switch to a different concrete class to get
better performance.

22
Example: ArrayList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};

// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);

// Display name list


for (int k = 0; k < nameList.size(); k++)
System.out.println(nameList.get(k));
}
}
23
An Example: LinkedList

Because we used a List reference to refer to the


concrete class objects, we can easily switch from an
ArrayList to a LinkedList : the only change is in the
class used to instantiate the collection.

24
Example: LinkedList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new LinkedList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};

// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);

// Display name list


for (int k = 0; k < nameList.size(); k++)
System.out.println(nameList.get(k));
}
}
25
Using an Iterator

To use an iterator with a collection,


1. Call the iterator():Iterator<E> method of the collection to retrieve an
iterator object.
2. Use the hasNext():boolean method to see if there still remain elements to
be returned, and the next():E method to return the next available element.
3. If desired, use the remove():void method to remove the element returned
by next().

26
The Iterator remove() method

• The remove() method removes the element returned


by the last call to next().

• The remove() method can be called at most one time


for each call to next().

27
Using an Iterator

List<String> nameList = new ArrayList<String>();


String [ ] names = {"Ann", "Bob", "Carol"};
// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);

// Display name list using an iterator


Iterator<String> it = nameList.iterator(); // Get the iterator
while (it.hasNext()) // Use the iterator
System.out.println(it.next());

28
ListIterator

The ListIterator extends Iterator by adding methods


for moving backward through the list (in addition to
the methods for moving forward that are provided
by Iterator)
hasPrevious() : boolean
previous() : E

29
Some ListIterator Methods
Method Description
add(el:E):void Adds el to the list at the position just before the
element that will be returned by the next call to the
next() method.
hasPrevious():boolean Returns true if a call to the previous() method will
return an element, false if a call to previous() will throw
an exception because there is no previous element.
nextIndex():int Returns the index of the element that would be
returned by a call to next(), or the size of the list if
there is no such element.
previous():E Returns the previous element in the list. If the iterator
is at the beginning of the list, it throws
NoSuchElementException.
previousIndex():int Returns the index of the element that would be
returned by a call to previous(), or -1.

set(el:E):void Replaces the element returned by the last call to


next() or previous() with a new element el.
30
Iterator Positions
Think of an iterator as having a cursor position that is initially
just before the element that will be returned by the first call to
next().

A call to next() puts the cursor just after the element returned,
and just before the element that will be returned by the next
call to next().

At any time, in a ListIterator, the cursor is in between two list


elements: A call to previous() will skip backward and return the
element just skipped, a call to next() will skip forward and and
return the element just skipped.

31
Iterator and ListIterator Exceptions

A call to previous() throws


NoSuchElementException when there is no element
that can be skipped in a backward move.

A call to next() throws NoSuchElementException


when there is no
element that can be skipped in a forward move.

32
Example Use of a ListIterator
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String>();
String [ ] names = {"Ann", "Bob", "Carol"};

// Add to arrayList using a ListIterator


ListIterator<String> it = nameList.listIterator();
for (int k = 0; k < names.length; k++)
it.add(names[k]);

// Get a new ListIterator for printing


it = nameList.listIterator();
while (it.hasNext())
System.out.println(it.next());
}

33
Enhanced For Loop

The enhanced for loop can be used with any


collection.

The compiler converts the enhanced for loop into a


traditional loop that uses the collection’s iterator.

34
Sets

Sets are collections that store elements, but have


no notion of a position of an element within the
collection.

The distinguishing feature of a set as a collection is


that it does not allow duplicates.

35
The Set Part of the JCF Hierarchy

AbstractCollection

AbstractSet

HashSet TreeSet

LinkedHashSet

36
The Set Part of the JCF

AbstractSet implements the Set Interface.

TreeSet implements the SortedSet interface, which


has methods for working with elements that have
an order that allows them to be sorted according to
their value.

37
HashSet

• HashSets store elements according to a hash code.


• A hash code of an element is an integer computed
from the value of the element that can be used to
help identify the element.
• The procedure used to compute the hash code of
an element is called the hashing function or the
hashing algorithm.

38
Examples of Hashing Functions

• For Integer objects, you can use the integer value of


the object (or its absolute value).

• For Character objects, you can use the UNICODE value


for the character.

• For String objects, you can use a function that takes


into account the UNICODE values of the characters
that make up the string, as well as the position
occupied by each character.

39
A Simplistic Hashing Function

A very simple (but not very good) hashing function


for strings might assign to each string the UNICODE
value of its first character.

Note that all strings with the same first character


are assigned the same hash code.

When two distinct objects have the same hash


code, we say that we have a collision.

40
Implementation of a HashSet

• A HashSet can be regarded as a collection of


“buckets.”
• Each bucket corresponds to a hash code, and stores
all objects in the set that have that particular hash
code.
• Some buckets will have just one element, whereas
other buckets may have many.
• A good hashing scheme should distribute elements
among the buckets so that all buckets have
approximately the same number of elements.

41
Implementation of a HashSet

The HashSet is a collection of buckets, and each


bucket is a collection of elements.
The collection of buckets is actually a list of
buckets, perhaps an ArrayList.
Each bucket may also be a list of elements, usually
a linked list.

42
How a HashSet Works
• To add an element X, the hash code for X is used (as
an index) to locate the appropriate bucket. X is then
added to the list for that bucket. If X is already in the
bucket (The test is done using the equals method),
then it is not added.

• To remove an item X, the hash code for X is computed.


The corresponding bucket is then searched for X, and
if it is found, it is removed.

43
Efficiency of HashSet Operations

Given an item X, computing the hash code for X


and locating the corresponding bucket can be done
very fast.

The time to search for, or remove X from the


bucket depends on how many elements are stored
in the bucket.

More collisions mean more elements in some


buckets, so we try to find a hashing scheme that
minimizes collisions.
44
HashSet Performance Considerations

To have good performance with a HashSet:


1. Have enough buckets: fewer buckets means
more collisions.
2. Have a good hashing function that spreads
elements evenly among the buckets. This keeps
the number of elements in each bucket small.

45
HashSet Capacity and Load Factor

• The load factor of a HashSet is the fraction of buckets


that must be occupied before the number of buckets
is increased.
• The number of buckets in a HashSet is called its
capacity.

46
Some HashSet Constructors

HashSet() Creates an empty HashSet object with a


default initial capacity of 16 and load factor
of 0.75.
HashSet(int initCapacity, Creates an empty HashSet object with the
float loadFactor) specified initial capacity and load factor.

HashSet(int initCapacity) Creates an empty HashSet object with the


specified initial capacity and a load factor of
0.75.

47
The hashCode() method

The Java Object class defines a method for computing


hash codes
int hashCode()
This method should be overriden in any class whose
instances will be stored in a HashSet.
The Object class’s hashCode() method returns a value
based on the memory address of the object.

48
Overriding the hashCode() Method

Observe these guidelines:


1. Objects that are equal according to their equals method should be
assigned the same hash code.
2. Because of 1), whenever you override a class’s equals() method, you
should also override hashCode().
3. Try to minimize collisions.

49
HashSet Example 1
import java.util.*;
/**
This program demonstrates how to add elements
to a HashSet. It also shows that duplicate
elements are not allowed.
*/
public class HashSetDemo1
{
public static void main(String[] args)
{
// Create a HashSet to hold String objects.
Set<String> fruitSet = new HashSet<String>();
// Add some strings to the set.
fruitSet.add("Apple");
fruitSet.add("Banana");
fruitSet.add("Pear");
fruitSet.add("Strawberry");
// Display the elements in the set.
System.out.println("Here are the elements.");
for (String element : fruitSet)
System.out.println(element);
// Try to add a duplicate element.
System.out.println("\nTrying to add Banana to " +
"the set again...");
if (!fruitSet.add("Banana"))
System.out.println("Banana was not added again.");
// Display the elements in the set.
System.out.println("\nHere are the elements once more.");
for (String element : fruitSet)
System.out.println(element);
}
}

50
A Car Class for Use With a HashSet
class Car
{
String vin, description;
public boolean equals(Object other) // Depends on vin only
{
if (!(other instanceof Car))
return false;
else
return vin.equalsIgnoreCase(((Car)other).vin);
}

public int hashCode() { return vin.hashCode();} // Depends on vin only

public Car(String v, String d) { vin = v; description = d; }


public String toString() { return vin + " " + description; }
}
51
A Car Class for use with a HashSet

Note that the Car class overrides both equals() and


hashCode().

52
Use of the Car Class with a HashSet
public static void main(String [ ] args)
{
Set<Car> carSet = new HashSet<Car>();
Car [ ] myRides = {
new Car("TJ1", "Toyota"),
new Car("GM1", "Corvette"),
new Car("TJ1", "Toyota Corolla")
};
// Add the cars to the HashSet
for (Car c : myRides)
carSet.add(c);

// Print the list using an Iterator


Iterator it = carSet.iterator();
while (it.hasNext())
System.out.println(it.next());
}
53
HashSet<Car> Program Output

GM1 Corvette
TJ1 Toyota

Note:
• The iterator does not return items in the order added to the
HashSet.
• The entry of the Toyota Corolla is rejected because it is equal
to an entry already stored (same vin).

54
HashSet Example 2
import java.util.*;
/**
This program creates a HashSet, adds some
names to it, gets an iterator for the set,
and searches the set for names.
*/
public class HashSetDemo2
{
public static void main(String[] args)
{
// Create a HashSet to hold names.
Set<String> nameSet = new HashSet<String>();
// Add some names to the set.
nameSet.add("Chris");
nameSet.add("David");
nameSet.add("Katherine");
nameSet.add("Kenny");
// Get an iterator for the set.
Iterator it = nameSet.iterator();

55
HashSet Example 2
// Display the elements in the set.
System.out.println("Here are the names in the set.");
while (it.hasNext())
System.out.println(it.next());
System.out.println();
// Search for "Katherine". We should find this
// name in the set.
if (nameSet.contains("Katherine"))
System.out.println("Katherine is in the set.");
else
System.out.println("Katherine is NOT in the set.");
// Search for "Bethany". We should not find
// this name in the set.
if (nameSet.contains("Bethany"))
System.out.println("Bethany is in the set.");
else
System.out.println("Bethany is NOT in the set.");
}
}

56
HashSet Example 3
/**
The Car class stores a VIN (Vehicle Identification
Number) and a description for a car.
*/
public class Car
{
private String vin; // Vehicle Identification Number
private String description; // Car description
/**
Constructor
@param v The VIN for the car.
@param desc The description of the car.
*/
public Car(String v, String desc)
{
vin = v;
description = desc;
}
/**
getVin method
@return The car's VIN.
*/
public String getVin()
{
return vin;
}

57
HashSet Example 3
/**
getDescription method
@return The car's description.
*/
public String getDescription()
{
return description;
}
/**
toString method
@return A string containing the VIN and description.
*/
public String toString()
{
return "VIN: " + vin +
"\tDescription: " +
description;
}
/**
hashCode method
@return A hash code for this car.
*/
public int hashCode()
{
return vin.hashCode();
}

58
HashSet Example 3
/**
equals method
@param obj Another object to compare this object to.
@return true if the two objects are equal, false otherwise.
*/
public boolean equals(Object obj)
{
// Make sure the other object is a Car.
if (obj instanceof Car)
{
// Get a Car reference to obj.
Car tempCar = (Car) obj;
// Compare the two VINs. If the VINs are
// the same, then they are the same car.
if (vin.equalsIgnoreCase(tempCar.vin))
return true;
else
return false;
}
else
return false;
}
}
59
HashSet Example 3
import java.util.*;
/**
This program stores Car objects in a HashSet and then
searches for various objects.
*/
public class CarHashSet
{
public static void main(String[] args)
{
// Create a HashSet to store Car objects.
Set<Car> carSet = new HashSet<Car>();
// Add some Car objects to the HashSet.
carSet.add(new Car("227H54", "1997 Volkswagen"));
carSet.add(new Car("448A69", "1965 Mustang"));
carSet.add(new Car("453B55", "2007 Porsche"));
carSet.add(new Car("177R60", "1980 BMW"));
// Display the elements in the HashSet.
System.out.println("Here are the cars in the set:");
for (Car c : carSet)
System.out.println(c);
System.out.println();

60
HashSet Example 3
// Search for a specific car. This one is in the set.
Car mustang = new Car("448A69", "1965 Mustang");
System.out.println("Searching for " + mustang);
if (carSet.contains(mustang))
System.out.println("The Mustang is in the set.");
else
System.out.println("The Mustang is NOT in the set.");
// Search for another car. This one is not in the set.
Car plymouth = new Car("911C87", "2000 Plymouth");
System.out.println("Searching for " + plymouth);
if (carSet.contains(plymouth))
System.out.println("The Plymouth is in the set.");
else
System.out.println("The Plymouth is NOT in the set.");
}
}

61
LinkedHashSet

A linkedHashSet is just a HashSet that keeps track of


the order in which elements are added using an
auxiliary linked list.

62
TreeSet

A TreeSet stores elements based on a natural order


defined on those elements.

The natural order is based on the values of the


objects being stored .

By internally organizing the storage of its elements


according to this order, a TreeSet allows fast search for
any element in the collection.

63
Order

An order on a set of objects specifies for any two


objects x and y, exactly one of the following:
x is less than y
x is equal to y
x is greater than y

64
Examples of Natural Orders

Some classes have a “natural” order for their objects:


• Integer, Float, Double etc has the obvious concept of natural order which tells
when one number is less than another.
• The String class has a natural alphabetic order for its objects.

65
The Comparable Interface

In Java, a class defines its natural order by


implementing the Comparable interface:
public interface Comparable<T>
{
int compareTo(T other);
}
The compareTo method returns a negative value, or
zero, or a positive value, to indicate that the calling
object is less than, equal to, or greater than the
other object.

66
Using a TreeSet with Comparable Elements

1. Make sure the class of your objects implements


Comparable.
2. Create an instance of TreeSet specialized for your class
Set<String> mySet = new TreeSet<String>();
3. Add elements.
4. Retrieve elements using an iterator. The iterator will return
elements in sorted order.

67
Sorting Strings Using a TreeSet
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
// Create TreeSet
Set<String> mySet = new TreeSet<String>();
// Add Strings
mySet.add("Alan");
mySet.add("Carol");
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}
68
The SortedSet Interface

TreeSet implements the SortedSet interface.


SortedSet methods allow access to the least and
greatest elements in the collection.
SortedSet methods allow various views of the
collection, for example, the set of all elements greater
than a given element, or less than a given element.

69
Comparators

A comparator is an object that can impose an order


on objects of another class.

This is different from the Comparable interface, which


allows a class to impose an order on its own objects.

70
The Comparator Interface

Interface Comparator <T>


{
int compare(T obj1, T obj2);
boolean equals(Object o);
}
The compare(x, y) method returns a negative value, or zero,
or a positive value, according to whether x is less than, equal
to, or greater than y.
The equals method is used to compare one comparator
object to another. It does not have to be implemented if the
equals inherited from Object is adequate.
71
Using TreeSets with Comparators
A TreeSet that stores objects of a class that does not
implement Comparable must use a comparator to
order its elements.

The comparator is specified as an argument to the


TreeSet constructor.

A comparator can also be used to make a TreeSet


order its elements differently from their natural order.

72
A Comparator for Ordering Strings in Reverse
Alphabetic Order

import java.util.*;
class RevStrComparator implements Comparator<String>
{
public int compare(String s1, String s2)
{
return - s1.compareTo(s2); // Note the negation operator
}
}

73
Using a TreeSet to Sort Strings in Reverse
Alphabetic Order
public class Test
{
public static void main(String [ ] args)
{ // Create Comparator
RevStrComparator comp = new RevStrComparator();
Set<String> mySet = new TreeSet<String>(comp);
// Add strings
mySet.add("Alan");
mySet.add("Carol");
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}

74
TreeSet Example 1
import java.util.*;
/**
This program demonstrates how a TreeSet
sorts its elements in ascending order.
*/
public class TreeSetDemo1
{
public static void main(String[] args)
{
// Create a TreeSet and store some values in it.
SortedSet<String> mySet = new TreeSet<String>();
mySet.add("Pear");
mySet.add("Apple");
mySet.add("Strawberry");
mySet.add("Banana");
// Display the elements in the TreeSet.
System.out.println("Here are the TreeSet elements " +
"in ascending order:");
for (String str : mySet)
System.out.println(str);
// Add a new element to the TreeSet.
System.out.println("\nAdding Blueberry to the set.");
mySet.add("Blueberry");
// Display the elements again.
System.out.println("\nHere are the TreeSet elements " +
"again:");
for (String str : mySet)
System.out.println(str);
}
}
75
TreeSet Example 2
import java.util.Comparator;
public class CarComparator<T extends Car>
implements Comparator<T>
{
public int compare(T car1, T car2)
{
// Get the two cars' VINs.
String vin1 = car1.getVin();
String vin2 = car2.getVin();
// Compare the VINs and return the
// result of the comparison.
return vin1.compareToIgnoreCase(vin2);
}
}

76
TreeSet Example 2
import java.util.*;
/**
This program demonstrates how a TreeSet
can use a Comparator to sort its elements.
*/
public class TreeSetDemo2
{
public static void main(String[] args)
{
// Create a TreeSet and pass an instance of
// CarComparator to it.
SortedSet<Car> carSet =
new TreeSet<Car>( new CarComparator<Car>() );
// Add some Car objects to the TreeSet.
carSet.add(new Car("227H54", "1997 Volkswagen"));
carSet.add(new Car("453B55", "2007 Porsche"));
carSet.add(new Car("177R60", "1980 BMW"));
carSet.add(new Car("448A69", "1965 Mustang"));
// Display the elements in the TreeSet.
System.out.println("Here are the cars sorted in " +
"order of their VINs:");
for (Car car : carSet)
System.out.println(car);
}
}

77
Maps

A map is a collection whose elements have two parts: a key


and a value.

The combination of a key and a value is called a mapping.

The map stores the mappings based on the key part of the
mapping, in a way similar to how a Set collection stores its
elements.

The map uses keys to quickly locate associated values.

78
The Map Part of the JCF Hierarchy

Map

AbstractMap

HashMap TreeMap

LinkedHashMap

79
The Map Interface

Map is a generic interface Map<K, V>

Map specifies two type parameters, K for the key,


and V for the value part of the mapping.

80
Some Methods of the Map Interface

clear() : void Removes all elements from the map.

containsValue(value: Returns true if the map contains a mapping with


Object):boolean the given value.
containsKey(key : Object) Returns true if the map contains a mapping with
: boolean the given key.
get(key : Object) : V Returns the value associated with the specified
key, or returns null if there is no such value.
isEmpty() : boolean Returns true if the key contains no mappings.

keySet() : Set<K> Returns the set of all keys stored in the map.

81
Some Methods of the Map Interface

put(key : K, value : V) : V Adds a mapping that associates V with K, and


returns the value previously associated with K.
Returns null if there was no value associated with K.
remove(key : Object) : V Removes the mapping associated with the given
key from the map, and returns the associated value.
If there is not such mapping, returns null.
size() : int Returns the number of mappings in the map.

values() : Collection<V> Returns a collection consisting of all values stored in


the map.

82
Concrete Map Classes

Maps store keys with attached values. The keys are


stored as sets.
• HashMap stores keys according to their hash codes, just like
HashSet stores its elements.
• LinkedHashMap is a HashMap that can iterate over the keys
in insertion order (order in which mappings were inserted)
or in access order (order of last access).
• TreeMap stores mappings according to the natural order of
the keys, or according to an order specified by a
Comparator.

83
HashMap Example 1
import java.util.*;
/**
This program stores mappings in a HashMap and then
searches for various objects.
*/
public class CarHashMap1
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);

84
HashMap Example 1
// Search for the Mustang by its VIN.
System.out.println("\nSearching for the car with " +
"VIN " + mustang.getVin());
Car foundCar = carMap.get(mustang.getVin());
// If the car was found, display it.
if (foundCar != null)
System.out.println(foundCar);
else
System.out.println("The Mustang is NOT in the set.");
// Search for another VIN. This one is not in the set.
System.out.println("\nSearching for the car with " +
"VIN 911C87");
foundCar = carMap.get("911C87");
// If the car was found display it.
if (foundCar != null)
System.out.println(foundCar);
else
System.out.println("That car is NOT in the set.");
}
}

85
HashMap Example 2
import java.util.*;
/**
This program retrieves a set of keys and a
collection of values from a HashMap.
*/
public class CarHashMap2
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);

86
HashMap Example 2
// Get a set containing the keys in this map.
Set<String> keys = carMap.keySet();
// Iterate through the keys, printing each one.
System.out.println("Here are the keys:");
for (String k : keys)
System.out.println(k);
// Get a collection containing the values.
Collection<Car> values = carMap.values();
// Iterate through the values, printing each one.
System.out.println("\nHere are the values:");
for (Car c : values)
System.out.println(c);
}
}

87
HashMap Example 3
import java.util.*;
/**
This program retrieves the mappings from a HashMap
as a Set of Map.Entry objects.
*/
public class CarHashMap3
{
public static void main(String[] args)
{
// Create a HashMap to store Car objects.
Map<String, Car> carMap =
new HashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the HashMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);

88
HashMap Example 3
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}

89
HashMap Example 4
import java.util.*;
/**
This program retrieves the mappings from a
LinkedHashMap as a Set of Map.Entry objects.
*/
public class CarHashMap4
{
public static void main(String[] args)
{
// Create a LinkedHashMap to store Car objects.
Map<String, Car> carMap =
new LinkedHashMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");

90
HashMap Example 4
// Put some mappings into the LinkedHashMap. In
// each mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}

91
HashMap Example 5
import java.util.*;
/**
This program displays the mappings stored in a
TreeMap. The mappings are displayed in ascending
key order.
*/
public class CarHashMap5
{
public static void main(String[] args)
{
// Create a TreeMap to store Car objects.
SortedMap<String, Car> carMap =
new TreeMap<String, Car>();
// Create some Car objects.
Car vw = new Car("227H54", "1997 Volkswagen");
Car mustang = new Car("448A69", "1965 Mustang");
Car porsche = new Car("453B55", "2007 Porsche");
Car bmw = new Car("177R60", "1980 BMW");
// Put some mappings into the TreeMap. In each
// mapping, the car's VIN is the key and the
// Car object containing that VIN is the value.
carMap.put(vw.getVin(), vw);
carMap.put(mustang.getVin(), mustang);
carMap.put(porsche.getVin(), porsche);
carMap.put(bmw.getVin(), bmw);

92
HashMap Example 5
// Get a set containing the mappings in this map.
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
// Iterate through the mappings, printing each one.
System.out.println("Here are the mappings:");
for (Map.Entry<String, Car> entry : cars)
{
System.out.println("Key = " + entry.getKey());
System.out.println("Value = " + entry.getValue());
System.out.println();
}
}
}

93
Exception handling in java with examples

Exception handling is one of the most important feature of java programming that allows us to handle the
runtime errors caused by exceptions. In this guide, we will learn what is an exception, types of it, exception
classes and how to handle exceptions in java with examples.

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception
occurs program execution gets terminated. In such cases we get a system generated error message. The good
thing about exceptions is that they can be handled in Java. By handling the exceptions we can provide a
meaningful message to the user about the issue rather than a system generated message, which may not be
understandable to a user.

Why an exception occurs?

There can be several reasons that can cause a program to throw exception. For example: Opening a non-
existing file in your program, Network connection problem, bad input data provided by user etc.

Exception Handling

If an exception occurs, which has not been handled by programmer then program execution gets terminated
and a system generated error message is shown to the user. For example look at the system generated
exception below:

An exception generated by the system is given below

Exception in thread "main" java.lang.ArithmeticException: / by zero at


ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number

This message is not user friendly so a user will not be able to understand what went wrong. In order to let
them know the reason in simple language, we handle exceptions. We handle such conditions and then prints
a user friendly warning message to user, which lets them correct the error as most of the time exception
occurs due to bad data provided by user.

Advantage of exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For
example, if a program has bunch of statements and an exception occurs mid way after executing certain
statements then the statements after the exception will not execute and the program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
Difference between error and exception

Errors indicate that something severe enough has gone wrong, the application should crash rather than try to
handle the error.

Exceptions are events that occurs in the code. A programmer can handle such conditions and take necessary
corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you try to divide a number by
zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its bounds, for
example array size is 5 (which means it has five elements) and you are trying to access the 10th element.

Types of exceptions

There are two types of exceptions in Java:


1)Checked exceptions
2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks
them during compilation to see whether the programmer has handled them or not. If these exceptions are not
handled/declared in the program, you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-
time so compiler does not check whether the programmer has handled them or not but it’s the responsibility
of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Compiler will never force you to catch such exception or force you to declare it in the method using throws
keyword.

Try Catch in Java – Exception handling

In the previous tutorial we discussed what is exception handling and why we do it. In this tutorial we will see
try-catch block which is used for exception handling.

Try block

The try block contains set of statements where an exception can occur. A try block is always followed by a
catch block, which handles the exception that occurs in associated try block. A try block must be followed
by catch blocks or finally block or both.

Syntax of try block

try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can throw a exception, enclosed
them in try block and handle that exception

Catch block

A catch block is where you handle the exceptions, this block must follow the try block. A single try block
can have several catch blocks associated with it. You can catch different exceptions in different catch blocks.
When an exception occurs in try block, the corresponding catch block that handles that particular exception
executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch
block for arithmetic exception executes.

Syntax of try catch in java

try
{
//statements that may cause an exception
}
catch (exception(type) e(object
{
//error handling code
}

Example: try catch block

If an exception occurs in try block then the control of execution is passed to the corresponding catch block.
A single try block can have multiple catch blocks associated with it, you should place the catch blocks in
such a way that the generic exception handler catch block is at the last(see in the example below).
The generic exception handler can handle all the exceptions but you should place is at the end, if you place it
at the before all the catch blocks then it will display the generic message. You always want to give the user a
meaningful message for each type of exception rather then a generic message.
class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:

You should not divide a number by zero


I'm out of try-catch block in Java.

Multiple catch blocks in Java

The example we seen above is having multiple catch blocks, lets see few rules about multiple catch blocks
with the help of examples. To read this in detail, see catching multiple exceptions in java.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or
ArithmeticException or NullPointerException or any other type of exception, this handles all of them. To see
the examples of NullPointerException and ArrayIndexOutOfBoundsException,.

catch(Exception e){
//This catch block catches all the exceptions
}

If you are wondering why we need other catch handlers when we have a generic that can handle all. This is
because in generic exception handler you can display a message but you are not sure for which type of
exception it may trigger so it will display the same message for all the exceptions and user may not be able
to understand which exception occurred. Thats the reason you should place is at the end of all the specific
exception catch blocks
3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception,

Example of Multiple catch blocks

class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Output:

Warning: ArithmeticException
Out of try-catch block...

In the above example there are multiple catch blocks and these catch blocks executes sequentially when an
exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first
place, just after try block then in case of any exception this block will execute as it can handle all exceptions.
This catch block should be placed at the last to avoid such situations.

Finally block

I have covered this in a separate tutorial here: java finally block. For now you just need to know that this
block executes whether an exception occurs or not. You should place those statements in finally blocks, that
must execute whether exception occurs or not.

How to Catch multiple exceptions

In the previous tutorial, I have covered how to handle exceptions using try-catch blocks. In this guide, we
will see how to handle multiple exceptions and how to write them in a correct order so that user gets a
meaningful message for each type of exception.
Catching multiple exceptions

Lets take an example to understand how to handle multiple exceptions.

class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:

You should not divide a number by zero


Out of the try-catch block

In the above example, the first catch block got executed because the code we have written in try block
throws ArithmeticException (because we divided the number by zero).

Now lets change the code a little bit and see the change in output:

class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:
Accessing array elements outside of the limit
Out of the try-catch block

In this case, the second catch block got executed because the code throws
ArrayIndexOutOfBoundsException. We are trying to access the 11th element of array in above program but
the array size is only 7.

What did we observe from the above two examples?


1. It is clear that when an exception occurs, the specific catch block (that declares that exception) executes.
This is why in first example first block executed and in second example second catch.
2. Although I have not shown you above, but if an exception occurs in above code which is not Arithmetic
and ArrayIndexOutOfBounds then the last generic catch handler would execute.

Lets change the code again and see the output:

class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the limit");
}
System.out.println("Out of the try-catch block");
}
}
Output:

Compile time error: Exception in thread "main" java.lang.Error:


Unresolved compilation problems: Unreachable catch block for ArithmeticException.
It is already handled by the catch block for Exception Unreachable catch block
for ArrayIndexOutOfBoundsException. It is already handled by the catch block for
Exception at Example.main(Example1.java:11)

Why we got this error?


This is because we placed the generic exception catch block at the first place which means that none of the
catch blocks placed after this block is reachable. You should always place this block at the end of all other
specific exception catch blocks.
Nested try catch block in Java – Exception handling

When a try catch block is present in another try block then it is called the nested try catch block. Each time a
try block does not have a catch handler for a particular exception, then the catch blocks of parent try block
are inspected for that exception, if match is found that that catch block executes.

If neither catch block nor parent catch block handles exception then the system generated message would be
shown for the exception, similar to what we see when we don’t handle exception.

Lets see the syntax first then we will discuss this with an example.

Syntax of Nested try Catch

....
//Main try block
try {
statement 1;
statement 2;
//try-catch block inside another try block
try {
statement 3;
statement 4;
//try-catch block inside nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2) {
//Exception Message
}
}
catch(Exception e1) {
//Exception Message
}

}
//Catch of Main(parent) try block
catch(Exception e3) {
//Exception Message
}
....

Nested Try Catch Example

Here we have deep (two level) nesting which means we have a try-catch block inside a nested try block. To
make you understand better I have given the names to each try block in comments like try-block2, try-
block3 etc.

This is how the structure is: try-block3 is inside try-block2 and try-block2 is inside main try-block, you can
say that the main try-block is a grand parent of the try-block3. Refer the explanation which is given at the
end of this code.

class NestingDemo{
public static void main(String args[]){
//main try-block
try{
//try-block2
try{
//try-block3
try{
int arr[]= {1,2,3,4};
/* I'm trying to display the value of
* an element which doesn't exist. The
* code should throw an exception
*/
System.out.println(arr[10]);
}catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
}
catch(ArithmeticException e){
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
}
catch(ArithmeticException e3){
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
}
catch(Exception e5){
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
Output:

ArrayIndexOutOfBoundsException handled in main try-block

As you can see that the ArrayIndexOutOfBoundsException occurred in the grand child try-block3. Since try-
block3 is not handling this exception, the control then gets transferred to the parent try-block2 and looked
for the catch handlers in try-block2. Since the try-block2 is also not handling that exception, the control gets
transferred to the main (grand parent) try-block where it found the appropriate catch block for exception.
This is how the the nesting structure works.

Example 2: Nested try block

class Nest{
public static void main(String args[]){
//Parent try block
try{
//Child try block1
try{
System.out.println("Inside block1");
int b =45/0;
System.out.println(b);
}
catch(ArithmeticException e1){
System.out.println("Exception: e1");
}
//Child try block2
try{
System.out.println("Inside block2");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
System.out.println("Just other statement");
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception");
System.out.println("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Inside parent try catch block");
}
catch(Exception e5){
System.out.println("Exception");
System.out.println("Inside parent try catch block");
}
System.out.println("Next statement..");
}
}
Output:

Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..

This is another example that shows how the nested try block works. You can see that there are two try-catch
block inside main try block’s body. I’ve marked them as block 1 and block 2 in above example.
Block1: I have divided an integer by zero and it caused an ArithmeticException, since the catch of block1 is
handling ArithmeticException "Exception: e1" displayed.

Block2: In block2, ArithmeticException occurred but block 2 catch is only


handling ArrayIndexOutOfBoundsException so in this case control jump to the Main try-catch(parent) body
and checks for the ArithmeticException catch handler in parent catch blocks. Since catch of parent try block
is handling this exception using generic Exception handler that handles all exceptions, the message “Inside
parent try catch block” displayed as output.
Parent try Catch block: No exception occurred here so the “Next statement..” displayed.

The important point to note here is that whenever the child catch blocks are not handling any exception, the
jumps to the parent catch blocks, if the exception is not handled there as well then the program will
terminate abruptly showing system generated message.

Java Finally block – Exception handling

In the previous tutorials I have covered try-catch block and nested try block. In this guide, we will see finally
block which is used along with try-catch.
A finally block contains all the crucial statements that must be executed whether exception occurs or not.
The statements present in this block will always execute regardless of whether exception occurs in try block
or not such as closing a connection, stream etc.

Syntax of Finally block

try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
A Simple Example of finally block

Here you can see that the exception occurred in try block which has been handled in catch block, after that
finally block got executed.

class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:

Number should not be divided by zero


This is finally block
Out of try-catch-finally
Few Important points regarding finally block

1. A finally block must be associated with a try block, you cannot use finally without a try block. You should
place those statements in this block that must be executed always.

2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient
for exception handling, however if you place a finally block then it will always run after the execution of try
block.

3. In normal case when there is no exception in try block then the finally block is executed after try block.
However if an exception occurs then the catch block is executed before finally block.

4. An exception in the finally block, behaves exactly like any other exception.

5. The statements present in the finally block execute even if the try block contains control transfer
statements like return, break or continue.
Lets see an example to see how finally works when return statement is present in try block:

Another example of finally block and return statement

You can see that even though we have return statement in the method, the finally block still runs.

class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
Output of above program:

This is Finally block


Finally block ran even after return statement
112
To see more examples of finally and return refer: Java finally block and return statement
.

Cases when the finally block doesn’t execute

The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

Finally and Close()

close() statement is used to close all the open streams in a program. Its a good practice to use close() inside
finally block. Since finally block executes even if exception occurs so you can be sure that all input and
output streams are closed properly regardless of whether the exception occurs or not.

For example:

....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
output.writeObject(writableObject);
}
finally{
op.close();
}
}
catch(IOException e1){
System.out.println(e1);
}
...
Finally block without catch

A try-finally block is possible without catch block. Which means a try block can be used with finally without
having a catch block.

...
InputStream input = null;
try {
input = new FileInputStream("inputfile.txt");
}
finally {
if (input != null) {
try {
in.close();
}catch (IOException exp) {
System.out.println(exp);
}
}
}
...
Finally block and System.exit()

System.exit() statement behaves differently than return statement. Unlike return statement whenever
System.exit() gets called in try block then Finally block doesn’t execute. Here is a code snippet that
demonstrate the same:

....
try {
//try block
System.out.println("Inside try block");
System.exit(0)
}
catch (Exception exp) {
System.out.println(exp);
}
finally {
System.out.println("Java finally block");
}
....
In the above example if the System.exit(0) gets called without any exception then finally won’t execute.
However if any exception occurs while calling System.exit(0) then finally block will be executed.

try-catch-finally block

 Either a try statement should be associated with a catch block or with finally.
 Since catch performs exception handling and finally performs the cleanup, the best approach is to use
both of them.

Syntax:

try {
//statements that may cause an exception
}
catch {
//error handling code
}
finally {
//statements to be executed
}
Examples of Try catch finally blocks

Example 1: The following example demonstrate the working of finally block when no exception occurs in
try block

class Example1{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/3;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:
First statement of try block
15
finally block
Out of try-catch-finally block
Example 2: This example shows the working of finally block when an exception occurs in try block but is
not handled in the catch block:

class Example2{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:

First statement of try block


finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at beginnersbook.com.Example2.main(Details.java:6)
As you can see that the system generated exception message is shown but before that the finally block
successfully executed.

Example 3: When exception occurs in try block and handled properly in catch block

class Example3{
public static void main(String args[]){
try{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:

First statement of try block


ArithmeticException
finally block
Out of try-catch-finally block

How to throw exception in java with example

In Java we have already defined exception classes such as ArithmeticException, NullPointerException,


ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger on different-2 conditions. For
example when we divide a number by zero, this triggers ArithmeticException, when we try to access the
array element out of its bounds then we get ArrayIndexOutOfBoundsException.

We can define our own set of conditions or rules and throw an exception explicitly using throw keyword.
For example, we can throw ArithmeticException when we divide number by 5, or any other numbers, what
we need to do is just set the condition and throw any exception using throw keyword. Throw keyword can
also be used for throwing custom exceptions, I have covered that in a separate tutorial, see Custom
Exceptions in Java.

Syntax of throw keyword:

throw new exception_class("error message");


For example:

throw new ArithmeticException("dividing a number by 5 is not allowed in this program");


Example of throw keyword

Lets say we have a requirement where we we need to only register the students when their age is less than 12
and weight is less than 40, if any of the condition is not met then the user should get an ArithmeticException
with the warning message “Student is not eligible for registration”. We have implemented the logic by
placing the code in the method that checks student eligibility if the entered student age and weight doesn’t
met the criteria then we throw the exception using throw keyword.

/* In this program we are checking the Student age


* if the student age<12 and weight <40 then our program
* should return that the student is not eligible for registration.
*/
public class ThrowExample {
static void checkEligibilty(int stuage, int stuweight){
if(stuage<12 && stuweight<40) {
throw new ArithmeticException("Student is not eligible for registration");
}
else {
System.out.println("Student Entry is Valid!!");
}
}

public static void main(String args[]){


System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}
Output:
Welcome to the Registration process!!Exception in thread "main"
java.lang.ArithmeticException: Student is not eligible for registration
at beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9)
at beginnersbook.com.ThrowExample.main(ThrowExample.java:18)
In the above example we have throw an unchecked exception, same way we can throw unchecked and user-
defined exception as well.

Throws clause in java – Exception handling

As we know that there are two types of exception checked and unchecked. Checked exception (compile
time force you to handle them, if you don’t handle them then the program will not compile.
On the other hand unchecked exception Runtime doesn’t get checked during compilation. Throws
keyword is used for handling checked exceptions . By using throws we can declare multiple exceptions in
one go.

What is the need of having throws keyword when you can handle exception using try-catch?

Well, thats a valid question. We already know we can handle exceptions using try-catch block.
The throws does the same thing that try-catch does but there are some cases where you would prefer throws
over try-catch. For example:

Lets say we have a method myMethod() that has statements that can throw either ArithmeticException or
NullPointerException, in this case you can use try-catch as shown below:

public void myMethod()


{
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}
But suppose you have several such methods that can cause exceptions, in that case it would be tedious to
write these try-catch for each method. The code will become unnecessary long and will be less-readable.

One way to overcome this problem is by using throws like this: declare the exceptions in the method
signature using throws and handle the exceptions where you are calling this method by using try-catch.
Another advantage of using this approach is that you will be forced to handle the exception when you call
this method, all the exceptions that are declared using throws, must be handled where you are calling this
method else you will get compilation error.

public void myMethod() throws ArithmeticException, NullPointerException


{
// Statements that might throw an exception
}

public static void main(String args[]) {


try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

Example of throws Keyword

In this example the method myMethod() is throwing two checked exceptions so we have declared these
exceptions in the method signature using throws Keyword. If we do not declare these exceptions then the
program will throw a compilation error.

import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException, ClassNotFoundException{
if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}
}

public class Example1{


public static void main(String args[]){
try{
ThrowExample obj=new ThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Output:

java.io.IOException: IOException Occurred

User defined exception in java

In java we have already defined, exception classes such as ArithmeticException, NullPointerException etc.
These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by
zero it triggers ArithmeticException, In the last tutorial we learnt how to throw these exceptions explicitly
based on your conditions using throw keyword.

In java we can create our own exception class and throw that exception using throw keyword. These
exceptions are known as user-defined or custom exceptions. In this tutorial we will see how to create your
own custom exception and throw it on a particular condition.
To understand this tutorial you should have the basic knowledge of try-catch block and throw in java.

Example of User defined exception in Java

/* This is my Exception class, I have named it MyException


* you can give any name, just remember that it should
* extend Exception class
*/
class MyException extends Exception{
String str1;
/* Constructor of custom exception class
* here I am copying the message that we are passing while
* throwing the exception to a string and then displaying
* that string along with the message.
*/
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}

class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
Output:

Starting of try block


Catch Block
MyException Occurred: This is My error Message

Explanation:
You can see that while throwing custom exception I gave a string in parenthesis ( throw new
MyException("This is My error Message"); . That’s why we have a parameterized constructor (with a String
parameter) in my custom exception class.

Notes:
1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.
Another Example of Custom Exception

In this example we are throwing an exception from a method. In this case we should use throws clause in the
method signature otherwise you will get compilation error saying that “unhandled exception in method”. To
understand how throws clause works, refer this guide: throws keyword in java.

class InvalidProductException extends Exception


{
public InvalidProductException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

public class Example1


{
void productCheck(int weight) throws InvalidProductException{
if(weight<100){
throw new InvalidProductException("Product Invalid");
}
}

public static void main(String args[])


{
Example1 obj = new Example1();
try
{
obj.productCheck(60);
}
catch (InvalidProductException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
}
}
Output:

Caught the exception


Product Invalid
Java Exception Handling examples

In this tutorial, we will see examples of few frequently used exceptions. If you looking for exception
handling tutorial refer this complete guide: Exception handling in Java.

Example 1: Arithmetic exception

Class: Java.lang.ArithmeticException
This is a built-in-class present in java.lang package. This exception occurs when an integer is divided by
zero.

class Example1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
Output of above program:

You Shouldn't divide a number by zero


Explanation: In the above example I’ve divided an integer by a zero and because of
this ArithmeticException is thrown.

Example 2: ArrayIndexOutOfBounds Exception

Class: Java.lang.ArrayIndexOutOfBoundsException
This exception occurs when you try to access the array index which does not exist. For example, If array is
having only 5 elements and we are trying to display 7th element then it would throw this exception.

class ExceptionDemo2
{
public static void main(String args[])
{
try{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Output:
ArrayIndexOutOfBounds
In the above example the array is initialized to store only 10 elements indexes 0 to 9. Since we are try to
access element of index 11, the program is throwing this exception.

Example 3: NumberFormat Exception

Class: Java.lang.NumberFormatException

This exception occurs when a string is parsed to any numeric variable.

For example, the statement int num=Integer.parseInt ("XYZ"); would


throw NumberFormatException because String “XYZ” cannot be parsed to int.

class ExceptionDemo3
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}
Output:

Number format exception occurred

Example 4: StringIndexOutOfBound Exception

Class: Java.lang.StringIndexOutOfBoundsException

 An object of this class gets created whenever an index is invoked of a string, which is not in the
range.
 Each character of a string object is stored in a particular index starting from 0.
 To get a character present in a particular index of a string we can use a method
charAt(int) of java.lang.String where int argument is the index.

E.g.

class ExceptionDemo4
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}
Output:

13
StringIndexOutOfBoundsException!!
Exception occurred because the referenced index was not present in the String.

Example 5: NullPointer Exception

Class: Java.lang.NullPointer Exception


An object of this class gets created whenever a member is invoked with a “null” object.

class Exception2
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}
Output:

NullPointerException..
Here, length() is the function, which should be used on an object. However in the above
example String object str is null so it is not an object due to which NullPointerException occurred.
File Handling
Files
• Files are stored are stored on disks
• Each files consist of multiple lines composed
of characters
• Each line ends with an end of line character
• The file itself may have an end of file character
• Programmers often need to read or write files
stored on disks
Streams
• Stream: an object that either delivers data to its destination (screen, file,
etc.) or that takes data from a source (keyboard, file, etc.)
– it acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program
– System.in is an input stream
• Output stream: a stream that accepts output from a program
– System.out is an output stream
• A stream connects a program to an I/O object
– System.out connects a program to the screen
– System.in connects a program to the keyboard
Text File I/O
• Important classes for text file output (to the file)
– PrintWriter
– FileOutputStream [or FileWriter]
• Important classes for text file input (from the file):
– BufferedReader
– FileReader
• FileOutputStream and FileReader take file names as arguments.
• PrintWriter and BufferedReader provide useful methods for
easier writing and reading.
• Usually need a combination of two classes
• To use these classes your program needs a line like the following:
import java.io.*;
Output to a File
Text File Output
• To open a text file for output: connect a text file to a stream for writing
FileOutputStream s = new FileOutputStream("out.txt");
PrintWriter outputStream = new PrintWriter(s);

• Goal: create a PrintWriter object


– which uses FileOutputStream to open a text file
• FileOutputStream “connects” PrintWriter to a text file.
Every File Has Two Names
1.the stream name used by Java
– outputStream in the example
2.the name used by the operating system
– out.txt in the example
Output File Streams

PrintWriter FileOutputStream

Memory Disk

smileyOutStream smiley.txt

PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“smiley.txt”) );


Methods for PrintWriter

• Similar to methods for System.out


1. println

outputStream.println(count + " " + line);

2. print
3. format
4. flush: write buffered output to disk
5. close: close the PrintWriter stream (and file)
Example: File Output
public class OutputDemo{
public static void main(String[] args)
{
PrintWriter outputStream = null;
try
{ outputStream =new PrintWriter(new FileOutputStream("out.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file out.txt. “ + e.getMessage());
System.exit(0);
}
System.out.println("Enter three lines of text:");

int count;
for (count = 1; count <= 3; count++)
{
outputStream.println(count + " abc ");
}
outputStream.close();
System.out.println("... written to out.txt.");
}
}
Overwriting/Appending a File
• Overwriting
– Opening an output file creates an empty file
– Opening an output file creates a new file if it does not already exist
– Opening an output file that already exists eliminates the old file and creates a new,
empty one and data in the original file is lost
outputStream = new PrintWriter(new FileOutputStream("out.txt"));

• Appending to a file
– To add/append to a file instead of replacing it, use a different constructor for
FileOutputStream:
outputStream = new PrintWriter(new FileOutputStream("out.txt", true));

– Second parameter: append to the end of the file if it exists.


Closing a File
• An output file should be closed when you are done writing to it (and
an input file should be closed when you are done reading from it).

• Use the close method of the class PrintWriter (or


BufferedReader close method).

• For example, to close the file opened in the previous example:


outputStream.close();
• If a program ends normally it will close any files that are open. Still the
an explicit call to close should be used because :

1. To make sure it is closed if a program ends abnormally (it could get


damaged if it is left open).

2. A file opened for writing must be closed before it can be opened for
reading.
Input
Input File Streams

BufferedReader FileReader

Memory Disk

inStream input.txt

BufferedReader inStream = new BufferedReader( new FileReader(“input.txt”) );


Text File Input
• To open a text file for input: connect a text file to a stream for reading

– a BufferedReader object uses FileReader to open a text file

– FileReader “connects” BufferedReader to the text file

• For example:

FileReader s = new FileReader(“input.txt");


BufferedReader inStream = new BufferedReader(s);
Methods for BufferedReader

• read: read a char at a time

• readLine: read a line into a String

• no methods to read numbers directly, so read numbers as


Strings and then convert them (StringTokenizer
later)

• close: close BufferedReader stream


Reading Words in a String:
Using StringTokenizer Class
• There are BufferedReader methods to read a line and a character, but
not just a single word

• StringTokenizer can be used to parse a line into words


– import java.util.*
– you can specify delimiters (the character or characters that separate
words)
• the default delimiters are "white space" (space, tab, and newline)
Example: StringTokenizer
import java.util.StringTokenizer;

public class fileex2 {


public static void main(String[] args) {

StringTokenizer st =new StringTokenizer("This is a string");

while(st.hasMoreTokens()){

System.out.println(st.nextToken());
}
}
}
Testing for End of File in a Text File
• When readLine tries to read beyond the end of a text file it returns
the special value null
– so you can test for null to stop processing a text file

• read returns -1 when it tries to read beyond the end of a text file
– the int value of all ordinary characters is nonnegative
Example: Using Null to
Test for End-of-File in a Text File
int count = 0;
String line = inputStream.readLine();

while (line != null)


{
count++;
outputStream.println(count + " " + line);
line = inputStream.readLine();
}

When using read test for -1

20
Using BufferedReader to Read from Keyboard

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class fileex3 {

public static void main(String[] args) {

BufferedReader st = new BufferedReader(new InputStreamReader(System.in));

try {
System.out.println(st.readLine());
System.out.println(st.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Alternative with Scanner
• Instead of BufferedReader with FileReader, then
StringTokenizer

• Use Scanner with File:


Scanner inFile =new Scanner(new File(“in.txt”));

• Similar to Scanner with System.in:


Scanner keyboard = new Scanner(System.in);
File Class [java.io]
• Acts like a wrapper class for file names
• A file name like "numbers.txt" has only String properties
• File has some very useful methods
– exists: tests if a file already exists
– canRead: tests if the OS will let you read a file
– canWrite: tests if the OS will let you write to a file
– delete: deletes the file, returns true if successful
– length: returns the number of bytes in the file
– getName: returns file name, excluding the preceding path
– getPath: returns the path name—the full name

File numFile = new File(“numbers.txt”);


if (numFile.exists())
System.out.println(numfile.length());
Reading in int’s
Scanner inFile = new Scanner(new File(“in.txt"));
int number;
while (inFile.hasInt())
{
number = inFile.nextInt();
// …
}
Reading in lines of characters
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
// …
}
BufferedReader vs Scanner
Parsing primitive types
• Scanner
– nextInt(), nextFloat(), … for parsing types
• BufferedReader
– read(), readLine(), … none for parsing types
– needs StringTokenizer then wrapper class methods like
Integer.parseInt(token)

Checking End of File/Stream (EOF)


• BufferedReader
– readLine() returns null
– read() returns -1
• Scanner
– nextLine() throws exception
– needs hasNextLine() to check first
– nextInt(), hasNextInt(), …
Exercise
• Create a java program which stores rollnumber,
name and marks of a student in a text file.
• It should be able to read and display these values
along with the Grade of the student based on the
following grading system
0-49  Fail
50-59  Pass
60- 69  Satisfactory
70-79  Good
Above 80  Excellent
Simple tutorial for using JDBC
The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database
applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL
statements to almost any relational database. JDBC is a Java API for executing SQL statements and
supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside
Java code. Because Java can run on a thin client, applets embedded in Web pages can contain
downloadable JDBC code to enable remote database access. You will learn how to create a table,
insert values into it, query the table, retrieve results, and update the table with the help of a JDBC
Program example.

Although JDBC was designed specifically to provide a Java interface to relational databases, you may
find that you need to write Java code to access non-relational databases as well.

JDBC Architecture

Java application calls the JDBC library. JDBC loads a driver which talks to the database

In general, to process any SQL statement with JDBC, you follow these steps:

① Establishing a connection.
② Create a statement.
③ Execute the query.
④ Process the ResultSet object.
⑤ Close the connection.

1. Configuring a JDBC development environment

First of all, you should download the JDBC Driver for your DBMS. For this class, you can use
“ojdbc6.jar” provided on class web-site. The ojdbc6.jar is a JDBC driver for Oracle Database 11g.

The below web sites are official pages for downloading official version of JDBC drivers.
Oracle : http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
Mysql : http://www.mysql.com/downloads/connector/j/

A. Install the latest version of the Java SE SDK on your computer.


B. Set up the classpath for a JDBC driver.
The JDBC driver is not needed for compiling the java source but it is needed to execute the
class. There are so many ways to set up this classpath according to the OS, programming
tools and your preferences. This tutorial provides the case to use Eclipse.
If you use the eclipse, you can use following description.
 Eclipse main menu-> Project -> Properties -> Java Build Path -> Librarie

 Click Add External JARs -> Select the JDBC driver. -> Open

 Click Add External JARs -> Select the JDBC driver. -> Open
 You can confirm the jar file is added then click OK.

2. Establishing a Connection

In this step of the jdbc connection process, we load the driver class by calling Class.forName() with
the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself.

Example for loading JDBC driver

String driverName = "oracle.jdbc.driver.OracleDriver"; // for Oracle


// String driverName = “com.mysql.jdbc.Driver”; //for MySql
try {
// Load the JDBC driver
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// Could not find the database driver
System.out.println("ClassNotFoundException : "+e.getMessage());
}

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC
driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system. Its getConnection() method is used to
establish a connection to a database. It uses a username, password, and a jdbc url to establish a
connection to the database and returns a connection object. A jdbc Connection represents a
session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL
statements are executed and results are returned. An application can have one or more connections
with a single database, or it can have many connections with different databases.

Example for JDBC connection

String serverName = "linux.grace.umd.edu";


String portNumber = "1521";
String sid = "dbclass1";

String url = "jdbc:oracle:thin:@" + serverName + ":" +


portNumber + ":" + sid; // for Oracle
//uri =”jdbc:mysql://server ip or address:port/database name”; //for Mysql
try {
// Create a connection to the database
connection = DriverManager.getConnection(url, username, password);

catch (SQLException e) {
// Could not connect to the database
System.out.println(e.getMessage());
}
Example for loading and connection

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestCon{

Connection connection = null;

String driverName ="oracle.jdbc.driver.OracleDriver"; // for Oracle


// String driverName = “com.mysql.jdbc.Driver”; //for MySql

String serverName = "ginger.umd.edu"; // Use this server.


String portNumber = "1521";
String sid = "dbclass1";

String url="jdbc:oracle:thin:@"+serverName+":"+ portNumber+":"+sid; // for Oracle


//uri =”jdbc:mysql://server ip or address:port/database name”; //for Mysql

String username = "your user name"; // You should modify this.


String password = "your password"; // You should modify this.

public TestCon() {}

public boolean doConnection(){


try {
// Load the JDBC driver
Class.forName(driverName);
// Create a connection to the database
connection = DriverManager.getConnection(url, username, password);

} catch (ClassNotFoundException e) {
// Could not find the database driver
System.out.println("ClassNotFoundException : "+e.getMessage());
return false;
} catch (SQLException e) {
// Could not connect to the database
System.out.println(e.getMessage());
return false;
}
return true;
}

public static void main(String arg[]){


TestCon con =new TestCon();
System.out.println("Connection : " +con.doConnection());
}

}
If the output of the previous example is “Connection : true”, your environment setting and connection
is correct. If not, try to check the jdbc driver classpath, your username and your password

3. Creating statements & executing queries


A Statement is an interface that represents a SQL statement. You execute Statement objects, and they
generate ResultSet objects, which is a table of data representing a database result set. You need
a Connection object to create a Statement object.

There are three different kinds of statements.

 Statement: Used to implement simple SQL statements with no parameters.


 PreparedStatement: (Extends Statement.) Used for precompiling SQL statements that might
contain input parameters. See Using Prepared Statements for more information.
 CallableStatement: (Extends PreparedStatement.) Used to execute stored procedures that may
contain both input and output parameters. See Stored Procedures for more information.

Example for Statement

Statement stmt = null;


try {
stmt = connection.createStatement();
} catch (SQLException e ) {
System.out.println(e.getMessage());
}

To execute a query, call an execute method from Statement such as the following:

 execute: Returns true if the first object that the query returns is a ResultSet object. Use this
method if the query could return one or moreResultSet objects. Retrieve the ResultSet objects
returned from the query by repeatedly calling Statement.getResutSet.
 executeQuery: Returns one ResultSet object.
 executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method if you are using INSERT,DELETE, or UPDATE SQL statements.

Example for executeQuery


String country=”D”;
Statement stmt = null;
String query = " SELECT * FROM CITY WHERE country='”+country+”'”;
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString(1); // or rs.getString("NAME");
String coun= rs.getString(2);
String province = rs.getString(3);
int population = rs.getInt(4);
}
stmt.close();
} catch (SQLException e ) {
System.out.println(e.getMessage());
}

The re.next() return „true‟ until there is no more result.

Example for executeQuery


String population=”1705000”;
String cityName=”Hamburg”;
String province=”Hamburg”;
Statement stmt = null;
try {
stmt = connection.createStatement();
String sql = "UPDATE CITY SET population='”+ population +”' WHERE NAME='”+
cityName +”' AND PROVINCE=‟”+ province +”‟";
stmt.executeUpdate(sql);s
stmt.close();
} catch (SQLException e ) {
System.out.println(e.getMessage());
}

Exmaple of simple JDBC program

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestCon{

Connection connection = null;

String driverName ="oracle.jdbc.driver.OracleDriver"; // for Oracle


// String driverName = “com.mysql.jdbc.Driver”; //for MySql

String serverName = "ginger.umd.edu";


String portNumber = "1521";
String sid = "dbclass1";

String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid; // for


Oracle
//uri =”jdbc:mysql://server ip or address:port/database name”; //for Mysql

String username = "XXXXXXXX"; //your username


String password = "XXXXXXXX"; //your password
public TestCon() {
}
public boolean doConnection(){
try {
// Load the JDBC driver
Class.forName(driverName);
// Create a connection to the database
connection = DriverManager.getConnection(url, username, password);

} catch (ClassNotFoundException e) {
// Could not find the database driver
System.out.println("ClassNotFoundException : "+e.getMessage());
return false;
} catch (SQLException e) {
// Could not connect to the database
System.out.println(e.getMessage());
return false;
}
return true;
}
public void printCounryByCapital(String capital) throws SQLException{

Statement stmt = null;


String query = "SELECT * FROM COUNTRY WHERE
CAPITAL='"+capital+"'";

stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString(1); // or rs.getString("NAME");
String code= rs.getString(2);
String cap = rs.getString(3);
String province = rs.getString(4);
int area = rs.getInt(5);
int population = rs.getInt(6);

System.out.println(" Name : "+name);


System.out.println(" Code : "+code);
System.out.println(" Capital : "+cap);
System.out.println(" Province : "+province);
System.out.println(" Area : "+area);
System.out.println(" Population : "+population);
}
}

public void printCityByCountry(String country) throws SQLException{

Statement stmt = null;


String query = " SELECT * FROM CITY WHERE country='"+country+"'";
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString(1); // or rs.getString("NAME");
String coun= rs.getString(2);
String province = rs.getString(3);
int population = rs.getInt(4);

System.out.println(" Name : "+name);


System.out.println(" Country : "+coun);
System.out.println(" Province : "+province);
System.out.println(" Population : "+population);
}
stmt.close();

}
public void updateCityPopulation(String cityName,String province,
String population)throws SQLException
{
Statement stmt = null;
stmt = connection.createStatement();
String sql = "UPDATE CITY SET population='"+ population
+"' WHERE NAME='"+cityName +"' AND
PROVINCE='"+ province +"'";
stmt.executeUpdate(sql);
stmt.close();
}

public static void main(String arg[]){


TestCon con =new TestCon();
System.out.println("Connection : " +con.doConnection());
try{
con.printCounryByCapital("Paris");
con.printCityByCountry("D");
con.updateCityPopulation("Munich","Bayern","3000");
}catch(SQLException ex){System.out.println(ex.getMessage());}
}
}

You might also like