[go: up one dir, main page]

0% found this document useful (0 votes)
13 views389 pages

Java

The document provides an introduction to Java programming, covering its history, features, and applications. It explains Java's data types, including primitive and non-primitive types, along with naming conventions for identifiers and variables. Additionally, it discusses operators and their precedence in Java programming.

Uploaded by

sonagopi249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views389 pages

Java

The document provides an introduction to Java programming, covering its history, features, and applications. It explains Java's data types, including primitive and non-primitive types, along with naming conventions for identifiers and variables. Additionally, it discusses operators and their precedence in Java programming.

Uploaded by

sonagopi249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 389

Introduction to Java Programming

• Java is a programming language and a platform


• Java is a high level , robust , secured and object-oriented Programming
Language .
• Programing language: A programming language is a way for
programmers (developers) to communicate with computers.
• Platform: Any hardware or software environment in which program runs
, is known as platform . Since Java has its own Java runtime
environment (JRE) , it is called platform.
History of Java

• Java Programming Language is originally developed by sun


microsystems (currently acquired by Oracle corporation ) which is
initiated by James Gosling and released in 1995 as core component of
sun microsystems java platforms.

• Latest release is Java 22


Features of Java
Where is used

• Desktop Application
• Web Application
• Enterprise application
• Mobile Application
• Embedded Application
• Smart Card Application
• Robotics
• Games etc
Java platforms /Editions
50 Keywords of
Rules to follow for keywords:
• Keywords cannot be used as an identifier for class, subclass, variable, and methods.
• Keywords are case-sensitive.
• const and goto are reserved words but not used.
• True, false and null are literals, not keywords.
• All keywords are in lower-case.
Java Identifiers
A Java identifier is a name given to a package, class, interface, method,
or variable. It allows a programmer to refer to the item from other
places in the program.

To make the most out of the identifiers you choose, make them
meaningful and follow the standard Java naming conventions.
A Few Words About Cases
• Using the right letter case is the key to following a naming convention:

• Lowercase is where all the letters in a word are written without any capitalization
(e.g., while, if, mypackage).

• Uppercase is where all the letters in a word are written in capitals. When there are
more than two words in the name use underscores to separate them (e.g.,
MAX_HOURS, FIRST_DAY_OF_WEEK).

• CamelCase (also known as Upper CamelCase) is where each new word begins with a
capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).

• Mixed case (also known as Lower CamelCase) is the same as CamelCase except the
first letter of the name is in lowercase (e.g., hasChildren, customerFirstName,
customerLastName)
Standard Java Naming Conventions
Packages: Names should be in lowercase. With small projects that only
have a few packages it's okay to just give them simple (but meaningful!)
names:
package pokeranalyzer
package mycalculator

In software companies and large projects where the packages might be


imported into other classes, the names will normally be subdivided.
Typically this will start with the company domain before being split into
layers or features:
package com.mycompany.utilities package
org.bobscompany.application.userinterface
Classes: Names should be in CamelCase. Try to use nouns because a
class is normally representing something in the real world:
class Customer class Account
Interfaces: Names should be in CamelCase. They tend to have a name
that describes an operation that a class can do:
interface Comparable interface Enumerable
Note that some programmers like to distinguish interfaces by beginning
the name with an "I":
interface IComparable interface IEnumerable
Methods: Names should be in mixed case. Use verbs to describe what
the method does:
void calculateTax() string getSurname()
Variables: Names should be in mixed case. The names should represent
what the value of the variable represents:
string firstName int orderNumber

Only use very short names when the variables are short-lived, such as in
for loops:
for (int i=0; i<20;i++)
{ //i only lives in here
}
Constants: Names should be in uppercase.
static final int DEFAULT_WIDTH static final int MAX_HEIGHT
Overall Identifiers notations

Package: lowercase
Classes: Camelcase
Interfaces: Camelcase
Methods: Mixedcase + verbs
Variables: Mixedcase
Constants: Uppercase
Variable and Data Type
• Variable is a space in memory where we can store data. It helps to
access the data easily.

• A data type defines the size and type of information stored in a


variable. Data types help in memory management. It helps to assigns
the memory depending upon the type of data type.

• Most importantly Java has numerous datatypes and all data types are
predefined, which is used to store a large amount of information.

• There are two main categories of data type primitive and non-
primitive which classified the various data type.
Primitive type includes:
Integer type: It is further divided into subcategories of datatypes.

byte: The byte data type holds an 8-bit signed two’s complement integer. It is also one of the
reserved words in Java. byte stores whole numbers ranges in between -128 to 127. As it is allocated
limited memory space, it can be used as a replacement of int datatype.
boolean: This datatype is used to store two possible value: either True or False. boolean type values
are not converted implicitly or explicitly to any other type (means typecasting is not possible).
short: It stores whole numbers and the range lies in between -32768 to 32767.
int: When creating variables consisting of numeric values, Java gives preference to int datatype as it
has a higher precedence order. So in a program if you have not defined the datatype, by default java
assumes it as int. It stores whole numbers from -2147483648 to 2147483647. Negative numbers are
also permissible here. It has a wider range compared to short and byte.
long: This datatype can store whole numbers from -9223372036854775808 to
9223372036854775807. For storing a large amount of data, long datatype is preferred over int. In
Java, the value of long datatype must end with literal “L”. Otherwise, Java considers it as int type.
Floating-point type: A floating-point datatypes are used for calculating simple to complex
fractional data. It is further subcategorized into two parts:
float: For storing fractional numbers, float datatype is used. It has a 7-decimal digit precision in
memory. It is not recommended to use float datatype while calculating financial figures or values. As
the value processed here is an approximate value and hence, not used for precise values such as
currency. By default, Java assumes floating-point datatype as double, so you need to add a literal at
the end, denoted by the letter “f”.
double: Another floating-point datatype used to store a huge amount of data in memory. It has a 15-
decimal digit precision in memory. Storing decimal values this data type is generally the default
choice.

Non-Primitive types include:


String: A collection of characters stored in memory is called a String.
Array: Collection of homogenous datatype is known as Array.
Understanding variables
The following program will demonstrate how we can declare and then initialize an int variable.

public static void main(String[] args) {


int value1;
value1=1;
System.out.println (value1);
}
Multiple variable initializations within a statement

public static void main(String[] args) {


int value1 = 1, value2 = 2;
System.out.println(value2);
}
Initialization of variable through arithmetic operation
public static void main(String[] args) {
int value1 = 1, value2 = (2 * 2) - 1;
System.out.println (value2);

}
Assigning one primitive variable to another
public static void main(String[] args) {
int value1 = 1;
int value2 = value1;
System.out.println (value2);
}
Naming Convention of varaibles
The names of variables are case sensitive “value” and “Value” both are different.
Space is not permitted in variable names.
Primitive Data Types
• Java supports eight primitive data types.
• These are the basic and predefined data type of the programming language.
• Java determines the size of each primitive data types, it cannot be changed.
• Primitive data types are represented by reserved keywords.

The primitive data type is divided into the following categories:


• Integer data type.
• Floating Point data type.
• Boolean data type.
• Char data type.
Integer data type
Integer data type is used to store integer numbers (number without a decimal point). The minimum and
maximum value that a datatype can store depends on the size of the data type.

The range of Integer data types


The following table lists represent the all integer data types, their storage requirements in bytes and the numeric
range they support.

Types Size Minimum value Maximum Value


byte 8 bit/1byte -128 127
short 16bit/2byte -32768 32767
int 32 bit/4byte -2,147,483,648 2,147,483,647
long 64 bit/8byte -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Note:
Depending upon the requirement we must choose the appropriate data type.
Integer data type

byte
The size of the byte type is 8bit/1byte. The minimum value of the byte is -128 and the maximum value is 127.

short
The short data type is integer compatible data type and used to contain integer value or an integer number. The size of the short type is
16bit/2byte. The minimum value of the short is -32768 and the maximum value is 32767.

int
The size of the int value is 32bit/4byte. The minimum value of int is -2147483648 and the maximum range is 2147483647.

long
The size of the long data type is 64bit/8byte. While declaring long data type always use suffix “L” by default Java considered it as an integer. Java is a case-
sensitive language so it is recommended use “L” in upper case.

Initialization of long variable:


long longMax = 9223372036854775807L;
long longMin = -9223372036854775808L;

L specifies that value is a long.


Floating Point data type
Floating point variables are used to deal with decimal value. There are two types of floating point data types.
The following table gives you details about floating point types with storage sizes and ranges of values with
their precision

Type Storage size Value range Precision


Float 4 byte 1.2E-38 to 3.4E+38 7 decimal places
Double 8 byte 2.3E-308 to 1.7E+308 16 decimal places
Float–float is used for floating- point (decimal) values, it occupies 32-bit memory

Initialization of float variable:

float var = 9.0f;


f specifies that value is a float.

Precision in float:
public static void main(String[] args) {
float var = 10f / 6f;
System.out.println(var);
}
Output:

1.6666666
Double – double is used for high precision floating point values, it occupies 64-bit memory
Initialization of double variable:
double var = 9.5d;
d specifies that value is double.
Precision in double data type is more than a float data type.

Precision in double:
public static void main(String[] args) {
double var = 10d / 6d;
System.out.println (var);
}
Output:
1.6666666666666667
Boolean
Boolean is a data type which represents one bit of information either true or false.
public static void main(String[] args) {
boolean var = true;
System.out.println (var);
}
Output: true
Char
A char data type is a single length entity. This could be an alphabet, a digit or a symbol. It is also used to hold
the Unicode for symbols. Value for char should be with single quotes.
public static void main(String[] args) {
char var = '\u00A7';
char var1 = 'A';
System.out.println (var); Note: We must only use the single quotes pointing to left
System.out.println (var1);
} The length should be one.
Single quote point to the left should be used
Output:
Any character on the keyboard is allowed
§
Example: ‘A’,’*’,’1’
A
Strings in Java
Initialization of String variable
In the below example, we will create a String. Here var is the reference of data “Hello World” of type String.
String var = “Hello World”; String methods
public class App {

Concatenate two Strings public static void main(String[] args) {


String x = "Study";
public static void main(String[] args) { String y = "easy";
String z = x.concat(y);
String var1 = "10";
z = z.replace("easy", "hard");
String var2 = "20";
System.out.println(var1 + var2); System.out.println(z);

} if(z.equals("Studyeasy")){
System.out.println("Text is Studyeasy");
}else{
System.out.println("Text is not
Studyeasy");
}
}
}
Type Casting
In Java, Type Casting is a process of converting a variable of one data type into another.
Typecasting is of two types:
Implicit typecasting.
Explicit typecasting.
Implicit typecasting
Implicit type casting is also known as Widening or Automatic typecasting. When a small range data type
variable is converted into a large range data type, The process is called implicit typecasting.
Example:
we initialize an int variable with a short value.
public static void main(String[] args) {
short x = 10;
int y = x;
System.out.println(y);
}
Output:10
Explicit typecasting
Explicit typecasting is also known as narrowing typecasting. When a large range data type is converted into small
range data.
Example
We initialize the short variable y with int x, when we try to execute, the program will crash with “type mismatch”
error. As we are trying to store large data type (int) into smaller data type variable (short).
public static void main(String[] args) {
int x = 10;
short y = x;
System.out.println(y);
}
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:

Type mismatch: cannot convert from int to short

at challanges.Hello.main(Hello.java:7)
In this example, we initialize the short variable by assigning an integer variable, in the narrowing
typecasting scenario; we have to explicitly typecast data.

public static void main(String[] args) {


int x = 10;
short y = (short)x;
System.out.println(y);
}
Output:10
A yet another example of narrowing typecasting, double data is explicitly converted into float.
public static void main(String[] args) {
double x = 10.0123456789d;
float y = (float)x;
System.out.println(y);
}
Output:10.012345
Program code of datatype
package Second;
public class Second {
public static void main(String[] args) {
int x;
x=3;
double y = 5.5;
System.out.println("x is "+x);
System.out.println("y is "+y);
}
}
X=2 001 010 011 100 101 110 111
x<<1 0100 4
x>>1 0 010
Operators & Operator Precedence
Arithmetic Operators
Mathematical operations are done by using arithmetic operators. Following table displays all the arithmetic
operators supported by java. Assume integer variable “A” holds value 5 and variable “B” holds value 10.
Addition Operator
Plus (+) operator is used for addition of two numbers. In addition to adding two numbers, the
addition operator is also used for string concatenation.

The following code demonstrates the addition of two numbers as well as concatenation
operation.
public static void main(String[] args) {
int x = 1+2;
String s = "Hello" + " world";
System.out.println(x);
System.out.println(s);
}
Output:
3
Hello world
Subtraction operator
Minus (-) operator is used for subtracting the second operand from the first.
public static void main(String[] args) {
int x = 1;
int y = 12 - x;
System.out.println(y);
}
Output:
11
Multiplication Operator
Multiplication (*) operator used for multiply two numbers.
In following illustration 12*2 gives 24.
public static void main(String[] args) {
int x = 1;
int y = 12 * 2;
System.out.println(y);
}
Output:
24
Division Operator
Division operator (/) used for divide numerator by de-numerator and it gives the quotient.
In the following illustration 12 divided by 2 and the result is 6.
public static void main(String[] args) {
int x = 1;
int y = 12 / 2;
System.out.println(y);
}
Output
6
Modulus operator
Modulus operator used to returns the remainder of one number divided by another.
In following illustration 13%2 and remainder are 1.
public static void main(String[] args) {
int mod = 13 % 2;

System.out.println(mod);
}
Output
1
Increment operator
Increment operator is a unary operator that increments its operand by one. This operator can be used for both postfix(x++) as well as a
prefix (++x).
Postfix- In the postfix form, it evaluates to the value of the operand before the increment operation.
Case 1
public static void main(String[] args) {
int x = 10;
System.out.println(x++);
}
Output
10
Prefix-In the prefix form it evaluates the value of the operand after the increment operation.
Case 2
public static void main(String[] args) {
int x = 10;
System.out.println(++x);
}
Output
11
Decrement operator:
Decrement operator is also a unary operator that decrements its operand by one. This operator can be used for both postfix(x–) as well as a
prefix (–x).
Postfix-In the postfix form, it evaluates to the value of the operand before the decrement operation.
Case 1
public static void main(String[] args) {
int x = 10;
System.out.println(x--);
}
Output
10
Prefix-In the prefix form it evaluates the value of the operand after the increment operation.
Case 2
public static void main(String[] args) {
int x = 10;
System.out.println(--x);
}
Output
9
Ternary Operator In Java
Ternary operator works on three operands. It returns a value based on a condition that evaluates either true or false statement. True and false
statements are also an expression that you want to evaluate. If the expression is true it evaluates expression true otherwise it evaluates the
expression false.
Syntax
Ternary operator has three operands: Condition? Expression 1: Expression 2

The condition is evaluated.


If the condition is true then Expression1 is returned.
If the condition is false then Expression2 will be returned.
Ternary operator examples
Ternary operator allows to returning an output based on the relational operator.

public static void main(String[] args) {


boolean x;
x = (5<4)?true:false;
System.out.println(x);
} Output

false
Example2:
public static void main(String[] args) {
int age = 12;
String a = "Allowed to vote";
String b = "Not allowed to vote";
String accessallowed = (age > 18) ? a : b;
System.out.println(accessallowed);
}
Output
Not allowed to vote
Ternary operator allows you to evaluate two primitive value are equal or not.
public static void main(String[] args) {
int x;
x = (10==9) ? 1 : 0;
System.out.println(x);
}
Output
0
Assignment Operators
Assignment operators are a binary operator that is used to assign a value of an expression to a variable on the
left-hand side of the operator, with the result of the value on the right-hand side of the equation.
Example1:
public static void main(String[] args) {
int x = 5;
x += 5;
System.out.println(x);
}
Output:10
Example2:
public static void main(String[] args) {
int x = 5;
x += 5;
x -= 5;
System.out.println(x);
}
Output:5
Example3:
public static void main(String[] args) { Example4:
int x = 5;
public static void main(String[] args) {
int x = 5;
x *= 5; x %= 5;
System.out.println(x); System.out.println(x);
} }
Output:0
Output:25
Example4;
public static void main(String[] args) {
int x = 5;
x /= 5;
System.out.println(x);
}
Output:1
Java Control Statements | Conditional & Looping Control Statements
They are mainly categorized in 2 types –
Conditional Control Statements
Whenever a condition is to be tested depending on which particular tasks are to be performed, Conditional control statements are used.
Looping / Iterative Control Statements
Whenever a particular task has to be iterated for a particular number of times or depending on some condition, Looping control statements are
used.
Java Conditional Statements.

• if statement
if(condition){
• if-else statement
//code to be executed
• if-else-if ladder }
• nested if statement

Java if Statement
• The Java if statement tests the condition. It executes the if block if condition is true.

public class IfExample {


public static void main(String[] args) {
int num=20;
if(num>0){
System.out.print("Positive");
}
}
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.

if(condition){ public class IfElseExample {


//code if condition is true public static void main(String[] args)
}else{ {
//code if condition is false int number=13;
} if(number%2==0){
System.out.println("even
number");
}else{
System.out.println("odd
number");
}
}
}
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements. It is used when more than 1 condition is to be checked in
relation with the problem.

if(condition1){ public class IfElseIfExample {


//code to be executed if condition1 public static void main(String[] args) {
is true int num=0;
}else if(condition2){
//code to be executed if condition2 if(num<0){
is true System.out.println("Negative");
} }
else if(condition3){ else if(num>0){
//code to be executed if condition3 System.out.println("Positive");
is true }
} }else{
... System.out.println("Neither Negative
else{ nor Positive");
//code to be executed if all the }
conditions are false }
} }
Java Switch Case Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. It is a multi-way branch
statement.

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10:
System.out.println("10");break;
case 20:
System.out.println("20");break;
case 30:
System.out.println("30");break;
default:System.out.println("Not in 10,
20 or 30");
}
}
}
While Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is
recommended to use while loop. Usually while loop is used to when we don’t know how many times do we need to iterate the
loop in advanced or the number of iterations is based on some condition.

public class WhileExample {


while(condition){
public static void main(String[] args)
//code to be executed
{
}
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you
must have to execute the loop at least once, it is recommended to use do-while loop. The Java do-while loop is executed at
least once because condition is checked after loop body.

public class DoWhileExample {


public static void main(String[] args) {
int i=10;
do{
System.out.println(i); // the loop will execute once even
when i=10 and condition is i<10
i++;
}while(i<10);
}
}
For Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to
use for loop. Typically used when number of iterations in pre defined or already known.

for loop syntax public class ForExample {


for(initialization;condition;incr/decr){ public static void main(String[] args) {
//code to be executed for(int i=1;i<=10;i++){
} System.out.println(i);
for(initialization;condition;incr/decr){ }
//code to be executed }
} }
Code Block, Indentation and Statement

Code Block
• Code block in Java is used for grouping of two or more statements. The code in Java always start with curly
braces and end with close curly braces.

• A code block can be used inside a block. There is no restriction number of block and the level of nesting the
block can be nested and can be included inside another Code block. It is generally used in loops statement
(For, while loop, do while loop). Class and method content are blocks too.

Code Indentation
• Indentation is part of style guide which is used to organize your source code in a good manner.
• An indentation is a group of style. This style should be followed by every programmer.
• If we follow proper style guide then the reader will be comfortable and understand the meaning of the
program.
The purpose of code indentation and style guide is to make the code:
• Easy to read
• Easy to understand
• Easy to modify
• Easy to maintain
• Easy to enhance

Incorrect Indentation
public static void main(String[] args) {

for (int i =1;i<=5; i++) {


for(int j=1; j<=i;j++) {
System.out.print("@ ");
}
System.out.println(" ");
}
}
Correct Indentation
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("@ ");
}
System.out.println(" ");
}
}
Statement
The statement is a complete set of information which provides some information to a programming language.

Expression statement
The expression is any section of the code that is used to evaluate the condition.

Declaration statement
Statement of the declaration is used to declare a variable.

Control flow statement


Control flow statement is If block, for, while loop. It is used to execute a set of statements repeatedly for
multiple times.
JavaBean class in Java
JavaBeans are classes that encapsulate many objects into a single object
(the bean). It is a java class that should follow following conventions:

• Must implement Serializable.


• It should have a public no-arg constructor.
• All properties in java bean must be private with public getters and
setter methods.
// Java program to illustrate the structure of JavaBean class

public class TestBean {


private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Java Program of JavaBean class

public class Student implements


java.io.Serializable
{
private int id;
public void setName(String name)
private String name;
{
public Student()
this.name = name;
{
}
}
public String getName()
public void setId(int id)
{
{
return name;
this.id = id;
}
}
}
public int getId()
{
return id;
}
Java program to access JavaBean class
package geeks;
public class Test {
public static void main(String args[])
{
Student s = new Student(); // object is created
s.setId(1);
System.out.println(s.getId());
s.setName("GFG"); // setting value to the object
System.out.println(s.getName());
}
}

Output:
1
GFG
What is a Class ?
It is a template or blueprint from which objects are created.
It is a logical entity. It can’t be physical.
A class in Java can contain:
Fields (variables)
methods
constructors
blocks
nested class and interface
What is n Object ?
An entity that has state and behavior is known as an object.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID.
• The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Relation Between Class and Object –
Object is an instance of a class.
Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
In another way, we can say that objects are variables of type class
Some Important Concepts that come along with Classes and Objects are –
• Instance variables
• Methods
• new keyword
Instance variable in Java
A variable which is created inside the class but outside the method, is known as instance variable.
Instance variable doesn’t get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword in Java
The new keyword is used to allocate memory at run time. All objects get memory in Heap
memory area.
package mystudentexample;
class Student{
int id; // instance variables
String name; // instance variables
}
public class MyStudentExample {
public static void main(String[] args) {
Student object1 = new Student();
object1.id = 1;
object1.name = “Srikanth";
Student obj2;
obj2 = new Student();
obj2.id = 2;
obj2.name = "Simple Snippets";
System.out.println(object1.id);
System.out.println(object1.name);
System.out.println(obj2.id);
System.out.println(obj2.name);
}
}
Java Methods
User-defined Methods
Types of Methods public class FunctionExample {
• Standard Library Methods
• User-defined Methods public int max(int x, int y)
{
if(x>y){
return x;
Standard Library Methods }
else {
public class Numbers { return y;
public static void main(String[] args) { }
}
System.out.print("Hello World");
public static void main(String[] args) {
} // TODO code application logic here
} FunctionExample obj = new FunctionExample();
int num = obj.max(5, 6); // FUNCTION CALL
System.out.println("Max value is: "+num);
}

}
Java Constructors Explained

A constructor is a special method in Java. It is called when an instance of object is created and
memory is allocated for the object. It is called constructor because it constructs the values at the time
of object creation.
Default Constructor
A constructor that has no parameter is known as default constructor. If we don’t define a constructor
in a class, then compiler creates default constructor(with no arguments) for the class.
Default constructor example
public class MyClass {
int number;
public MyClass() {
System.out.println("Constructor Called");
number=5;
}
public static void main(String[] args) {

MyClass obj = new MyClass(); // Constructor Called


System.out.println("Number value is: "+obj.number);
}
}
Parameterized Constructor
public class MyClass {
int number;
public MyClass(int x) {
System.out.println("Parameterized Constructor Called");
number=x;
}

public static void main(String[] args) {

MyClass obj = new MyClass(4); // Parameterized Constructor Called


System.out.println("Number value is: "+obj.number);
}
}
Constructor Overloading void displayData()
public class MyClass { {
int num1; System.out.println("Num1: "+num1+"\nNum2:
double num2; "+num2);
//Default Constructor
}
public MyClass()
public static void main(String[] args) {
{
System.out.println("Default Constructor Called");
MyClass obj1 = new MyClass(); // Default
num1=1;
num2=1.5;
Constructor Called
}
obj1.displayData();
//Parameterized Constructor 1 MyClass obj2 = new MyClass(5); //
public MyClass(int x) { Parameterized Constructor 1 Called
System.out.println("Parameterized Constructor 1 Called"); obj2.displayData();
num1=x; MyClass obj3 = new MyClass(5,5.5); //
} Parameterized Constructor 2 Called
//Parameterized Constructor 2 obj3.displayData();
public MyClass(int x, double z) { }
System.out.println("Parameterized Constructor 2 Called"); }
num1=x;
num2=z;
}
Simple Java Program for Practice
1. Swap of two numbers
Public class swap{
public static void main(String[] args)
{
int first = 5, second = 10;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
// Value of first is assigned to temporary
int temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}}
2. Number is positive or negative
public static void main(String[] args)
{
double number = 12;
if (number < 0.0)
{
System.out.println(number + " is a negative
number.");
}
else if ( number > 0.0)
{
System.out.println(number + " is a positive
number.");
}
else
{
System.out.println(number + " is 0.");
}
}
Recursion in Java
Recursion in Java is a process in which a method calls itself continuously. Using recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A method in java that calls itself is called
recursive method.
public class FactorialExample {
static int fact(int n)
{
if(n!=1)
{
return n*(fact(n-1));
}
else
{
return 1;
}
}
public static void main(String[] args)
{
System.out.println("Factorial of 4 is: "+fact(4));
}
}
Method Overloading
Method overloading in Java is a feature which makes it possible to use the same method name to
perform different tasks.
public static void main(String[] args)
{
public class Methodoverloading int a=5;
{ double b = 7.5;
double add(int x, double y) float c = 4.5f;
{ double result;
return(x+y); Methodoverloading obj = new Methodoverloading();
} result = obj.add(a, b);
double add(double x, int y) System.out.println("Addtion is: "+result);
{ result = obj.add(b, a);
return(x+y); System.out.println("Addtion is: "+result);
} result = obj.add(b,a,c);
double add(double x, int y, float z) System.out.println("Addtion is: "+result);
{ }
return(x+y+z); }
} Output:
Addition is: 12.5
Addition is: 12.5
Addition is: 17.0
static keyword
The static keyword in java is used primarily for memory management.
Static keyword can be used with class, variable, method and blocks.
The static keyword belongs to the class than instance of the class i.e if
you make a member static, you can access it without object.
The static can be:
• variable (also known as class variable)
• method (also known as class method)
• block
1. static Variable
public class Cube public static void main(String[] args)
{
{
Cube c1=new Cube();
int side;
Cube c2=new Cube(5);
static int objectCount=0; Cube c3=new Cube(8);
Cube() Cube c4=new Cube(10);
{ Cube c5=new Cube(11);
objectCount++; System.out.println("Number of Cube
} Objects: "+objectCount);
Cube(int x) }
}
{
Output: 05
side=x;
objectCount++;
}
2. static Method
Main Use: Object creation isn’t required, we can
directly access static method from main function
public class Cube
{
static int calculateCube(int side)
{
return (side*side*side);
}
public static void main(String[] args)
{
//System.out.println("Cube value of 5 is: "+calculateCube(5));
System.out.println("Cube value of 5 is: "+Cube.calculateCube(5));
}
}
NOTE:
Why java main method is static?
The main reason why java main() method is made static is because object is not required to call static method.
If it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory
allocation.
3. static Blocks in Java Output:
So in general static block – static block is invoked
• Is used to initialize the static data member. Cube value of 5 is: 125
• It is executed before main method at the time of classloading.
public class Cube {
static
{
System.out.println("static block is invoked");
}
static int calculateCube(int side)
{
return (side*side*side);
}
public static void main(String[] args) {
//System.out.println("Cube value of 5 is: "+calculateCube(5));
System.out.println("Cube value of 5 is: "+Cube.calculateCube(5));
}
}
CODE: static Class in Java
class JavaExample
{
private static String str = "TNS Java Sessions";
static class MyNestedClass
{
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
Arrays in Java with Program Examples
Arrays in Java are a group of like-typed variables that are referred to by a common name.
Array is a collection of similar type of elements that have contiguous memory location.
• Arrays in Java are Objects.
• In Java all arrays are dynamically allocated.(discussed below)
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• In case of primitives data types, the actual values are stored in contiguous memory locations.
• In case of objects of a class, the actual objects are stored in heap segment.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Single Dimensional Arrays
Creating, Initializing, and Accessing an Array
The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;
Instantiating an Array in Java
int intArray[]; //declaring array int[] intArray = new int[20]; // combining both statements in one
intArray = new int[20]; // allocating memory to array
class Testarray {
public static void main(String args[]) {

int a[] = new int[5]; //declaration and instantiation


a[0] = 10; //initialization
a[1] = 20;
a[2] = 70;
a[3] = 40;
a[4] = 50;

//printing array
for (int i = 0; i < a.length; i++) //length is the property of array
System.out.println(a[i]);

}
}
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
class Student // Elements of array are objects of a class Student. // so on...
public class GFG arr[2] = new Student(3,"shikar");
{ { arr[3] = new Student(4,"dharmesh");
public static void main (String[] args) arr[4] = new Student(5,"mohit");
public int roll_no; {
public String name; // declares an Array of integers. // accessing the elements of the specified
Student[] arr; array
Student(int roll_no, String name) for (int i = 0; i < arr.length; i++)
// allocating memory for 5 objects of type Student. System.out.println("Element at " + i + " : "
{
arr = new Student[5]; +
this.roll_no = roll_no; arr[i].roll_no +" "+ arr[i].name);
// initialize the first elements of the array }
this.name = name; arr[0] = new Student(1,"aman"); }
}
// initialize the second elements of the array
} arr[1] = new Student(2,"vaibhav");
Java Multi Dimensional Arrays
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
2-D Array in Java Example Program
class multiDimensional
{
public static void main(String args[])
{
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Jagged array in java is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D
arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.
Inheritance and types
// Program to demonstrate 2-D jagged array in Java
// Displaying the values of 2D Jagged array
class Main System.out.println("Contents of 2D
{ Jagged Array");
public static void main(String[] args) for (int i=0; i<arr.length; i++)
{ {
// Declaring 2-D array with 2 rows
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
int arr[][] = new int[2][];
System.out.println();
// Making the above array Jagged }
// First row has 3 columns }
arr[0] = new int[3]; }
// Second row has 2 columns
arr[1] = new int[2]; Contents of 2D Jagged Array
// Initializing array 012
int count = 0; 34
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
Strings
• string is basically an object that represents sequence of char values. An array of characters works same as
Java string.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";

• Java String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three
classes.

• The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created.
For mutable strings, you can use StringBuffer and StringBuilder classes.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.

How to create a string object?


There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
• String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool,
a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:
• String s1="Welcome";
Why Java uses the concept of String literal?
• String s2="Welcome";//It doesn't create a new instance To make Java more memory efficient (because no new objects
are created if it exists already in the string constant pool).
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed
in the string constant pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
public class StringExample{
Output:
public static void main(String args[]){
String s1="java";//creating string by Java string literal java
char ch[]={'s','t','r','i','n','g','s'}; strings
example
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Immutable String in Java
In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new String object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with Sachin
Tendulkar. That is why String is known as immutable.
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
Note:
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not modified.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override the methods of the String class. So that it can
provide the same features to the new String objects as well as to the old ones.
Java String compare
We can compare String in Java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare String in Java:


By Using equals() Method
By Using == Operator
By compareTo() Method
1) By Using equals() Method
The String class equals() method compares the original content of the string. It compares values of string for equality. String
class provides the following two methods:
• public boolean equals(Object another) compares this string to the specified object.
• public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring case.

class Teststringcomparison1{
class Teststringcomparison2{
public static void main(String args[]){
public static void main(String args[]){
String s1="Sachin";
String s1="Sachin";
String s2="Sachin"; String s2="SACHIN";
String s3=new String("Sachin");
String s4="Saurav"; System.out.println(s1.equals(s2));//false
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true System.out.println(s1.equalsIgnoreCase(s2));//tru
System.out.println(s1.equals(s4));//false e
} }
} }
2) By Using == operator

The == operator compares references not values.


class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:

true
false
3) String compare by compareTo() method
The above code, demonstrates the use of == operator used for comparing two String objects.
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or
greater than second string.
Suppose s1 and s2 are two String objects. If:
s1 == s2 : The method returns 0.
s1 > s2 : The method returns a positive value.
s1 < s2 : The method returns a negative value.
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
String Concatenation in Java
In Java, String concatenation forms a new String that is the combination of multiple strings. There are two ways to concatenate strings in Java:
• By + (String concatenation) operator
• By concat() method
1) String Concatenation by + (String concatenation) operator
Java String concatenation operator (+) is used to add strings. For Example:

class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output:
Sachin Tendulkar
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string.
Syntax:
public String concat(String another)

class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
There are some other possible ways to concatenate Strings in Java,
String s2="Tendulkar";
String s3=s1.concat(s2);
1. String concatenation using StringBuilder class
System.out.println(s3);//Sachin Tendulkar 2. String concatenation using format() method
} 3. String concatenation using String.join() method (Java Version 8+)
} 4. String concatenation using StringJoiner class (Java Version 8+)
Test it Now 5. String concatenation using Collectors.joining() method (Java Version 8+)
Output:

Sachin Tendulkar
Substring in Java
• A part of String is called substring. In other words, substring is a subset of another String.
• Java String class provides the built-in substring() method that extract a substring from the given string by using the index
values passed as an argument.
• In case of substring() method startIndex is inclusive and endIndex is exclusive.

You can get substring from the given String object by one of the two methods:

• public String substring(int startIndex):


This method returns new String object containing the substring of the given string from specified startIndex (inclusive). The
method throws an IndexOutOfBoundException when the startIndex is larger than the length of String or less than zero.
• public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from specified startIndex to endIndex. The
method throws an IndexOutOfBoundException when the startIndex is less than zero or startIndex is greater than endIndex or
endIndex is greater than length of String.
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java is the same as
String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in
an order.
Important Constructors of StringBuffer Class
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
What is a mutable String?
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes are used for
creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.
StringBufferExample.java
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.

StringBufferExample2.java

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:

HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.

StringBufferExample3.java

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:

HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.

StringBufferExample4.java

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:

Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:

olleH
Java StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as StringBuffer
class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class


Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
Java StringBuilder Examples
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this String.
StringBuilderExample.java

class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:

Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.

StringBuilderExample2.java

class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:

HJavaello
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.

StringBuilderExample3.java

class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:

HJavalo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

StringBuilderExample4.java

class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:

Hlo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

StringBuilderExample4.java

class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:

Hlo
Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given
below:
Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.

//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.

public class ConcatTest{

public static void main(String[] args){

long startTime = System.currentTimeMillis();

StringBuffer sb = new StringBuffer("Java");

for (int i=0; i<10000; i++){

sb.append("Tpoint");

System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");

startTime = System.currentTimeMillis();

StringBuilder sb2 = new StringBuilder("Java");

for (int i=0; i<10000; i++){

sb2.append("Tpoint");

System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");

Time taken by StringBuffer: 16ms

Time taken by StringBuilder: 0ms


Java String charAt()
• The Java String class charAt() method returns a char value at the given index number.
• The index number starts from 0 and goes to n-1, where n is the length of the string.
• It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a
negative number.
Syntax
public char charAt(int index)
• The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a
string.
• It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length
Internal implementation
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
Note:
throw new StringIndexOutOfBoundsException(index);
CharSequence interface, located inside java.lang package.
}
return value[index];
}
2 public class CharAtExample{
1 Java String charAt() Method Examples public static void main(String args[]){
public class CharAtExample{
String name="javatpoint";
char ch=name.charAt(10);//returns the char value at the 10th index
public static void main(String args[]){
System.out.println(ch);
String name="javatpoint"; }}
char ch=name.charAt(4);//returns the char value at the 4th index Output:
System.out.println(ch);
}} Exception in thread "main"
Output:
java.lang.StringIndexOutOfBoundsException:
String index out of range: 10
t
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)
Accessing First and Last Character by Using the charAt() Method
public class CharAtExample3 {
public static void main(String[] args) {
String str = "Welcome to Javatpoint portal";
int strLength = str.length();
// Fetching first character
System.out.println("Character at 0 index is: "+ str.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: "+ str.charAt(strLength-1));
}
}

Output:
Character at 0 index is: W
Character at last index is: l
Print Characters Presented at Odd Positions by Using the charAt() Method
Let's see an example where we are accessing all the elements present at odd index.
Output:
FileName: CharAtExample4.java
Char at 1 place e
Char at 3 place c
public class CharAtExample4 { Char at 5 place m
public static void main(String[] args) {
Char at 7 place
Char at 9 place o
String str = "Welcome to Javatpoint portal"; Char at 11 place J
for (int i=0; i<=str.length()-1; i++) { Char at 13 place v
if(i%2!=0) { Char at 15 place t
Char at 17 place o
System.out.println("Char at "+i+" place "+str.charAt(i));
Char at 19 place n
} Char at 21 place
} Char at 23 place o
} Char at 25 place t
Char at 27 place l
}
Counting Frequency of a character in a String by Using the charAt() Method
FileName: CharAtExample5.java
public class CharAtExample5 {
public static void main(String[] args) {
String str = "Welcome to Javatpoint portal";
int count = 0;
for (int i=0; i<=str.length()-1; i++) {
if(str.charAt(i) == 't') {
count++;
}
}
System.out.println("Frequency of t is: "+count);
}
}
Output:
Frequency of t is: 4
Java String compareTo()
The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a
positive number, negative number, or 0.
It compares strings on the basis of the Unicode value of each character in the strings.
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
Syntax
public int compareTo(String anotherString)
The method accepts a parameter of type String that is to be compared with the current string.

It returns an integer value. It throws the following two exceptions:


ClassCastException: If this object cannot get compared with the specified object.
NullPointerException: If the specified object is null.
Java String compareTo() Method Example
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-1 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//1 because "h" is 2 times greater than "f"
}}
Java String concat
The Java String class concat() method combines specified string at the end of this string. It returns a
combined string. It is like appending another string.

Signature
The signature of the string concat() method is given below:

public String concat(String anotherString)


Parameter
anotherString : another string i.e., to be combined at the end of this string.

Returns
combined string
Java String concat() method example
public class ConcatExample{
public static void main(String args[]){
String s1="java string";
// The string s1 does not get changed, even though it is invoking the method
// concat(), as it is immutable. Therefore, the explicit assignment is required here.
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}
java string
java string is immutable so assign it explicitly
Java String concat() Method Example 3
Let's see an example where we are concatenating spaces and special chars to the string object. It is done using the chaining of the concat()
method.
public class ConcatExample3 {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Javatpoint";
String str3 = "Reader";
// Concatenating Space among strings
String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
System.out.println(str4);
// Concatenating Special Chars
String str5 = str1.concat("!!!");
System.out.println(str5); }}

Output:
Hello Javatpoint Reader
Hello!!!
Java String contains()
The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found
in this string otherwise returns false.

Signature
The signature of string contains() method is given below:

public boolean contains(CharSequence sequence)


Parameter
sequence : specifies the sequence of characters to be searched.

Returns
true if the sequence of char value exists, otherwise false.

Exception
NullPointerException : if the sequence is null.
Java String contains() Method Example
FileName: ContainsExample.java

class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}
Output:

true
true
false
The contains() method searches case-sensitive char sequence. If the argument is not case sensitive, it returns false. Let's see an
example.

FileName: ContainsExample2.java

public class ContainsExample2 {


public static void main(String[] args) {
String str = "Hello Javatpoint readers";
boolean isContains = str.contains("Javatpoint");
System.out.println(isContains);
// Case Sensitive
System.out.println(str.contains(“JAVATPOINT")); // false
}
}
Output:
true
false
Java String endsWith()
The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with
the given suffix; else returns false.

Signature
The syntax or signature of endsWith() method is given below.

public boolean endsWith(String suffix)


Parameter
suffix : Sequence of character

Returns
true or false
Java String endsWith() Method Example
FileName: EndsWithExample.java

public class EndsWithExample{


public static void main(String args[]){
String s1="java by javatpoint";
System.out.println(s1.endsWith("t"));
System.out.println(s1.endsWith("point"));
}}
Output:

true
true
Java String equals()
The Java String class equals() method compares the two given strings based on the content of the string. If any character is not
matched, it returns false. If all characters are matched, it returns true.

The String equals() method overrides the equals() method of the Object class.

Signature
publicboolean equals(Object anotherObject)
Parameter
anotherObject : another object, i.e., compared with this string.

Returns
true if characters of both strings are equal otherwise false.
Java String equals() Method Example
FileName: EqualsExample.java
public class EqualsExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
Output:
true
false
false
Java String equalsIgnoreCase()
The Java String class equalsIgnoreCase() method compares the two given strings on the basis of the content of the string
irrespective of the case (lower and upper) of the string. It is just like the equals() method but doesn't check the case sensitivity.
If any character is not matched, it returns false, else returns true.

Signature
publicboolean equalsIgnoreCase(String str)
Parameter
str : another string i.e., compared with this string.

Returns
It returns true if characters of both strings are equal, ignoring case otherwise false.
Java String equalsIgnoreCase() Method Example
FileName: EqualsIgnoreCaseExample.java

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same
System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
}}
true
true
false
format()
getbytes()
getchars()
inexof()
intern()
isempty()
join()
lastindexof()
length()
replace()
replaceall()
split()
startswith()
substring()
tochararray()
toLowercase()
toUpperCase()
trim()
valueof()
Java Single Inheritance Program Example –
class Animal class TestInheritance
{ {
void eat() public static void main(String args[])
{
{
Dog d=new Dog();
System.out.println("eating...");
d.bark();
}
d.eat();
} }
class Dog extends Animal }
{
void bark()
{
System.out.println("barking...");
}
}
Single Level Inheritence – Program 2
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Java Multilevel Inheritance Program Example –
class Animal {
class TestInheritance2 {
void eat() { public static void main(String args[]) {
System.out.println("eating..."); BabyDog d = new BabyDog();
} d.weep();
} d.bark();
d.eat();
class Dog extends Animal {
}
void bark() {
}
System.out.println("barking...");
}
}
class BabyDog extends Dog {
void weep() {
System.out.println("weeping...");
}
}
Multilevel Inheritence – Example2 Class SubClass2 extends SubClass1
{
Class SuperClass public void methodC()
{ {
public void methodA()
System.out.println("SubClass2");
}
{
public static void main(String args[])
System.out.println("SuperClass"); {
} SubClass2 obj = new SubClass2();
} SubClass2.methodA(); //calling super class
Class SubClass1 extends SuperClass method
{
SubClass2.methodB(); //calling subclass 1
method
public void methodB()
SubClass2.methodC(); //calling own method
{
}
System.out.println("SubClass1 "); }
}
}
Java Hierarchial Inheritance Program Example –
class Animal { class TestInheritance3 {
void eat() { public static void main(String args[]) {
System.out.println("eating..."); Cat c = new Cat();
}
c.meow();
c.eat();
}
//c.bark();//C.T.Error
class Dog extends Animal { }
void bark() { }
System.out.println("barking...");
}
}
class Cat extends Animal {
void meow() {
System.out.println("meowing...");
}
}
Java Hierarchial Inheritance Program Example –2
Class A Class C extends A
{
{
public void methodC()
public void methodA() {
{ System.out.println("Sub class Method C");
System.out.println("Super class method"); }
}
public static void main(String args[])
{
}
A obj1 = new A();
Class B extends A B obj2 = new B();
{ C obj3 = new C();
public void methodB() obj1.methodA(); //calling super class method
obj2.methodA(); //calling A method from subclass
{
object
System.out.println("Sub class Method B"); obj3.methodA(); //calling A method from subclass
} object
} }
}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A
and B classes have same method and you call it from child class object, there will be ambiguity to
call method of A or B class.
In C++ we have virtual keyword to tackle this ambiguity however, in Java Multiple Inheritance is
possible only via Interfaces.
Java Even Odd Program Code Example –
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Java Largest of Three Numbers Program Code Example –
import java.util.Scanner;

class LargestOfThreeNumbers

public static void main(String args[])

int x, y, z;

System.out.println("Enter three integers ");

Scanner in = new Scanner(System.in);

x = in.nextInt();

y = in.nextInt();

z = in.nextInt();

if ( x > y && x > z )

System.out.println("First number is largest.");

else if ( y > x && y > z )

System.out.println("Second number is largest.");

else if ( z > x && z > y )

System.out.println("Third number is largest.");

else

System.out.println("Entered numbers are not distinct.");

}
Swapping of 2 Variables using 3rd Variable in C++
#include <iostream>
using namespace std;

int main() {
int a,b,c;
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
cout<<"Before Swapping: a: "<<a<<" b: "<<b<<endl;
// start: swapping logic
c=a;
a=b;
b=c;
// end: swapping logic
cout<<"After Swapping: a: "<<a<<" b: "<<b<<endl;
return 0;
}
Swapping of 2 Variables Without using 3rd Variable in C++
#include <iostream>
using namespace std;

int main() {
int a,b;

cout<<"Enter value of a: ";


cin>>a;
cout<<"Enter value of b: ";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"After swap a: "<<a<<" b: "<<b;
return 0;
}
Java program to check LEAP year
public class JavaApplication4 {
public static void main(String[] args) {
int year = 2020;
if(year%400==0)
{
System.out.println("Leap Year");
}
else if(year%4==0 && year%100!=0)
{
System.out.println("Leap Year");
}
else
{
System.out.println("Not a Leap Year");
}
}
}
Java program to Find Factorial of a Number
public class JavaApplication4 {
public static void main(String[] args) {

int num = 4;
int factorial =1;
for(int i = num; i>0; i--)
{
factorial = factorial *i;
}
System.out.println("Factorial is: "+factorial);

}
}
Java program to Find if a Number is PALINDROME or not –

package javaapplication4;

public class JavaApplication4 {

public static void main(String[] args) {

int num=121;

int temp=num;

int rev = 0;

while(num>0)

rev = rev*10;

rev = rev + num%10;

num = num/10;

if(temp == rev)

System.out.println("Palindrome");

else

System.out.println("Not Palindrome");

}
Java Program to Print FIBONACCI Series using FOR LOOP
// 0 + 1 + 1 + 2 + 3 + 5 + 8 +

package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c;
for(int i = 0; i<5 ; i++)
{
System.out.print(a+" ");
c = a+b;
a=b;
b=c;
}

}
}
Polymorphism in Java – Method Overloading | Method Overriding
• Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms.
So Polymorphism means the ability to take many forms.
• Polymorphism is a concept by which we can perform a single task in different ways.

• Compile Time Polymorphism – Method Overloading


• Run Time Polymorophism – Method Overriding
Run Time Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at
runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. Thus this happens only when
Inheritance is implemented.
The method to be called is based on the object being referred to by the reference variable.
Some Rules to follow in Method Overriding –
• Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than
the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in
the subclass.
• Final methods can not be overridden.
• Static methods can not be overridden(Method Overriding vs Method Hiding).
• Private methods can not be overridden.
• The overriding method must have same return type (or subtype)
• Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.
// A Simple Java program to demonstrate // Driver class
// method overriding in java class Main
// Base Class {
public static void main(String[] args)
class Parent
{
{ // If a Parent type reference refers
void show() { System.out.println("Parent's show()"); } // to a Parent object, then Parent's
}
// show is called
Parent obj1 = new Parent();
// Inherited class obj1.show();
class Child extends Parent
{ // If a Parent type reference refers
// to a Child object Child's show()
// This method overrides show() of Parent
// is called. This is called RUN TIME
@Override // POLYMORPHISM.
void show() { System.out.println("Child's show()"); } Parent obj2 = new Child();
} obj2.show();
}
}
Packages in Java
• Package in java as the name suggests is a pack(group) of classes, interfaces and other packages.
• Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

Packages are used for:


• Preventing naming conflicts. For example there can be two classes with name Teacher in two
packages, college.staff.icse.Teacher and college.staff.cbse.Teacher
• Making searching/locating and usage of classes, interfaces, enumerations and annotations easier.
• Providing access control: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member
(without any access specifier) is accessible by classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding).
Package in java can be categorized in two form,
• built-in package
• user-defined package.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
import package.*;
import package.classname;
1) Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
• The import keyword is used to make the classes and interface of another package accessible to the
current package.
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Packages Example Step 2: import pack.*;
Step1 : package pack; import Subpackage.*;
public class A{ class B{
public void msg(){System.out.println("Hello A");} public static void main(String args[]){
A obj = new A();
}
C obj1 = new C();
Step 1.1 package pack; D obj2 = new D();
public class C { obj.msg();
public void msg() obj1.msg();
{ obj2.msg();
System.out.println("Hello C"); }
}
}
}
Step 1.3 package Subpackage;

public class D {

public void msg()


{System.out.println("Hello D");}
}
Classes-Getters and Setters:
• In Java, Getter and setter methods are used to retrieve and update the private variables.
• When you hide the implementation of the object of the class from the outer world, you declare them as private.
• As private members of the class are not accessible from outside the class, so we use the getter and setter method to retrieve and update the
values of private members.
public class Car {
private String doors;
private String engine;
private String drivers;
public int speed;
}
public class Hello {
public static void main(String[] args) {
Car obj = new Car();
obj.speed=1;
System.out.println(obj.speed);
}
}
Output:
1
Example2
public class Car {
private String doors;
private String engine; public class Hello{
private String drivers; public static void main(String[] args) {
private int speed; Car car = new Car ();
car.setspeed (10);
public void setspeed(int speed) { System.out.println (car.getspeed());
this.speed=speed; }
} }

public int getspeed() { Output :


return speed; 10
}

}
Source >> Generate Getter and Setter public String getEngine() {
public class Car { return engine;
private String doors;
}
private String engine;
private String drivers;
private int speed; public void setEngine(String engine) {
this.engine = engine;
public int getspeed() { }
return speed;
} public String getDrivers() {
return drivers;
public void setspeed(int speed) {
this.speed = speed; }
}
public void setDrivers(String drivers) {
public String getDoors() { this.drivers = drivers;
return doors; }
}
public void setDoors(String doors) {
}
this.doors = doors;
}
public class Car {
private String doors;
private String engine; public static void main(String[] args) {
private String driver; Car car = new Car ();
private int speed; car.setspeed (10);
car.setDoors ("closed");
car.setEngine ("on");
public String run() { car.setDrivers ("seated");
if(doors.equals("closed") &&
engine.equals("on")&& driver.equals("seated")
//calling the function
&& speed System.out.println (car.run ());
>0) {
return "car is running"; }
}else {
return "car is not Output
running"; car is running
}
}
Access Modifiers in Java
Access modifiers in java specify the scope of a class, constructor ,
variable , method or data member.
There are four types of access modifiers available in java:
• Private - The private access modifier is accessible only within class
• Default – No keyword required - accessible only within package.
• Protected - is accessible within package and outside the package but
through inheritance only
• Public - The public access modifier is accessible everywhere
Private Access Modifier
The private access modifier is accessible only within class. The private access modifier is
specified using the keyword private.
• The methods or data members declared as private are accessible only within the
class in which they are declared.
• Any other class of same package will not be able to access these members.
• Classes or interface can not be declared as private.
package p1; class B Output
class A { error: display() has private access in A
{ public static void main(String args[]) obj.display();
private void display() {
A obj = new A();
{
//trying to access private method of
System.out.println("TNS Sessions");
another class
} obj.display();
} }
}
Default Access Modifier
If you don’t use any modifier, it is treated as default by default. The default modifier is accessible
only within package.
• The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package.

package p1; package p2;


//Class MyClass1 is having Default import p1.*;
access modifier //This class is having default access modifier
class MyClass1 class MyClass2
{ {
void display() public static void main(String args[])
{ {
System.out.println("Hello World!"); //accessing class MyClass1 from package p1
} MyClass1 obj = new MyClass1();
} obj.display();
}
}
Output
Compile time error
Protected Access Modifier
The protected access modifier is specified using the keyword protected.
• The protected access modifier is accessible within package and outside the package but through inheritance only.
• The protected access modifier can be applied on the data member, method and constructor.
• It can’t be applied on the class.

package p1; package p2;


import p1.*;
public class A public class B extends A
{ {
protected void display() public static void main(String[] args)
{
{ B obj = new B();
System.out.println("TNS obj.display();
Sessions"); }
}
} Output: TNS Sessions
}
Public Access Modifier
The public access modifier is specified using the keyword public.
• The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
• Classes, methods or data members which are declared as public are accessible from every where in
the program. There is no restriction on the scope of a public data members.

package p1; package p2;


public class A import p1.*;
class B
{ {
public void display() public static void main(String[] args)
{ {
System.out.println("TNS Sessions"); A obj = new A();
obj.display();
} }
} }
Output: TNS Sessions
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context.
Final can be:
1. variable
2. method
3. class
Final is a non-access modifier applicable only to a variable, a method or a class.
Basically final keyword is used to perform 3 tasks as follows –
1. To create constant variables
2. To prevent method overriding
3. To prevent Inheritance
Java final variable
• If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Java final method
• If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


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

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


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

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Is final method inherited?
Yes, final method is inherited but you cannot override it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Super Keyword in Java
The super keyword in java is a reference variable which is used to refer immediate parent class
object. The keyword “super” came into the picture with the concept of Inheritance.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.
Uses of java super Keyword –
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor
1) super is used to refer immediate parent class instance variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
2) super can be used to invoke parent class method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
3) super is used to invoke parent class constructor.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Methods
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract void disp();
1. In Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.

abstract class Base


class Main
{ {
public static void main(String args[])
abstract void fun();
{
} // Uncommenting the following line will cause compiler error as the
class Derived extends Base // line tries to create an instance of abstract class.
// Base b = new Base();
{ // We can have references of Base type.
void fun() Base b = new Derived();
b.fun();
{ }
System.out.println("Derived fun() called"); }
Output
} Derived fun() called
}
2. An abstract class can contain constructors in Java. And a constructor of abstract class is
called when an instance of a inherited class is created.
abstract class Base
{ void fun()
Base() {
System.out.println("Derived fun() called");
{
}
System.out.println("Base Constructor Called");
}
} class Main
abstract void fun(); {
} public static void main(String args[])
class Derived extends Base {
Derived d = new Derived();
{
}
Derived()
}
{ Output
System.out.println("Derived Constructor Called"); Base Constructor Called
} Derived Constructor Called
Java Interfaces Explained with Program
• An interface in java is a mechanism to achieve abstraction.
• Like a class, an interface can have methods and variables, but the methods declared in interface are by default
abstract (only method signature, no body).
• It is used to achieve abstraction and multiple inheritance in Java
• Interfaces specify what a class must do and not how.
• It is the blueprint of the class.
• If a class implements an interface and does not provide method bodies for all functions specified in the
interface, then class must be declared abstract.
• By interface, we can support the functionality of multiple inheritance.
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
• An interface can contain any number of methods.
How to Declare Interfaces ?
Interface is declared by using interface keyword. It provides total abstraction; means all the
methods in interface are declared with empty body and are public and all fields are public, static
and final by default. A class that implement interface must implement all the methods declared in
the interface
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
interface Bank
class ICICI implements Bank
{ {
public float rateOfInterest()
float rateOfInterest();
{
} return 9.7f;
}
class SBI implements Bank
}
{ public class JavaApplication4
{
public float rateOfInterest()
public static void main(String[] args)
{ {
Bank b = new SBI();
return 9.15f;
System.out.println("ROI: " + b.rateOfInterest());
} }
}
}
Multiple Interfaces
To implement multiple interfaces, separate them with a comma: class Main {
interface FirstInterface { public static void main(String[] args) {
public void myMethod(); // interface method DemoClass myObj = new DemoClass();
} myObj.myMethod();
interface SecondInterface { myObj.myOtherMethod();
public void myOtherMethod(); // interface method }
} }
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
Java Scanner Class
The Scanner class of the java.util package is used to read input data from different sources like input streams, users, files, etc
Import Scanner Class
As we can see from the above example, we need to import the java.util.Scanner package before we can use the Scanner class.
import java.util.Scanner;

Example 1: Read a Line of Text Using Scanner


import java.util.Scanner;
class Main {
Note : The System.in parameter is used to take input from
public static void main(String[] args) { the standard input. It works just like taking inputs from the
// creates an object of Scanner keyboard.
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: "); We have then used the nextLine() method of the Scanner
// takes input from the keyboard class to read a line of text from the user.
String name = input.nextLine(); Output:
// prints the name
System.out.println("My name is " + name); Enter your name: Suresh
// closes the scanner My name is Suresh
input.close();
}
}
Java Scanner Methods to Take Input
The Scanner class provides various methods that allow us to read inputs of different types.

Method Description
nextInt() reads an int value from the user
nextFloat() reads a float value form the user
nextBoolean() reads a boolean value from the user
nextLine() reads a line of text from the user
next() reads a word from the user
nextByte() reads a byte value from the user
nextDouble() reads a double value from the user
nextShort() reads a short value from the user
nextLong() reads a long value from the user
Example 2: Java Scanner nextInt()

import java.util.Scanner; Output:


class Main {
public static void main(String[] args) { Enter an integer:
22
// creates a Scanner object
Using nextInt(): 22
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
// reads an int value
int data1 = input.nextInt();
System.out.println("Using nextInt(): " + data1);
input.close();
}
}
Example 3: Java Scanner nextDouble()
import java.util.Scanner;
class Main {
Output:
public static void main(String[] args) {
// creates an object of Scanner Enter Double value: 33.33
Using nextDouble(): 33.33
Scanner input = new Scanner(System.in);
System.out.print("Enter Double value: ");
// reads the double value
double value = input.nextDouble();
System.out.println("Using nextDouble(): " + value);
input.close();
}
}
Example 4: Java Scanner next()
import java.util.Scanner;
class Main {
Output:
public static void main(String[] args) {
// creates an object of Scanner Enter Double value: 33.33
Using nextDouble(): 33.33
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// reads the entire word
String value = input.next();
System.out.println("Using next(): " + value);
input.close();
}
}
Example 4: Java Scanner next()
import java.util.Scanner;
class Main {
Output:
public static void main(String[] args) {
// creates an object of Scanner Enter your name: Jonny Walker
Using next(): Jonny
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// reads the entire word
String value = input.next();
System.out.println("Using next(): " + value);
input.close();
}
}
Example 5: Java Scanner nextLine()
import java.util.Scanner;
class Main { Output:
public static void main(String[] args) {
Enter your name: Suresh Raina
// creates an object of Scanner Using nextLine(): Suresh Raina
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// reads the entire line
String value = input.nextLine();
System.out.println("Using nextLine(): " + value);
input.close();
}
}
Java Scanner with BigInteger and BigDecimal
Java scanner can also be used to read the big integer and big decimal numbers.
nextBigInteger() - reads the big integer value from the user
nextBigDecimal() - reads the big decimal value from the user

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Scanner; Output:
class Main { Enter a big integer: 987654321
public static void main(String[] args) { Using nextBigInteger(): 987654321
// creates an object of Scanner Enter a big decimal: 9.55555
Scanner input = new Scanner(System.in);
Using nextBigDecimal(): 9.55555
System.out.print("Enter a big integer: ");
// reads the big integer
BigInteger value1 = input.nextBigInteger();
System.out.println("Using nextBigInteger(): " + value1);
System.out.print("Enter a big decimal: ");
// reads the big decimal
BigDecimal value2 = input.nextBigDecimal();
System.out.println("Using nextBigDecimal(): " + value2);
input.close();
}
}
Java Scanner
• Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner
class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default.
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Java File Handling
Java Create and Write To Files
Create a File
To create a file in Java, you can use the createNewFile() method.
This method returns a boolean value: true if the file was successfully created, and false if the file already exists.
Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some
reason):
Example
catch (IOException e) {
import java.io.File; // Import the File class
System.out.println("An error occurred.");
import java.io.IOException; // Import the IOException class to handle errors
e.printStackTrace();
public class CreateFile { }
public static void main(String[] args) { }
try { }
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
}
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you
are done writing to the file, you should close it with the close() method:

import java.io.FileWriter; // Import the FileWriter class


import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter:
Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename1.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Delete a File
To delete a file in Java, use the delete() method:

Example
import java.io.File; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("filename1.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Java - Exceptions
• An exception (or exceptional event) is a problem that arises during the execution of a program.
• When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.

An exception can occur for many different reasons.


• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of memory.

Categories of Exceptions
• Checked exceptions
• Unchecked exceptions
• Errors
Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as compile time exceptions.
For example: if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to
handle the exception.
import java.io.File; C:\>javac FilenotFound_Demo.java
import java.io.FileReader; FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be
thrown
public class FilenotFound_Demo { FileReader fr = new FileReader(file);
^
1 error
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of
an API.
public class Unchecked_Demo {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5


at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error
which is derived from the Throwable class.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description

Try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not
throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't


throw an exception. It specifies that there may occur an exception
in the method. It is always used with method signature.
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Exception in thread main java.lang.ArithmeticException:/


by zero
rest of the code...
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will
occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
• Java try block is used to enclose the code that might throw an exception. It must be used within the method.
• If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is
recommended not to keeping the code in try block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}
Problem without exception handling Solution by exception handling

public class TryCatchExample1 { public class TryCatchExample2 {

public static void main(String[] args) {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception int data=50/0; //may throw exception
}
//handling the exception
System.out.println("rest of the code");
catch(ArithmeticException e)
{
} System.out.println(e);
}
System.out.println("rest of the code");
}
}

}
Java catch multiple exceptions
public class MultipleCatchBlock2 {
public class MultipleCatchBlock1 {
public static void main(String[] args) {
public static void main(String[] args) {
try{
try{ int a[]=new int[5];
int a[]=new int[5];
a[5]=30/0; System.out.println(a[10]);
} }
catch(ArithmeticException e) catch(ArithmeticException e)
{ {
System.out.println("Arithmetic Exception occurs"); System.out.println("Arithmetic Exception occurs");
} }
catch(ArrayIndexOutOfBoundsException e) catch(ArrayIndexOutOfBoundsException e)
{ {
System.out.println("ArrayIndexOutOfBounds System.out.println("ArrayIndexOutOfBounds
Exception occurs"); Exception occurs");
} }
catch(Exception e) catch(Exception e)
{ {
System.out.println("Parent Exception occurs"); System.out.println("Parent Exception occurs");
} }
System.out.println("rest of the code"); System.out.println("rest of the code");
} }
} }
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java Nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
class Excep6{
public static void main(String args[]){
going to divide
try{
java.lang.ArithmeticException: / by zero
try{
java.lang.ArrayIndexOutOfBoundsException: Index
System.out.println("going to divide");
5 out of bounds for length 5
int b =39/0;
other statement
}catch(ArithmeticException e){System.out.println(e);}
normal flow..
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.

Case 1: exception doesn't occur. Case 2: exception occurs and not handled.
class TestFinallyBlock{ class TestFinallyBlock1{
public static void main(String args[]){ public static void main(String args[]){
try{ try{
int data=25/5; int data=25/0;
System.out.println(data); System.out.println(data);
} }
catch(NullPointerException e){System.out.println(e);} catch(NullPointerException e)
finally{System.out.println("finally block is always {System.out.println(e);}
executed");} finally{System.out.println("finally block is always
System.out.println("rest of the code..."); executed");}
} System.out.println("rest of the code...");
} }
}
Output: Output:
5
finally block is always executed
finally block is always executed
rest of the code... Exception in thread main
java.lang.ArithmeticException:/ by zero
Case 3: exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

Output: Exception in thread main


java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.

The syntax of java throw keyword is given below.


throw exception;
Example Output:
public class TestThrow1{
static void validate(int age){
Exception in thread main
if(age<18)
java.lang.ArithmeticException:not valid
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an
exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
import java.io.IOException; void p(){
class Testthrows1{ try{
void m()throws IOException{
n();
}catch(Exception e){System.out.println("exception
throw new IOException("device error");//checked exception
handled");}
} }
void n()throws IOException{ public static void main(String args[]){
m(); Testthrows1 obj=new Testthrows1();
} obj.p();
System.out.println("normal flow...");
}
}
Java Pass by Value vs Pass by Reference
• Pass by Value: The method parameter values are copied to another variable and then the copied variable is passed, that’s
why it’s called pass by value.
• Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by
reference.
• Code for pass by value
public class JavaApplication4 { Output:
static void displayPrimitive(int a) Before the function a: 5
{ Inside Display Primitive method
System.out.println("Inside Display Primitive method");
a :10
a=a+5;
After the function a: 5
System.out.println("a :"+a);
}
public static void main(String[] args) {
int a =5;
System.out.println("Before the function a: "+a);
displayPrimitive(a);
System.out.println("After the function a: "+a);
}
}
Pass by Reference –
public class JavaApplication4 {
Output:
static void displayArray(int[] a) Before the method
{ 222
System.out.println("\nInside Display Array method"); Inside Display Array method
a[0]=0; a[1]=0; a[2]=0; 000
for(int i=0;i<3;i++) After the function
System.out.print(a[i]+" ");
000
}
public static void main(String[] args) {
int arr[] = {2,2,2};
System.out.println("Before the function");
for(int i=0;i<3;i++)
System.out.print(arr[i]+" ");
displayArray(arr);
System.out.println("\nAfter the function");
for(int i=0;i<3;i++)
System.out.print(arr[i]+" ");
}
}
Wrapper Classes in Java | Autoboxing vs Unboxing
• The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into corresponding
objects.
• A Wrapper class is a class whose object wraps or contains a primitive data types.
• Wrapper classes in java provides the mechanism to convert primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive
automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa
unboxing.
Autoboxing
Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing.
For example – conversion of int to Integer, long to Long, double to Double etc.
The Java compiler applies autoboxing when a primitive value is:
• Passed as a parameter to a method that expects an object of the corresponding wrapper class.
• Assigned to a variable of the corresponding wrapper class.
• Program: Primitive Types to Wrapper Objects
class Main {
public static void main(String[] args) {

// create primitive types


Output
int a = 5;
double b = 5.65; An object of Integer is created.
An object of Double is created.
//converts into wrapper objects
Integer aObj = Integer.valueOf(a);
Double bObj = Double.valueOf(b);

if(aObj instanceof Integer) {


System.out.println("An object of Integer is created.");
}

if(bObj instanceof Double) {


System.out.println("An object of Double is created.");
}
}
}
However, the Java compiler can directly convert the primitive types into corresponding objects. For example,

int a = 5;
// converts into object
Integer aObj = a;

double b = 5.6;
// converts into object
Double bObj = b;
This process is known as auto-boxing
Unboxing
It is just the reverse process of autoboxing. Converting an object of a wrapper class to its corresponding primitive type is
known as unboxing.
The Java compiler applies unboxing when an object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding primitive type.
• Wrapper Objects into Primitive Types

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

// creates objects of wrapper class The value of a: 23


Integer aObj = Integer.valueOf(23);
The value of b: 5.55
Double bObj = Double.valueOf(5.55);

// converts into primitive types


int a = aObj.intValue();
double b = bObj.doubleValue();

System.out.println("The value of a: " + a);


System.out.println("The value of b: " + b);
}
}
However, the Java compiler can automatically convert objects into corresponding primitive types. For example,

Integer aObj = Integer.valueOf(2);


// converts into int type
int a = aObj;

Double bObj = Double.valueOf(5.55);


// converts into double type
double b = bObj;
This process is known as unboxing.
Advantages of Wrapper Classes
In Java, sometimes we might need to use objects instead of primitive data types. For example, while working with collections.
// error
ArrayList<int> list = new ArrayList<>();

// runs perfectly
ArrayList<Integer> list = new ArrayList<>();
• Basic Concepts required to understand Collections
Variables concept
• int x=10, y=20,z=30; // 10000 values …. Worst practice
Collection vs collection framework
Arrays
• Student[] s = new student[10000]; 0,1,2,…..9999 Collection(I) : group of individual objects as a single
unit
Limitations of arrays
• Fixed Size( You cant change once the size is fixed) Student <- S1,s2,s3…sn
• Homogeneous
• No standard method (readymade methods are not supported)
Collection framework: Several classes and interfaces is
• treeset collection contains insert() , contains (),clear(), remove() required / used to implement collection.(sort , search)

• Collections Java : collection , Collection Framework


• Size is growable in nature C++: Containers , STL
• Both homogeneous and heterogenous
• Readymade ds available
• 9 key interfaces in CF (Collection Interface and Map Interface)
• 1 Collection(I)- root Interface
• 2 List (I) :Duplicates allowed , Insertion order is preserved .
• Cls implement ( AL , LL , Vector , Stack)

• 3 set (I) : duplicates not allowed , insertion order not preserved.(2,4,1)


• 4 sorted set(I)
• 5 Navigable Sorted Set(I)
Cls implemented (Treeset)
• 6 queue (I)
Cls implemented PQ
• 7 Map Interface – Root Interface (Key value pair) {1:srikanth , 2:suresh}
• Keys: Duplictaes not allowed , values :Duplictaes allowed
• Cls implemented ( Hasmap , linked hashmap)

• 8sorted map (I) : (K:V) in some sorted order


• 9 navigable map(I)
• Cls implemented is Tree map

• {1:cse , 2:ise , 3:mech , 1:ece}


Collection in Java
• Any group of individual objects which are represented as a single unit
is known as the collection of the objects.
• In Java, a separate framework named the “Collection Framework” has
been defined in JDK 1.2 which holds all the collection classes and
interface in it.
• The Collection interface (java.util.Collection) and Map interface
(java.util.Map) are the two main “root” interfaces of Java collection
classes.
Before Collection Framework(or before JDK 1.2)
• Before Collection Framework(or before JDK 1.2) was introduced, the
standard methods for grouping Java objects (or collections) were
Arrays or Vectors or Hashtables.
• All of these collections had no common interface. Therefore, though
the main aim of all the collections are same, the implementation of all
these collections were defined independently and had no correlation
among them.
• And also, its very difficult for the users to remember all the different
methods, syntax and constructors present in every collection class.
// Array instance creation requires [],
// Java program to demonstrate // while Vector and hastable require ()
// why collection framework was needed // Vector element insertion requires
import java.io.*;
addElement(),
import java.util.*;
// but hashtable element insertion requires put()
class CollectionDemo {
// Accessing the first element of the
public static void main(String[] args) // array, vector and hashtable
{ System.out.println(arr[0]);
// Creating instances of the array,vector and hashtable System.out.println(v.elementAt(0));
System.out.println(h.get(1));
int arr[] = new int[] { 1, 2, 3, 4 };

Vector<Integer> v = new Vector(); // Array elements are accessed using [],


// vector elements using elementAt()
Hashtable<Integer, String> h // and hashtable elements using get()
= new Hashtable(); }
}
// Adding the elements into the vector
v.addElement(1);
v.addElement(2);
Output:
1
// Adding the element into the hashtable 1
h.put(1, "geeks"); geeks
h.put(2, "4geeks");
Disadvantages
• As we can observe, none of these collections(Array, Vector or
Hashtable) implements a standard member access interface, it was
very difficult for programmers to write algorithms that can work for
all kinds of Collections.
• Another drawback is that most of the ‘Vector’ methods are final,
meaning we cannot extend the ’Vector’ class to implement a similar
kind of Collection.
• Therefore, Java developers decided to come up with a common
interface to deal with the above-mentioned problems
• Introduced the Collection Framework in JDK 1.2 post which both,
legacy Vectors and Hashtables were modified to conform to the
Collection Framework.
Advantages of the Collection Framework:
Consistent API: The API has a basic set of interfaces like Collection, Set, List, or
Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these
interfaces have some common set of methods.

Reduces programming effort: A programmer doesn’t have to worry about the


design of the Collection but rather he can focus on its best use in his program.
Therefore, the basic concept of Object-oriented programming (i.e.) abstraction has
been successfully implemented.

Increases program speed and quality: Increases performance by providing high-


performance implementations of useful data structures and algorithms because in
this case, the programmer need not think of the best implementation of a specific
data structure. He can simply use the best implementation to drastically boost the
performance of his algorithm/program.
Methods of the Collection Interface
Method Description
add(Object) This method is used to add an object to the collection.
addAll(Collection c) This method adds all the elements in the given collection to this collection.
clear() This method removes all of the elements from this collection.
contains(Object o) This method returns true if the collection contains the specified element.
containsAll(Collection c) This method returns true if the collection contains all of the elements in the given collection.
equals(Object o) This method compares the specified object with this collection for equality.
hashCode() This method is used to return the hash code value for this collection.
isEmpty() This method returns true if this collection contains no elements.
iterator() This method returns an iterator over the elements in this collection.
max() This method is used to return the maximium value present in the collection.
parallelStream() This method returns a parallel Stream with this collection as its source.
remove(Object o) This method is used to remove the given object from the collection. If there are duplicate values, then this method removes
the first occurrence of the object.
removeAll(Collection c) This method is used to remove all the objects mentioned in the given collection from the collection.
removeIf(Predicate filter) This method is used to removes all the elements of this collection that satisfy the given predicate.
retainAll(Collection c) This method is used to retains only the elements in this collection that are contained in the specified collection.
size() This method is used to return the number of elements in the collection.
spliterator() This method is used to create a Spliterator over the elements in this collection.
stream() This method is used to return a sequential Stream with this collection as its source.
toArray() This method is used to return an array containing all of the elements in this collection.
Interfaces which extend the Collections Interface
The collection framework contains multiple interfaces where every interface is used to store a
specific type of data. The following are the interfaces present in the framework.

• Iterable Interface :
• Collection Interface
• List Interface : Array List , Linked list , Vector , stack
• Queue Interface : Priority queue
• Deque Interface : array Dequeue
• Set Interface : Hashset , Linked hashset
• Sorted Set Interface :Treeset
• Map Interface : Hashmap
1 Iterable Interface:
• This is the root interface for the entire collection framework. The collection interface extends the
iterable interface.
• Therefore, inherently, all the interfaces and classes implement this interface.
• The main functionality of this interface is to provide an iterator for the collections. Therefore, this
interface contains only one abstract method which is the iterator.
• It returns the Iterator iterator();
2 Collection Interface:
• This interface extends the iterable interface and is implemented by all the classes in the collection
framework.
• This interface contains all the basic methods which every collection has like adding the data into
the collection, removing the data, clearing the data, etc.
• All these methods are implemented in this interface because these methods are implemented by all
the classes irrespective of their style of implementation.
3 List Interface:
• This is a child interface of the collection interface.
• This interface is dedicated to the data of the list type in which we can store all the ordered
collection of the objects.
• This also allows duplicate data to be present in it. This list interface is implemented by various
classes like ArrayList, Vector, linked list , Stack, etc.
• Since all the subclasses implement the list, we can instantiate a list object with any of these
classes.
• For example,
List <T> al = new ArrayList<> ();
List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
The classes which implement the List interface are as follows:
3. a ArrayList:
• ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed.
• The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects
are removed from the collection.
• Java ArrayList allows us to randomly access the list. ArrayList can not be used for primitive types,
like int, char, etc. We will need a wrapper class for such cases.
// Java program to demonstrate the
// working of ArrayList in Java // Remove element at index 3
import java.io.*;
al.remove(3);
import java.util.*;
// Displaying the ArrayList
class GFG { // after deletion
public static void main(String[] args)
{ System.out.println(al);

// Declaring the ArrayList with // Printing elements one by one


// initial size n
ArrayList<Integer> al
for (int i = 0; i < al.size(); i++)
= new ArrayList<Integer>(); System.out.print(al.get(i) + " ");
}
// Appending new elements at }
// the end of the list
for (int i = 1; i <= 5; i++) Output:
al.add(i); [1, 2, 3, 4, 5]
[1, 2, 3, 5]
// Printing elements
System.out.println(al);
1235
3.B LinkedList:
LinkedList class is an implementation of the LinkedList data structure which is a linear data
structure where the elements are not stored in contiguous locations and every element is a separate
object with a data part and address part.
The elements are linked using pointers and addresses. Each element is known as a node.
// Java program to demonstrate the // Remove element at index 3
// working of LinkedList in Java ll.remove(3);

import java.io.*; // Displaying the List


import java.util.*; // after deletion
System.out.println(ll);
class GFG {
public static void main(String[] args)
{ // Printing elements one by one
for (int i = 0; i < ll.size(); i++)
// Declaring the LinkedList System.out.print(ll.get(i) + " ");
LinkedList<Integer> ll }
= new LinkedList<Integer>(); }
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
ll.add(i); Output:
[1, 2, 3, 4, 5]
// Printing elements [1, 2, 3, 5]
System.out.println(ll); 1235
3.C Vector:
• A vector provides us with dynamic arrays in Java. Though, it may be slower than standard arrays
but can be helpful in programs where lots of manipulation in the array is needed.
• This is identical to ArrayList in terms of implementation. However, the primary difference
between a vector and an ArrayList is that a Vector is synchronized and an ArrayList is non-
synchronized
// Java program to demonstrate the // Remove element at index 3
// working of Vector in Java
v.remove(3);
import java.io.*;
import java.util.*; // Displaying the Vector
// after deletion
class GFG { System.out.println(v);
public static void main(String[] args)
{ // Printing elements one by one
for (int i = 0; i < v.size(); i++)
// Declaring the Vector
Vector<Integer> v
System.out.print(v.get(i) + " ");
= new Vector<Integer>(); }
}
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
v.add(i); Output:
[1, 2, 3, 4, 5]
// Printing elements
System.out.println(v);
[1, 2, 3, 5]
1235
3.D Stack
• Stack class models and implements the Stack data structure.
• The class is based on the basic principle of last-in-first-out.
• In addition to the basic push and pop operations, the class provides three more functions of empty,
search and peek.
// Java program to demonstrate the System.out.println();
// working of a stack
stack.pop();
import java.util.*;
public class GFG { // Iterator for the stack
public static void main(String args[]) itr
{
= stack.iterator();
Stack<String> stack = new Stack<String>();
stack.push("Geeks");
stack.push("For"); // Printing the stack
stack.push("Geeks"); while (itr.hasNext()) {
stack.push("Geeks"); System.out.print(itr.next() + " ");
}
// Iterator for the stack }
Iterator<String> itr }
= stack.iterator();

// Printing the stack


while (itr.hasNext()) { Output:
System.out.print(itr.next() + " "); Geeks For Geeks Geeks
} Geeks For Geeks
4. Queue Interface:
• As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a
real-world queue line.
• This interface is dedicated to storing all the elements where the order of the elements matter. For
example, whenever we try to book a ticket, the tickets are sold at the first come first serve basis.
Therefore, the person whose request arrives first into the queue gets the ticket.
• There are various classes like PriorityQueue, Deque, ArrayDeque, etc. Since all these subclasses
implement the queue, we can instantiate a queue object with any of these classes.

For example,
Queue <T> pq = new PriorityQueue<> ();
Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.
4.A Priority Queue:
A PriorityQueue is used when the objects are supposed to be processed based on the priority.
It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements of the
queue are needed to be processed according to the priority and this class is used in these cases.
The PriorityQueue is based on the priority heap.

// Java program to demonstrate the working of // Printing the top element of PriorityQueue
// priority queue in Java System.out.println(pQueue.peek());
import java.util.*;
// Printing the top element and removing it
class GfG { // from the PriorityQueue container
public static void main(String args[]) System.out.println(pQueue.poll());
{
// Creating empty priority queue // Printing the top element again
PriorityQueue<Integer> pQueue System.out.println(pQueue.peek());
= new PriorityQueue<Integer>(); }
}
// Adding items to the pQueue using add() Output:
pQueue.add(1); 1
pQueue.add(2); 1
pQueue.add(3); 2
5. Deque Interface: This is a very slight variation of the queue data structure.
Deque, also known as a double-ended queue, is a data structure where we can add and remove the
elements from both the ends of the queue.
This interface extends the queue interface. The class which implements this interface is ArrayDeque.
Since this class implements the deque, we can instantiate a deque object with this class.

For example,
Deque<T> ad = new ArrayDeque<> ();
Where T is the type of the object.

The class which implements the deque interface is ArrayDeque.

ArrayDeque: ArrayDeque class which is implemented in the collection framework provides us with
a way to apply resizable-array. This is a special kind of array that grows and allows users to add or
remove an element from both sides of the queue.
// Java program to demonstrate the // addFirst() method to insert the
// ArrayDeque class in Java // elements at the head
de_que.addFirst(564);
import java.util.*;
public class ArrayDequeDemo { de_que.addFirst(291);
public static void main(String[] args)
{ // addLast() method to insert the
// Initializing an deque // elements at the tail
ArrayDeque<Integer> de_que de_que.addLast(24);
= new ArrayDeque<Integer>(10); de_que.addLast(14);
// add() method to insert
System.out.println(de_que);
de_que.add(10);
de_que.add(20); }
de_que.add(30); }
de_que.add(40);
de_que.add(50);

System.out.println(de_que); Output:
[10, 20, 30, 40, 50]
// clear() method
[264,291, 564, 24, 14]
de_que.clear();
6 Set Interface:
A set is an unordered collection of objects in which duplicate values cannot be stored.
This collection is used when we wish to avoid the duplication of the objects and wish to store only
the unique objects.
This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc.
Since all the subclasses implement the set, we can instantiate a set object with any of these classes.
For example,

Set<T> hs = new HashSet<> ();


Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();
Where T is the type of the object.
6.A HashSet:
The HashSet class is an inherent implementation of the hash table data structure.
The objects that we insert into the HashSet do not guarantee to be inserted in the same order. The
objects are inserted based on their hashcode. This class also allows the insertion of NULL elements.
// Java program to demonstrate the // Traversing elements
// working of a HashSet
Iterator<String> itr = hs.iterator();
import java.util.*; while (itr.hasNext()) {
public class HashSetDemo { System.out.println(itr.next());
public static void main(String args[])
{
}
// Creating HashSet and }
// adding elements }
HashSet<String> hs = new HashSet<String>();

hs.add("Geeks"); Output:
hs.add("For"); Very helpful
hs.add("Geeks");
hs.add("Is");
Geeks
hs.add("Very helpful"); For
Is
6.B LinkedHashSet:
A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to
store the data and retains the ordering of the elements.

// Java program to demonstrate the // Traversing elements


// working of a LinkedHashSet
Iterator<String> itr = lhs.iterator();
import java.util.*; while (itr.hasNext()) {
public class LinkedHashSetDemo { System.out.println(itr.next());
public static void main(String args[]) }
{
// Creating LinkedHashSet and }
// adding elements }
LinkedHashSet<String> lhs
= new LinkedHashSet<String>();

lhs.add("Geeks");
lhs.add("For"); Output:
lhs.add("Geeks"); Geeks
lhs.add("Is");
lhs.add("Very helpful"); For
Is
7. Sorted Set Interface:
This interface is very similar to the set interface. The only difference is that this interface has extra
methods that maintain the ordering of the elements.
The sorted set interface extends the set interface and is used to handle the data which needs to be
sorted. The class which implements this interface is TreeSet.
Since this class implements the SortedSet, we can instantiate a SortedSet object with this class. For
example,

SortedSet<T> ts = new TreeSet<> ();


Where T is the type of the object.
The class which implements the sorted set interface is TreeSet.
7.A TreeSet: The TreeSet class uses a Tree for storage. The ordering of the elements is maintained
by a set using their natural ordering whether or not an explicit comparator is provided.
This must be consistent with equals if it is to correctly implement the Set interface.
It can also be ordered by a Comparator provided at set creation time, depending on which
constructor is used.
// Java program to demonstrate the ts.add("Geeks");
ts.add("For");
// working of a TreeSet ts.add("Geeks");
ts.add("Is");
ts.add("Very helpful");
import java.util.*;
public class TreeSetDemo { // Traversing elements
Iterator<String> itr = ts.iterator();
public static void main(String args[]) while (itr.hasNext()) {
{ System.out.println(itr.next());
}
// Creating TreeSet and }
// adding elements }
TreeSet<String> ts
= new TreeSet<String>(); Output:
For
Geeks
Is
Very helpful
8. Map Interface:
A map is a data structure which supports the key-value pair mapping for the data.
This interface doesn’t support duplicate keys because the same key cannot have multiple mappings.
A map is useful if there is a data and we wish to perform operations on the basis of the key.
This map interface is implemented by various classes like HashMap, TreeMap etc.
Since all the subclasses implement the map, we can instantiate a map object with any of these
classes. For example,

Map<T> hm = new HashMap<> ();


Map<T> tm = new TreeMap<> ();
Where T is the type of the object.
8.A HashMap:
HashMap provides the basic implementation of the Map interface of Java. It stores the data in (Key,
Value) pairs.
To access a value in a HashMap, we must know its key. HashMap uses a technique called Hashing.
Hashing is a technique of converting a large String to small String that represents the same String so
that the indexing and search operations are faster.
// Finding the value for a key
// Java program to demonstrate the System.out.println("Value for 1 is " + hm.get(1));
// working of a HashMap
// Traversing through the HashMap
import java.util.*;
public class HashMapDemo {
for (Map.Entry<Integer, String> e : hm.entrySet())
public static void main(String args[]) System.out.println(e.getKey() + " " + e.getValue());
{ }
// Creating HashMap and }
// adding elements
HashMap<Integer, String> hm
= new HashMap<Integer, String>();
Output:
hm.put(1, "Geeks"); Value for 1 is Geeks
hm.put(2, "For"); 1 Geeks
hm.put(3, "Geeks"); 2 For
3 Geeks
Generics in Java
Generics was added in Java 5 to provide compile-time type checking and removing risk of
ClassCastException that was common while working with collection classes. The whole collection
framework was re-written to use generics for type-safety.
List list = new ArrayList();
list.add("abc");
list.add(new Integer(5)); //OK

for(Object obj : list){


//type casting leading to ClassCastException at runtime
String str=(String) obj;
}

Above code compiles fine but throws ClassCastException at runtime because we are trying to cast
Object in the list to String whereas one of the element is of type Integer.
After Java 5, we use collection classes like below.

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

// java 7 ? List<String> list1 = new ArrayList<>();


list1.add("abc");
//list1.add(new Integer(5)); //compiler error

for(String str : list1){


//no type casting needed, avoids ClassCastException
}

Notice that at the time of list creation, we have specified that the type of elements in the list will be
String. So if we try to add any other type of object in the list, the program will throw compile-time
error. Also notice that in for loop, we don’t need typecasting of the element in the list, hence removing
the ClassCastException at runtime.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()

// A Simple Java program to show working of user defined


// Generic classes

// We use < > to specify Parameter type


class Test<T>
// instance of String type
{
// An object of type T is declared Test <String> sObj =
T obj;
Test(T obj) new Test<String>("GeeksForGeeks");
{ this.obj = obj; } // constructor System.out.println(sObj.getObject());
public T getObject() { return this.obj; }
} }
}
// Driver class to test above
class Main
Output:
{
public static void main (String[] args) 15
{
// instance of Integer type GeeksForGeeks
Test <Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());
We can also pass multiple Type parameters in Generic classes.
// To print objects of T and U
public void print()
// A Simple Java program to show multiple {
System.out.println(obj1);
// type parameters in Java Generics
System.out.println(obj2);
}
// We use < > to specify Parameter type }
class Test<T, U>
// Driver class to test above
{ class Main
T obj1; // An object of type T {
U obj2; // An object of type U public static void main (String[] args)
{
Test <String, Integer> obj =
// constructor new Test<String, Integer>("GfG", 15);
Test(T obj1, U obj2)
{ obj.print();
}
this.obj1 = obj1; }
this.obj2 = obj2; Output:
}
GfG
15
Generic Functions:
We can also write generic functions that can be called with different types of arguments based on the
type of arguments passed to generic method, the compiler handles each method.
// A Simple Java program to show working of user defined
// Generic functions
// Calling generic method with String argument
genericDisplay("GeeksForGeeks");
class Test
{
// Calling generic method with double argument
// A Generic method example
genericDisplay(1.0);
static <T> void genericDisplay (T element)
}
{
}
System.out.println(element.getClass().getName() +
Output :
" = " + element);
}

// Driver method
java.lang.Integer = 11
public static void main(String[] args)
java.lang.String = GeeksForGeeks
{
java.lang.Double = 1.0
// Calling generic method with Integer argument
genericDisplay(11);
Advantages of Generics:
Programs that uses Generics has got many benefits over non-generic code.

• Code Reuse: We can write a method/class/interface once and use for any type we want.
• Type Safety : Generics make errors to appear compile time than at run time (It’s always better to
know problems in your code at compile time rather than making your code fail at run time).
Suppose you want to create an ArrayList that store name of students and if by mistake programmer
adds an integer object instead of string, compiler allows it. But, when we retrieve this data from
ArrayList, it causes problems at runtime.
// A Simple Java program to demonstrate that NOT using String s1 = (String)al.get(0);
// generics can cause run time exceptions String s2 = (String)al.get(1);
import java.util.*;

class Test
// Causes Runtime Exception
{ String s3 = (String)al.get(2);
public static void main(String[] args) }
{ }
// Creatinga an ArrayList without any type specified Output :
ArrayList al = new ArrayList();

al.add("Sachin");
Exception in thread "main" java.lang.ClassCastException:
al.add("Rahul"); java.lang.Integer cannot be cast to java.lang.String
al.add(10); // Compiler allows this at Test.main(Test.java:19)
How generics solve this problem?
At the time of defining ArrayList, we can specify that this list can take only String objects.

// Using generics converts run time exceptions into


// compile time exception.
import java.util.*;
String s1 = (String)al.get(0);
class Test
String s2 = (String)al.get(1);
{
String s3 = (String)al.get(2);
public static void main(String[] args)
}
{
}
// Creating a an ArrayList with String specified
Output:
ArrayList <String> al = new ArrayList<String> ();
15: error: no suitable method found for add(int)
al.add("Sachin");
al.add(10);
al.add("Rahul");

// Now Compiler doesn't allow this


al.add(10);
Individual Type Casting is not needed: If we do not use generics, then, in the above example
every-time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval
operation is a big headache. If we already know that our list only holds string data then we need not
to typecast it every time

// We don't need to typecast individual members of ArrayList


import java.util.*;

class Test
{
public static void main(String[] args) Generics promotes code reusability.
{
// Creating a an ArrayList with String specified
ArrayList <String> al = new ArrayList<String> (); Implementing generic algorithms: By using
generics, we can implement algorithms that
al.add("Sachin");
al.add("Rahul");
work on different types of objects and at the
same they are type safe too.
// Typecasting is not needed
String s1 = al.get(0);
String s2 = al.get(1);
}
}
Bounded types with generics in Java
There may be times when you want to restrict the types that can be used as type arguments in a
parameterized type. For example, a method that operates on numbers might only want to accept
instances of Number or its subclasses
Declare a bounded type parameter

List the type parameter’s name.


Along by the extends keyword
And by its upper bound.(which in below example is A.)
Syntax

<T extends superClassName>


Let’s take an example on how to implement bounded types (extend superclass) with generics.
class B extends A
// This class only accepts type parametes as any class {
public void displayClass()
// which extends class A or class A itself. {
System.out.println("Inside sub class B");
// Passing any other type will cause compiler time error } Output :
}

class Bound<T extends A> class C extends A


Inside sub class C
{
{ public void displayClass()
{
Inside sub class B
private T objRef; System.out.println("Inside sub class C"); Inside super class A
}
}
public Bound(T obj){
this.objRef = obj; public class BoundedClass
{
} public static void main(String a[])
{
public void doRunTest(){
// Creating object of sub class C and
this.objRef.displayClass(); // passing it to Bound as a type parameter.
} Bound<C> bec = new Bound<C>(new C());
} bec.doRunTest();

// Creating object of sub class B and


class A // passing it to Bound as a type parameter.
{ Bound<B> beb = new Bound<B>(new B());
beb.doRunTest();
public void displayClass()
{ // similarly passing super class A
System.out.println("Inside super class A"); Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
}
} }
}
Now, we restricted to only of type A and its sub classes, So it will throw an error for any other type
class B extends A
or sub classes. {
public void displayClass()
// This class only accepts type parametes as any class {
System.out.println("Inside sub class B");
// which extends class A or class A itself. }
}
// Passing any other type will cause compiler time error
class C extends A Output :
class Bound<T extends A> {
{ public void displayClass()
{
System.out.println("Inside sub class C");
error: type argument
private T objRef;
}
} String is not within bounds
of type-variable T
public Bound(T obj){ public class BoundedClass
this.objRef = obj; {
public static void main(String a[])
} {
// Creating object of sub class C and
// passing it to Bound as a type parameter.
public void doRunTest(){ Bound<C> bec = new Bound<C>(new C());
this.objRef.displayClass(); bec.doRunTest();
}
// Creating object of sub class B and
} // passing it to Bound as a type parameter.
Bound<B> beb = new Bound<B>(new B());
beb.doRunTest();
class A
{ // similarly passing super class A
public void displayClass() Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
{
System.out.println("Inside super class A"); Bound<String> bes = new Bound<String>(new String());
bea.doRunTest();
} }
} }
Multiple Bounds
Bounded type parameters can be used with methods as well as classes and interfaces.
Java Generics supports multiple bounds also, i.e . In this case A can be an interface or class. If A is
class then B and C should be interfaces. We can’t have more than one class in multiple bounds.
class A implements B
Syntax {
<T extends superClassName & Interface> public void displayClass()
{
class Bound<T extends A & B> System.out.println("Inside super class A");
{
}
private T objRef; }

public Bound(T obj){ public class BoundedClass


this.objRef = obj; {
} public static void main(String a[])
{
public void doRunTest(){
this.objRef.displayClass(); //Creating object of sub class A and
} //passing it to Bound as a type parameter.
} Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
interface B
{
}
public void displayClass();
} }
Output :
Inside super class A
Defining bounded-types for class
You can declare a bound parameter just by extending the required class with the type-parameter,
within the angular braces as −
class Sample <T extends Number>
class Sample <T extends Number>{
T data;
Sample(T data){
this.data = data; Output
} Data value is: 20
public void display() {
System.out.println("Data value is: "+this.data); Data value is: 20.22
} Data value is: 125.332
}
public class BoundsExample {
public static void main(String args[]) {
Sample<Integer> obj1 = new Sample<Integer>(20); Note:Now, if you pass other types as parameters
obj1.display(); to this class (say, String for example) a compile
Sample<Double> obj2 = new Sample<Double>(20.22d); time error will be generated.
obj2.display();
Sample<Float> obj3 = new Sample<Float>(125.332f);
obj3.display();
}
}
Example
public class BoundsExample {
public static void main(String args[]) {
Sample<Integer> obj1 = new Sample<Integer>(20);
obj1.display();
Sample<Double> obj2 = new Sample<Double>(20.22d);
obj2.display();
Sample<String> obj3 = new Sample<String>("Krishna");
obj3.display();
}
}
Compile time error
BoundsExample.java:16: error: type argument String is not within bounds of type-variable T
Sample<String> obj3 = new Sample<String>("Krishna");
^
where T is a type-variable:
T extends Number declared in class Sample
BoundsExample.java:16: error: type argument String is not within bounds of type-variable T
Sample<String> obj3 = new Sample<String>("Krishna"); ^
where T is a type-variable:
T extends Number declared in class Sample
2 errors
Wildcards in Java
• The question mark (?) is known as the wildcard in generic programming .
• It represents an unknown type.
• The wildcard can be used in a variety of situations such as the type of a parameter, field, or local
variable, sometimes as a return type.
Types of wildcards in Java:
Upper Bounded Wildcards: These wildcards can be used when you want to relax the restrictions on
a variable.
For example, say you want to write a method that works on List < integer >, List < double >, and
List < number > , you can do this using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?’), followed by the extends
keyword, followed by its upper bound.

public static void add(List<? extends Number> list)


//Java program to demonstrate Upper Bounded Wildcards
private static double sum(List<? extends Number>
import java.util.Arrays;
import java.util.List; list)
{
class WildcardDemo double sum=0.0;
{ for (Number i: list)
public static void main(String[] args) {
{ sum+=i.doubleValue();
}
//Upper Bounded Integer List
List<Integer> list1= Arrays.asList(4,5,6,7);
return sum;
//printing the sum of elements in list }
System.out.println("Total sum is:"+sum(list1)); }
Output:
//Double list
List<Double> list2=Arrays.asList(4.1,5.1,6.1);

//printing the sum of elements in list


Total sum is:22.0
System.out.print("Total sum is:"+sum(list2));
} Total sum is:15.299999999999999
Lower Bounded Wildcards:
It is expressed using the wildcard character (‘?’), followed by the super keyword, followed by its
lower bound: <? super A>.
Syntax: Collectiontype <? super A>
import java.util.Arrays;
import java.util.List;
public static void
class WildcardDemo
{ printOnlyIntegerClassorSuperClass(List<? super
public static void main(String[] args) Integer> list)
{
{
//Lower Bounded Integer List
List<Integer> list1= Arrays.asList(4,5,6,7); System.out.println(list);
}
//Integer list object is being passed
printOnlyIntegerClassorSuperClass(list1);
}
Output:
//Number list
List<Number> list2= Arrays.asList(4,5,6,7);
[4, 5, 6, 7]
//Integer list object is being passed [4, 5, 6, 7]
printOnlyIntegerClassorSuperClass(list2);
}
Here arguments can be Integer or superclass of Integer(which is Number).
The method printOnlyIntegerClassorSuperClass will only take Integer or its superclass objects.
However if we pass list of type Double then we will get compilation error. It is because only the
Integer field or its superclass can be passed . Double is not the superclass of Integer.

Unbounded Wildcard: This wildcard type is specified using the wildcard character (?),
• When the code is using methods in the generic class that don’t depend on the type parameter
Unbounded Wildcard: This wildcard type is specified using the wildcard character (?),
• When the code is using methods in the generic class that don’t depend on the type parameter
import java.util.Arrays;
import java.util.List;

class unboundedwildcardemo
{ private static void printlist(List<?> list)
public static void main(String[] args) {
{
System.out.println(list);
//Integer List }
List<Integer> list1= Arrays.asList(1,2,3);
}
//Double list
Output:
List<Double> list2=Arrays.asList(1.1,2.2,3.3);
[1, 2, 3]
printlist(list1); [1.1, 2.2, 3.3]

printlist(list2);
}
What is Thread in java?
A thread is a lightweight sub process, a smallest unit of processing.
Multithreading in Java Programming
• Multithreading in java is a process of executing multiple threads simultaneously.
• Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization
of CPU. Each part of such program is called a thread.
• Thread is basically a lightweight sub-process, a smallest unit of processing.
• Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing
because threads share a common memory area. They don’t allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
• Multitasking
• Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking
can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Advantages of Java Multithreading
• It doesn’t block the user because threads are independent and you can perform multiple operations at same time.
• You can perform many operations together so it saves time.
• Threads are independent so it doesn’t affect other threads if exception occur in a single thread.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

• New
• Runnable
• Running
• Non-Runnable (Blocked/Waiting)
• Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running
thread.

3) Running
The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked/Wait)
This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated
A thread is in terminated or dead state when its run() method exits.
Multithreading in Java by Inheriting Thread Class
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part
of such program is called a thread. So, threads are light-weight processes within a process.
As discussed in the previous post Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
class MultithreadingDemo extends Thread
{ public class JavaApplication4 { Output –
public void run()
{
public static void main(String[] args) {
try main Thread 1 is running
{
for(int i=0;i<5;i++){ MultithreadingDemo object = new main Thread 1 is running
// Displaying the thread that is running
System.out.println ("Thread " +
MultithreadingDemo(); main Thread 1 is running
object.start();
Thread.currentThread().getId() + Thread 10 is running
for(int i=0;i<5;i++){
}
" is running");
// Displaying the thread that is running main Thread 1 is running
} System.out.println ("main Thread " + Thread 10 is running
catch (Exception e) Thread.currentThread().getId() + main Thread 1 is running
{ " is running");
// Throwing an exception } Thread 10 is running
}
System.out.println ("Exception is caught");
} Thread 10 is running
} } Thread 10 is running
}
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance.
But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like
yield(), interrupt() etc. that are not available in Runnable interface.
Multithreading in Java by Implementing Runnable Interface
Output –
class MultiThread implements Runnable {
Main Thread id: 1
@Override Thread 10 is running
public void run() { Main Thread id: 1
for (int i = 0; i < 10; i++) { Main Thread id: 1
System.out.println("Thread " + Thread.currentThread().getId()+ " is running"); Main Thread id: 1
} Thread 10 is running
} Thread 10 is running
} Thread 10 is running
Thread 10 is running
public class JavaApplication4 { Main Thread id: 1
Thread 10 is running
public static void main(String[] args) { Main Thread id: 1
Thread object = new Thread(new MultiThread()); Main Thread id: 1
object.start(); Main Thread id: 1
for (int i = 0; i < 10; i++) { Main Thread id: 1
System.out.println("Main Thread id: " + Thread.currentThread().getId()); Main Thread id: 1
} Thread 10 is running
} Thread 10 is running
} Thread 10 is running
Thread 10 is running
Sleep method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
• public static void sleep(long miliseconds)throws InterruptedException
• public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){

try{Thread.sleep(500);}catch(InterruptedException
e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
t1.start();
}
}
Priority of a Thread (Thread Priority)
In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of thread. Whenever we create a thread in
Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be given by programmer
explicitly.
Accepted value of priority for a thread is in range of 1 to 10.

There are are 3 basic priority constants defined in the Thread Class –

public static int MIN_PRIORITY (1)


public static int NORM_PRIORITY (5)
public static int MAX_PRIORITY (10)
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

} Output:running thread name is:Thread-0


public static void main(String args[]){ running thread priority is:10
running thread name is:Thread-1
TestMultiPriority1 m1=new TestMultiPriority1();
running thread priority is:1
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}
ow is a table of differences between Git and GitHub:

S.No. Git GitHub

1. Git is a software. GitHub is a service.

2. Git is a command-line tool GitHub is a graphical user


interface

3. Git is installed locally on the GitHub is hosted on the web


system

GitHub is maintained by
4. Git is maintained by linux. microsoft.

Git is focused on version control GitHub is focused on centralized


5. and code sharing. source code hosting.

Git is a version control system to GitHub is a hosting service for


6. manage source code history. Git repositories.

7. Git was first released in 2005. GitHub was launched in 2008.

Git has no user management GitHub has built-in user


8. feature. management feature.
Servlets
• Servlet technology is used to create a web application (resides at server side and generates a dynamic web
page).

• Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was common as a server-side programming language. However, there were
many disadvantages to this technology.

• There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet is a technology which is used to create a web application.
Servlet is an API that provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any Servlet.
Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can
respond to any requests.
Servlet is a web component that is deployed on the server to create a dynamic web page.
What is a web application?
A web application is an application accessible from the web. A web application is composed of web components like Servlet,
JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server
and respond to the HTTP request.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request information to the external program
to process the request. For each request, it starts a new process.

Disadvantages of CGI

• If the number of clients increases, it takes


more time for sending the response.
• For each request, it starts a process, and the
web server is limited to start processes.
• It uses platform dependent language e.g. C,
C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI.

• The web container creates threads for handling the


multiple requests to the Servlet.

• Threads have many benefits over the Processes such


as they share a common memory area, lightweight,
cost of communication between the threads are low.

The advantages of Servlet are as follows:

• Better performance: because it creates a thread for


each request, not process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection,
etc.
• Secure: because it uses java language.
Creating Servlet in myeclipse IDE
You need to follow the following steps to create the servlet in the myeclipse IDE. The steps are as
follows:
• Create a web project
• create a html file
• create a servlet
• start myeclipse tomcat server and deploy project

1) Create the web project:


• For creating a web project click on File Menu -> New -> web project -> write your project name
e.g. first -> Finish.
Create the html file:
As you can see that a project is created named first. Now let's explore this project.
Create the servlet:
For creating a servlet click on File Menu -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all
the checkboxes except doGet() -> next -> Finish.
4) Start the server and deploy the project:
For starting the server and deploying the project in one step Right click on your
project -> Run As -> MyEclipse server application.
Servlet Terminology Description

Website: static vs dynamic It is a collection of related web pages that may contain text,
images, audio and video.

HTTP It is the data communication protocol used to establish


communication between client and server.

HTTP Requests It is the request send by the computer to a web server that
contains all sorts of potentially interesting information.

Get vs Post It gives the difference between GET and POST request.
Website
• Website is a collection of related web pages that may contain text, images, audio and video.
• The first page of a website is called home page.
• Each website has specific internet address (URL) that you need to enter in your browser to access
a website.
A website can be of two types:
• Static Website
• Dynamic Website
Static website
• Static website is the basic type of website that is easy to create.
• You don't need the knowledge of web programming and database design to create a static website.
• Its web pages are coded in HTML.

The codes are fixed for each page so the information contained in the page does not change and it
looks like a printed page.
Dynamic website
• Dynamic website is a collection of dynamic web pages whose content changes dynamically.
• It accesses content from a database or Content Management System (CMS). Therefore, when you
alter or update the content of the database, the content of the website is also altered or updated.
Static Website Dynamic Website

Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly.

It uses the HTML code for developing a website. It uses the server side languages such
as PHP,SERVLET, JSP, and ASP.NET etc. for
developing a website.

It sends exactly the same response for every request. It may generate different HTML for each of the request.

The content is only changed when someone publishes The page contains "server-side" code which allows the
and updates the file (sends it to the web server). server to generate the unique content when the page is
loaded.

Flexibility is the main advantage of static website. Content Management System (CMS) is the main
advantage of dynamic website.
HTTP (Hyper Text Transfer Protocol)
• It is the data communication protocol used to establish communication between client and server.

• HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query
results, HTML files etc on the World Wide Web (WWW) with the default port is TCP 80.

• It provides the standardized way for computers to communicate with each other.
HTTP Requests
• The request sent by the computer to a web server, contains all sorts of potentially interesting information; it is
known as HTTP requests.

• The HTTP client sends the request to the server in the form of request message which includes following
information:

• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Requested URI (Uniform Resource Identifier)
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header
The HTTP request methods are:
HTTP Request Description
GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with extra
info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET but
with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
Get vs. Post
There are many differences between the Get and Post request. Let's see these differences:

GET POST

1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data is data can be sent because data is sent in
sent in header. body.

2) Get request is not secured because data Post request is secured because data is not
is exposed in URL bar. exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means Post request is non-idempotent.


second request will be ignored until response
of first request is delivered
GET and POST
Two common methods for the request-response between a server and client are:

GET- It requests the data from a specified resource


POST- It submits the processed data to a specified resource
Anatomy of Get Request
The query string (name/value pairs) is sent inside the URL of a GET request:

GET/RegisterDao.jsp?name1=value1&name2=value2
As we know that data is sent in request header in case of get request. It is the default request type. Let's see what
information is sent to the server.
Some other features of GET requests are:

• It remains in the browser history


• It can be bookmarked
• It can be cached
• It have length restrictions
• It should never be used when dealing with sensitive data
• It should only be used for retrieving the data
Anatomy of Post Request
The query string (name/value pairs) is sent in HTTP message body for a POST request:
POST/RegisterDao.jsp HTTP/1.1
Host: www. javatpoint.com
name1=value1&name2=value2

As we know, in case of post request original data is sent in message body. Let's see how information is passed to
the server in case of post request.
JSP Elements

Expression Elements
<%= new java.util.Date() %>
<br/>
JSP Comments (Unexecutable Parts)
<%= 25*4 %>
<% -- response.sendRedirect("http://studyeasy.org"); --%>
<br/>

<%= 25>4 %>

Declarative Elements
<%! JSP Scriplets
String message(){ <%
return "I love JSP"; for(int i=0;i<10;i++){
} out.print("<br/>");
%> out.print(i);
}
<%= message() %> %>
List of Content Types
There are many content types. The commonly used content types are given below:

text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
images/png
images/gif
audio/mp3
video/mp4
video/quicktime etc.
Servlet API
• The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

• The javax.servlet package contains many interfaces and classes that are used by the servlet or web container.
These are not specific to any protocol.

• The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:

Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:

GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:

HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:

HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
HttpUtils (deprecated now)
Servlet Interface
Servlet interface provides common behavior to all the servlets.
Servlet interface defines methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle
methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle
methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are invoked
by the web container.
Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and
invoked by the web container only once.

public void service(ServletRequest request,ServletResponse provides response for the incoming request. It is invoked at each
response) request by the web container.

public void destroy() is invoked only once and indicates that servlet is being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer, copyright, version
etc.
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
import java.io.*;
import javax.servlet.*; res.setContentType("text/html");

PrintWriter out=res.getWriter();
public class First implements Servlet{ out.print("<html><body>");
ServletConfig config=null; out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
public void init(ServletConfig config){
}
this.config=config; public void destroy(){System.out.println("servlet is
System.out.println("servlet is destroyed");}
initialized"); public ServletConfig getServletConfig(){return config;}
} public String getServletInfo(){return "copyright 2007-1010";}

}
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

• Servlet class is loaded.


• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet instance
is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init method
is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface.
Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the
service() method to handle requests coming from the client( browsers) and to write the formatted response back to
the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service()
method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete,
etc. methods as appropriate.

Here is the signature of this method −


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc.
methods as appropriate. So you have nothing to do with service() method but you override either doGet() or
doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of
these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by
doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method
of a single instance of the servlet.
Agenda -20/5/2021
1 Jsp form design
2 servelets form design
3 jsp servelets form design with validation
4 jsp elements ( expression , scriplets , comments, declaration , derective )
5 include files into jsp file
6 import clases into jsp file
7 get and post method

Forward and redirect


(M)VC
Java Beans scope
• JSP Elements

Scripting elements Syntax Example

Expression <%= expression %> <% = 2*5 %>

Scriplet <% scriplets %> < % out.println(“Hello”);%>

Declaration <%! Declarations %> <%! Public int count =0; %>

Directive <%@ directive %> <%@ page %>

Comment <% -- comment code --%> <% -- jsp elements -- %>


Agenda -5/5/2021

1forwarding and Redirecting the pages under JSP


2MVC architecture and simple example
3 form Elements
4 Form Design by using JSP
5 Form Design by using Servelts controller
6 Form Validation
Agenda -6/5/2021

1 Encapsulation – setters and getters


2 java beans – Different scope (session , application , page , request)
3 beans with webforms
JSTL Core Tags
The JSTL core tag provides variable support, URL management, flow control etc. The syntax used for including JSTL core
library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag work.
c:import It Retrives relative or an absolute URL and display the contents to either a String in 'var',a Reader in 'varReader' or
the page.
c:set It sets the result of an expression under evaluation in a 'scope' variable.
c:remove It is used for removing the specified scoped variable from a particular scope.
c:catch It is used for Catches any Throwable exceptions that occurs in the body.
c:if It is conditional tag used for testing the condition and display the body content only if the expression evaluates is
true.
c:choose, c:when, c:otherwise It is the simple conditional tag that includes its body content if the evaluated condition is
true.
c:forEach It is the basic iteration tag. It repeats the nested body content for fixed number of times or over collection.
c:forTokens It iterates over tokens which is separated by the supplied delimeters.
c:param It adds a parameter in a containing 'import' tag's URL.
c:redirect It redirects the browser to a new URL and supports the context-relative URLs.
c:url It creates a URL with optional query parameters.
JSTL Function Tags
The JSTL function provides a number of standard functions, most of these functions are common string manipulation functions. The
syntax used for including JSTL function library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
JSTL Functions Description
fn:contains() It is used to test if an input string containing the specified substring in a program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case insensitive way.
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as XML markup.
fn:indexOf() It returns an index within a string of first occurrence of a specified substring.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a particular string value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase()It converts all the characters of a string to lower case.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given start and end position.
fn:substringAfter() It returns the subset of string after a specific substring.
fn:substringBefore() It returns the subset of string before a specific substring.
fn:length() It returns the number of characters inside a string, or the number of items in a collection.
fn:replace() It replaces all the occurrence of a string with another string sequence.
JSTL Formatting tags
• The formatting tags provide support for message formatting, number and date formatting etc. The url
for the formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
• The JSTL formatting tags are used for internationalized web sites to display and format text, the time,
the date and numbers. The syntax used for including JSTL formatting library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
fmt:parseNumber It is used to Parses the string representation of a currency, percentage or number.
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time formatting.
fmt:formatNumber It is used to format the numerical value with specific format or precision.
fmt:parseDate It parses the string representation of a time and date.
fmt:bundle It is used for creating the ResourceBundle objects which will be used by their tag
body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable or the
named scoped variable.
fmt:message It display an internationalized message.
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.
JSTL SQL Tags
• The JSTL sql tags provide SQL support. The url for the sql tags is http://java.sun.com/jsp/jstl/sql
and prefix is sql.
• The SQL tag library allows the tag to interact with RDBMSs (Relational Databases) such as
Microsoft SQL Server, mySQL, or Oracle. The syntax used for including JSTL SQL tags library in
your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
sql:setDataSource It is used for creating a simple data source suitable only for prototyping.
sql:query It is used for executing the SQL query defined in its sql attribute or the body.
sql:update It is used for executing the SQL update defined in its sql attribute or in the tag
body.
sql:param It is used for sets the parameter in an SQL statement to the specified value.
sql:dateParam It is used for sets the parameter in an SQL statement to a specified java.util.Date
value.
sql:transaction It is used to provide the nested database action with a common connection.
Web Services
• A service on web , for machine consumption
• A web service can have multiple micro services.
Rules: Posts
Operation Method URL Pattern

View All GET /posts

View specific GET /posts/id

Add POST /posts

Update PUT /posts

Delete DELETE /posts


3. In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but
can only be inherited.
abstract class Base Output
{ Base fun() called
void fun()
{
System.out.println("Base fun() called");
}
}
class Derived extends Base
{
}
class Main {
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}
}
4. Abstract classes can also have final methods (methods that cannot be overridden). For example, the following program compiles and
runs fine.

abstract class Base class Main


{ {
final void fun() public static void main(String
{ args[])
System.out.println("Derived fun() called"); {
}
Base b = new Derived();
b.fun();
}
}
class Derived extends Base
}
{ Output
} Derived fun() called
Hibernate
Hibernate ORM(hibernate in short , is an object relational mapping tool for the java programming
language.
What is object relational mapping tool ?
Object – relational mapping (ORM ,O/RM and O/R mapping tool) in computer science is a
programming technique for converting data between incompitable type systems in object –oriented
programming languages.

Java Object ---------- Hibernate ----------Database--------


Public class users { Users
Int userId; user_id INT(45)
String username; username VARCHAR(45)
String password; Hibernate password VARCHAR(45)
String firstName; firstname VARCHAR(45)
String lastName; lastname VARCHAR(45)
}
Benefits
• Hibernate is database independent
• Handles low level SQL for you
• Minimizes JDBC related code in your APP
Junit – 5
JUnit is a unit testing framework for Java programming language.
JUnit has been important in the development of test-driven development

Features of JUnit
JUnit is an open source framework, which is used for writing and running tests.
Provides annotations to identify test methods.
Provides assertions for testing expected results.
Provides test runners for running tests.
JUnit tests allow you to write codes faster, which increases quality.
JUnit is elegantly simple. It is less complex and takes less time.
JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to
manually comb through a report of test results.
JUnit tests can be organized into test suites containing test cases and even other test suites.
JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails.
What is a Unit Test Case ?
A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected.
To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java
programming language.
Lambda Expressions
• Lambda expression is a new and important feature of Java which was included in Java SE 8.
• It provides a clear and concise way to represent one method interface using an expression.
• The Lambda expression is used to provide the implementation of an interface which has
functional interface.
• It saves a lot of code. In case of lambda expression, we don't need to define the method again for
providing the implementation. Here, we just write the implementation code.
• Java lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
• Lambda expression provides implementation of functional interface.
• An interface which has only one abstract method is called functional interface.
• Java provides an anotation @FunctionalInterface, which is used to declare an interface as
functional interface.
Why use Lambda Expression
• To provide the implementation of Functional interface.
• Less coding.
Java Lambda Expression Syntax
(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.


No Parameter Syntax
() -> {
//Body of no parameter lambda
}
One Parameter Syntax
(p1) -> {
//Body of single parameter lambda
}
Two Parameter Syntax
(p1,p2) -> {
//Body of multiple parameter lambda
}
Without Lambda Expression
interface Drawablee{
public void draw();
}
class test implements Drawablee {
int width =10;
public void draw(){System.out.println("Drawing "+width);
}
};
public class LambdaExpressionExample0 {
public static void main(String[] args) {
//without lambda, Drawable implementation using anonymous class
Drawablee d = new test();
d.draw();
}
}
Output:
Drawing 10
Without Lambda Expression by using anonymous class
interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;

//without lambda, Drawable implementation using anonymous class


Drawable d=new Drawable(){
public void draw(){System.out.println("Drawing "+width);}
};
d.draw();
}
}

Output:
Drawing 10
With Lambda Expression
Now, we are going to implement the above example with the help of Java lambda expression.
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}
public class LambdaExpressionExample2 {
public static void main(String[] args) {
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
Output:
Drawing 10
Java Lambda Expression Example: No Parameter
interface Sayable{
public String say();
}
public class LambdaExpressionExample3{
public static void main(String[] args) {
Sayable s=()->{
return "I have nothing to say.";
};
System.out.println(s.say());
}
}
Output:

I have nothing to say.


Java Lambda Expression Example: Single Parameter

interface Sayable{
public String say(String name);
} Output:
public class LambdaExpressionExample4{ Hello, Sonoo
Hello, Sonoo
public static void main(String[] args) {
// Lambda expression with single parameter.
Sayable s1=(name)->{
return "Hello, "+name;
};
System.out.println(s1.say("Sonoo"));
// You can omit function parentheses
Sayable s2= name ->{
return "Hello, "+name;
};
System.out.println(s2.say("Sonoo"));
}
}
Java Lambda Expression Example: Multiple Parameters
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample5{
public static void main(String[] args) {
// Multiple parameters in lambda expression
Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
// Multiple parameters with data type in lambda expression
Addable ad2=(int a,int b)->(a+b);
System.out.println(ad2.add(100,200));
}
}
Output:
30
300
Java Lambda Expression Example: with or without return keyword
In Java lambda expression, if there is only one statement, you may or may not use return keyword. You must use return keyword when lambda
expression contains multiple statements.
interface Addable{
int add(int a,int b);
} Output:
public class LambdaExpressionExample6 {
public static void main(String[] args) { 30
// Lambda expression without return keyword. 300
Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
// Lambda expression with return keyword.
Addable ad2=(int a,int b)->{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}
Java Lambda Expression Example: Foreach Loop
import java.util.*;
public class LambdaExpressionExample7{
Output:
public static void main(String[] args) {
ankit
List<String> list=new ArrayList<String>(); mayank
list.add("ankit"); irfan
list.add("mayank");
jai
list.add("irfan");
list.add("jai");

list.forEach(
(n)->System.out.println(n)
);
}
}
Java Lambda Expression Example: Multiple Statements
@FunctionalInterface
interface Sayable{
String say(String message);
}
public class LambdaExpressionExample8{
public static void main(String[] args) {
// You can pass multiple statements in lambda expression
Sayable person = (message)-> {
String str1 = "I would like to say, ";
String str2 = str1 + message;
return str2;
};
System.out.println(person.say("time is precious."));
}
}
Output:
I would like to say, time is precious.
• Default method vs static method in an interface in Java
• An interface in Java is similar to class but, it contains only abstract
methods and fields which are final and static.
• Since Java8 static methods and default methods are introduced in
interfaces.
• Default Methods - Unlike other abstract methods these are the
methods can have a default implementation. If you have default
method in an interface, it is not mandatory to override (provide body)
it in the classes that are already implementing this interface.
• You can access the default methods of an interface using the objects of
the implementing classes.
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
Output: display method of MyInterface
Static methods - They are declared using the static keyword and will be
loaded into the memory along with the interface. You can access static
methods using the interface name.

If your interface has a static method you need to call it using the name
of the interface, just like static methods of a class.
interface MyInterface{
public void demo();
public static void display() {
System.out.println("This is a static method");
}
}
public class InterfaceExample{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.demo();
MyInterface.display();
}
}
Output
This is the implementation of the demo method
This is a static method
Difference between static and default methods −
Calling the method
You can call a static method using the name of an interface.
To call a default method you need to use the object of the implementing class.
Overriding the method
If you want, you can override a default method of an interface from the implementing class.
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public void display() {
System.out.println("display method of class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}
Output: display method of class
interface MyInterface{
public static void display() {
System.out.println("Static method of the interface");
}
}
public class InterfaceExample{
public static void display() {
System.out.println("Static method of the class");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
MyInterface.display();
InterfaceExample.display();
}
}
Output:Static method of the interface
Static method of the class
Stream API In java8
• A Stream in Java can be defined as a sequence of elements from a source. The source of elements here refers
to a Collection or Array that provides data to the Stream.

• Stream operations
1. Intermediate Operations
2. Terminal or Aggregate Operations

• Java streams are designed in such a way that most of the stream operations (called intermediate operations)
return a Stream.
• This helps to create a chain of stream operations. This is called stream pipe-lining.
• Java streams also support the aggregate or terminal operations on the elements. The aggregate operations are
operations that allow us to express common manipulations on stream elements quickly and clearly, for
example, finding the max or min element, finding the first element matching giving criteria, and so on.
Difference between Collections and streams
• A Collection is an in-memory data structure that holds all the data structure’s values.
• Every element in the Collection has to be computed before it can be added to the Collection.
• While a Stream is conceptually a pipeline in which elements are computed on demand.
• This concept gives rise to significant programming benefits. The idea is that a user will extract only the
values they require from a Stream.

• Based on the above points, a stream is :

1. Not a data structure


2. Designed for lambdas
3. Do not support indexed access
4. Can easily be aggregated as arrays or lists
Creating Streams
concat()
empty()
generate()
iterate()
of()
Intermediate Operations
filter()
map()
flatMap()
distinct()
sorted()
peek()
limit()
skip()
Terminal Operations
forEach()
forEachOrdered()
toArray()
reduce()
collect()
min()
max()
count()
anyMatch()
allMatch()
noneMatch()
findFirst()
findAny()
New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API :

Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and
doesn’t have setter methods.
Less operations : In old API there are only few date operations but the new API provides us with many date
operations.
Java 8 under the package java.time introduced a new date-time API, most important classes among them are :

Local : Simplified date-time API with no complexity of timezone handling.


Zoned : Specialized date-time API to deal with various timezones.
LocalDate/LocalTime and LocalDateTime API : Use it when time zones are NOT required.
Serialization and Deserialization
Serialization in Java is the concept of representing an object's state as a byte stream.
The byte stream has all the information about the object. Usually used in Hibernate, JMS, JPA, and EJB,
serialization in Java helps transport the code from one JVM to another and then de-serialize it there.

Serialization is a mechanism for storing an object’s states into a persistent storage like disk files, databases, or
sending object’s states over the network. The process of retrieval and construction of objects from disk files,
databases and network is called de-serialization.
Here are some examples of using serialization:
- Storing data in an object-oriented way to files on disk, e.g. storing a list of Student objects.

- Saving program’s states on disk, e.g. saving state of a game.

- Sending data over the network in form objects, e.g. sending messages as objects in chat application.
JRE System library

• JRE System Library implements the Java API in Eclipse IDE. So all the predefined functions of Java, can be
accessed by the Java Programs written in Eclipse IDE because of this JRE System Library.
• Eclipse IDE adds the JRE System Library to the Java Projects on their creation automatically.

Annotations
• Annotations in java provide additional information to the compiler and JVM.
• An annotation is a tag representing metadata about classes , interfaces , variables , methods and fields.
S.No List Set
1. The list implementation allows us to add the same or duplicate The set implementation doesn't allow us to add the same or
elements. duplicate elements.

2. The insertion order is maintained by the List. It doesn't maintain the insertion order of elements.

3. List allows us to add any number of null values. Set allows us to add at least one null value in it.

4. The List implementation classes are LinkedList and ArrayList. The Set implementation classes are TreeSet, HashSet and
LinkedHashSet.

5. We can get the element of a specified index from the list using We cannot find the element from the Set based on the index
the get() method. because it doesn't provide any get method().

6. It is used when we want to frequently access the elements by It is used when we want to design a collection of distinct
using the index. elements.
ArrayList Linked List

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linked


array to store the elements. list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedList is faster than


is slow because it internally uses an array. If ArrayList because it uses a doubly linked
any element is removed from the array, all list, so no bit shifting is required in memory.
the other elements are shifted in memory.
3) ArrayList is better for storing and LinkedList is better for
accessing data. manipulating data.
4) The memory location for the elements of The location for the elements of a linked list
an ArrayList is contiguous. is not contagious.

5) Generally, when an ArrayList is initialized, There is no case of default capacity in a


a default capacity of 10 is assigned to the LinkedList. In LinkedList, an empty list is
ArrayList. created when a LinkedList is initialized.

You might also like