0% found this document useful (0 votes)
2 views

JavaCBook

Java is a platform-independent programming language used across various devices and applications, including standalone, web, enterprise, and mobile applications. It features a rich set of characteristics such as simplicity, object-oriented design, and high performance, and is categorized into three main editions: Java SE, Java EE, and Java ME. The document also covers Java's history, versions, naming conventions, variable types, data types, and operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JavaCBook

Java is a platform-independent programming language used across various devices and applications, including standalone, web, enterprise, and mobile applications. It features a rich set of characteristics such as simplicity, object-oriented design, and high performance, and is categorized into three main editions: Java SE, Java EE, and Java ME. The document also covers Java's history, versions, naming conventions, variable types, data types, and operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

JavaCBook(Core Java):

What is Java

Java is a both programming language and a platform.

Java is a platform independent language, Which means Java program can be developed on any
Operating system, and compiled into a bytecode that byte code can be run on any platform without
recompile the java program.

There are Three billion devices are using java, for example mobile phones,java powers set-top
boxes, printers, Web cams, games, car navigation systems, medical devices, etc…

Features of Java

The following are the main features of java

 Simple
 Object oriented
 Distributed
 Multithreaded
 Dynamic
 Architecture neutral
 Portable
 High performance
 Robust
 Secure

Types of java applications

Java supports four different types of applications.

Standalone applications:Standalone applications(Desktop applications) are run in our local system, This
applications contains main method

This applications we need to install in every system, For example Adobe reader, media player, etc…

This applications can be devolped by using AWT(Abstract Window Toolkit), swing, SWT(Standard
Widget Toolkit), etc…

Web applications:Web applications are server and client side programming, This applications are run on
server which will process clinet(browser) requests

For example webmail, This applications can be developed by using servlets, JSP(Java Server Pages),
Struts, Spring, JSF(JavaServer Faces), etc…

Enterprise Applications:This applications are deployed on a variety of platforms, They are data-centric,
user-friendly, and must meet stringent requirements for security, administration, and maintenance. In
short, they are highly complex systems

For example Banking applications, This applications can be developed by usng EJB(Enterprise Java
Beans), etc…
Mobile Applications:This applications are run on mobiles, for example whatsapp, MyJio, etc…, This
applications are developed by using java, andriod, IOS, etc…

Java Editions

There are mainly 3 editions are available in java

Java SE (Java Standard Edition):

Java SE contains core packages like java.lang, java.util, java.io, java.net, java.math, etc…

This will contain core concepts like OOPS, Exceptions, Collections, Threads, Inner classes, Reflection,
I/O Streams, AWT, Swing, etc…

Java SE mainly used to develop standalone applications.

Java EE (Java Enterprise Edition):

Java EE contains advanced concepts like Servlet, JSP, EJB, etc…

Java EE mainly used to develop web and enterprise applications.

Java ME (Java Micro Edition)

Java ME was designed for mobile applications.

History of Java

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
Java was originally designed for interactive television, but it was too advanced for the digital cable
television industry at the time. The language was initially called Oak after an oak tree that stood
outside Gosling‟s office. Later the project went by the name Green and was finally renamed Java, from
Java coffee,said to be consumed in large quantities by the language‟s creators.[citation needed]
Gosling designed Java with a C/C++-style syntax that system and application programmers would find
familiar.

Sun Microsystems released the first public implementation as Java 1.0 in 1995. It promised “Write
Once, Run Anywhere” (WORA), providing no-cost run-times on popular platforms. Fairly secure and
featuring configurable security, it allowed network- and file-access restrictions. Major web browsers
soon incorporated the ability to run Java applets within web pages, and Java quickly became popular.
The Java 1.0 compiler was re-written in Java by Arthur van Hoff to comply strictly with the Java 1.0
language specification. With the advent of Java 2 (released initially as J2SE 1.2 in December 1998 –
1999), new versions had multiple configurations built for different types of platforms. J2EE included
technologies and APIs for enterprise applications typically run in server environments, while J2ME
featured APIs optimized for mobile applications. The desktop version was renamed J2SE. In 2006, for
marketing purposes, Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.

On November 13, 2006, Sun released much of Java as free and open source software, (FOSS), under
the terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the process, making
all of Java‟s core code available under free software/open-source distribution terms, aside from a small
portion of code to which Sun did not hold the copyright.
Versions

Major release versions of Java, along with their release dates:

 JDK 1.0 (January 21, 1996)


 JDK 1.1 (February 19, 1997)
 J2SE 1.2 (December 8, 1998)
 J2SE 1.3 (May 8, 2000)
 J2SE 1.4 (February 6, 2002)
 J2SE 5.0 (September 30, 2004)
 Java SE 6 (December 11, 2006)
 Java SE 7 (July 28, 2011)
 Java SE 8 (March 18, 2014)
 Java SE 9 (September 21, 2017)
 What is JDK,JRE and JVM in java

JDK(Java Development Kit)

 JDK contains tools needed to develop the Java programs.


 You need JDK, if at all you want to write your own programs, and to compile them.
 JDK is mainly targeted for java development.

JRE(Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. JRE is targeted for
execution of Java files.

JVM(Java Virtual Machine)

 JVM doesn‟t exist physically.


 JVM is responsible for executing the java program line by line.
 The JVM interprets the byte code into the machine code depending upon the underlying
operating system and hardware combination. It is responsible for all the things like garbage
collection, array bounds checking, etc… Java Virtual Machine provides a platform-independent
way of executing code.

JIT(Just In Time)

JIT compiler is part of JVM which increases the speed of execution of a java program.
JVM Architechture:

Class loader sub system: Class loader sub system will loads the class file in to the JVM.

Method area: Method area stores the class code like static varaibles and method code

Stack: Stack holds local varaibles and method temprory output,


When ever a method loads a separate frame will created in stack, That will be executed java method

Heap: Java objects are created in heap memory

PC(Program Counter) registers: This will conatain memory address of instructions of the methods,
For every method separate PC register will create.

Native Method Stack: This will execute native methods

Java naming conventions

Naming conventions specify the rules to be followed by java programmers while writing the names of
class, package, variables and methods etc.

Naming conventions make programs more understandable by making them easier to read.

Package

Package names should written in small letters(lower case).

Examples:

java.util
java.net
java.io

Keyword

Keywords should written in lower case.

Examples:

void
static
Class:

Class name starts with capital letter and every inner word starts with upper capital letter(upper case ).

Examples:

String
StringBuffer
OutputStreamReader

Interface

Interface name starts with upper case letter and every inner word starts with upper case letter.

Examples:

Collection
Runnable
SortedSet

Method

Methods name starts with lower case letter and every inner word starts with upper case letter.

Examples:

println()
readLine()

variables in java

Variable is used to store a value. It‟s nothing but name of the memory location.

1 int x = 5;

„x‟ is name of the memory location.

Variable declaration

1 int i;

Variable initialization

1 int i = 5;

Types of variables

There are 3 types of variables are available in java.


 Instance Variables(Non-Static)
 Static Variables (class variables)
 Local Variables

Instance Variables

 Declaring a variable without static keyword is known as instance varaible


 Instance variables are declared inside a class and outside of method and block.
Ex:

public class A{
1
int i = 5;
2
}

 Instance variables can access using object (object.variableName)


 Instance variables are stored in the objects in heap.
 We cannot access instance variables in static methods.
 Instance variables defines the state of an object.
 Each object have their own unique copies of instance variables. When the value of instance
variable is modified in an object it doesn‟t effect the instance variables of other objects.

Static Variables(Class Variables)


 A variable which is declared with static keyword is called Static variable.

Ex:

1 public class A{
2 static int i = 5;
3 }

 Static variables called as class variables, Because They are associated with the class, rather
than with any object.Static variables are loads at the time of class loading.
 Class variables are used to refer a common property , for example College name of the students
 Static variables will have only one copy in memory and that is shared by all objects. If we make
any changes on it by using an object that will also effects the other objects.
 We can access static variables by using class name (className.variableName)
 We can access static variables in static and non-static methods.
 Static variables are stored in method area.

Local Variables

 Local variables are declared inside a method.


Ex:

1 public class A{
2 public void display(){
3 int i = 5;
4 }
5 }
 Local variables are not accessible out side of the method
 Local variables should be initialized before using them, Otherwise compiler will throw The local
variable may not have been initialized exception
 Data types in java

 We need a variable to store some data, Every variable has a data type in java.
 Different data types can be used to store different types of values.
 Every data type has a range and default value.
 In Java for every data type JVM allocates some memory.

Types of data types

There are two types of data types are available in java.

1. Primitive
2. Non-Primitive

Primitive Data Types

Data Type Default Value Default Size Value Range

Byte 0 1 byte (8 bits) -128 to 127 (-27 to 27-1)

Short 0 2 bytes (16 bits) -32768 to 32767 (-215 to 215-1)

-2,147,483,648 to 2,147,483,647

Int 0 4 bytes(32 bits) (-231 to 231-1)

-9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

Long 0L 8 bytes (64 bits) (-263 to 263-1)

Float 0.0f 4 bytes (32 bits) 3.40282347 x 1038 to 1.40239846 x 10-45

1.7976931348623157 x 10308 to

Double 0.0 8 bytes (64 bits) 4.9406564584124654 x 10-324


single character which is enclosed with in the

Char „\u0000‟ 2 bytes (16 bits) single quotes

Boolean False 1 bit true or false

byte :

Size: 1 byte(8 bits).

Range: -128(-27) to 127(27-1)

Default Value: 0

The byte data type can be useful for saving memory in large arrays, where the memory savings
actually matters.

Ex.

1 byte b = 29;

short :

Size: 2 bytes(16 bits).

Range: -32768(-215) to 32767(215-1)

Default Value: 0

The short data type can be useful for saving memory in large arrays, where the memory savings
actually matters.

Ex.

1 short sh = 74;

int :

Size: 4 bytes(32 bits).

Range: -231 to 231-1

Default Value: 0

Ex.

1 int i =10;

long :

Size: 8 bytes(64 bits).


Range: -263 to 263-1

Default Value: 0L

Ex.

1 long v = 130L;

In the above statement, if L is not there then JVM allots 2 bytes of memory to v, Because 2 bytes is
sufficient to store the value 130.

float :

Size: 4 bytes(32 bits).

Range: 3.4e+38 to 3.4e-45

Default Value: 0.0f

Float allows up to 7 digits after decimal point.

Ex.

1 float pi = 3.142F;

In the above statement, if F is not written at the end then JVM would have allotted 8 bytes assuming
the value to be double

double :

Size: 8 bytes(64 bits).

Range: 1.7e+308 to 1.7e-324

Default Value: 0.0d

Double allows up to 15 digits after decimal point.

Ex.

1 double d = 1999.268628265

boolean :

Size: 1 bit.

The boolean data type has only two possible values true and false.

Default Value: false

Ex: 1.boolean result=true;

char :
Size: 2 bytes(16 bits).

This data type represents single character which is enclosed with in the single quotes

Default Value: „\u0000‟

Ex.

1 char ch= „a‟;

Non-Primitive Data Types

String :

Default Value: null

String represents a group of characters which is enclosed with in the double quotes.

Ex.

1 String str = “Hello”;

Derived data types

Derived data types are those whose variables allow us to store multiple values of same type. But they
never allows to store multiple values of different types. In general derived data type can be achieve
using array.

Ex.

1 int[] arr = {1,3,6,7,5};

User defined data types

User defined data types are those which are developed by programmers, Because in java every class is
a data type.

Operators in java

Operators are standard symbols that are used to perform some specific operations involving one or
more operands and finally produces a result.

Below are the various types of operators used in Java programming.

Assignment Operator:

= Simple assignment operator

Arithmetic Operators:
+ Additive operator (also used for String concatenation)

– Subtraction operator

* Multiplication operator

/ Division operator

% Remainder operator

Unary Operators:

Unary plus operator; indicates positive value (numbers are positive without this,

+ however)

– Unary minus operator; negates an expression

++ Increment operator; increments a value by 1

— Decrement operator; decrements a value by 1

! Logical complement operator. It inverts the value of a Boolean

Type Comparison Operator:

Instanceof Compares an object to a specified type

Equality and Relational Operators:

== Equal to

!= Not equal to

> Greater than

>= Greater than or equal to

< Less than


<= Less than or equal to

Logical Operators:

&& Logical-AND

|| Logical-OR

Bitwise and Bit Shift Operators:

~ Unary bitwise complement

<< Signed left shift

>> Signed right shift

>>> Unsigned right shift

& Bitwise AND

^ Bitwise exclusive OR

| Bitwise inclusive OR

Ternary Operator:

?: Ternary (shorthand for if-then-else statement)

Arithmetic Operators

Arithmetic Operators are used to perform fundamental arithmetic operations like addition, subtraction,
multiplication and division.
List of arithmetic operators:

Additive operator (also used for String

+ concatenation)

– Subtraction operator

* Multiplication operator
/ Division operator

% Remainder operator

Addition operator(+):

The addition operator produces the sum of numeric operands or string concatenation.
Ex:

1 public class AdditionEx {


2 public static void main(String[] args) {
3 int i = 5;
4 int j = 10;
5 int k = i + j;
6 System.out.println(k);
7 }
8 }
Output: 15

Subtraction operator(-):

The subtraction operator subtracts the two operands, producing their difference
Ex:

1 public class SubtractionEx {


2 public static void main(String[] args) {
3 int i = 10;
4 int j = 5;
5 int k = i - j;
6 System.out.println(k);
7 }
8 }
Output : 5
Multiplication operator(*):

The multiplication operator produces the product of the operands.


Ex:

1 public class MultiplicationEx {


2 public static void main(String[] args) {
3 int i = 10;
4 int j = 5;
5 int k = i * j;
6 System.out.println(k);
7 }
8 }
Output : 50

Division operator(/):

The division operator produces the quotient of its operands where the left operand is the dividend and
the right operand is the divisor.
Ex:

1 public class DivisionEx {


2 public static void main(String[] args) {
3 int i = 11;
4 int j = 2;
5 int k = i / j;
6 System.out.println(k);
7 }
8 }
Output : 5

Remainder operator(%):

The remainder operator returns the remainder left over when one operand is divided by a second
operand.
Ex:

public class RemainderEx {


public static void main(String[] args) {
int i = 11;
int j = 2;
int k = i % j;
System.out.println(k);
}
}
Output : 1

Unary Operators

Unary Operators: The unary operators are act on only one operand.

– Unary minus operator; negates an expression

++ Increment operator; increments a value by 1

–– Decrement operator; decrements a value by 1

Unary minus operator(-):

The unary minus operator is used to negate a value, That means minus operator converts positive to
negative, Negative to poistive

1 public class UnaryMinusEx {


2 public static void main(String[] args) {
3 int i = 10;
4 System.out.println(-i);
5 System.out.println(-(-i));
6 }
7 }
Output : -10
10
Increment operator(++):

This operator increases the value of a variable by 1

There are two types of increment operators

 Pre increment(++variable)
 Post increment(variable++)

Pre increment(++variable):

Writing ++ before a variable is known as pre increment


When the increment operator appears before a variable, the variable is incremented first, and then the
result is used in the current expression
Ex:

1 public class PreIncrementEx1 {


2 public static void main(String[] args) {
3 int i = 10;
4 //First increment i value then assign to k
5 int k = ++i;
6 System.out.println(k);
7 System.out.println(i);
8 }
9 }
Output :
11
11

Ex:
public class PreIncrementEx2 {
public static void main(String[] args) {
1
int i = 10, j = 5;
2
/*
3
* i value is incremented first, and then the result is
4
* used in the ++i + j expression
5
*/
6
int k = ++i + j;
7
System.out.println("k value: "+k);
8
System.out.println("i value: "+i);
9
}
}
Output :
k value: 16
i value: 11

Post increment (variable++):

Writing ++ after a variable is known as post increment


When the operator appears after the variable, first variable is used in the current expression then
variable value will be increased
Ex:

1 public class PostIncrementEx1 {


2 public static void main(String[] args) {
3 int i = 10, j = 5;
4 /*
5 * first i value is used in current expression, after that i value will
6 * be increased
7 */
8 int k = i++ + j;
9 System.out.println("k value: " + k);
10 System.out.println("i value: " + i);
11 }
12 }
Output
k value: 15
i value: 11

Ex:
1 public class PostIncrementEx2 {
2 public static void main(String[] args) {
3 int i = 10;
4 //First i value is assign to k then i value will be increased
5 int k = i++;
6 System.out.println(k);
7 System.out.println(i);
8 }
9 }
Output:
10
11

This operator decrements the value of a variable by 1


There are two types of decrement operators

 Pre decrement(- -variable)


 Post decrement(variable- -)

Writing – – before a variable is known as pre decrement


When the decrement operator appears before a variable, the variable is decrements first, and then the
result is used in the current expression

Ex:

1 public class PreDecrement {


2 public static void main(String[] args) {
3 int i = 10;
4 //First i value is assign to k then i value will be decreased
5 int k = --i;
6 System.out.println(k);
7 System.out.println(i);
8 }
9 }
Output : 10
9

Ex:
1 public class PreDecrement {
2 public static void main(String[] args) {
3 int i = 10, j = 5;
4 /*
5 * i value is decrement first, and then the result is
6 * used in the --i + j expression
7 */
8 int k = --i + j;
9 System.out.println("k value: "+k);
10 System.out.println("i value: "+i);
11 }
12 }
Output :
k value: 14
i value: 9

Writing – – after a variable is known as post decrement


When the operator appears after the variable, first variable is used in the current expression then
variable value will be decreased
1 public class PostDecrementEx {
2 public static void main(String[] args) {
3 int i = 10;
4 // First i value is assign to k then i value will be decreased
5 int k = i--;
6 System.out.println(k);
7 System.out.println(i);
8 }
9 }
Output:
10
9

Equality and Relational Operators:

These operators are used for the purpose of comparing, For example to know which one is bigger or
whether two quantities are equal or not.

== Equal to

!= Not equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

The main use of relational operators is in the construction of conditions in statements


1 if(condition_is_true){
2 Statements_to_be_executed
3 }

Ex:

public class OperatorsEx {


public static void main(String[] args) {
int i = 10, j = 5;
if (i > j) {
System.out.println("i is greater then j");
} else if (i < j) {
System.out.println("j is greater then i");
}
if (i >= 10) {
System.out.println("i value is greater then or equal to 10");
}
if (j <= 10) {
System.out.println("j value is less then or equal to 10");
}
if (i == 10) {
System.out.println("i value is equal to 10");
}
if (j == 5) {
System.out.println("j value is equal to 5");
}
}
}
Output:
i is greater then j
i value is greater then or equal to 10
j value is less then or equal to 10
i value is equal to 10
j value is equal to 5

Logical Operators

Logical operators are used to construct compound conditions, A compound condition is a combination
of several simple conditions

&& Logical-AND

|| Logical-OR

! Logical NOT operator. It inverts the value of a Boolean

Logical-AND Operator(&&):

The Logical-AND operator returns true when all the conditions are true, Otherwise it returns false.
Ex:

1 public class LogicalAndEx {


2 public static void main(String[] args) {
3 int i = 10, j = 5;
4 if (i == 10 && j == 5) {
5 System.out.println("Both conditions are true");
6 }
7 }
8 }
Output:
Both conditions are true

The above example if both conditions(i == 10 and j == 5) are true, then i == 10 && j == 5 returns
true.
The Logical-AND operator(&&) doesn‟t check second condition if first condition is false. It checks
second condition only if first condition is true.

Logical-OR Operator(||):

The Logical-OR operator(||) returns true if either one or both conditions are true, otherwise it returns
false.

Ex:

1 public class LogicaOrlEx {


2 public static void main(String[] args) {
3 int i = 10, j = 5;
4 if (i == 10 || j == 6) {
5 System.out.println("Either one or both conditions are true");
6 }
7 }
8 }
Output:
Either one or both conditions are true

The above example if either one or both conditions(i == 10 or j == 6) are true, then i == 10 || j == 6
returns true.
The Logical-OR || operator doesn‟t check second condition if first condition is true. It checks second
condition only if first condition is false.

Logical complement operator(!):

It inverts the boolean value

1 public class LogicalComplementOperator {


2 public static void main(String[] args) {
3 boolean b = true;
4 System.out.println(!b);
5 }
6 }
Output:
false

Bitwise and Bit Shift Operators

Bitwise and Bit Shift Operators:


~ Unary bitwise complement

<< Signed left shift

>> Signed right shift

>>> Unsigned right shift

& Bitwise AND

^ Bitwise exclusive OR

| Bitwise inclusive OR

Difference between print() and println() method

Both are used to print output in console

System.out.print() statement keeps the cusrsor in the same line after printing the output.

public class Main{


1
public static void main(String[] args) {
2
System.out.print("Hello ");
3
System.out.print("World");
4
}
5
}
Output: Hello World

System.out.println() statement moves cusrsor to the next line after printing the output.

public class Main{


public static void main(String[] args) {
System.out.println("Hello ");
System.out.println("World");
}
}
Output:
Hello
World

Keywords in java

Keyword Description

Abstract abstract keyword is used to declare an abstract class and abstract method.
assert keyword is used in an assert statement

Syntax: assert expression1 : expression2;

expression1 is a boolean.If expression1 returns False then the an error will be thrown

Assert with expression2 message in it

It is actually a primitive type. It has only two possible values: true and false. And the

Boolean default value is false

We use this in loops. While executing a loop at any point of time if we want to stop

Break execute the loop, we will use break keyword to jump out of the loop

Byte byte is a primitive data type which holds an 8 bit signed integer

case is used as part of switch statement to switch between the statements while

Case matching the value

catch is used along with try while handling the exceptions

Catch [Refer Exception handling]

char represents a primitive datatype which can hold a character within single-quote.

Char Ex: char c = „a‟;

Class class is a keyword used to declare a class

continue keyword is used whenever we want to skip the remaining statements in the

Continue current loop and continue executing the next iteration

default keyword used as part of switch statement. It is used to execute if there is no

Default matching case provided. It is optional.

do is a keyword used in do-while loop. In do-while loop first statements get executed

Do and then the condition is evaluated

Double double is a primitive data type which holds an 64 bit float

else is a keyword used in if-else condition. The statements in else block will be

Else executed if the condition in if block returns False


Enum enum is used to define a group of constants

extends is a keyword used for both classes and interfaces to extend the abilities of

another class or interface. A class can extend only class, and an interface can extend

Extends many interfaces

final is a keyword used for classes, methods and variables.

Final [Refer final keyword in Java]

finally is a keyword used to represent a block of statements. It can be used as an

optional with try block while handling exceptions.

Finally [Refer Exception handling in Java]

Float float is a primitive data type which holds an 32 bit float

For for is a keyword used in for-loop

if is a keyword in if statement which tests a boolean condition and if the cindition

If returns True then the statements under if statements get executes

implements is a keyword used in the class declaration to add the functionality of

Implements interfaces to the current class

import is a keyword used to specify the package or a class to be used in the current

Import class

instanceof is a keyword used as an operator to check whether an object reference is

Instanceof of type of specified class. If yes it returns True or else it returns False

Int int is a primitive data type which can hold 32 bit signed integer

Interface interface keyword used to declare an interface

Long long is a primitive data type which can hold 64 bit signed integer

native is a keyword used to declare method to specify that the method implemented

Native is not Java but it is in another language


New new is a keyword used to create an object of a class or an array in the heap

Package package is a keyword to declare a package to group a set of classes

private is a keyword which is used to declare a method, field, or an inner class to

Private provide private member access

protected is a keyword which is used to declare a method, field, or an inner class to

Protected provide protected member access

public is a keyword which is used to declare a method, field, or an inner class to

Public provide public member access

return is a keyword declared at the end of the method and it is used return a value

Return to the caller of the method

Short short is a primitive data type which can hold 16-bit signed two‟s complement integer

static is a keyword used for inner classes, methods, and fields

Static [Refer static keyword in Java]

strictfp keyword is used to restrict the precision and rounding of floating point

Strictfp calculations to ensure portability

super is a keyword used in a sub-class to refer it‟s super-class state or behavior also

Super constructors

Switch switch is a keyword used in switch statement

synchronized is a keyword used for a method or to declare a block of statements.

This enables a method or a block of statements to be executed only by single thread

Synchronized while other threads being waiting to get execute

This this is a keyword used to refer current class instance

Throw throw is a keyword used to throw an exception explicitly

Throws throws is a keyword used to specify which exceptions are expecting to be thrown by
the code within the method

Transient transient is a keyword used for variables to prevent to participate in serialization

try is a keyword to define a try-block which contains a set of statements which can

Try possibly throw exception

Void void is a keyword used for a method to define that it returns nothing

volatile is a keyword used to specify that a variable will be modified concurrently by

Volatile different threads

while is a keyword used in while-loop. It tests a boolean expression and executes the

While defined statements under the loop if the expression returns True

Find the average value from all odd indexed elements from given array

/*
Find out the average value from all odd indexed elements
from a given array
*/
1
class FindAvgValueFromOdd {
2
public static void main(String[] args) {
3
int[] arr = { 5, 24, 3, 65, 27, 34, 40, 52 };
4
int sum = 0;
5
for (int i = 1; i < arr.length; i = i + 2) {
6
sum += arr[i];
7
}
8
double avg = (double) sum / (arr.length / 2);
9
System.out.println("Average value from all odd indexed elements" + avg);
10
}
11
}
12

Output: Average value from all odd indexed elements43.75

Control statements in java

Control statements

Control statements are the statements which alter the flow of execution and provide the better control
to the programmer on the flow of execution
The following control statements are available in Java.

 If-else statement
 switch statement
 for loop
 for-each loop
 while loop
 do-while statement
 break statement
 continue statement

break

Break is used to stop execution of a loop.

Syntax :

while(condition){
if(condition){
break;
}
}

Ex:

int i =0;

while(i > 10){

if(i== 5){
break;
}
System.out.println(i);
}

continue

continue is used to skip the current iteration and it continues rest of iterations.

while(condition){

if(condition){
continue;
}
}

Ex:

int i =0;
while(i > 10){
if(i== 5){
continue;
}
System.out.println(i);
}

for-each Loop

for-each loop is used iterate the collection.

for(var : collection){
//group of statements
}

if-else

if-else is used to execute a block of code based on condition


Java supports different types of if-else statements

if statement:

If we want to check one condition such case we will use if statement


syntax:

1 if(condition){

2 //if code

3 }

The above case if the specified condition is true then if code get executed .

Ex: Check Whether a number is poistive or not

1 public class IfExample {

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

3 int i = 5;

4 if (i > 0) {

5 System.out.println(i + " is a poistive number");

6 }

7 }

8 }

Output:

5 is a poistive number
if-else statement:

If we want to check two conditions such case we will use if-else statement
syntax:

1 if(condition){

2 //if code;

3 }

4 else{

5 // else code;

6 }

Above case if the specified condition is true then if code get executed, otherwise else code get
executed.

In the above example the if code and else code represents either single statement or group of
statements, If it is single statement Flower brackets({}) are optional.

syntax:

1 if(condition)

2 statement1;

3 else

4 statement2;

Ex: Check Whether a Number is Even or Odd

1 public class IfElseEx {

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

3 int num=4;

4 if(num%2==0)

5 System.out.println(num+" is an even number");

6 else

7 System.out.println(num+" is an odd number");

8 }

9 }

Output: 4 is an even number


Ex: Check Whether a year is leap year or not

public class LeapYearExample {

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

2 int year = 2004;

3 if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0)){

4 System.out.println(year + " is a leap year");

5 } else {

6 System.out.println(year + " is not a leap year");

7 }

8 }

Output : 2004 is a leap year

if-else-if ladder:

If we want to check more then two conditions such case we will use if-else-if ladder statement
syntax:

1 if(condition1){

2 statement1;

3 }

4 else if(condition2){

5 statement2;

6 }

7 else if(condition3){

8 statement3;

9 }

10 -

11 -

12 else{

13 statement;

14 }
If-condition1 is true then statement1 get executed , otherwise it will check condition2 if it is true then
statement2 get executed, otherwise it will check condition3 if it is true then statement3 get executed
like that it will check all conditions if any condition is true then appropriate statement get execute, if
all the conditions fails then finally else statement get executed.

Ex: Find Largest number between two numbers

public class CompareTwoNumbers {

public static void main(String[] args) {

int i = 5, j = 10;

if (i > j) {

System.out.println(i + " is a biggest number");

} else if (i < j) {

System.out.println(j + " is a biggest number");

} else {

System.out.println("Both numbers are equal");

Output: 10 is a biggest number

Switch Statement

 The switch statement is like if-else-if ladder


 The switch statement can be used to execute one statement from multiple conditions, based on
the value of an argument
 switch allows only one default case
 If no case matches, then the default statement get executed

Syntax :

1 switch(argument){

2 case value1: statement1;

3 break; //optional

4 case value2: statement2;

5 break; //optional

6 case value3: statement3;

7 break; //optional

8 .......
9 .......

10 .......

11 default: default statement; //optional

12 }

 Switch statement allows only byte, char, short, int , String and enum as an argument
 switch doesn‟t allow float, double and long as an argument

When a break statement is encountered, the control moves out of the switch statement. If no break
statement is given, all the case statements are executed until a break is encountered or the switch
statement ends.

Switch Example with break:

public class SwitchEx {

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

2 int i = 2;

3 switch (i) {

4 case 1: System.out.println("1");

5 break;

6 case 2: System.out.println("2");

7 break;

8 case 3: System.out.println("3");

9 break;

10 case 4: System.out.println("4");

11 break;

12 case 5: System.out.println("5");

13 break;

14 default: System.out.println("No match found");

15 }

16 }

Output: 2

Switch Example without break:


public class SwitchEx {
1
public static void main(String[] args) {
2
int i = 2;
3
switch (i) {
4
case 1: System.out.println("1");
5
case 2: System.out.println("2");
6
case 3: System.out.println("3");
7
case 4: System.out.println("4");
8
case 5: System.out.println("5");
9
default: System.out.println("No match found");
10
}
11
}
12
}

Output :

2
3
4
5
No match found

for loop

For loop is used to execute a block of code repeatedly until the condition is true

Java supports 3 types of for loop

1. for loop
2. nested for loop
3. for-each loop

For loop can write in different ways


1) Syntax :

1 for(initialization ; condition ; increment/decrement){

2 //group of statements

3 }

Ex:

1 for(int i = 0 ; i < 10 ; i++){


2 System.out.println(i);

3 }

Initialization part is optional in for loop.


2) Syntax :

1 initialization;

2 for(; condition ; increment/decrement){

3 //group of statements

4 }

Ex:

1 int i =0;

2 for(; i < 10 ; i++){

3 System.out.println(i);

4 }

Conditional part is optional in for loop, If are not providing any condition complier will provide true
value.
3) Syntax :

1 for(initialization ; ; increment/decrement){

2 //group of statements

3 }

Ex:

1 for(int i =0; ; i++){

2 System.out.println(i);

3 }

increment/decrement part is optional in for loop.


4) Syntax :

1 for(initialization ; condition ; ){//infinite loop

2 //group of statements

3 }
Ex:

1 for(int i = 0 ; i < 10 ; ){

2 System.out.println(i);

3 }

All parts are optional in for loop.


5) Syntax :

1 for( ; ; ){//infinite loop

2 //group of statements

3 }

Ex:

1 int i = 0;

2 for( ; ; ){

3 System.out.println(++i);

4 }

For loop example

1 public class ForLoopEx {

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

3 for (int i = 0; i <= 10; i++) {

4 System.out.println(i);

5 }

6 }

7 }

Output:

0
1
2
3
4
5
6
7
8
9

while loop

while loop is used to execute group of statements repeatedly as long as the condition is true.

Syntax :

1 while(condition){

2 //group of statements

3 }

Ex:

1 int i = 0;

2 while(i < 10){

3 System.out.println(++i);

4 }

do-while loop

do-while loop is used to execute group of statements repeatedly as long as the condition is true, but
the difference between while loop and do-while loop is while loop every time will check the condition
where as do-while loop first time it won‟t check the condition.

Syntax :

1 do{

2 //group of statements

3 } while(condition);

Ex:

int i = 0;

do{

System.out.println(++i)

} while(i < 10);


OOPS

What is OOPS?

OOPS (Object Oriented Programming System) is an approach designing the programs using classes and
objects.

Features of OOPS

Following are the main features of OOPS supported by Java

 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

Class

class is a blueprint for creating objects, class refers common properties and functions of Objects
A class can produce any number of objects of its own type.

Class contains

 instance variables
 class variables(static variables)
 instance methods
 class methods (static methods)
 constructors
 instance blocks
 static blocks
 nested classes
 nested intefaces

Example:

1 Public Class Person{

2 String name;

3 String gender;

4 float height;

5 float weight;

6 Public void walk(){

7 System.out.Println(“Person is now walking”);


8 }

Object

 An object can be anything which is existing physically in the real world, For example book, pen,
person, car
 An object contains state and behavior
For example a dog object contains states like color, name, breed as well as behaviors like
wagging the tail, barking, eating.
 Object maintains its state in instance variables and implements its behavior with the methods.

Suppose to a build a house we need a planning which contains the architecture (blue print) of the
house. The blue print is a class in this scenario. After building the house according to that particular
plan, the house will be physically existed. So the outcome „house‟ is the Object.

Creating Object:

Generally we can create an object to a class by using “new” operator. [There are several ways to
create an object. We will discuss the remaining ways in the coming topics]

1 Person raju = new Person();

In the above statement, “raju” is a reference of Person object. By using this reference we can reuse
Person object.
Below image explains the same scenario diagrammatically

What will happen when we create an Object using new operator

1. First JVM determines the amount of memory needed for the new object, Then JVM allocates the
memory on the heap
2. All instance variables get initialized
3. JVM will invoke appropriate constructor, based on the arguments specified in the new statement
4. Before the constructor executes, super class constructor and instance blocks gets executed
5. The body of the constructor gets executed
6. The new operator returns a reference to the new object
Methods

Method is a group of statements which performs a task.

 A method must return a value


 If a method not return any value then return type is void
 Void is a keyword which will return no value
 Method may or may not contains parameters.

1 public int add(int i, int j){

2 int result = i+j;

3 return result;

4 }

Types Of Methods

In Java we have two types of methods.

 Instance Methods
 Static Methods

Instance Methods

 A method declared without a static keyword is known as instance method.


 We can call the instance methods by using object
Syntax: object.methodName()
Ex:

1 StringBuffer sb = new StringBuffer("New");

2 sb.append("york");

 We can overload as well as override the instance methods.


 Instance methods can access instance variables and static variables directly
 Instance methods can access other instance methods and static methods directly

Instance method without parameters

Public void add()

Instance method with parameters

Public void add(int i)


Public void add(int i, char c)

Different ways to declare an instance method:

1 Public void add()

2 Public synchronized void add()

3 synchronized Public void add()

4 Public int add(int i, int j)

5 synchronized Public int add(int i,int j)

6 Public synchronized int add(int i,int j)

Static Methods(Class Methods)

 A method which is declared with static keyword is known as static method(class method)
 we can call a static method by using the Class-Name
syntax: ClassName.methodName()

Ex:

1 String.valueOf(5);

 We can overload the static methods, but we can‟t override static methods
 Static methods can access static variables and other static methods directly
 Static methods cannot access instance variables and instance methods directly,But we can
access by creating an object
 Static methods doesn‟t allowthis keyword

Static method without parameters

Public static void add()

Static method with parameters

Public static void add(int i)


Public static void add(int i, char c)

Ways to declare a static method


1 public static void add()

2 public static synchronized void add()

3 static synchronized public void add()

4 Public static int add(int i, int j)

5 static synchronized public int add(int i,int j)

6 public static synchronized int add(int i,int j)

7 public synchronized static int add(int i,int j)

8 static public synchronized void show(int i)

What is method signature in Java?

Method name along with parameters is known as method signature.

Syntax: methodName(parameters-list)
Ex:Println(String str)

Constructor

Constructor is similar to a method but it will not return any value even void also(If method not return
any value then return type is void) .

We cannot call the constructor explicitly, Constructor implicitly called by JVM at the time of object
creation[Ex. Person p = new Person()]

Constructor is used to initialize the instance variables at run time.

Constructor rules:

 Constructor name should be the class name.


 We can‟t override a constructor but we can overload the constructor
 Constructor can throws an exception
 Constructor doesn‟t have any return type.
 Constructor doesn‟t allow final,abstract,synchronized,static and native keywords

Types of constructors:

Java supports two types of constructors

 Default constructor(no-arg constructor).


 parameterized constructor

If constructor doesn‟t have any parameters, it is called as a Default Constructor(no-arg constructor).

1 public class Person {

2 Person() {

3 System.out.println("This is a default constructor”);


4 }

5 }

If a constructor contains 1 or more parameters, then it is called as a Parameterized Constructor. In


such case we have to pass the values at the time of object creation to a Parameterized constructor.

1 public class Person {

2 Person(String str) {

3 System.out.println("This is a Parameterized constructor”);

4 }

5 }

In case if we did not provide any constructor(default or parameterized constructor), then Java compiler
will provide a default constructor.

parameterized constructor contains one or more parameters.

We can call from one constructor to another constructor of the same class by using “this” keyword. In
case if we are calling a parameterized constructor from a constructor, we should pass the parameters.

We can call super class constructor by using “super” keyword.

Advantages of constructors:

Constructor is used to initialize the instance variables at run time.

Private constuctor

When ever we declare private constructor in a class , that class can’t be extended as well we
can’t create object outside of that class.
Ex:

package com.core;
1
public class Test
2
{
3
private Test()
4
{
5
}
6
}
Encapsulation in java

 Binding data(variables) and functions(methods) into a single unit is called encapsulation.


Ex. java bean
 The main advantage of encapsulation is providing security to our data, We can achieve it by
using privatemodifier.
 Private variables and methods can access only inside class, outside of the class can‟t accessible.

A Java Bean class is the best example for a well implemented encapsulation in Java. Check the below
example code.

Example [Java Bean]:

public class Person { p


u
b
private String name; l
private String gender; i
c
public void setName(String name){
this.name = name;
} c
public void setGender(String gender) { l
this.gender = gender; a
} s
public String getName(){
s
return name;
}
public String getGender() { P
return gender; e
} r
} s
Inheritance o
n
What is Inheritance?
{
 Inheritance is nothing but deriving new classes from the existing classes is called
inheritance.
 The existing class is called super class or parent class and the newly created class
is called sub class or child class p
 We can achieve inheritance in Java by using extends keyword . r
 The main advantage of inheritance is code reusability(we can reuse the super class i
code without rewriting it in sub class).
v
 Using inheritance we can reuse super class variables and methods in sub class.
 By default Object class is the super class of every class in Java. a
 We can‟t extends final class. t
 Java doesn‟t support for multiple inheritance. e
 We can achieve multiple inheritance through interfaces in Java.
S
package com.test; t
r
class A { i
1
n
int i = 10;
2 g
public void printMsg1() {
3 n
System.out.println("Inside printMsg1 method"); a
4 m
}
e
5
} ;
6
p
10 r
public class B extends A { i
11 v
int j = 20; a
12
t
public void printMsg2() {
13 e
System.out.println("i value " + i);
14 S
System.out.println("j value " + j); t
15 r
//calling super class method
i
16
printMsg1(); n
17 g
System.out.println("Inside printMsg2 method");
18 g
} e
19
n
public static void main(String[] args) {
20 d
B b = new B(); e
21 r
b.printMsg2(); ;
22
}

Output:
p
i value 10
u
j value 20
b
Inside printMsg1 method
l
Inside printMsg2 method
i
c
In the above example, A class is called “super class”, and B class is called“sub class”. Super
class variables and methods reusing in sub class without rewriting it in sub class.
v
o
When ever super class object is created then memory allocated to only super class
i
members,so we can access only super class members.
d
Ex:
s
1 A a = new A(); e
t
2 System.out.println(a.i); N
a
3 a.printMsg1();
m
e
When ever sub class object is created then memory allocated to both super class and sub (
class members, so we can access super and sub class members. S
t
Ex: r
i
1 B b = new B(); n
g
2 System.out.println(b.i);

3 System.out.println(b.j); n
a
4 b.printMsg1(); m
e
5 b.printMsg2();
)
{
Super class reference can refer both super class and sub class object, but it can access only
super class members.

Ex:

1 A a = new B(); t
h
2 System.out.println(a.i); i
s
3 a.printMsg1(); .
n
a
Sub class reference can refer only sub class object, but it can access both super class and
sub class members. m
e
Ex:
=
1 B b = new B();
n
2 System.out.println(b.i); a
m
3 System.out.println(b.j);
e
4 b.printMsg1(); ;

5 b.printMsg2(); }

p
Sub class reference can‟t refer super class object. u
b
Ex: l
i
1 B b = new A();//will not compile c
v
Types of inheritance o
i
There are five types of inheritance d

s
e
t
G
e
n
1 class A { d
e
2 ----------
r
3 } (
S
4 class B extends A { t
r
5 ----------
i
6 } n
g

g
e
n
d
e
r
)

t
1 class A {
h
2 ---------- i
s
3 } .
g
4 class B extends A {
e
5 ---------- n
d
6 } e
r
7 class C extends B {
=
8 ----------

9 } g
e
n
d
e
r
;

p
u
b
l
i
1 class A { c

2 ----------
S
3 } t
r
4 class B extends A { i
n
5 ----------
g
6 }
g
7 class C extends A { e
t
8 ---------- N
a
9 }
m
e
(
)
{

r
e
t
u
1 class A { r
n
2 ----------
n
3 } a
m
4 class B{
e
5 ---------- ;

6 } }

7 class C extends A,B { p


u
8 ---------- b
l
9 }
i
c
Java doesn‟t support for multiple inheritance.
S
t
r
i
n
g

g
e
class A { t
1 G
---------- e
2 n
} d
3
e
class B extends A{
r
4
---------- (
5 )
}
6 {
class C extends A {
7 r
----------
e
8
t
}
9 u
class D extends B,C { r
10 n
----------
11 g
}
e
n
Java doesn‟t support for hybrid inheritance. d
e
What is multiple inheritance in Java? r
;
If a class extends more then one class is known as multiple inheritance.
}

Why multiple inheritance is not supported in java? }

Assume that we have three classes like Parent1, Parent2 and Child, If the Child class
extends Parent1, Parent2 which contains same method, And we are trying to invoke the
common method from child class, In such case JVM gets confuse which method needs to
invoke, This is called diamond problem.

1 class Parent1{

2 void printMessage(){

3 System.out.println("Parent1 method");

4 }

5 }
6 class Parent2{

7 void printMessage(){

8 System.out.println("Parent2 method");

9 }

10 }

11 class Child extends Parent1,Parent2{

12 Public Static void main(String args[]){

Child child =new Child();

child.printMessage();//Now which printMessage() method would be invoked?

Types of Relationships

Inheritance supports two types of Relationships in java

1. ―IS-A‖ Relationship
2. ―HAS-A‖ Relationship

IS-A Relationship:

IS-A Relationship can achieve through inheritance by using the “extends” keyword.

HAS-A Relationship:

HAS-A relationship can achieve through association, Association is nothing but establishing
the relationship between two separate classes through their objects.The relationship can be
one to one, One to many, many to one and many to many.

Composition and Aggregation are the two forms of association.

Aggregation

Aggregation is a special case of association.


Aggregation is a Weak Has-A relationship
In aggregation contained object can exists without the existence of container object.
For example without job, person can exist.
Example:

1 public class Person {

2 private String name;

3 private String gender;


4 public void setName(String name){

5 this.name = name;

6 }

7 public String getName(){

8 return name;

9 }

10 public String getGender() {

11 return gender;

12 }

13 public void setGender(String gender) {

14 this.gender = gender;

15 }

16 }

1 public class Job {

2 private String jobName;

3 private Person person;

4 public void setPerson(Person person) {

5 this.person = person;

6 }

7 public void setJobName(String jobName) {

8 this.jobName = jobName;

9 }

10 public String getJobName() {

11 return jobName;

12 }

13 public Person getPerson() {

14 return person;

15 }
16 }

1 public class Main {

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

4 Person person = new Person();

5 person.setName("Ram");

6 person.setGender("Male");

7 Job job = new Job();

8 job.setJobName("Software");

9 job.setPerson(person);

10 }

11 }

In the above Main class we have created object to Person then we are passing to the Job object by
means of setter methods. so here Person object exists with out Job object also.

Composition

Composition is a special case of Aggregation.

Composition is a Strong Has-A relationship.

In composition the contained object cannot exists without the existence of container object, then the
relationship is called as Composition.

for example fish doesn‟t exist without water.

Address.java

1 package com.test;

2 public class Address {

3 private int addrId;

4 private String street;

5 private String city;

6 public int getAddrId() {

7 return addrId;
8 }

9 public void setAddrId(int addrId) {

10 this.addrclass= addrId;

11 }

12 public String getStreet() {

13 return street;

14 }

15 public void setStreet(String street) {

16 this.street = street;

17 }

18 public String getCity() {

19 return city;

20 }

21 public void setCity(String city) {

22 this.city = city;

23 }

24 }

Employee.java

1 package com.test;

2 public class Employee {

3 private String empName;

4 private int empId;

5 private float salary;

6 private Address addr= new Address();

7 public String getEmpName() {

8 return empName;

9 }

10 public void setEmpName(String empName) {

11 this.empName = empName;
12 }

13 public int getEmpId() {

14 return empId;

15 }

16 public void setEmpId(int empId) {

17 this.empclass= empId;

18 }

19 public float getSalary() {

20 return salary;

21 }

22 public void setSalary(float salary) {

23 this.salary = salary;

24 }

25 public Address getAddr() {

26 return addr;

27 }

28 }

In the above case Employee object contains Address object, but with out Employee object there is
no Address object this is called Composition.

Polymorphism

What is Polymorphism?

Polymorphism is nothing but an object or method having multiple behaviours.

Types of polymorphism

Java supports two types of polymorphism.

 Static polymorphism
 Dynamic polymorphism

Static polymorphism:

 The Polymorphism exhibited at compilation time is called static polymorphism


 Static polymorphism supports method over loading
Dynamic Polymorphism:

 The Polymorphism exhibited at runtime is called dynamic polymorphism


 Dynamic Polymorphism supports method overriding

Method overloading

If a class contains two or more methods having same name with different parameters(different method
signature) is known as method overloading
In method overloading the return type may or may not be same

1 Public class A{

2 Public void show(){

3 System.out.println("inside show()");

4 }

5 Public void show(int x){

6 System.out.println("inside show(int x)");

7 }

8 Public void show(String str){

9 System.out.println("inside show(String str)");

10 }

11 }

Method Overriding

Declaring same method in sub class which is already exists in super class is known as method
overriding, Here the sub class method will override super class method

In method overriding the super class method is called overridden method and the sub class method
is called overriding method

Overriding Rules:

 overridden and overriding methods should exist in super and sub class
 overridden and Overriding methods name and parameters should be same and return type can
be same or covariant return type.
 Private methods can not be overridden
 Static methods can not be overridden
 Final methods can not be overridden
 Overriding method can not throw super class exception of overridden method exception.
For example overridden method throws IOException, In such case overriding method should
not throw Exception, Because Exception is super class of IOException
 Overriding method scope can not reduced of overridden method scope
For example overridden method scope is protected, In such case overriding method scope can
not be private or default
 Overriding method scope can be same or increase of overridden method scope
For example overridden method scope is protected, In such case overriding method scope can
be protected or public

Example -1:

1 Public class Parent{

2 Public void show(int x){

3 System.out.Println(x);

4 }

5 Public void display(String str){

6 System.out.Println(str);

7 }

8 }

Public class Child extends Parent {

public void test(){

System.out.Println(“inside test()”);

public void display(String str){

System.out.Println(str);

Child.java

1 class TestOverriding{

2 Public static void main(String args[]){

3 Child childObj = new Child();

4 childObj.display(“Hello”);

5 childObj.show(10);
6 childObj.toString();

7 }

8 }

 In the above example, we are overriding display() method in the Child class. The
display()method in the Child class(subclass) is called “overriding method”
 While executing childObj.display(“Hello”), JVM calls the display()from the Child class(sub classs)
 In case of childObj.show(10), initially JVM checks whether the method is existed or not in the
Child class(sub class)
 In our case show(int x) is not there. Then the JVM checks whether the Parent class(super class)
has the method show(int x), Yes it is there, so it will execute that method
 In case of childObj.toString(), this method is not provided in both the Child and Parent classes
then the JVM checks the Object class(which is the super class of all the classes in Java) and
continue to execute it

Example -2:

1 class TestOverriding2{

2 Public static void main(String args[]){

3 Parent parentRef = new Child();

4 parentRef.show(10);

5 parentRef. test();//will not compile

6 }

7 }

In the above example, Parent class(super class) reference is holding the Child class(sub class) object.

 In case of parentRef.show(10), at compile time the Java Compiler will checks forshow(int x)
method whether it is existing in Parent class. Yes the method is existing in Parent class
 In case of parentRef.test(), at compile time the Java Compiler will check whether test() method
is existed in the Parent class. In our case it is not existed in the Parent class so the compiler
throws an exception

covariant return type

Overriding method return type should be sub return type of overriden method return type, is known as
covariant return type

Example -3:

1 package com.test;

2 class Parent{

3 }

1 package com.test;
2 class Child extends Parent{

3 }

1 package com.test;

2 class A{

3 public Parent display(){ //overriden method

4 System.out.println("printing from A's display(String str)");

5 return new Parent();

6 }

7 }

1 Ppackage com.test;

2 class B extends A{

3 public Child display(){ //overriding method

4 System.out.println("printing from B's display(String str)");

5 return new Child();

6 }

7 }

Overloading vs Overriding

Method Overloading Method Overriding

If two or methods which are exists in

the same class with same method If two or methods which are exists in super and sub

name along with different parameters classes with same method name along same

list is called method overloading. parameters list is called method overloading.

Return type must be same, But from JDK5 method

Return type may or may not be same. overriding supports co-variant return type.

Methods can be overloaded in

inheritance also. Methods can be overridden only in inheritance.


In method overriding method can have same access

specifier or Overriding method access specifier scope

can be increase of overridden access specifier method

scope.

for example overridden method scope is protected, In

such case overriding method scope can be protected or

public

In method overloading access

specifiers may or may not be same. private -> default -> protected -> public

Overriding method can not throws super class exception

of overridden method exception.

for example overridden method throws IOException, In

such case overriding method should not throws

Overloaded methods can throws any Exception, Because Exception is super class of

exception. IOException

private, final and static methods can be

overloaded. private, final and static methods can not be overridden.

Methods can be overloaded in the same

class. Methods overriding can not possible in the same class.

Typecasting in java

Why we need Type casting?

When ever we assign a value to a variable using assignment operator, Java compiler checks whether
the variables are of the same data type on both sides of equal operator. If the data types are not the
same then we will get an exception, to over come this situation we should convert the data types to
same on the both sides. To convert the data type, we will use the cast operator.

Converting from one data type to another data type is called type casting.
There are two types of casting in Java:
 implicit casting
 explicit casting

implicit casting

 Internally the casting is done by the Java compiler automatically


 In case of Primitive Data types, Java compiler converts lower data type to higher data type
 An implicit cast happens when you‟re doing a “widening conversion”
 Widening Conversion is converting from lower data type to higher data type

Order of Primitive Data types:

order follows from lower to higher

1 char c = „x‟;

2 int i = c; // it is acceptable

explicit casting

 A casting done by programmer is called explicit casting


 Explicit casting is compulsory while converting from higher data type to lower data type
 An explicit cast happens when you are doing a “Narrowing conversion”
 Narrowing Conversion is converting from higher data type to lower data type

Example:

int i = 66;
1
char c = i; //not acceptable
2
char c = (char) i; // acceptable

In the above example we are forcing int data type to char.

Abstraction

 Abstraction is the process of hiding the unwanted implementation details and exposing only
required features.
 Abstraction can achieved by using interfaces and abstract classes in java.
 An interface provides complete(100%) abstraction where as the abstract class provides partial(0
to 100%) abstraction.

Abstract class

 Abstract is a keyword in Java


 Classes and methods can be declared as abstract
 Abstract class is a class which is declared with abstract keyword.

Ex:
1 abstract class Vehicle {

2 }

 Abstract class can contains both abstract and concrete methods.


 An abstract method is a method which has only the declaration without having any
implementation(without body).

Ex:

1 public String getMessage();

 A concrete method is a method which contains the method body.

1
public void getMessage(){
2
}
3

 Abstract class may or may not contains concrete methods, that means abstract class can
contains all abstract methods.
 Abstract class may or may not contains abstract methods, that means abstract class contains all
concrete methods.
 We can not create object to abstract class.
 An abstract class can extends another abstract class or a class.
 All abstract methods of abstract class should be implemented in the sub classes.
 If any abstract method is not implemented, then the sub classes should be declared as abstract.
 Even if a single method is declared as abstract in a class, the class itself can be declared as
abstract.
 An abstract class can have constructors and instance variables.
 Should not use final and abstract modifiers together in java.

Ex:

abstract class AbstractTest {

public abstract void show();

public void printMsg() {

System.out.println("inside printMsg method");

}
Interface

 An interface is blueprint of a class


 Interfaces are declared using interface keyword

Ex:

1 interface Collection{

2 }

An interface contains constants and abstract methods(declarations without any implementation).

Ex:

1 public static float PI = 3.14f;

2 public abstract void display();

 Using interface we can achieve 100% abstraction.


 We can‟t create object to an interface.
 By default all methods are public and abstract in interface
 By default all variables are public , static and final in interface

 A class can implements an interface by using implements keyword


 A Class which implements an interface that needs to provide the implementation for all the
methods which are declared in Interface, Otherwise that class needs to declare as an abstract.
 Multiple inheritance can achieve through interfaces in Java
 A class can implements one or more interfaces.
 An Interface can extends one or more interfaces.
 An interface can not implements other interface.
 Interfaces methods can not be static , synchronize , final , protected , private or native .

Ex:

1 public interface A {

2 int i = 10;

3 void show();

4 }

5 public class B implements A{

6 public void show(){

7 System.out.println("inside B");
8 }

9 }

10

What is functional interface in java?

Functional interface is an interface which contains only one method.


Ex: Predicate and Function, etc…

What is marker interface or tagged interface?

Marker interface is an interface which doesn‟t contains any methods.


Ex: serializable, Cloneable , etc…

String

 String represents a group of characters which is enclosed with in the double quotes.

Ex:

1 String str = "Hello";

 String is a class as well as data type since all the classes are data types in Java.
 String default value is null.
 String is an immutable object. immutability means unchangeable.
 Once String object is created then the content of the object can‟t be modified.

String Constructors :

String() :
Creating string object with empty content.
Ex:

1 String str=new String();

String(byte[] bytes):
Creating string object with byte array argument.
Ex:

1 byte[] arr={104,101,108,108,111};

2 String str=new String(arr);

String(char[] value):
Creating string object with char array argument.
Ex:

1 char[] arr={'h','e','l','l','o'};
2 String str=new String(arr);

String(char[] value, int offset, int count):


Creating a new String that contains characters from a subarray of the character array argument.
Ex:

1 char[] arr={'h','e','l','l','o'};

2 String str=new String(arr,2,3);

String(String original):
The newly created string is a copy of the argument string.
Ex:

1 String str=new String(“hello”);

String(StringBuffer buffer):
Create new String object with string buffer argument.
Ex:

1 StringBuffer sb=new StringBuffer("hello");

2 String str=new String(sb);

String(StringBuilder builder):
Create new String object with string builder argument.
Ex:

1 StringBuilder sb=new StringBuilder("hello");

2 String str=new String(sb);

String Methods:

char charAt(int intex): Returns the char value at the specified index of the string.
Ex:

1 char c=str.charAt(2);

int compareTo(String anotherString): This method is useful to compare two strings and we can
know which string is bigger or smaller
Ex:

1 int i=str.compareTo(“ok”);

String concat(String str): Concatenates the specified string to the end of this string.
Ex:

1 str.concat(“john”);
boolean contains(CharSequence s): Returns true if and only if this string contains the specified
sequence of char values.
Ex:

1 Boolean value=str.contains(“llo”);

int length(): Returns number characters of string.


Ex:

1 int count=str.length();

boolean equals(String s): Return true if both strings content are same otherwise returns false.
Ex:

1 bolean value=str.equals(“hello”);

String trim(): Removes starting and ending spaces of a string.


Ex:

1 String str1=str.trim();

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


Ex:

1 char[] arr=str.toCharArray();

String[] split(String delimiter): Splits this string around matches of the given delimiter.
Ex:

1 String str=”Hello how are you”;

2 String[] arr=str.split(“ “);

String toLowerCase(): Converts all of the characters in this string to lower case.
Ex:

1 String s=str.toLowerCase();

String toUpperCase(): Converts all of the characters in this string to upper case.
Ex:

1 String s=str.toUpperCase();

boolean startsWith(String prefix): Returns true if this string starts with specified prefix, other
returns false.
Ex:

1 boolean value=str.startsWith(“h”);
boolean endsWith(String suffix): Returns true if this string ends with specified suffix, other returns
false.
Ex:

1 boolean value=str.endsWith(“o”);

String replace(char oldChar, char newChar): Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
Ex:

1 String s=str.replace(„l‟, „s‟);

String subString(int index): Returns a new string that is a substring of this string, from the index.
Ex:

1 String s=str.subString(2);

String substring(int startIndex, int endIndex): Returns a new string that is substring of this
string, from start index to end index .
Ex:

1 String s=str.subString(1,4);

boolean isEmpty(): Returns true if the length of string is 0., otherwise returns false.
Ex:

1 boolean value=str.isEmpty();

int indexOf(char ch): Returns the index within this string of the first occurrence of the specified
character.

Ex:

1 int index= str.indexOf(„l‟);

int lastIndexOf(char ch): Returns the index within this string of the first occurrence of the specified
substring.
Ex:

1 int index= str.lastIndexOf(„l‟);

String valueOf(int i): Converts from int to string.


Ex:

1 int i=10;

2 String str=String.valueOf(i);
Creating String object

String object can create in two ways.

1. Using new operator


Ex:

1 String strObj1 = new String(“Hello”);

2. Using String Literal


String literal object is created by using double quotesEx:

1 String str1 = ”Hello”;

1. Using literal operator(String literal):

String literal object is created in String Constant Pool, Before creating the object JVM will check
in String Constant Pool(String literal Pool) is there any object is exists with same content or not. If
any object exist with the same content then JVM will create a new reference for existing object.
otherwise it creates a new object in String constant pool.

Example:

1 String str1 = ”Hello”;

2 String str2 = “Hello”;

 In the above Literal example by executing String str1 = ”Hello”, JVM creates a new String object
in string constant pool, Because first time string constant pool doesn‟t contain any object with
“Hello” content.
 While executing the statement String str2 = “Hello”, Instead of creating a new object JVM will
create a new reference(str2) for existing object. Because already string constant pool contains
an object with “Hello” content.

The following image shows how JVM creates objects in case of literal.

2. Using new operator:

In case new operator, JVM always create a new object in the heap without checking is there any object
exist with same content or not.
Ex.

1 String str1 = new String(“Hello”);


2 String str2 = new String(“Hello”);

In the above case JVM creates three String objects two objects in heap, another one is in String
constant pool.

 While executing String str1 = new String(“Hello”), JVM creates two String objects one is in Heap
another one is in string constant pool.

 While executing String str2 = new String(―Hello”), JVM creates only one String object in
Heap, Because already string constant pool contains an object with “Hello” content.

The following image shows how JVM creates objects

String immutability

Immutability:

String is an immutable object, immutability means once String object is created, then the content of
the object can‟t be modified.
If we make any changes on String object instead of modifying the original object JVM will create a new
object.

1 String str= new String(”Hello”);

2 str.concat(” Raj”);

3 System.out.Println(str);

Output: Hello

In the above scenario we are trying to modify the content of str object, but instead of modifying the
original object(str) content , JVM will create a new object in Heap.

Below diagram illustrates the behaviour of JVM while executing the statement. String str=”Hello”;
In the above scenario we are trying to modify the content of str object, but instead of modifying the
original object(str) content , JVM will create a new object in Heap.

Below diagram illustrates the behaviour of JVM while executing the statement. String str=”Hello”;

From the above diagram, str is holding the object which has the content “Hello”

Below diagram illustrates the behaviour of JVM while executing the statement str.concat(” Raj”);

 While executing the statement str.concat(‖ Raj‖), we are trying to modify content of the str
 Instead of modifying the str object, JVM creates a new object with “Hello Raj” content.
 Here we can understand that once an object is created, then the content of the original object
cant be modified.

But we can explicitly refer the newly created object.

Ex:

1 String str= new String(”Hello”);

2 str = str.concat(” Raj”);

3 System.out.Println(str);

Output : Hello Raj

Why string is Immutable?

1 String str1 = ”hello”;

2 String str2 = ”hello”;

3 String str3 = ”hello”;


 In the above example str1, str2, str3 are pointing to the same object containing “hello”
1 str3 = “Welcome”;

 In the above line we have changed str3 value from “hello” to “welcome”.
 If String is not immutable then the changes will effect remaining references(str1,str2).
 To overcome this problem String has been made immutable.

In the above example by executing String str1 = ”hello”, String str2 = ”hello” and String str3 = ”hello”,
all the references are pointing to the same object. Refer the below diagram.

Suppose if String is not immutable and for executing str3 = “Welcome”, the same will be effected
to str1 and str2which are pointing to the same object. Refer the below diagram

String concatenation

String concatenation can be done in two ways:


1.concatenation operator ( + )
2.concat() method.

Concate operator (+) can concat String along with primtive values. concate operator(+) internally uses
StringBuffer to concate the values.

Explanation with Examples :

public class StringTest {

public static void main(String[] args) {

String str = new String ("New");

str = str+"york";

System.out.println("String concat with concat operator: "+str);

System.out.println("Numbers and Characters: "+10000+"BC");

}
Output:

String concat with concat operator: Newyork


Numbers and Characters: 10000BC

concat() method concatenates the specified string to the end of current string, concat() method can
concat only String objects.

1
public class StringTest2 {
2
public static void main(String[] args) {
3
String str = new String ("New");
4
str = str.concat("york");
5
System.out.println("String concatenation with concat method: "+str);
6
}
7
}
8

Output : String concatenation with concat method: Newyork

String Comparison

There are 3 ways we can compare the Strings in java.

 == operator
 equals()
 compareTo(String str)

By using == operator:

== operator checks the references(memory addresses) of two objects, but not content.

Example:

1 public class DoubleEqualsTest {

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

3 String str = "ok";

4 String str1 = "hello";

5 String str2 = "hello";

6 String str3 = new String("hello");

7 String str4 = new String("hello");

8 System.out.println(str == str1);

9 System.out.println(str1 == str2);
10 System.out.println(str1 == str3);

System.out.println(str3 == str4);

output:

false
true
false
false

Detailed explanation is given in the following diagram.


By following the above diagram we can understand that…

 str and str1 holding different objects, So both str and str1 memory addresses are different.
Then str==str1statement returns “false”.
 str1 and str2 are holding same object based on String Constant Pool concept. So
both str and str1 memory addresses are same, Then str1==str2 statements returns “true”.
 both str1 and str3 holding different objects in such case memory addresses are different ,
So str==str3statement returns “false”.
 str3 and str4 holding different objects in suchcase memory addresses are different ,
So str3==str4 statement returns “false”.

By using equals() method:

equals() method checks the content of the the objects.

Example:

1 public class EqualsTest {

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

3 String str = "hello";

4 String str1 = "ok";

5 String str2 = "hello";

6 String str3 = new String("hello");

7 String str4 = new String("hello");

8 System.out.println(str.equals(str1));

9 System.out.println(str.equals(str2));

10 System.out.println(str.equals(str3));

11 System.out.println(str3.equals(str4));

12 }
13 }

output:

false
true
true
true

Through the above example program we can observe…

 str.equals(str1)statement returns “false” because contents in the both objects are different
 str.equals(str2) statement returns “true”
 str.equals(str3) statement returns “true”
 str3.equals(str4) statement returns “true”
 str, str2, str3 and str4 object‟s contents are the same, So for the above three statements the
result is “true”

By using compareTo() method:

This method is useful to compare two strings and we can know which string is bigger or smaller. And
the syntax is string1.compareTo(string2)

 If string1 and string2 are equal, then this method returns 0


 If string1 is greater than string2, then it returns a positive number
 If string1 is less than string2, then it returns a negative number
 This method compares the strings in dictionary order.

public class TestComapreTo {

public static void main(String[] args) {

String str = "ram";

String str1 = "ramya";

String str2 = "ram";

String str3 = "apple";

System.out.println(str.compareTo(str1));

System.out.println(str.compareTo(str2));

System.out.println(str.compareTo(str3));

output:
-2
0
17

In the above program, str.compareTo(str1)) statement returns “-2”. Because “ramya” comes
after ”ram” in the dictionary
 str.compareTo(str2)) statement returns ”0”. Because for both str and str2 the contents are
equal
 str.compareTo(str3)) statement returns ”17”. Because “ram” comes after “apple” in dictionary

Difference between == and equals() method in string?

 Both == and equals() are used to compare strings


 In case of == operator, it compares references(memory addresses) of the string objects
 In case of equals() method, it compares the contents of the string objects

intern() mehod

intern() method always returns the object from String constant pool, If the object is not avaialble then
JVM will create a new object in String constant pool.

public class Main

1 {

2 public static void main(String[] args)

3 {

4 String s1 = "Hello";

5 String s2 = "Hello";

6 String s3 = new String("Hello");

7 System.out.println(s1 == s2);

8 System.out.println(s1 == s3);

9 System.out.println(s1 == s3.intern());

10 }

output:

true
false
true

StringBuffer

 StringBuffer is a mutable object, which means the content of the object can be modified.
 StringBuffer is a synchronized

What is a mutable class?

If we perform any operation on a mutable class object, directly the original object gets
effected.StringBuffer objects does the same, by making changes using any of StringBuffer operations
then the original StringBuffer object will be effected.

Constructors:
StringBuffer():

Construct a StringBuffer with empty content, and an initial capacity of 16 characters.

1 StringBuffer sb = new StringBuffer();

StringBuffer(String str):
Constructs a string buffer initialized to the contents of the specified string.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

StringBuffer(int capacity):

Constructs a string buffer with no characters in it and the specified initial capacity.
EX:

1 StringBuffer sb = new StringBuffer(20);

Methods in StringBuffer:

StrinBuffer append(String s):


Appends the specified string to this character sequence
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb.append(“ john”);

StringBuffer append(StringBuffer sb):

Appends the specified StringBuffer to this sequence.


EX:

1 StingBuffer sb = new StringBuffer(“Hello”);

2 StringBuffer sb1 = new StringBuffer(“ john”);

3 sb.append(sb1);

int capacity():
Returns the current capacity.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 int count = sb.capacity();

char charAt(int index):


Returns the char value in this sequence at the specified index
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 char c = sb.charAt(2);

StringBuffer delete(int startIndex , int endIndex):


Removes the characters in a substring of this sequence.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb.delete(2 , 4);

StringBuffer reverse():
Causes this character sequence to be replaced by the reverse of the sequence.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb.reverse();

void setCharAt(int index, char ch):


The character at the specified index is set to ch.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb.setCharAt( 2 , „k‟);

void setLength(int newLength):

Sets the length of the character sequence.


EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb.setLength(4);

String substring(int start):


Returns a new String that contains a subsequence of characters currently contained in this character
sequence.
EX:

1 StringBuffer sb = new StringBuffer(“Hello john”);

2 String str = sb.subString(3);

String substring(int start, int end):


Returns a new String that contains a subsequence of characters currently contained in this sequence.
EX:
1 StringBuffer sb = new StringBuffer(“ Hello john”);

2 String str = sb.subString(2 , 6);

String toString():
Returns a string representing the data in this sequence.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 String str = sb.toString();

void trimToSize():
Attempts to reduce storage used for the character sequence.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb.trimToSize();

void ensureCapacity(int minimumCapacity):


Ensures that the capacity is at least equal to the specified minimum.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 sb. ensureCapacity(32);

int indexOf(String str):


Returns the index within this string of the first occurrence of the specified substring.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 int index = sb. indexOf(“l”);

int lastIndexOf(String str) :


Returns the index within this string of the rightmost occurrence of the specified substring.
EX:

1 StringBuffer sb = new StringBuffer(“Hello”);

2 int count = lastIndexOf(“l”);

int length():

Returns the character count.


EX:

1 StringBuffer sb = new StringBuffer(“Hello”);


2 Int length = sb.length();

Example :

public class StringBufferTest {

public static void main(String[] args) {

StringBuffer sBuffer1 = new StringBuffer("New");

sBuffer1.append("york");

System.out.println("Using StringBuffer append(): "+sBuffer1);

output: Using StringBuffer append(): Newyork

StringBuilder

 StringBuilder is very similar like StringBuffer. Everything including all the operations are the
same, Only difference is StringBuilder is not synchronized.
 Since StringBuilder is not thread-safe, it is faster than StringBuffer.

Constructors in StringBuilder:

StringBuilder():

Construct a StringBuilder with empty content, and an initial capacity of 16 characters.


EX:

1 StringBuilder sb = new StringBuilder();

StringBuilder(String str):
Constructs a string buffer initialized to the contents of the specified string.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

StringBuilder(int capacity):

Constructs a string buffer with no characters in it and the specified initial capacity.
EX:

1 StringBuilder sb = new StringBuilder(20);

Methods in StringBuilder:

StrinBuffer append(String s):


Appends the specified string to this character sequence
EX:
1 StringBuilder sb = new StringBuilder(“Hello”);

2 sb.append(“ john”);

StringBuilder append(StringBuilder sb):

Appends the specified StringBuilder to this sequence.


EX:

1 StingBuffer sb = new StringBuilder(“Hello”);

2 StringBuilder sb1 = new StringBuilder(“ john”);

3 sb.append(sb1);

int capacity():
Returns the current capacity.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 int count = sb.capacity();

char charAt(int index):

Returns the char value in this sequence at the specified index


EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 char c = sb.charAt(2);

StringBuilder delete(int startIndex , int endIndex):


Removes the characters in a substring of this sequence.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 sb.delete(2 , 4);

StringBuilder reverse():
Causes this character sequence to be replaced by the reverse of the sequence.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 sb.reverse();

void setCharAt(int index, char ch):


The character at the specified index is set to ch.
EX:
1 StringBuilder sb = new StringBuilder(“Hello”);

2 sb.setCharAt( 2 , „k‟);

void setLength(int newLength):

Sets the length of the character sequence.


EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 sb.setLength(4);

String substring(int start):


Returns a new String that contains a subsequence of characters currently contained in this character
sequence.
EX:

1 StringBuilder sb = new StringBuilder(“Hello john”);

2 String str = sb.subString(3);

String substring(int start, int end):


Returns a new String that contains a subsequence of characters currently contained in this sequence.
EX:

1 StringBuilder sb = new StringBuilder(“ Hello john”);

2 String str = sb.subString(2 , 6);

String toString():
Returns a string representing the data in this sequence.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 String str = sb.toString();

void trimToSize():
Attempts to reduce storage used for the character sequence.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 sb.trimToSize();

void ensureCapacity(int minimumCapacity):


Ensures that the capacity is at least equal to the specified minimum.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);


2 sb. ensureCapacity(32);

int indexOf(String str):


Returns the index within this string of the first occurrence of the specified substring.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 int index = sb. indexOf(“l”);

int lastIndexOf(String str) :


Returns the index within this string of the rightmost occurrence of the specified substring.
EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 int count = lastIndexOf(“l”);

int length():

Returns the character count.


EX:

1 StringBuilder sb = new StringBuilder(“Hello”);

2 Int length = sb.length();

StringTokenizer

StringTokenizer

 StringTokenizer is a class which is existing in java.util package


 It is used to break a string into tokens

Constructors:

StringTokenizer(String str):
Creates a string tokenizer for the specified string.

StringTokenizer(String str, String delim):


Creates a string tokenizer for the specified string.

StringTokenizer(String str, String delim, boolean returnDelims):


Creates a string tokenizer for the specified string.

Methods:

int countTokens():
Calculates the number of times that this tokenizer‟s nextToken method can be called before it
generates an exception.
boolean hasMoreElements():
Returns the same value as the hasMoreTokens method.

boolean hasMoreTokens():
Tests if there are more tokens available from this tokenizer‟s string.

Object nextElement():
Returns the same value as the nextToken method, except that its declared return value is Object
rather than String.

String nextToken():
Returns the next token from this string tokenizer.

String nextToken(String delim):


Returns the next token in this string tokenizer‟s string.

Example:

Below is the program to split the String based on empty spaces

import java.util.StringTokenizer;

public class StringTokenizerEx {

public static void main(String[] args) {

String str="Hi welcome to java";

StringTokenizer st=new StringTokenizer(str,” ”);

while (st.hasMoreTokens()) {

String word=st.nextToken();

System.out.println(word);

output:

Hi
welcome
to
java

Call by value

Passing values as parameters to methods is known as call by value.


Java supports only call by value, call by reference is not possible in java, Because java always pass
primitive values to methods instead of passing references
What will happen when we pass primitive value as parameter to methods

While passing primitive values to methods, the original values are not be passed just the copy of the
value will be passed. If any changes happened to them inside method that will not effect original value

Example:

public class PrimitiveCheck {

public static void main(String[] args) {


1
int i = 10;
2
System.out.println("Before method calling i value==" + i);
3
//calling incrementvalue() method
4
incrementvalue(i);
5
System.out.println("After method calling i value==" + i);
6
}
7
public static void incrementvalue(int i) {
8
//changing i value
9
i++;
10
System.out.println("i value inside method==" + i);
1
}

output:

Before method calling i value==10


i value inside method==11
After method calling i value==10

What will happen when we pass Object as a parameter to method

While passing any object to method, Instead of passing reference it will pass memory address(memory
address is an integer value) of the object so if any changes happened on the object content in method,
then the original object content will be effected.
But in case of String the original value will not be effected, Because String is an immutable object

public class Employee {

private int empId;

private String empName;

public Employee(int empId, String empName) {

this.empId = empId;
this.empName = empName;

public int getEmpId() {

return empId;

public void setEmpId(int empId) {

this.empId = empId;

public String getEmpName() {

return empName;

public void setEmpName(String empName) {

this.empName = empName;

public class ObjectCheck {

public static void main(String[] args) {

Employee emp = new Employee(1, "Ram");

System.out.println("Before method calling id value==" + emp.getEmpId());

System.out.println("Before method calling name value==" + emp.getEmpName());

employeeManuplate(emp);

System.out.println("After method calling id value==" + emp.getEmpId());

System.out.println("After method calling name value==" + emp.getEmpName());

public static void employeeManuplate(Employee e) {

//Modifying employee object content

e.setEmpName("RamaKrishna");
System.out.println("id inside method==" + e.getEmpId());

System.out.println("name inside method==" + e.getEmpName());

output:

Before method calling id value==1


Before method calling name value==Ram
id inside method==1
name inside method==RamaKrishna
After method calling id value==1
After method calling name value==RamaKrishna

Static keyword

static is a keyword in Java


Static keyword can be used for variable, method, block and inner class

static variable :

Declaring variable with static keyword is known as static variable


Static variables are called as class variables.
This variables will load at the time of class loading.
Static variables can access with class name[Ex. className.variable] In case of static variables single
copy is shared to all objects
Ex:

1 public static String word=” Hello”;

static methods :

Declaring method with static keyword is known as static method


This methods are called class level methods, this methods will load at the time of class loading.
Static method can access with class name(className.method).
Ex:

1 public static String getName(){

2 return "myName";

3 }

static block :

Declaring block with static keyword is known as static block


static block is used to initialize static variables
Static block is invoked when classloader loads the class

package com.core;
public class Test

public static final int i;

static{

i = 10;

} }

Inner classes:

We can declare inner classes as static.


Ex:

1 class OuterClass {

2 ...

3 static class StaticNestedClass {

4 ...

5 }

6 }

Instance block

 Declaring a block without any keyword is known as instance block


 Instance block is used to initialize the instance variables.
 Instance block executes before the constructor get executed

Example:

1 package com.core;

2 public class Test

3 {

4 {

5 int i = 10;

6 System.out.println("inside instance block");

7 }

8 public Test()

9 {
10 System.out.println("inside constructor");

11 }

12 }

13

1 package com.core;

3 public class Main

4 {

5 public static void main(String[] args)

6 {

7 Test test = new Test();

8 }

9 }

output :

inside instance block


inside constructor

final keyword

Final is a keyword in java.


We can use final keyword at different level.

 Variable level
 Method level
 Object level
 Class level

Variable Level

When we use final keyword at variable level, we can‟t modify the value of the variable (modifying is
possible by using the Reflection).
Ex:

1 public final int i=10;

Method level

when we use final keyword at method level, that method can‟t be overridden.

Ex:
1 public final void getName(){

2 System.out.println("displaying name");

3 }

Object level

When we use final keyword at object level, that object reference can‟t be assigned to other object.

Ex 1:

1 final List list=new ArrayList ();

2 list=new LinkedList(); //Not Acceptable

Ex 2:

1 final String str = "hello";

2 str = "Bye"; //Not Acceptable

In the above case we have declared List reference as final and it is holding ArrayList object. If we try to
assign final List reference to LinkedList object it will through a compile time exception.
Because final reference can‟t be assigned to any object.

In the above Example 2, final str is already holding hello object and we are trying to modify str so we
will get an exception here.

Class level

 When we use final at class level, we can‟t extend that class.


 This is useful to make sure the same properties and behaviour of a class be can‟t be changed by
anyone for security purpose.
 Most of the classes in java.lang package, which are said to be the fundamentals of designing
Java are actuallyfinal.
 String is also an example for a final class. And that‟s the reason we can‟t override String„s
methods.

Ex:

package com.core;

final public class Test

public final void getName()

System.out.println("displaying name");
}

Inner class

What is an Inner class?

A class with in another class is known as Inner class or nested class.

1 class OuterClass {

2 ...

3 class NestedClass {

4 ...

5 }

6 }

Advantages of inner classes

Using inner classes we can develop more readable and maintainable code.

Using inner classes we are logically grouping classes that are only used in one place.

Inner classes increases security.

Types of inner classes

There are four types of inner classes.

1) Member class

2) Static member class

3) Local class

4) Anonymous class

Member class

A class that is define as a member of another class is known as member class.

1 public class Outer {

3 class Inner{

4 public void show(){


5 System.out.println("Inside show method of inner class");

6 }

7 }

8 }

9 public class Main {

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

11 Outer outerObj = new Outer();

12 Outer.Inner innerObj = outerObj.new Inner();

13 innerObj.show();

14

Static member class

A class that is defined as a static member of another class is known as static inner class. It is also
called as top level inner class.

public class Outer {


1
public void getMessage(){
2
System.out.println("inside getMessage method");
3
}
4
static class Inner{
5
public void show(){
6
System.out.println("Inside show method of inner class");
7
}
8
}

}
14
public class Main {
1
public static void main(String[] args) {
1
Outer outer = new Outer();
outer.getMessage();

//Creating object to static inner class

Outer.Inner innerObj = new Outer.Inner();

innerObj.show();

Local class

A class that is defined inside a method is known as local class.

public class Outer {


1
public static void main(String[] args) {
2
class Inner {
3
public void display() {
4
System.out.println("Inside show method of inner class");
5
}
6
}
7
Inner inner = new Inner();
8
inner.display();
9
}

Anonymous class

A class which declared inside of a class without any name is known as anonymous inner class.It is
always is used to write a sub class to an interface or a class.

public interface Test {

void show();

public class Main {

public static void main(String[] args) {

//Anonymous class
Test test = new Test(){

public void show(){

System.out.println("Inside show method of inner class");

};

test.show();

Exceptions

An Exception is an abnormal condition which interrupts the normal flow of the program.

Ex: Number dividing with zero.(int x = 10/0).

Exceptions are basically two types:

 CheckedException
 UncheckedException
Checked vs unchecked exceptions

Checked Exception :

 Checked exception is an exception which extends Exception class.


 Checked exceptions are caught at the compile time by Java compiler
 If program contains checked exceptions, then the program will not compile.
 To overcome the above problem to compile the program must write try-catch block or throws
keyword.

Ex:
IOException
ClassNotFoundException
SQLException
FileNotFoundException

Unchecked Exception (Runtime Exception):

 Unchecked exception is an exception which extends RuntimeException class.


 Unchecked exceptions are caught at runtime by JVM.
 Unchecked exceptions needs to handle using try-catch blocks.

Ex:
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NullPointerException
ClassCastException

Error :

it is an error-situation which can‟t be handled by the developer himself


Ex:
OutOfHeapMemory

Exception Handling

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception handling.
Let‟s take a scenario:

1 statement 1;

2 statement 2;

3 statement 3;

4 statement 4;

5 statement 5;//exception occurs

6 statement 6;

7 statement 7;
8 statement 8;

9 statement 9;

10 statement 10;

Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of
the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest
of the statement will be executed. That is why we use exception handling in java.

Generally exceptions can handle by using try, catch and finally block.

try :

 The try block contains set of statements which can cause the exception.
 For every try block we should have atleast one catch or finally block
 One try block can have multiple catch blocks or one finally block

catch :

 Catch block executes when an exception occurred in try block


 The catch block contains statements to display information about the exception
 catch block contains a group of statements that will be executed if that particular exception
is occurred in try block
For example if a NumberFormatException occurs in try block then the statements enclosed
in catch block for NumberFormatException gets executed.
 Catch block declaration should contain the particular exception thrown in the try block
Ex:catch(NumberFormatException e){
}


 While providing multiple catch blocks first we should catch sub-class exception then we
should catch the super-class exception otherwise we will get Unreachable Catch block
Exception at compile time
 We shouldn‟t provide a catch block without defining a try block

finally :

 finally block is used to close the resources like database connections, files, and JMS connections
 finally block will be executed irrespective of whether there is an exception occurred in the try
block or not

Possibilities of try-catch:

try with catch block

try{

catch(Exception e){

try without catch block


try{

finally{

try with multiple catch blocks

1 try{

3 }

4 catch(Exception e1){

6 }

7 catch(Exception e2){

9 }

multiple try-catch blocks

1 try{

3 }

4 catch(Exception e1){

6 }

7 try{

9 }

10 catch(Exception e2){

11

12 }

nested try blocks


1

2 try{

4 try{

6 }

7 catch(Exception e){

8 }

9 }

10 catch(Exception e){

11 }

12

try-catch inside catch block.

2
try{
3
}
4
catch(Exception e){
5
try{
6
}
7
catch(Exception e){
8
}
9
}
10

11

try-catch block inside try and catch.

try{

try{

}
catch(Exception e){

catch(Exception e){

try{

catch(Exception e){

Example for using try-catch-finally blocks:

public class ExceptionEx {

public static void main(String[] args) {

try {

int i = 4 / 2;

System.out.println(i);

int j = 5 / 0;

System.out.println(j);

catch (ArithmeticException ae) {

ae.printStackTrace();

finally{

System.out.println("inside finally block");

System.out.println("Outside of Exception Handling");

Output:

2
java.lang.ArithmeticException: / by zero
at ExceptionEx.main(ExceptionEx.java:6)
inside finally block
Outside of Exception Handling

In the above program, we are dividing 5 with 0. In this case we will get ArithematicalException.
We are handing this exception using try-catch-finally blocks. Even though we are getting exception,
remaining code had been executed without any interruption.

Multiple catch blocks Example:

import java.io.FileInputStream;

1 import java.io.FileNotFoundException;

2 import java.io.IOException;

3 public class ExceptionHandlingEx {

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

5 FileInputStream fis = null;

6 try {

7 fis = new FileInputStream("fileName");

8 int character;

9 while ((character = fis.read()) != -1) {

10 System.out.print(character);

11 }

12 } catch (FileNotFoundException e) {

13

14 e.printStackTrace();

15 } catch (IOException e) {

16

17 e.printStackTrace();

18 }

19

20 finally {

21 System.out.print(“Inside Finally block”);

}
}

In the above example our code throws FileNotFoudException and IOException. While providing catch
blocks, first we are catching FileNotFoudException because it is sub-class exception of IOException.

Custom Checked Exceptions

We can create custom(user defined) checked exceptions by extends Exception class.

class should contain default and one parametrized constructor with String.

public class MyCheckedException extends Exception {

//Default constructor

public MyCheckedException() {

//Parameterized constructor with String

public MyCheckedException(String msg) {

super(msg);

Ex:

public class CheckedExceptionTest {

public static void main(String[] args) {

CheckedExceptionTest test = new CheckedExceptionTest();

try {

test.numberCheck(-1);

} catch (MyCheckedException e) {

System.out.println("Exception says: "+e.getMessage());

public boolean numberCheck(int number) throws MyCheckedException{

if(number < 0)

throw new MyCheckedException("Negative values not allowed!!");

return true;
}

Output:

Exception says: Negative values not allowed!!

Custom Unchecked Exceptions

We can create custom(user-defined) unchecked exceptions by extends RuntimeException class.

class should contain default and one parametrized constructor with String.

public class MyOwnUncheckedException extends RuntimeException {

//Default constructor

MyOwnUncheckedException(){

//Parametrized constructor with String

MyOwnUncheckedException(String msg) {

super(msg);

Ex:

public class UncheckedTest {

public static void main(String[] args) {

UncheckedTest test = new UncheckedTest();

try {

test.numberCheck(-1);

} catch (MyOwnUncheckedException e) {

System.out.println("Exception says: " + e.getMessage());

public boolean numberCheck(int number) {


if (number < 0)

throw new MyOwnUncheckedException("Negative values not allowed!!");

return true;

Output : Exception says: Negative values not allowed!!

throw, throws keywords

throw:

 throw is a keyword, that can be used to throw user defined exceptions.


 throw keyword is used to throw exceptions explicitly.
 Using throws keyword we can throw predefined exceptions as well as user defined but it is
always recommended to throw user defined exceptions.

Example:

1
public class ThrowTest {
2
public boolean numberCheck(int number) {
3
if(number < 0)
4
throw new ArithmeticException("No negatives allowed!!");
5
return true;
6
}
7
public static void main(String[] args) {
8
ThrowTest test = new ThrowTest();
9
try {
10
test.numberCheck(-1);
11
} catch (ArithmeticException e) {
12
System.out.println("Exception says: "+e.getMessage());
13
}
14
}
15
}
16

Output: Exception says: No negatives allowed!!


 In the above example, we have specified ArithmeticException object reference with the „throw„
statement and hence we have thrown the ArithmeticException explicitly if the number is
negative.
 Also we have specified our own message within throw statement that is to be displayed in the
console

throws:

 throws is a keyword which is used to throw an exception. If programmer doesn‟t want to handle
any exception caused by a method, then programmer can throw the exception by
using throws keyword so that the exception will be handled by the method caller or the JVM.
 throws keyword is used at method level.
 If a method contains statements causing any exceptions then the method should specify all the
possible exceptions to the caller of that method.

Example:

1 import java.io.FileInputStream;

2 import java.io.IOException;

4 public class ThrowsExample {

5 public static void main(String[] args) throws FileNotFoundException,IOException{

6 FileInputStream fis = new FileInputStream("fileName");

7 int character;

8 while ((character = fis.read()) != -1) {

9 System.out.print(character);

10 }

11 }

12 }

In the above program FileInputStream is throwing FileNotFoundException and IOException. So we are


not handling these exceptions in our example program, instead we are simply throwing that exception
in the method declaration itself by using throws keyword.

This main() method is called by JVM. So JVM itself is responsible to handle this exception.

Nested try Blocks

Writing try block inside another try block is known as nested try block.

Ex:

public class NestedTryTest {

public static void main(String[] args) {


int array[] = new int[10];

try {

try {

array[10] = 10;

} catch (ArrayIndexOutOfBoundsException e) {

e.printStackTrace();

try {

int x= 10/0;

} catch (ArithmeticException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

Output:

java.lang.ArrayIndexOutOfBoundsException: 10
at com.exception.NestedTryTest.main(NestedTryTest.java:10)
java.lang.ArithmeticException: / by zero
at com.exception.NestedTryTest.main(NestedTryTest.java:17)

finally Block

 The statements inside the finally block always gets executed, regardless whether an exception is
occurred or not in a try block.
 Even though there is a return statement in the try or catch block, the code inside the finally
block gets executed before completion of the method execution
 finally block is used to close the resources like database connections, files, and JMS connections
 finally block statements always gets executed regardless of whatever happens in the try block.
So it is suggestible to keep all the cleanup code in the finally block

Example:

package com.test;
public class FinallyTest {

public static void main(String[] args) {

int result =0;

//first case

try {

result = 252/0;

} catch (ArithmeticException e){

System.out.println("inside catch (ArithmeticException e)");

} catch (Exception e) {

System.out.println("inside catch (Exception e)");

e.printStackTrace();

} finally {

System.out.println("inside Finally Block");

System.out.println("result: "+result);

//second case

try {

result = 252/2;

} catch (Exception e) {

e.printStackTrace();

}finally {

System.out.println("No Problem here!!");

System.out.println("result: "+result);

System.out.println("Leaving Now!!");

Output:

inside catch (ArithmeticException e)


inside Finally Block
result: 0
No Problem here!!
result: 126
Leaving Now!!

In the first case of the above example, ArithmeticException had been occurred while
dividing by zero. Since it is ArithmeticException, its own catch block [catch (ArithmeticException e)] got
executed and printed the message in console. Then the control has executed the print statement
written within the finally block

 In the second case, even though there is no any exception occurred in the try block, finally
block had been executed

Collection:

Arrays also used to store the group of objects. But arrays size are fixed, That means the size of the
arrays can not be changed once they are created. This causes lot of problems while handling group of
objects. To overcome this problems java has introduced Collection framework

What is Collection?

 Collection represents a group of objects as a single entity


 Collection exists in java.util package
 Collection is used to store, retrieve and manipulate the group of objects
 Collection provides set of classes and interfaces that implements data structures

Difference between array and Collection

Array Collection

Arrays are fixed size, You can not change the size of the

arrays once they are created Collection are growable in nature

Performance point of view arrays is highly recommended Performance point of view collection is

to use not recommended to use

Collection can hold both homogeneous

Arrays can hold only homogeneous type of elements and heterogeneous type of elements

Arrays can be used to store both primitive values and collection can be used to store only

objects objects but not primitive values

Underlying data structure is available

There is no underlying data structure for arrays for every collection class
Collection Hierarchy :

Collection:

As in the above diagram the root of the collection hierarchy is Collection interface. A collection
represents a group of objects known as its elements.Collection interface has the below stated methods.

List:

List is a child interface of Collection


Insertion order is preserved in List
List allows duplicates elements

Implementation classes of List interface:

 ArrayList
 LinkedList
 Vector

Set: Set is a child interface of Collection


Insertion order is not preserved in Set
Set doesn‟t allow duplicates elements
Implementation classes of Set interface:

 HashSet
 LinkedHashSet
 TreeSet
 CopyOnWriteArraySet
 EnumSet

SortedSet:

SortedSet is a child interface of Set


SortedSet stores the elements in sorting order
SortedSet doesn‟t allow duplicates elements

Implementation classes of SortedSet interface:

 TreeSet

NavigableSet:

NavigableSet is a child interface of SortedSet


NavigableSet provided several methods for navigation purposes
NavigableSet introduced in java 1.6 version
NavigableSet doesn‟t allow duplicates elements

Implementation classes of NavigableSet interface:

 TreeSet

Queue:

Queue is a child interface of Collection


Queue orders the elements in a FIFO (first-in, first-out) order, Always the first element is removed first
and last element is removed at last.

Implementation classes of Queue interface:

 LinkedList
 PriorityQueue
 ArrayDeque

List, Set, SortedSet, NavigableSet and Queue is used to store a group of individual objects.
If we want to store a group of objects as a key-value pair then we should go for Map

Map:

Map interface is used to store a group of objects as a key-value pair


Both key and value are objects
Map doesn‟t allow duplicate keys but values can be duplicated

Note: Map is not child interface of Collection

Implementation classes of Map interface:

 HashMap
 Hashtable
 TreeMap
 IdentityHashMap
 LinkedHashMap
 ConcurrentHashMap
 EnumMap
 WeakHashMap
 Properties

SortedMap:

SortedMap is a child interface of Map


SortedMap interface stores the key-value pair in sorting order, Sorting done by only based on key but
not value.
Both key and value are objects
SortedMap doesn‟t allow duplicate keys but values can be duplicated

Implementation classes of SortedMap interface:

 TreeMap

NavigableMap:

NavigableMap is a child interface of SortedMap


NavigableMap provided several methods for navigation purposes
NavigableMap introduced in java 1.6 version
NavigableMap doesn‟t allow duplicate keys but values can be duplicated

Implementation classes of NavigableMap interface:

 TreeMap

Collection API:

Collection interface contains the most common methods which can be applied for any collection object
List contains the following methods.

Methods :

boolean add(E e):


Ensures that this collection contains the specified element .

boolean addAll(Collection<? extends E> c):


Adds all of the elements in the specified collection to this collection .

void clear():
Removes all of the elements from this collection .

boolean contains(Object o):


Returns true if this collection contains the specified element.

boolean containsAll(Collection<?> c):


Returns true if this collection contains all of the elements in the specified collection.

boolean equals(Object o):


Compares the specified object with this collection for equality.
int hashCode():
Returns the hash code value for this collection.

boolean isEmpty():
Returns true if this collection contains no elements.

Iterator iterator():
Returns an iterator over the elements in this collection.

boolean remove(Object o):


Removes a single instance of the specified element from this collection, if it is present.

boolean removeAll(Collection<?> c):


Removes all of this collection‟s elements that are also contained in the specified collection .

boolean retainAll(Collection<?> c):


Retains only the elements in this collection that are contained in the specified collection .

int size():
Returns the number of elements in this collection.

Object[] toArray():
Returns an array containing all of the elements in this collection.

<T> T[] toArray(T[] a):


Returns an array containing all of the elements in this collection; the runtime type of the returned
array is that of the specified array.

Iterators in java

There are 4 ways to retrieve the elements from the collection

1. Iterator
2. ListIterator
3. Enumeration
4. for-each

Iterator

Iterator is an interface. By using iterator we can retrieve the elements one by one from the collection.

Methods in Iterator:
boolean hasNext() :
Returns true if the iteration has more elements.

elementNext():
This method returns the next element in the iterator.

void remove():

Removes from the underlying collection the last element returned by this iterator.

ListIterator

ListIterator is an interface.
By using ListIterator we can retrieve the elements from the list , both forward and reverse direction.
Methods in ListIterator:
void add(E e):
Inserts the specified element into the list

boolean hasNext() :
Returns true if this list iterator has more elements when traversing the list in the forward direction.

boolean hasPrevious():
Returns true if this list iterator has more elements when traversing the list in the reverse direction.

element next():
Returns the next element in the list and advances the cursor position.

int nextIndex():
Returns the index of the element that would be returned by a subsequent call to next().

element previous():
Returns the previous element in the list and moves the cursor position backwards.

int previousIndex():
Returns the index of the element that would be returned by a subsequent call to previous().

void remove():
Removes from the list the last element that was returned by next() or previous()

void set(E e):


Replaces the last element returned by next() or previous() with the specified element

Enumeration

Enumeration is an interface.
By using enumeration interface we retrieve the elements from the collection one by one like itertor.But
enumeration normally we are using to iterate over legacy collection(Vector).

Methods:
boolean hasMoreElements():
Tests if this enumeration contains more elements.

element nextElement():
Returns the next element of this enumeration if this enumeration object has at least one more element
to provide.

For-each Loop

for-each loop is like for loop which repeatedly executes a group of statements for each element of the
collection.

Format:

1 for(variable : collection-object)

2 {

3 Group of statements

4 }
Generics

This feature introduced in JDK 5 to write type safe programs.

Before JDK 5 we can store any type of objects in non-generic collection

From JDK 5 compiler will forces the programmer to store specific type of objects in generic collection.

Advantages with Generics

 It allows to write type safe program.


 Doesn‟t required typecasting
 We can avoid ClassCastException

Syntax

ClassName&ltReferenceDataType&gt ref = new ClassName&ltReferenceDataType&gt();

Examples :

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

public class GenericsEx {

public static void main(String[] args) {

List list=new ArrayList();

list.add(2);

list.add(8);

list.add("Apple");

Iterator it=list.iterator();

while (it.hasNext()) {

int i = (Integer) it.next();

System.out.println(num);

Output:

2
8
Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Integer at com.core.GenericsEx.main(GenericsEx.java:18)

In the above program we have added string and integer objects to the list , but while iterating we are
typecasting to integer. string can‟t be typecasted to integer. So we are getting ClassCastException
here.

Below program is an example using Generics.

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

public class GenericsEx {

public static void main(String[] args) {

List<Integer> list=new ArrayList<Integer>();

list.add(2);

list.add(8);

list.add(4);

list.add(1);

Iterator<Integer> iterator = list.iterator();

while (iterator.hasNext()) {

Integer num = (Integer) iterator.next();

System.out.println(num);

Output:

2
8
4
1

ArrayList in java

 ArrayList implements List interface


 ArrayList is non-synchronized.
 ArrayList internally stores elements in growable array
 ArrayList allows duplicate elements
 ArrayList allows null values
 ArrayList maintains insertion order
 In case of search operations ArrayList is faster because it is index based and it‟s implementing
RandomAccess interface
 ArrayList default storing capacity is 10
 ArrayList storing capacity will be increased by half of it‟s original storing capacity when the
current storing capacity reaches to maximum
 Insertion or deletion operations in mid of ArrayList is slow, Because it needs to shift the
elements
 ArrayList supports Iterator and ListIterator
 The underlying data structure for ArrayList is resizable array or growble array
 ArrayList can be synchronized by using Collections.synchronizedList(List list) method

ArrayList class contains the following constructors and methods

Constructors :

ArrayList(): Constructs an empty list with an initial default capacity of ten.


Ex.

1 ArrayList list = new ArrayList();

ArrayList(Collection<? extends E> c): Constructs a list containing the elements of the specified
collection, in the order they are returned by the collection‟s iterator.

1 ArrayList list=new ArrayList(Any implementation class of Collection interface);

ArrayList(int initialCapacity): Constructs an empty list with the specified initial capacity.
Ex.

1 ArrayList list=new ArrayList(16);

Methods:

Method Description

boolean add(E e) Appends the specified element to the end of this list.

Inserts the specified element at the specified

void add(int index, E element) position in this list.

Appends all of the elements in the specified

collection to the end of this list, in the order that

they are returned by the specified collection‟s

boolean addAll(Collection<? extends E> c): Iterator.

boolean addAll(int index, Collection<? Inserts all of the elements in the specified collection
extends E> c): into this list, starting at the specified position.

void clear(): Removes all of the elements from this list.

Object clone(): Returns a shallow copy of this ArrayList instance.

Returns true if this list contains the specified

boolean contains(Object o): element.

Increases the capacity of this ArrayList instance, if

necessary, to ensure that it can hold at least the

number of elements specified by the minimum

capacity argument.
void ensureCapacity(int minCapacity):

Returns the element at the specified position in this

Element get(int index): list.

Returns the index of the first occurrence of the

specified element in this list, or -1 if this list does

not contain the element.


int indexOf(Object o):

Returns true if this list contains no elements.


boolean isEmpty():

Returns an iterator over the elements in this list in

proper sequence.
Iterator iterator():

Returns the index of the last occurrence of the

specified element in this list, or -1 if this list does

not contain the element.


int lastIndexOf(Object o):

Returns a list iterator over the elements in this list

(in proper sequence).


ListIterator listIterator():

Returns a list iterator over the elements in this list

(in proper sequence), starting at the specified

position in the list.


ListIterator listIterator(int index):

element remove(int index): Removes the element at the specified position in


this list.

Removes the first occurrence of the specified

element from this list, if it is present.


boolean remove(Object o):

Removes from this list all of its elements that are

contained in the specified collection.


boolean removeAll(Collection<?> c):

Removes from this list all of the elements whose

index is between fromIndex, inclusive, and toIndex,


void removeRange(int fromIndex, int
exclusive.
toIndex):

Retains only the elements in this list that are

contained in the specified collection.


boolean retainAll(Collection<?> c):

Replaces the element at the specified position in this

list with the specified element.


element set(int index, E element):

Returns the number of elements in this list.


Int size():

Returns a view of the portion of this list between the

specified fromIndex, inclusive, and toIndex,

exclusive.
List subList(int fromIndex, int toIndex):

Returns an array containing all of the elements in

this list in proper sequence (from first to last

element).
Object[] toArray():

Trims the capacity of this ArrayList instance to be

the list‟s current size.


void trimToSize():

Example program for adding elements to the ArrayList

1 import java.util.ArrayList;

2 public class AddingtoArrayList {

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

4 ArrayList list = new ArrayList();


5 list.add("hello");

6 list.add("ok");

7 list.add("bye");

8 System.out.println(list);

Output : [hello, ok, bye]

Different Ways Of Iterating An ArrayList

ArrayList can iterate in multiple ways

 Using for loop


 Using Iterator
 Using ListIterator
 Using for-each(Enhanced for loop)

Iterating ArrayList using for loop

import java.util.ArrayList;

public class ForLoopEx {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

list.add(5);

list.add(4);

1 list.add(8);

list.add(10);

list.add(12);

for (int i = 0; i < list.size(); i++) {

System.out.println(list.get(i));

Output :

5
4
8
10
12

Iterating ArrayList using Iterator

import java.util.ArrayList;

import java.util.Iterator;

public class Main {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

list.add(5);

list.add(4);

list.add(8);

list.add(10);

list.add(12);

//list.iterator() method return Iterator object

Iterator<Integer> iterator = list.iterator();

while (iterator.hasNext()) {

int i = iterator.next();

System.out.println(i);

Output :

5
4
8
10
12

Iterating ArrayList using ListIterator

import java.util.ArrayList;

import java.util.ListIterator;

public class Main {

public static void main(String[] args) {


ArrayList<Integer> list = new ArrayList<>();

list.add(5);

list.add(4);

list.add(8);

list.add(10);

list.add(12);

ListIterator<Integer> listIterator = list.listIterator();

System.out.println("Iterating forward direction: ");

while (listIterator.hasNext()) {

int i = listIterator.next();

System.out.println(i);

System.out.println("Iterating backward direction: ");

while (listIterator.hasPrevious()) {

int i = listIterator.previous();

System.out.println(i);

Output:

Iterating forward direction:


5
4
8
10
12
Iterating backward direction:
12
10
8
4
5

Iterating ArrayList using For-each loop

import java.util.ArrayList;
public class Main {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

list.add(5);

list.add(4);

list.add(8);

list.add(10);

list.add(12);

for (int i : list) {

System.out.println(i);

Output:

5
4
8
10
12

Iterating custom objects ArrayList

Iterating custom(Uesr-defined) objects ArrayList

public class Employee {

private String name;

private int empId;

public Employee(String name, int empId) {

this.name = name;

this.empId = empId;

public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

public int getEmpId() {

return empId;

public void setEmpId(int empId) {

this.empId = empId;

Iterating ArrayList using for-each loop

Main.java

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

Employee employee1 = new Employee("Krish", 173);

Employee employee2 = new Employee("Ram", 174);

Employee employee3 = new Employee("sachin", 175);

ArrayList<Employee> list = new ArrayList<>();

list.add(employee1);

list.add(employee2);

list.add(employee3);

for (Employee emp : list) {

System.out.println(emp.getEmpId() + " " + emp.getName());

Output :
173 Krish
174 Ram
175 sachin

Iterating ArrayList using Iterator

Main.java

import java.util.ArrayList;

import java.util.Iterator;

public class Main {

public static void main(String[] args) {

Employee employee1 = new Employee("Krish", 173);

Employee employee2 = new Employee("Ram", 174);

Employee employee3 = new Employee("sachin", 175);

ArrayList<Employee> list = new ArrayList<>();

list.add(employee1);

list.add(employee2);

list.add(employee3);

Iterator<Employee> iterator = list.iterator();

while (iterator.hasNext()) {

Employee employee = iterator.next();

System.out.println(employee.getEmpId()+" "+employee.getName()); }

Output:

173 Krish
174 Ram
175 sachin

ArrayList Programming Interview Questions

package com.mypackage;

import java.util.ArrayList;

import java.util.Collections;
import java.util.Iterator;

import java.util.List;

public class ListEx {

public static void main(String[] args) {

List<Integer> list = new ArrayList<>();

list.add(5);

list.add(2);

list.add(8);

list.add(4);

Iterator<Integer> iterator = list.iterator();

Collections.reverse(list);

Collections.sort(list);

while (iterator.hasNext()) {

int i = iterator.next();

System.out.println(i);

Output:

Exception in thread “main” java.util.ConcurrentModificationException


at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at com.mypackage.ListEx.main(ListEx.java:21)

Vector in java

 Vector stores elements in growable array like ArrayList


 Vector is an implementation class of List interface
 Vector is a legacy class
 Vector maintains insertion order
 Vector is synchronized
 Vector default capacity is 10
 Vector allows duplicate elements
 Vector allows null values
 In case of search operations Vector is faster because it is index based and it‟s implementing
RandomAccess interface
 Vector storing capacity will be increased by double of it‟s original storing capacity when the
current storing capacity reaches to maximum
 Vector supports Enumerator, Iterator and ListIterator
Vector class contains the following constructors and methods

Vector Constructors

Vector(): It creates a vector object with empty content


Ex:

1 Vector v= new vector();

Vector(Collection<? extends E> c) : It creates a vector object with specified collection


Ex:

1 ArrayList list = new ArrayList();

2 list.add(“apple”);

3 Vector v = new Vector(list);

Vector(int initialCapacity) : It creates a vector object with empty content with the given initial
capacity.
Ex:

1 Vector v= new Vector(15);

Vector(int initialCapacity, int capacityIncrement): It creates a vector object with empty content
with the given initial capacity and capacity increment.
Ex:

1 Vector v= new Vector(15, 5);

Methods:

Method Description

Appends the specified element to the end of this

boolean add(E e): Vector

Inserts the specified element at the specified

void add(int index, E element): position in this Vector

Appends all of the elements in the specified

Collection to the end of this Vector, in the order that

they are

boolean addAll(Collection<? extends E> c): returned by the specified Collection‟s Iterator
boolean addAll(int index, Collection<? Inserts all of the elements in the specified Collection

extends E> c): into this Vector at the specified position

Adds the specified component to the end of this

void addElement(E obj): vector, increasing its size by one

int capacity(): Returns the current capacity of this vector

void clear(): Removes all of the elements from this Vector

Object clone(): Returns a clone of this vector

Returns true if this vector contains the specified

boolean contains(Object o): element

Returns true if this Vector contains all of the

boolean containsAll(Collection<?> c): elements in the specified Collection

Copies the components of this vector into the

void copyInto(Object[] anArray): specified array

Element elementAt(int index): Returns the component at the specified index.

Returns an enumeration of the components of this

Enumeration elements(): vector.

Increases the capacity of this vector, if necessary, to

ensure that it can hold at least the number of

components specified by the minimum capacity

void ensureCapacity(int minCapacity): argument.

Compares the specified Object with this Vector for

boolean equals(Object o): equality.

Returns the first component (the item at index 0) of

element firstElement(): this vector.

element get(int index):


Returns the element at the specified position in this
Vector.

Int hashCode(): Returns the hash code value for this Vector.

Returns the index of the first occurrence of the

specified element in this vector, or -1 if this vector

Int indexOf(Object o): does not contain the element.

Returns the index of the first occurrence of the

specified element in this vector, searching forwards

int indexOf(Object o, int index): from index, or returns -1 if the element is not found.

Inserts the specified object as a component in this

void insertElementAt(E obj, int index): vector at the specified index.

boolean isEmpty(): Tests if this vector has no components.

Returns an iterator over the elements in this list in

Iterator iterator(): proper sequence.

element lastElement(): Returns the last component of the vector.

Returns the index of the last occurrence of the

specified element in this vector, or -1 if this vector

int lastIndexOf(Object o): does not contain the element.

Returns the index of the last occurrence of the

specified element in this vector, searching

backwards from index, or returns -1 if the element

int lastIndexOf(Object o, int index): is not found.

Returns a list iterator over the elements in this list

ListIterator listIterator(): (in proper sequence).

Returns a list iterator over the elements in this list

(in proper sequence), starting at the specified

ListIterator listIterator(int index): position in the list.


Removes the element at the specified position in this

element remove(int index): Vector.

Removes the first occurrence of the specified

element in this Vector If the Vector does not contain

boolean remove(Object o): the element, it is unchanged.

Removes from this Vector all of its elements that are

boolean removeAll(Collection<?> c): contained in the specified Collection.

Removes all components from this vector and sets

void removeAllElements(): its size to zero.

Removes the first (lowest-indexed) occurrence of

boolean removeElement(Object obj): the argument from this vector.

void removeElementAt(int index): Deletes the component at the specified index.

Removes from this list all of the elements whose

void removeRange(int fromIndex, int index is between fromIndex, inclusive, and toIndex,

toIndex): exclusive.

Retains only the elements in this Vector that are

boolean retainAll(Collection<?> c): contained in the specified Collection.

Replaces the element at the specified position in this

element set(int index, E element): Vector with the specified element.

Sets the component at the specified index of this

void setElementAt(E obj, int index): vector to be the specified object.

void setSize(int newSize): Sets the size of this vector.

int size(): Returns the number of components in this vector.

Returns a view of the portion of this List between

List subList(int fromIndex, int toIndex): fromIndex, inclusive, and toIndex, exclusive.
Returns an array containing all of the elements in

Object[] toArray(): this Vector in the correct order.

Returns a string representation of this Vector,

containing the String representation of each

String toString(): element.

Trims the capacity of this vector to be the vector‟s

void trimToSize(): current size.

Ex:

1 import java.util.Vector;

2 public class VectorEx {

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

4 Vector<String> list = new Vector<>();

5 list.add("hello");

6 list.add("ok");

7 list.add("bye");

8 System.out.println(list);

9 }

10 }

Output: [hello, ok, bye]

Vector Programs

Below is the program to add and retrieve elements from a vector

1 import java.util.Enumeration;

2 import java.util.Vector;

4 public class VectorEx {

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


6 Vector<String> vector = new Vector<>();

7 vector.add("Apple");

8 vector.add("Orange");

9 vector.add("Banana");

10 Enumeration<String> e = vector.elements();

11 while (e.hasMoreElements()) {

12 String fruit = e.nextElement();

13 System.out.println(fruit);

14 }

Output:

3
Apple
Orange
Banana

Below is the program to perform some operations on Vector

1 import java.util.Enumeration;

2 import java.util.Vector;

3 public class VectorEx {

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

5 Vector<String> vector = new Vector<>();

6 vector.add("Apple");

7 vector.add("Orange");

8 vector.add("Banana");

9 System.out.println(vector.size());

10 System.out.println(vector.contains("Orange"));

11 System.out.println(vector.elementAt(1));

12 System.out.println(vector.firstElement());

13 System.out.println(vector.get(0));
14 System.out.println(vector.isEmpty());

15 }

16 }

17

Output :

3
true
Orange
Apple
Apple
false

LinkedList

 LinkedList implements both List and Deque interfaces


 LinkedList is non-synchronized
 LinkedList allows both null values and duplicates
 LinkedList stores elements in the form of nodes.
 LinkedList internally follows double linkedlist data structure to store elements.
 Each node contains 3 fields. mid Field contains data, right and left Fields contains references to
previous and next nodes [refer the below
diagram]

 In case of inserting or deleting elements in between the collection, LinkedList is faster then
ArrayList because it performs these operations without any shifting, By simply updating the
previous and next nodes of the elements
 LinkedList supports Iterator and ListIterator.

What s single LinkedList?

In single LinkedList the node consists of only two fields one is data field another one is the reference to
next node.

What is Double LinkedList?

In double LinkedList the node has three fields, first field reference to the previous node , second field
value of the element and third field reference to the next node.

LinkedList class contains the following constructors and methods

Constructors:

LinkedList() : Constructs an empty list.


Ex: LinkedList ll= new LinkedList ();
LinkedList(Collection<? extends E> c): Constructs a list containing the elements of the specified
collection, in the order they are returned by the collection‟s iterator.
Ex:

1 ArrayList arl= new ArrayList ();

2 arl.add(“Apple”);

3 arl.add(“Orange”);

4 LinkedList ll= new LinkedList (arl);

Methods:

Method: Description

boolean add(E e): Appends the specified element to the end of this list.

Inserts the specified element at the specified position in this

void add(int index, E element): list.

Appends all of the elements in the specified collection to the

boolean addAll(Collection<? end of this list, in the order that they are returned by the

extends E> c): specified collection‟s iterator.

boolean addAll(int index, Inserts all of the elements in the specified collection into this

Collection<? extends E> c): list, starting at the specified position.

void addFirst(E e): Inserts the specified element at the beginning of this list.

void addLast(E e): Appends the specified element to the end of this list.

void clear(): Removes all of the elements from this list.

Object clone(): Returns a shallow copy of this LinkedList.

boolean contains(Object o): Returns true if this list contains the specified element.

Returns an iterator over the elements in this deque in

Iterator descendingIterator(): reverse sequential order.

element element():
Retrieves, but does not remove, the head (first element) of
this list.

element get(int index): Returns the element at the specified position in this list.

element getFirst(): Returns the first element in this list.

element getLast(): Returns the last element in this list.

Returns the index of the first occurrence of the specified

element in this list, or -1 if this list does not contain the

int indexOf(Object o): element.

Returns the index of the last occurrence of the specified

element in this list, or -1 if this list does not contain the

Int lastIndexOf(Object o): element.

ListIterator listIterator(int Returns a list-iterator of the elements in this list (in proper

index): sequence), starting at the specified position in the list.

Adds the specified element as the tail (last element) of this

boolean offer(E e): list.

boolean offerFirst(E e): Inserts the specified element at the front of this list.

boolean offerLast(E e): Inserts the specified element at the end of this list.

Retrieves, but does not remove, the head (first element) of

element peek(): this list.

Retrieves, but does not remove, the first element of this list,

element peekFirst(): or returns null if this list is empty.

Retrieves, but does not remove, the last element of this list,

element peekLast(): or returns null if this list is empty.

element poll(): Retrieves and removes the head (first element) of this list.

element pollFirst():
Retrieves and removes the first element of this list, or
returns null if this list is empty.

Retrieves and removes the last element of this list, or returns

element pollLast(): null if this list is empty.

element pop(): Pops an element from the stack represented by this list.

void push(E e): Pushes an element onto the stack represented by this list.

element remove(): Retrieves and removes the head (first element) of this list.

element remove(int index): Removes the element at the specified position in this list.

Removes the first occurrence of the specified element from

boolean remove(Object o): this list, if it is present.

element removeFirst(): Removes and returns the first element from this list.

boolean Removes the first occurrence of the specified element in this

removeFirstOccurrence(Object o): list (when traversing the list from head to tail).

element removeLast(): Removes and returns the last element from this list.

boolean Removes the last occurrence of the specified element in this

removeLastOccurrence(Object o): list (when traversing the list from head to tail).

Replaces the element at the specified position in this list with

element set(int index, E element): the specified element.

int size(): Returns the number of elements in this list.

Returns an array containing all of the elements in this list in

Object[] toArray(): proper sequence (from first to last element).

Below is the program to add elements and do some operations on a LinkedList

1 import java.util.Iterator;

2 import java.util.LinkedList;

3 public class LinkedListEx {


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

5 LinkedList ll = new LinkedList();

6 ll.add("Apple");

7 ll.add("Mango");

8 ll.add("Banana");

9 System.out.println(ll.get(0));

10 System.out.println(ll.getFirst());

11 System.out.println(ll.getLast());

12 System.out.println(ll.contains("Mango"));

13 System.out.println(ll.size());

14 System.out.println(ll.subList(1, 2));

Output:

Apple
Apple
Banana
true
3
[Mango]

HashSet

 HashSet implements Set interface


 HashSet doesn‟t allow duplicates elements
 If we try to insert duplicate elements, it won‟t throw any exception but HashSet treat as
duplicate and return only one element
 HashSet is non-synchronized
 HashSet is an unordered collection, which means whatever the order we have inserted, we
won‟t get the same order at time of retrieval, Because elements are stored based on hash value
 HashSet internally uses equals() and hashcode() methods to find the duplicates
 HashSet allows one null element , if we insert more null elements it will consider as a duplicate
and results only one null element
 We can explicitly synchronized HashSet by using Collections.synchronizedSet(Set set)
 HashSet internally uses HashMap [The object we have inserted into the HashSet that will put in
the HashMap as a key and the value is a dummy object (private static final Object PRESENT =
new Object()) ] to store the elements.
 HashSet doesn‟t have any method provided to retrieve the object based on the index
 HashSet supports Iterator
 HashSet has default capacity 16 and load factor 0.75
 Load factor specifies the point where exactly the capacity of HashSet should increased
For example, the product of capacity and load factor is 16*0.75=12. This means after storing
the 12th element into the HashSet its capacity will be internally increased to insert more
elements
HashSet class contains the following constructors and methods:

Constructors:

HashSet(): It creates a new HashSet object with empty content


Ex: HashSet hs= new HashSet();

HashSet(Collection<? extends E> c): It creates a new HashSet object with the specified collection.
Ex:

1 ArrayList list= new ArrayList ();

2 list.add(“Apple”);

3 list.add(“Grape”);

4 HashSet hs= new HashSet (arl);

HashSet(int initialCapacity): It creates a new HashSet object with the specified initial capacity and
default load factor (0.75).
Ex: HashSet hs=new HashSet (12);

HashSet(int initialCapacity, float loadFactor): Constructs it creates a new HashSet object with the
specified initial capacity and the specified load factor.
Ex:

1 HashSet hs=new HashSet(12, 0.5);

Methods

Method Description

Adds the specified element to this set if it is not

boolean add(E e): already present.

void clear(): Removes all of the elements from this set.

Object clone(): Returns a shallow copy of this HashSet instance

Returns true if this set contains the specified

boolean contains(Object o): element.

boolean isEmpty(): Returns true if this set contains no elements.

Iterator iterator(): Returns an iterator over the elements in this set.


Removes the specified element from this set if it is

boolean remove(Object o): present.

Returns the number of elements in this set (its

int size(): cardinality).

Ex:

import java.util.HashSet;

public class HashSetEx {

public static void main(String[] args) {

HashSet<String> hashSet = new HashSet<>();

hashSet.add("hello");

hashSet.add("ok");

hashSet.add("bye");

System.out.println(hashSet);

Output : [hello, ok, bye]

HashSet Programs

Below is the program to add elements and iterating the HashSet using for-each-loop

import java.util.HashSet;

public class HashSetEx {

public static void main(String[] args) {

HashSet<String> hSet = new HashSet<>();

hSet.add("Maruthi");

hSet.add("Audi");

hSet.add("BMW");

hSet.add("Maruthi");

for (String carModel : hSet) {


System.out.println(carModel);

Output:

3
Audi
BMW
Maruthi

Below is the program to perform some operations on a HashSet

1 import java.util.HashSet;

2 import java.util.Iterator;

3 public class HashSetEx {

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

5 HashSet<String> hSet = new HashSet<>();

6 hSet.add("Maruthi");

7 hSet.add("Audi");

8 hSet.add("BMW");

9 hSet.add("Maruthi");

10 System.out.println(hSet.size());

11 System.out.println(hSet.contains("Audi"));

12 System.out.println(hSet.isEmpty());

13 //iterating using Iterator

14 Iterator iterate = hSet.iterator();

15 while(iterate.hasNext()){

16 String car=(String) iterate.next();

17 System.out.println(car);

18 }

19 //iterating using enhanced for-loop

20 for(String s : hSet)

21 {
22 System.out.println(s);

Output:

3
true
false
Audi
BMW
Maruthi

LinkedHashSet

 LinkedHashSet is similar like HashSet but only difference is it follows the insertion order
 It implements Set interface
 LinkedHashSet doesn‟t allow duplicate elements but it allows null values
 It supports Iterator
 It internally uses LinkedHashMap [The object we have inserted into the LinkedHashSet that will
put in the LinkedHashMap as a key and the value is a dummy object (private static final Object
PRESENT = new Object())]
 Default initial capacity 16 and load factor 0.75

LinkedHashSet class contains the following constructors and methods

Constructors:

LinkedHashSet(): Constructs a new, empty linked hash set with the default initial capacity (16) and
load factor (0.75)
Ex:

1 HashSet hs= new HashSet();

LinkedHashSet(Collection<? extends E> c): Constructs a new linked hash set with the same
elements as the specified collection.
Ex:

1 ArrayList list= new ArrayList ();

2 list.add(“Apple”);

3 list.add(“Grape”);

4 HashSet hs= new HashSet (arl);

LinkedHashSet(int initialCapacity): Constructs a new, empty linked hash set with the specified
initial capacity and the default load factor (0.75)
Ex:
1 LinkedHashSet hs=new LinkedHashSet (12);

LinkedHashSet(int initialCapacity, float loadFactor): Constructs a new, empty linked hash set
with the specified initial capacity and load factor
Ex:

1 LinkedHashSet hs=new LinkedHashSet (12, 0.5);

Methods:

Method Description

boolean add(E e): Adds the specified element to this set if it is not already present

void clear(): Removes all of the elements from this set

Returns a shallow copy of this LinkedHashSet instance: the elements

Object clone(): themselves are not cloned

boolean contains(Object

o): Returns true if this set contains the specified element

boolean isEmpty(): Returns true if this set contains no elements

Iterator iterator(): Returns an iterator over the elements in this set

boolean remove(Object

o): Removes the specified element from this set if it is present

int size(): Returns the number of elements in this set (its cardinality)

Example:

Below is the program performing some operations on LinkedHashSet

1 import java.util.Iterator;

2 import java.util.LinkedHashSet;

3 public class LinkedHashSetEx {

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

5 LinkedHashSet lhs = new LinkedHashSet();


6 lhs.add("Maruthi");

7 lhs.add("Audi");

8 lhs.add("BMW");

9 lhs.add("Maruthi");

10 System.out.println(lhs.size());

11 System.out.println(lhs.contains("Audi"));

12 System.out.println(lhs.isEmpty());

13 Iterator it= lhs.iterator();

14 while(it.hasNext()){

15 String car=(String) it.next();

16 System.out.println(car);

17 }

18 }

Output :

3
true
false
Maruthi
Audi
BMW

TreeSet

 TreeSet implements SortedSet interface


 TreeSet exists in java.util package
 TreeSet stores elements in ascending order
 TreesSet doesn‟t allow duplicate elements
 TreesSet doesn‟t allow null values
 TreeSet is non-synchronized
 If we want to add customized objects to TreeSet, That customized object class should
implements Comparableor Comparator interface

TreeSet class contains the following constructors and methods

Constructors:

TreeSet(): Creates a new, empty tree set, sorted according to the natural ordering of its elements.

TreeSet(Collection c): Creates a new tree set containing the elements in the specified collection,
sorted according to the natural ordering of its elements.
TreeSet(Comparator comparator): Creates a new, empty tree set, sorted according to the specified
comparator.

TreeSet(SortedSet s): Creates a new tree set containing the same elements and using the same
ordering as the specified sorted set.

Methods:

Method Description

Adds the specified element to this set if it is not

boolean add(E e): already present.

boolean addAll(Collection<? extends E> Adds all of the elements in the specified collection to

c): this set.

void clear(): Removes all of the elements from this set.

Object clone(): Returns a shallow copy of this TreeSet instance.

Returns true if this set contains the specified

boolean contains(Object o): element.

Returns the first (lowest) element currently in this

element first(): set

Returns the least element in this set strictly greater

than the given element, or null if there is no such

element higher(element e): elemen

boolean isEmpty(): Returns true if this set contains no elements.

Returns an iterator over the elements in this set in

Iterator iterator(): ascending order.

Returns the last (highest) element currently in this

element last(): set.

Returns the greatest element in this set strictly less


element lower(element e):
than the given element, or null if there is no such
element.

Returns a view of the portion of this set whose

SortedSet subSet(element fromElement, elements range from fromElement, inclusive, to

element toElement): toElement, exclusive.

Removes the specified element from this set if it is

boolean remove(Object o): present.

Returns the number of elements in this set (its

int size(): cardinality).

TreeSet programs

Below program is to we are passing strings to the TreeSet to sort

import java.util.TreeSet;

public class TreeSetEx {

public static void main(String[] args) {

TreeSet&lt;String> ts=new TreeSet&lt;String>();

ts.add("Apple");

ts.add("Mango");

ts.add("Banana");

ts.add("Orange");

System.out.println(ts);

System.out.println(ts.size());

System.out.println(ts.contains("Mango"));

System.out.println(ts.first());

System.out.println(ts.subSet("Banana", "Orange"));

Output:

3
[Apple, Banana, Mango, Orange] 4
true
Apple
[Banana, Mango]

Examples for Sorting customized objects in TreeSet by implementing Comparable

public class Employee implements Comparable {

private int empId;

private String empName;

public Employee(int empId, String empName) {

super();

this.empclass= empId;

this.empName = empName;

public int getEmpId() {

return empId;

public void setEmpId(int empId) {

this.empclass= empId;

public String getEmpName() {

return empName;

public void setEmpName(String empName) {

this.empName = empName;

public int compareTo(Object obj) {

Employee e1 = (Employee) obj;

if (this.empId > e1.empId) {

return 1;

} else if (this.empId < e1.empId) {

return -1;

}
return 0;

public String toString(){

return empId+" "+empName;

Employee.java

import java.util.TreeSet;

public class EmployeeMain {

public static void main(String[] args) {

TreeSet<Employee> set=new TreeSet<Employee>();

set.add(new Employee(123, "Ram"));

set.add(new Employee(120, "Ajay"));

set.add(new Employee(119, "Boss"));

System.out.println(set);

Output:

[119 Boss, 120 Ajay, 123 Ram]

Examples for Sorting customized objects in TreeSet by implementing Comparator

1 public class Employee {

2 private int empId;

3 private String empName;

4 public Employee(int empId, String empName) {

5 super();

6 this.empclass= empId;

7 this.empName = empName;

8 }

9 public int getEmpId() {


10 return empId;

11 }

12 public void setEmpId(int empId) {

13 this.empclass= empId;

14 }

15 public String getEmpName() {

16 return empName;

17 }

18 public void setEmpName(String empName) {

19 this.empName = empName;

20 }

public String toString(){

return empId+" "+empName;

Employee.java

Below is our comparator class that was written to sort Employee's IDs

1 import java.util.Comparator;

2 public class EmpIdComparator implements Comparator {

3 public int compare(Object obj1, Object obj2){

4 Employee e1=(Employee)obj1;

5 Employee e2=(Employee) obj2;

6 if(e1.getEmpId() > e2.getEmpId()){

7 return 1;

8 }

9 else if (e1.getEmpId() < e2.getEmpId()) {

10 return -1;

11 }

12 return 0;
13 }

14 }

15

Let's test our logic...

import java.util.TreeSet;

public class EmployeeMain {

public static void main(String[] args) {

TreeSet<Employee> set=new TreeSet<Employee>(new EmpIdComparator());

set.add(new Employee(123, "Ram"));

set.add(new Employee(120, "Ajay"));

set.add(new Employee(119, "Boss"));

System.out.println(set);

Output : [119 Boss, 120 Ajay, 123 Ram]

HashMap

 HashMap is uses to store key-value pair


 HashMap is non-synchronized
 HashMap doesn‟t allow duplicate keys
 HashMap allows null as key and value
 HashMap is an unordered collection, which means whatever the order we have inserted, we
won‟t get the same order at time of retrieval
 Default capacity is 16, default load factor is 0.75
 If we try to add duplicate keys, it will not through any exception instead it just overrides the
existing value of that particular key
 Always it checks whether a key is already exists or not by using equals() and hashCode()
methods

HashMap class contains the following constructors and methods

Constructors:

HashMap(): Constructs an empty HashMap with the default initial capacity (16) and the default load
factor (0.75).
Ex:

1 HashMap <String, String> hm = new HashMap <String, String>();


HashMap(int initialCapacity): Constructs an empty HashMap with the specified initial capacity and
the default load factor (0.75).
Ex:

1 HashMap<String, String> hm = new HashMap<String, String> (12);

HashMap(int initialCapacity, float loadFactor) : Constructs an empty HashMap with the specified
initial capacity and load factor.
Ex:

1 HashMap<String, Integer> hm = new HashMap<String, Integer> (11, 0.5);

HashMap(Map<? extends K,? extends V> m): Constructs a new HashMap with the same mappings
as the specified Map.
Ex:

1 HashMap<String, Integer> hm1 = new HashMap<String, Integer> ();

2 HashMap <String, Integer> hm2= new HashMap<String, Integer> (hm1);

Methods:

Method Description

void clear(): Removes all of the mappings from this map.

Returns a shallow copy of this HashMap instance:

Object clone(): the keys and values themselves are not cloned.

Returns true if this map contains a mapping for the

boolean containsKey(Object key): specified key.

Returns true if this map maps one or more keys to

boolean containsValue(Object value): the specified value.

Returns a Set view of the mappings contained in this

Set<Map.Entry<K,V>> entrySet(): map.

Returns the value to which the specified key is

mapped, or null if this map contains no mapping for

V get(Object key): the key.

boolean isEmpty():
Returns true if this map contains no key-value
mappings.

Returns a Set view of the keys contained in this

Set<K> keySet(): map.

Associates the specified value with the specified key

V put(K key, V value): in this map.

void putAll(Map<? extends K,? extends V> Copies all of the mappings from the specified map to

m): this map.

Removes the mapping for the specified key from this

V remove(Object key): map if present.

Returns the number of key-value mappings in this

int size(): map.

Returns a Collection view of the values contained in

Collection values(): this map.

HashMap Programs

Below are the programs to add elements to HasMap and iterating in different ways

1 import java.util.HashMap;

2 import java.util.Set;

3 import java.util.Map.Entry;

4 public class HashMapEx {

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

6 HashMap<String, Integer> map=new HashMap<String, Integer>();

7 map.put("Apple", 20);

8 map.put("Mango", 10);

9 map.put("Orange", 13);

10 System.out.println("map===>"+map);

11 Set<Entry<String,Integer>> entrySet = map.entrySet();


12 for (Entry<String, Integer> entry : entrySet) {

13 System.out.println(entry);

Output:

map===>{Mango=10, Apple=20, Orange=13}


Mango=10
Apple=20
Orange=13

22 Points You Should Know About ArrayList

1. ArrayList introduced in java1.2 version


2. ArrayList is non-legacy class
3. ArrayList implements List interface and extends AbstractList
4. ArrayList implements RandomAccess interface so any random element can access with same
speed
5. ArrayList is a index based collection
6. ArrayList is non-synchronized
7. Multiple threads can access ArrayList simultaneously, Hence ArrayList is not thread safe
8. ArrayList internally stores the elements in growable array
9. ArrayList allows duplicate elements
10. ArrayList allows multiple null values
11. ArrayList is an ordered collection that means the insertion order is preserved
12. In case of search operations ArrayList is faster because it is index based and is implementing
RandomAccess interface
13. ArrayList default capacity is 10
14. ArrayList storing capacity will be increased by half of its original storing capacity when the
current storing capacity reaches to maximum
For example ArrayList default capacity is 10 until 10 elements it will not increase the capacity of
ArrayList, if we are trying to add 11th element, then the capacity increases by suing below
formula
int newCapacity = (oldCapacity * 3)/2 + 1;
15. capacity represents the maximum number of elements the list can hold. size represents how
many elements are currently existing in the lis
16. Adding and removing the elements in the mid of the ArrayList is costly because it needs to shift
the elements
For example, ArrayList contains 15 elements , if we try to add a new element at index 3, it
needs to shift the elements from 3rd index
17. ArrayList supports Iterator and ListIterator
18. The underlying data structure for ArrayList is resizable array or growble array
19. ArrayList can be synchronized using Collections.synchronizedList(List list) method
20. The subList(int fromIndex, int toIndex) method of ArrayList returns a List object between the
specified fromIndex, inclusive, and toIndex, exclusive
21. toArray() method of ArrayList converts ArrayList to Object array
22. toString() method is overridden in ArrayList
23. ArrayList implements Serializable and Cloneable interfaces
24. ArrayList is not synchronized so in the multi-threaded programming an ArrayList object allows
multiple threads at time, For reading operations it is faster and we will get reliable results but in
case of writing(manipulations) operations, we will not get reliable results
Sorting ArrayList in Java

ArrayList sorting can be done by simply calling the Collections.sort(List list) method
Collections.sort(List list) method by default sort all wrapper class objects and String objects

In case List contains String objects, The List will be sorted alphabetically
import java.util.ArrayList;
1
import java.util.Collections;
2
import java.util.List;
3
public class StringListEx {
4
public static void main(String[] args) {
5
List<String> list = new ArrayList<>();
6
list.add("Krishna");
7
list.add("Ram");
8
list.add("Arjun");
9
list.add("Laxman");
10
list.add("Venkat");
11
System.out.println("Before sorting: " + list);
12
Collections.sort(list);
13
System.out.println("After sorting: " + list);
14
}

Output:

Before sorting: [Krishna, Ram, Arjun, Laxman, Venkat]

After sorting: [Arjun, Krishna, Laxman, Ram, Venkat]

Collections.sort() method can be used for sorting the Integer objects as well.

1 import java.util.ArrayList;

2 import java.util.Collections;

3 import java.util.List;

4 public class StringListEx {


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

6 List<Integer> list = new ArrayList<>();

7 list.add(2);

8 list.add(7);

9 list.add(5);

10 list.add(6);

11 list.add(4);

12 list.add(3);

13 list.add(1);

14 System.out.println("Before sorting: " + list);

15 Collections.sort(list);

16 System.out.println("After sorting: " + list);

17 }

Output:

Before sorting: [2, 7, 5, 6, 4, 3, 1]

After sorting: [1, 2, 3, 4, 5, 6, 7]

Removing duplicate elements from ArrayList

Removing duplicate elements from ArrayList using contains() method

1 import java.util.ArrayList;

2 import java.util.List;

3 public class RemovingDuplicateEx1 {

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

5 List<String> duplicateList = new ArrayList<>();

6 List<String> uniqueList = new ArrayList<>();

7 duplicateList.add("Krishna");

8 duplicateList.add("Ram");

9 duplicateList.add("Arjun");
10 duplicateList.add("Laxman");

11 duplicateList.add(null);

12 duplicateList.add("Venkat");

13 duplicateList.add("Venkat");

14 duplicateList.add(null);

15 System.out.println("Before removing duplicates: " + duplicateList);

16 for (String name : duplicateList) {

17 //Add an element to uniqueList to if uniqueList doesn't contains

18 if(!uniqueList.contains(name)) {

19 uniqueList.add(name);

20 }

21 }

22 System.out.println("After removing duplicates: " + uniqueList);

Output :

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

After removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat]

By converting List to Set we can avoid duplicate elements, Since Set doesn‟t contain duplicate
elements

1 import java.util.ArrayList;

2 import java.util.HashSet;

3 import java.util.List;

4 import java.util.Set;

6 public class RemovingDuplicateEx1 {

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

8 List<String> list = new ArrayList<>();

9 list.add("Krishna");
10 list.add("Ram");

11 list.add("Arjun");

12 list.add("Laxman");

13 list.add(null);

14 list.add("Venkat");

15 list.add("Venkat");

16 list.add(null);

17 System.out.println("Before removing duplicates: " + list);

18 //Converting List to Set

19 Set<String> set = new LinkedHashSet<>(list);

20 System.out.println("After removing duplicates: " + set);

Output:

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

After removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat]

Java 8 streams provide a very simple way to remove duplicate elements from a list. Using the distinct
method.

1 import java.util.ArrayList;

2 import java.util.List;

3 import java.util.stream.Collectors;

5 public class RemovingDuplicateEx1 {

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

7 List<String> list = new ArrayList<>();

8 list.add("Krishna");

9 list.add("Ram");

10 list.add("Arjun");

11 list.add("Laxman");
12 list.add(null);

13 list.add("Venkat");

14 list.add("Venkat");

15 list.add(null);

16 System.out.println("Before removing duplicates: "+list);

17 list = list.stream().distinct().collect(Collectors.toList());

18 System.out.println("Before removing duplicates: "+list);

19 }

Output:

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

After removing duplicates: [Krishna, Ram, Arjun, Laxman, null, Venkat]

How to remove null values from ArrayList

Null values can be removed from ArrayList in different ways

By using remove() method of ArrayList

1 import java.util.ArrayList;

2 import java.util.List;

3 public class RemovingDuplicateEx1 {

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

5 List<String> list = new ArrayList<>();

6 list.add("Krishna");

7 list.add("Ram");

8 list.add("Arjun");

9 list.add("Laxman");

10 list.add(null);

11 list.add("Venkat");

12 list.add("Venkat");

13 list.add(null);

14 System.out.println("Before updating list: " + list);


15 for (int i = 0; i < list.size(); i++) {

16 if(list.get(i) == null) {

17 list.remove(i);

18 }

19 }

20 System.out.println("After updating list: " + list);

Output:

Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, Venkat, Venkat]

Iterating ArrayList

1 import java.util.ArrayList;

2 import java.util.List;

3 public class RemovingDuplicateEx1 {

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

5 List<String> list1 = new ArrayList<>();

6 List<String> list2 = new ArrayList<>();

7 list1.add("Krishna");

8 list1.add("Ram");

9 list1.add("Arjun");

10 list1.add("Laxman");

11 list1.add(null);

12 list1.add("Venkat");

13 list1.add("Venkat");

14 list1.add(null);

15 System.out.println("Before removing null values: " + list1);

16 for (String name : list1) {

17 if (null != name) {

18 list2.add(name);
19 }

20 }

21 System.out.println("Before removing duplicates: " + list2);

Output:

Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, Venkat, Venkat]

By using removeAll() method

1 import java.util.ArrayList;

2 import java.util.Collections;

3 import java.util.List;

4 public class RemovingDuplicateEx1 {

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

6 List<String> list = new ArrayList<>();

7 list.add("Krishna");

8 list.add("Ram");

9 list.add("Arjun");

10 list.add("Laxman");

11 list.add(null);

12 list.add("Venkat");

13 list.add("Venkat");

14 list.add(null);

15 System.out.println("Before removing null values: "+list);

16 list.removeAll(Collections.singleton(null));

17 System.out.println("Before removing duplicates: "+list);

18 }

Output:
Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, Venkat, Venkat]

By using removeIf() method

import java.util.ArrayList;

import java.util.List;
1
import java.util.Objects;
2
public class RemovingDuplicateEx1 {
3
public static void main(String[] args) {
4
List<String> list = new ArrayList<>();
5
list.add("Krishna");
6
list.add("Ram");
7
list.add("Arjun");
8
list.add("Laxman");
9
list.add(null);
10
list.add("Venkat");
11
list.add("Venkat");
12
list.add(null);
13
System.out.println("Before removing null values: "+list);
14
list.removeIf(Objects::isNull);
15
System.out.println("Before removing duplicates: "+list);
16
}

Output:

Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, Venkat, Venkat]

Using Java 8, We can do this using stream() and filter()

1 import java.util.ArrayList;

2 import java.util.List;

3 import java.util.stream.Collectors;
4 public class RemovingDuplicateEx1 {

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

6 List<String> list = new ArrayList<>();

7 list.add("Krishna");

8 list.add("Ram");

9 list.add("Arjun");

10 list.add("Laxman");

11 list.add(null);

12 list.add("Venkat");

13 list.add("Venkat");

14 list.add(null);

15 System.out.println("Before removing null values: "+list);

16 list = list.stream().filter(t -> t != null).collect(Collectors.toList());

17 System.out.println("Before removing duplicates: "+list);

Output:

Before removing null values: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

Before removing duplicates: [Krishna, Ram, Arjun, Laxman, Venkat, Venkat]

How to update an element at specified index in ArrayList

Using set(int index, E element) method we can replace the element at the specified position in this list
with the specified element

1 import java.util.ArrayList;

2 import java.util.List;

3 public class RemovingDuplicateEx1 {

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

5 List<String> list = new ArrayList<>();

6 list.add("Krishna");

7 list.add("Ram");

8 list.add("Arjun");
9 list.add("Laxman");

10 list.add(null);

11 list.add("Venkat");

12 list.add("Venkat");

13 list.add(null);

14 System.out.println("Before updating list`: " + list);

15 //set(int index, E element) replaces the element at specified index

16 list.set(1, "John");

17 System.out.println("After updating list`: " + list);

18 }

Output:

Before updating list`: [Krishna, Ram, Arjun, Laxman, null, Venkat, Venkat, null]

After updating list`: [Krishna, John, Arjun, Laxman, null, Venkat, Venkat, null]

Difference between ArrayList and Vector

ArrayList Vector

ArrayList is non synchronized Vector is synchronized

ArrayList is introduced in java1.2 Vector is introduced in java1.0

ArrayList is a non-legacy Collection Vector is a legacy Collection

Vector storing capacity will be increased

ArrayList storing capacity will be increased by half of it‟s by double of it‟s original storing

original storing capacity, when the current storing capacity capacity, when the current storing

reaches to maximum capacity reaches to maximum

Vector doesn‟t allow multiple threads at

ArrayList allows multiple threads at a time a time


Vector is performance is low, Because it

ArrayList is performance is high, Because threads need not makes the threads to wait for object

to wait for object lock to access ArrayList object lock to enter into vector object

Vector supports Iterator, ListIterator and

ArrayList supports Iterator and ListIterator Enumeration

24 Points You Should Know About Vector

1. Vector introduced in java1.0 version


2. Vector is legacy class
3. Vector implements List interface and extends AbstractList
4. Vector implements RandomAccess interface so any random element can access with same
speed
5. Vector is a index based collection
6. Vector internally stores the elements in growable array
7. Vector default capacity is 10
8. Vector is synchronized
9. Multiple threads can‟t access Vector object simultaneously, Hence Vector is a thread safe
10. Vector allows duplicate elements
11. Vector allows multiple null values
12. Vector is an ordered collection that means the insertion order is preserved
13. In case of search operations Vector is faster because it is index based and is implementing
RandomAccess interface
14. Vector storing capacity will be increased by double of its original storing capacity when the
current storing capacity reaches to maximum
For example Vector default capacity is 10 until 10 elements it will not increase the capacity of
Vector, if we are trying to add 11th element, then the capacity increases to 20. [capacity
represents the maximum number of elements the list can hold. size represents how many
elements are currently existing in the list]
15. Adding and removing the elements in the mid of the Vector is costly because it needs to shift
the elements
For example, Vector contains 15 elements , if we try to add a new element at index 3, it needs
to shift the elements from 3rd index
16. Vector supports Enumerator, Iterator and ListIterator
17. The underlying data structure for Vector is resizable array or growble array
18. Every method is synchronized in Vector
19. The subList(int fromIndex, int toIndex) method of Vector returns a List object between the
specified fromIndex, inclusive, and toIndex, exclusive
20. toArray() method of Vector converts ArrayList to Object array
21. toString() method is overridden in Vector to display the content
22. Vector implements Serializable and Cloneable interfaces
23. Vector is synchronized so in the multi-threaded programming an Vector object allows single
thread at time, In such case vector may reduce the performance of the application
24. Vector contains elements() which returns Enumeration object containing all elements of the
Vector, Where as ArrayList doesn‟t have such method

How to write our own ArrayList in Java

Implementing our own ArrayList class, Which contains add(), get(), remove(), size() methods.
MyArrayList.java
1 import java.util.Arrays;

2 public class MyArrayList {

3 private Object[] arr;

4 private int size;

5 public MyArrayList() {

6 // Calling parameterized constructor

7 this(10);

8 }

9 public MyArrayList(int initialCapacity) {

10 if (initialCapacity < 0)

11 throw new IllegalArgumentException("Invalid Argument ");

12 // Creating array with Initial capacity

13 this.arr = new Object[initialCapacity];

14 }

15 public boolean add(Object obj) {

16 ensureCapacity(size + 1); // Increments modCount!!

17 arr[size++] = obj;

18 return true;

19 }

20 public void ensureCapacity(int currentIndex) {

21 int oldCapacity = arr.length;

22 // Validating the current index is greater then array size or not

23 if (currentIndex > oldCapacity) {

24 int newCapacity = (oldCapacity * 3) / 2 + 1;

25 arr = Arrays.copyOf(arr, newCapacity);

26 }

27 }

28 public int size() {

29 return size;

30 }
31 public Object get(int index) {

32 if (index >= size) {

33 throw new IndexOutOfBoundsException("Invalid index");

34 }

35 return arr[index];

36 }

37 public Object remove(int index) {

38 if (index >= size) {

39 throw new IndexOutOfBoundsException("Invalid index");

40 }

41 Object oldValue = arr[index];

42 int numMoved = size - index - 1;

43 if (numMoved > 0)

44 System.arraycopy(arr, index + 1, arr, index, numMoved);

arr[--size] = null;

return oldValue;

Main.java

1 public class Main {

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

4 MyArrayList list = new MyArrayList();

5 list.add("Apple");

6 list.add("Mango");

7 list.add("Orange");

8 list.add("Banana");

9 list.add("Pineapple");

10 list.add("Grapes");
11 list.add(10);

12 list.remove(4);

13 for (int i = 0; i < list.size(); i++) {

14 System.out.println(list.get(i));

15 }

16 }

17 }

Output:

Apple
Mango
Orange
Banana
Grapes
10

25 Points You Should Know About LinkedList

1. LinkedList implements both List and Deque interfaces


2. LinkedList is a non-legacy class
3. LinkedList introduced in java1.2
4. LinkedList is non-synchronized
5. LinkedList allows duplicates elements
6. LinkedList allows null values
7. LinkedList stores elements in the form of nodes
8. LinkedList internally follows double linkedlist data structure to store elements.
9. Each node contains 3 fields. mid Field contains data, right and left Fields contains references to
previous and next nodes [refer the below
diagram]

10. In case of inserting or deleting elements in between the collection, LinkedList is faster then
ArrayList because it performs these operations without any shifting, By simply updating the
previous and next nodes of the elements
11. LinkedList supports Iterator and ListIterator.
12. LinkedList can be synchronized by using Collections.synchronizedList(List list) method
13. The iterator() and listIterator() both methods are return fail-fast iterators
14. If the LinkedList is structurally modified at any time while iterating, The iterator will throw
a ConcurrentModificationException except through the Iterator‟s own remove or add
methods
15. LinkedList contains descendingIterator() method which returns an Iterator object containing all
elements of a LinkedList in the reverse order
16. LinkedList contains offer() and poll() methods which make LinkedList to work as a Queue
17. LinkedList contains pop() and push() methods which makes LinkedList as a Stack
18. LinkedList contains add() or addLast() or offer() or offerLast() to add the elements at the end of
the LinkedList
19. LinkedList contains addFirst() or offerFirst() to add the elements at the head of the LinkedList
20. pollLast() and removeLast() methods remove the elements from the tail of the LinkedList
21. poll() or pollFirst() or remove() or removeFirst() methods remove the elements from the head
of the LinkedList
22. The subList(int fromIndex, int toIndex) method of Vector returns a List object between the
specified fromIndex, inclusive, and toIndex, exclusive
23. toArray() method of Vector converts ArrayList to Object array
24. toString() method is overridden in Vector to display the content in array format
25. Vector implements Serializable and Cloneable interfaces

What s single LinkedList?

In single LinkedList the node consists of only two fields one is data field another one is the reference to
next node.

What is Double LinkedList?

In double LinkedList the node has three fields, first field reference to the previous node , second field
value of the element and third field reference to the next node.

Hashtable

 Hashtable is similar to HashMap except synchronization


 Hashtable is used to store key-value pair
 Hashtable is a legacy class
 Hashtable is synchronized
 Hashtable implements Map interface and extends Dictionary class
 Hashtable doesn‟t follows the insertion order, Because Hashtable internally stores key-value
based on key element hashcode
 Hashtable doesn‟t allow null key or null value, If we try to insert we will
get NullpointerException
 Hashtable doesn‟t allow duplicate keys but values can be duplicated
 If we try to add duplicate keys, it will not throw any exception instead it just overrides the value
of existing key
 Default capacity is 11, default load factor is 0.75
 Hashtable identify the duplicate keys using equals() and hashcode() methods

Hashtable class contains the following constructors and methods

Constructors:

Hashtable(): Constructs a new, empty hashtable with a default initial capacity (11) and load factor
(0.75).

1 Hashtable <String, String> ht = new Hashtable <String, String>();

Hashtable(int initialCapacity): Constructs a new, empty hashtable with the specified initial capacity
and default load factor (0.75).

1 Hashtable <String, String> ht = new Hashtable <String, String>(0.90);

Hashtable(int initialCapacity, float loadFactor): Constructs a new, empty hashtable with the
specified initial capacity and the specified load factor.
1 Hashtable <String, String> ht = new Hashtable <String, String>(20, 0.90);

Hashtable(Map t): Constructs a new hashtable with the same mappings as the given Map.

Hashtable <String, String> ht1 = new Hashtable <String, String>();


1
Hashtable <String, String> ht2 = new Hashtable <String, String>(ht1);

Methods:

Method Description

void clear(): Clears this hashtable so that it contains no keys

Object clone(): Creates a shallow copy of this hashtable

Returns true if this map contains a mapping for the

specified key.Tests if the specified object is a key in

boolean containsKey(Object key): this hashtable

Returns true if this hashtable maps one or more keys

boolean contains(Object value): to this value

Returns an enumeration of the values in this

Enumeration elements(): hashtable

Returns a Set view of the mappings contained in this

Set<Map.Entry<K,V>> entrySet(): map

Returns the value to which the specified key is

mapped, or null if this map contains no mapping for

V get(Object key): the key

boolean isEmpty(): Tests if this hashtable maps no keys to values.

Enumeration keys(): Returns an enumeration of the keys in this hashtable

Returns a Set view of the keys contained in this

Set<K> keySet(): map.


Maps the specified key to the specified value in this

V put(K key, V value): hashtable

void putAll(Map<? extends K,? extends V> Copies all of the mappings from the specified map to

m): this hashtable

Removes the key (and its corresponding value) from

V remove(Object key): this hashtable

int size(): Returns the number of keys in this hashtable

Returns a Collection view of the values contained in

Collection values(): this map

Array

Array is an object
Arrays are used to store multiple elements
Arrays are allowed only same type of elements
Arrays are stored elements on index based
Array index starts with 0, The first element of the array is stored at 0 index
Elements are accessed from array by using there indexes
Arrays are fixed size, Which means the size of the array can not be modified once they are created

Types of Arrays in java

Arrays are categorized in to two types

1. Single Dimensional Array


2. Multidimensional Array

Single dimensional array

Single Dimensional Array

Single dimensional or one dimensional array represents a row or a column of elements


Declaration of single dimensional array:

Single dimensional can declared in 3 ways, They are

1 int[] arr;

2 int arr[];

3 int []arr;

The above case int represents integer type elements, Which can be stored into array

Declaring different data type arrays


1 String[] arr; //Represents String type elements

2 float arr[]; //Represents float type elements

3 char []arr; //Represents char type elements

4 Employee[] arr; //Represents Employee type elements

Instantiation of single dimensional Array in java

Instantiation of array can be done in different ways

Using new operator

Every array is an object in java, So array can be created by using new operator
At the time of instantiation we must specify the size of the array otherwise we will get compile time
error
The size represents number of elements can be stored into the array
The size value must be byte, short, int and char type only
syntax:
int[] arr = new int[size];
Ex:

1 int[] arr1 = new int[5]; //Creates an array with size 5

2 int arr2[] = new int['a']; //Creates an array with size 97 'a' ASCII value is 97

3 byte b =10;

4 int []arr3 = new int[b]; //Creates an array with size 10

When JVM executes int[] arr1 = new int[5]; line of code JVM allots memory for storing 5 int values
into the array, But actually we have not stored any values, In such case JVM stores integer default
values
Storing elements into the array

Elements can be stored into the array using index

1 arr1[0] = 20;

2 arr1[1] = 25;

3 arr1[2] = 30;

4 arr1[3] = 31;

5 arr1[4] = 32;

Elements are stored into the array the following manner

Wihout new operator

Array can be created without new operator also


Here we can store elements into the array directly at the time array declaration itself

1 int[] arr = {1, 4, 5, 8, 3};

When JVM executes above line of code, elements are stored into the array the following manner

Retrieving elements from array

Elements are retrieved from array using index


Ex:

1 public class ArrayEx {

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

3 int[] arr = { 1, 4, 5, 8, 7 };

4 System.out.println(arr[0]);

5 System.out.println(arr[1]);

6 System.out.println(arr[2]);

7 System.out.println(arr[3]);

8 System.out.println(arr[4]);
9 }

Output:

1
4
5
8
7

Retrieving elements from array using for loop

1 public class ArrayEx1 {

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

3 int[] arr = { 1, 4, 5, 8, 7 };

4 for (int i = 0; i < arr.length; i++) {

5 System.out.println(arr[i]);

6 }

7 }

8 }

Output:

14587

Multidimensional Array in java

Multidimensional Array represents 2D(2 dimesional), 3D(3 dimesional), … arrays.


2D array is nothing but combination of two or more 1D arrays
3d array is nothing but combination of two or more 2D arrays

Two dimensional array

Two dimensional array can declared in multiple ways, They are

int[][] arr;(or) int arr[][];(or) int [][]arr;(or) int []arr[];

Instantiation of two dimensional array in java

Instantiation of two dimensional array can be done in different ways

Using new operator

int[][] arr=new int[3][4]

You might also like