Java All
Java All
Output:
Start Time for StringBuffer: 2019-07-22 13:58:03.159
End Time for StringBuffer: 2019-07-22 13:58:03.176
Time taken to Execute StringBuffer process 17ms
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = N; i > 0 ; i--) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
}
String Buffer
StringBuffer is a peer class of String that provides much of
the functionality of strings.
String represents fixed-length, immutable character
sequences.
StringBuffer represents growable and writeable character
sequences.
StringBuffer may have characters and substrings inserted
in the middle or appended to the end.
StringBuffer will automatically grow to make room for
such additions and often has more characters preallocated
than are actually needed, to allow room for growth.
+ invokes string buffer automatically and manage the
String class. Its overloaded
String Buffer
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
String Buffer
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " +
sb.capacity());
} Output:
buffer = Hello
} length = 5
capacity = 21
String Buffer
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
Output:
} buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
String Buffer- insert( )
The insert( ) method inserts one string into another. It is
overloaded to accept values of all the simple types, plus
Strings, Objects,
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
String Class
Strings, which are widely used in Java
programming, are a sequence of characters.
In Java programming language, strings are
treated as objects.
ouput: a
String Functions
int compareTo(String anotherString)
Compares two strings lexicographically.
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
Output:
result = str2.compareTo( str3 );
0
System.out.println(result);
10
result = str3.compareTo( str1 );
-10
System.out.println(result);
}
}
String Functions
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Addition of 2 matrices in java
class Testarray{
public static void main(String args[]){
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Classes and Objects
Object − Objects have states and behaviors.
Example: A dog has states - color, name, breed as well
as behaviors – wagging the tail, barking, eating. An
object is an instance of a class.
Class − A class can be defined as a
template/blueprint that describes the behavior/state
that the object of its type support.
Classes
A class is a group of objects which have common
properties. 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
methods
constructors
Blocks
class <class_name>{
field;
method;
}
Objects
It is a basic unit of Object-Oriented
Programming and represents the real-life entities. A
typical Java program creates many objects, which as
you know, interact by invoking methods. An object
consist of :
State : It is represented by attributes of an object. It
also reflect the properties of an object.
Behavior : It is represented by methods of an object.
It also reflects the response of an object with other
objects.
Identity : It gives a unique name to an object and
enables one object to interact with other objects.
Objects
Objects correspond to things found in the real
world.
For example, a graphics program may have
objects such as “circle”, “square”, “menu”.
An online shopping system might have objects
such as “shopping cart”, “customer”, and “product”
When an object of a class is created, the class is
said to be instantiated.
All the instances share the attributes and the
behavior of the class. But the values of those
attributes, i.e. the state are unique for each object.
A single class may have any number of instances.
Objects
Example of a class
Public Class Account
{
Char Name[20];
int Account Type; AC1.Name ox10 Arunkumar
int Account Number; AC1.Account Type ox20 1
float Balance AC1.AccountNumber ox22 1234567
AC1.Balance ox24 10000.00
Input( );
Deposit (int x ); AC2.Name ox40 Arun
Withdraw (int x ); AC2.Account Type ox60 2
Enquire ( ); AC2.AccountNumber ox62 1234568
}; AC2.Balance ox64 10000.00
Account AC1;
Account AC2; AC3.Name ox70 Kumar
Account AC3; AC3.Account Type ox90 3
AC3.AccountNumber ox92 1234569
AC3.Balance ox94 10000.00
Public Class Account
{ public void enquire()
String Name; int Account Type; {
int Account Number; float Balance; System.out.println(balance);
public Account(String name, int
}
act, int acn, float bal)
Public static void main(String args[ ])
{
{
this.name=name
Account AC1=new Account(“Arun”,1, 1234,
this.account type=act; 100.00)
this.account number=acn; Account AC2=new Account(“ar”,2, 123, 100.00)
this.balance=bal; Account AC3=new Account(“arn”,2, 12, 100.00)
}
AC1.Deposit(500);
Public void deposit( int x)
AC2.Deposit(500);
{
AC3.Deposit(500);
balance +=x;
AC1.Withdraw(500);
}
AC2. Withdraw(400);
Public void withdraw(int x)
AC3. Withdraw(400);
{
}
balance-=x;
}
}
Object and Class Example: main outside
class
class Student{
int id;
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Object and Class Example: Rectangle
class Rectangle{
class TestRectangle1{
int length;
public static void main(String args[]){
int width;
Rectangle r1=new Rectangle();
void insert(int l, int w){
Rectangle r2=new Rectangle();
length=l;
r1.insert(11,5);
width=w;
r2.insert(3,15);
}
r1.calculateArea();
void calculateArea()
r2.calculateArea();
{
}
System.out.println(length*width);
}
}
}
Anonymous object
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
Test(int i, int j) {
a = i; b = j;
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Test incrByTen() {
Test temp = new Test(a+10); return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen(); System.out.println("ob2.a after second
increase: "+ ob2.a);
}
}
class Stack {
// Initialize top-of-stack
Stack() {
tos = -1;
}
}
class TestStack {
System.out.println("Stack in mystack2:");
}
Constructors
In Java, constructor is a block of codes similar to
method. It is called when an instance of object is
created, and memory is allocated for the object.
It is a special type of method which is used to
initialize the object.
It is called constructor because it constructs the
values at the time of object creation.
It is not necessary to write a constructor for a
class. It is because java compiler creates a default
constructor if your class doesn't have any.
Constructor
Rules
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
Default constructor (no-arg constructor)
Parameterized constructor
Default constructor
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Parameterized constructor
class Student{ void display(){
int id; String name; int age; System.out.println(id+" "+name+" "+age);
Student(int i,String n){ }
id = i;
name = n; public static void main(String args[]){
} Student s1 = new Student(111,"Karan");
Student(int i,String n,int a){ Student s2 = new Student(222,"Aryan",25);
id = i; s1.display();
name = n; s2.display();
age=a; }
} }
Difference between constructor and
method in java
Java Constructor Java Method
Constructor must not have return Method can have return type.
type.
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Java static variable
The static variable can be used to refer the
common property of all objects
The static variable gets memory only once in
class area at the time of class loading.
class Student{
int rollno;
String name;
String college="ITS";
}
Java static variable
class Student{
int rollno;
String name;
public static void main(String args[]){
static String college =“VIT"; Student s1 = new Student8(111,"Karan")
;
Student(int r,String n){ Student s2 = new Student8(222,"Aryan"
rollno = r; );
name = n;
}
void display ()
s1.display();
{ s2.display();
System.out.println(rollno+" "+n }
ame+" "+college);
}
}
Access Control
Encapsulation links data with the code that
manipulates it.
However, encapsulation provides another
important attribute: access control.
Through encapsulation, you can control what
parts of a program can access the members of a class.
By controlling access, you can prevent misuse.
Default, public, private, and protected.
Access control
public specifier - member can be accessed by any
other code.
Private - member can only be accessed by other
members of its class.
Default - When no access specifier is used, then
by default the member of a class is public within its
own package, but cannot be accessed outside of its
package.
Program
class AccessTest {
class Test {
public static void main(String args[]) {
int a; // default access
Test ob = new Test();
public int b; // public access
ob.a = 10;
private int c; // private access
ob.b = 20;
void setc(int i) {
// ob.c = 100; // Error!
c = i;
ob.setc(100); // OK
}
System.out.println(
"a, b, and c: " + ob.a + " " + ob.b + " " +
int getc() { ob.getc());
return c; }
} }
}
Stack with access control
class Stack { class TestStack {
private int stck[] = new int[10]; public static void main(String args[]) {
private int tos; Stack mystack1 = new Stack();
Stack() { Stack mystack2 = new Stack();
tos = -1; // push some numbers onto the stack
} for(int i=0; i<10; i++) mystack1.push(i);
void push(int item) { for(int i=10; i<20; i++) mystack2.push(i);
if(tos==9) // pop those numbers off the stack
System.out.println("Stack is full."); System.out.println("Stack in mystack1:");
Else stck[++tos] = item; for(int i=0; i<10; i++)
} System.out.println(mystack1.pop());
int pop() { System.out.println("Stack in mystack2:");
if(tos < 0) { for(int i=0; i<10; i++)
System.out.println("Stack underflow."); System.out.println(mystack2.pop());
return 0; // these statements are not legal
} // mystack1.tos = -2;
Else return stck[tos--]; // mystack2.stck[3] = 100;
} }
} }
Nested class
Defining a class within another class is known as
nested classes.
The scope of a nested class is bounded by the
scope of its enclosing class.
A nested class has access to the members,
including private members, of the class in which it is
nested.
The enclosing class does not have access to the
members of the nested class.
class InnerClassDemo {
Inner class public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
// Outer.Inner inner = outer.new
class Outer { Inner();
int outer_x = 100; }
void test() { }
Inner inner = new Inner();
inner.display(); To create an instance of Inner outside of Outer
can be done by qualifying its name with Outer,
} as in Outer.Inner.
class Inner {
void display() {
System.out.println("display: outer_x = " +
outer_x);
}
}//inner class ends
}//outer class ends
Inner class
Instance of Inner can be created only within the
scope of class Outer.
The Java compiler generates an error message if
any code outside of class Outer attempts to
instantiate class Inner.
To create an instance of Inner outside of Outer
can be done by qualifying its name with Outer, as in
Outer.Inner.
class InnerClassDemo {
Inner class example public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
class Outer { }
int outer_x = 100;
void test() {
class Inner {
void display() {
System.out.println("display: outer_x = " +
outer_x);
}
}//inner ends
Inner inner = new Inner();
inner.display();
}//test func ends
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Dynamic stack
class DynStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
DynStack(int size) {
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
// if stack is full, allocate a larger stack
if(tos==stck.length-1) {
int temp[] = new int[stck.length * 2]; // double size
for(int i=0; i<stck.length; i++) temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
}
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class IFTest2 {
public static void main(String args[]) {
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
// these loops cause each stack to grow
for(int i=0; i<12; i++) mystack1.push(i);
for(int i=0; i<20; i++) mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<12; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<20; i++)
System.out.println(mystack2.pop());
}
}
Refer InterfaceStack.pdf
Different from classes
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The
only fields that can appear in an interface must be
declared both static and final.
An interface is not extended by a class; it is
implemented by a class.
An interface can extend multiple interfaces.
Interfaces
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Packages
Java provides a mechanism for partitioning the
class name space into more manageable chunks.
This mechanism is the package. The package is
both a naming and a visibility control mechanism.
You can define classes inside a package that are
not accessible by code outside that package.
You can also define class members that are only
exposed to other members of the same package.
Package
package command is first statement in a Java
source file.
Any classes declared within that file will belong
to the specified package.
The package statement defines a name space in
which classes are stored.
If you omit the package statement, the class
names are put into the default package, which has no
name.
package pkg;
package pkg1[.pkg2[.pkg3]];
package java.awt.image;
Package Example
package MyPack; class AccountBalance {
class Balance { public static void main(String args[]) {
String name; Balance current[] = new Balance[3];
double bal; current[0] = new Balance("K. J. Fielding",
Balance(String n, double b) { 123.23);
name = n; current[1] = new Balance("Will Tell",
157.02);
bal = b;
current[2] = new Balance("Tom Jackson", -
}
12.33);
void show() {
for(int i=0; i<3; i++) current[i].show();
if(bal<0)
}
System.out.print("--> ");
}
System.out.println(name + ": $" + bal);
}
}
AccountBalance.java and put it in a directory called MyPack.
java MyPack.AccountBalance
Access Control
Importing Packages
Java includes the import statement to bring certain
classes, or entire packages, into visibility.
Once imported, a class can be referred to directly, using
only its name. The import statement is a convenience to
the programmer and is not technically needed to write a
complete Java program
import pkg1[.pkg2].(classname|*);
import java.util.Date;
import java.io.*;
import java.util.*;
class MyDate extends Date {
}
class MyDate extends java.util.Date {
Interfaces
Interface
Using the keyword interface, you can fully
abstract a class’ interface from its implementation.
Using interface, you can specify what a class
must do, but not how it does it.
Interfaces are syntactically similar to classes, but
they lack instance variables, and their methods are
declared without any body.
Any number of classes can implement an
interface. Also, one class can implement any number
of interfaces.
Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Defining an Interface
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Interface
Variables can be declared inside of interface declarations
They are implicitly final and static, meaning they cannot
be changed by the implementing class.
interface Callback {
void callback(int param);
}
class Client implements Callback {
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
Refer InterfaceStack.pdf
Different from classes
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The
only fields that can appear in an interface must be
declared both static and final.
An interface is not extended by a class; it is
implemented by a class.
An interface can extend multiple interfaces.
Interfaces
Interface inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
class Employee
{
private int ID;
private String name;
private int age;
private static int nextId=1;
public Employee(String name,int age)
{
this.name = name;
this.age = age;
this.ID = nextId++;
}
public void show()
{
System.out.println
("Id="+ID+"\nName="+name+"\nAge="+age);
}
public void showNextId()
{
System.out.println
("Next employee id will be="+nextId);
}
}
class UseEmployee
{
public static void main(String []args)
{
Employee E=new Employee("GFG1",56);
Employee F=new Employee("GFG2",45);
Employee G=new Employee("GFG3",25);
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
{ //It is sub block to keep
Employee X=new Employee("GFG4",23);
Employee Y=new Employee("GFG5",21);
X.show();
Y.show();
X.showNextId();
Y.showNextId();
}
//After countering this brace, X and Y
//will be removed.Therefore,
//now it should show nextId as 4.
E.showNextId();//Output of this line
//should be 4 but it will give 6 as output.
} //end of main
}/end of class
Output:
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6
//revised program
class Employee
{
private int ID;
private String name;
private int age;
private static int nextId=1;
public Employee(String name,int age)
{
this.name = name;
this.age = age;
this.ID = nextId++;
}
public void show()
{
System.out.println
("Id="+ID+"\nName="+name+"\nAge="+age);
}
public void showNextId()
{
System.out.println
("Next employee id will be="+nextId);
}
protected void finalize()
{
--nextId;
//In this case,
//gc will call finalize()
//for 2 times for 2 objects.
}
}
class UseEmployee
{
public static void main(String []args)
{
Employee E=new Employee("GFG1",56);
Employee F=new Employee("GFG2",45);
Employee G=new Employee("GFG3",25);
E.show();
F.show();
G.show();
E.showNextId();
F.showNextId();
G.showNextId();
} //end of main
}/end of class
Output:
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4
Garbage Collection
Garbage collection is the process of cleaning the
heap memory.
Usually, the space for objects are allocated on
heap and accessed by references.
If there is no references to access the object,
then the object is a waste in heap and its eligible for
garbage collection
Heap Memory
E = null
Heap Memory
System.out.println(x.compareTo(3));
System.out.println(x.compareTo(5));
System.out.println(x.compareTo(8));
}
}
o/p
1
0
-1
equals()
Determines whether this number object is equal to the
argument.
System.out.println(x.equals(y));
System.out.println(x.equals(z));
System.out.println(x.equals(a));
}
}
o/p
false
true
false
valueOf()
Returns an Integer object holding the value of the specified
primitive.
toString()
Returns a String object representing the value of a
specified int or Integer. Also toStirng has power of
converting a whole object to a string
System.out.println(x.toString());
}
}
Output
5
12
parseInt()
This method is used to get the primitive data type of a
certain String.
System.out.println(x);
System.out.println(c);
System.out.println(b);
}
}
Output
9
5.0
1092
abs()
Returns the absolute value of the argument.
ceil()
Returns the smallest integer that is greater than or equal
to the argument. Returned as a double.
floor()
Returns the largest integer that is less than or equal to the
argument. Returned as a double.
round()
Returns the closest long or int, as indicated by the
method's return type to the argument.
min()
Returns the smaller of the two arguments.
max()
Returns the larger of the two arguments.
exp()
Returns the base of the natural logarithms, e, to the power
of the argument.
log()
Returns the natural logarithm of the argument.
pow()
Returns the value of the first argument raised to the power
of the second argument.
sqrt()
Returns the square root of the argument.
sin()
Returns the sine of the specified double value.
cos()
Returns the cosine of the specified double value.
tan()
Returns the tangent of the specified double value.
asin()
Returns the arcsine of the specified double value.
acos()
Returns the arccosine of the specified double value.
atan()
Returns the arctangent of the specified double value.
atan2()
Converts rectangular coordinates (x, y) to polar coordinate
(r, theta) and returns theta.
toDegrees()
Converts the argument to degrees.
toRadians()
Converts the argument to radians.
random()
Returns a random number.
Need for wrapper classes
Normally, when we work with Numbers, we use
primitive data types such as byte, int, long, double,
etc.
Example
int i = 5000;
float gpa = 13.65;
double mask = 0xaf;
However, in development, we come across
situations where we need to use objects instead of
primitive data types. In order to achieve this, Java
provides wrapper classes
Wrapper classes
All the wrapper classes (Integer, Long, Byte,
Double, Float, Short) are subclasses of the abstract
class Number.
Wrapper classes
The object of the wrapper class contains or wraps
its respective primitive data type.
Converting primitive data types into object is
called boxing or autoboxing, and this is taken care by
the compiler. Therefore, while using a wrapper class
you just need to pass the value of the primitive data
type to the constructor of the Wrapper class.
Wrapper object will be converted back to a
primitive data type, and this process is called
unboxing. The Number class is part of the java.lang
package.
Boxing and UnBoxing Example
public class Test {
public static void main(String args[]) {
Integer x = 5; // boxes int to an Integer object
int x1= x + 10; // unboxes the Integer to a int
System.out.println(x1);
}
}
Output: 15
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 (Unboxing through method
invocation).
Assigned to a variable of the corresponding primitive type
Exception Handling
Exception Handling
A Java exception is an object that describes an exceptional
(that is, error) condition that has occurred in a piece of code.
When an exceptional condition arises, an object representing
that exception is created and thrown in the method that
caused the error
The exception is caught and processed.
Exceptions can be generated by the Java run-time system, or
they can be manually generated by your code
Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally. Briefly, here is how
they work.
Exception Handling
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Exception Types
All exception types are subclasses of the built-in class
Throwable.
Throwable are two subclasses that partition exceptions into
two distinct branches.
Exception
This class is used for exceptional conditions that user programs should
catch. division by zero and invalid array indexing
Error
Defines exceptions that are not expected to be caught under normal
circumstances by your program. Stack overflow is an example of such an
error
Example
import java.util.Random;
class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt(); c = r.nextInt(); a = 12345 / (b/c);
} catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Nested try Statements
The try statement can be nested. That is, a try statement can
be inside the block of another try.
Each time a try statement is entered, the context of that
exception is pushed on the stack.
If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted.
throw
It is possible for your program to throw an exception
explicitly, using the throw statement.
throw ThrowableInstance;
The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception
throw example
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
throws
If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that callers of the
method can guard themselves against that exception.
A throws clause lists the types of exceptions that a method
might throw.
type method-name(parameter-list) throws exception-list
{
// body of method
}
throws example
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
finally
When exceptions are thrown, execution in a method takes a
rather abrupt, nonlinear path that alters the normal flow
through the method.
If a method opens a file upon entry and closes it upon exit,
then you will not want the code that closes the file to be The
finally keyword is designed to address this bypassed by the
exception-handling mechanism.
contingency.
finally
finally creates a block of code that will be executed after a
try/catch block has completed and before the code
following the try/catch block.
The finally block will execute whether or not an exception
is thrown. If an exception is thrown, the finally block will
execute even if no catch statement matches the exception
finally example
class FinallyDemo { // Execute a try block normally.
static void procA() { static void procC() {
try { try {
System.out.println("inside procA"); System.out.println("inside procC");
throw new RuntimeException("demo"); } finally {
} finally { System.out.println("procC's finally");
System.out.println("procA's finally"); }
} }
} public static void main(String args[]) {
static void procB() { try {
try { procA(); inside procA
System.out.println("inside procB"); } catch (Exception e) { procA’s finally
return; System.out.println("Exception caught"); Exception caught
} finally { } inside procB
System.out.println("procB's finally"); procB(); procB’s finally
} procC(); inside procC
} } procC’s finally
}
Checked
Checked: are the exceptions that are checked at compile time. If
some code within a method throws a checked exception, then the
method must either handle the exception or it must specify the
exception using throws keyword.
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Checked
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Unchecked
Unchecked are the exceptions that are not checked at
compiled time. In C++, all exceptions are unchecked, so it
is not forced by the compiler to either handle or specify the
exception.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
User Defined Exception
User Defined Exception
Java’s built-in exceptions handle most common errors.
Probably if you want to create your own exception types to
handle situations specific to your applications we go for user
defined exceptions
By creating a sub class to Exception class we can define our
own exception.
Exception class is the sub class of Throwable class. So all the
methods supported by throwable is available into our own
defined exception class.
Throwable class methods
Throwable fillInStackTrace( )
Throwable getCause( )
String getMessage( )
Throwable initCause(Throwable causeExc)
void printStackTrace( )
void printStackTrace(PrintStream stream)
String toString( )
Example
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
Example
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) { Called compute(1)
System.out.println("Caught " + e); Normal exit
} Called compute(20)
} Caught MyException[20]
}
// Using join() to wait for threads to finish.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
// wait for threads to finish
try {
System.out.println("Waiting for threads to
finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Extending Thread
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second
thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread
Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Not only may the results vary from machine to machine, but
running the same program multiple times on the same
machine may produce different results. Never assume one
thread will do something before another thread does, unless
you've used synchronization to force a specific ordering of
execution.
Multiple Threads
Program can spawn as many threads as it needs
Refer MultipleThread.pdf
isAlive and join
The isAlive( ) method returns true if the thread upon
which it is called is still running. It returns false otherwise.
The join method allows one thread to wait for the
completion of another.
t.join();
If t is a Thread object whose thread is currently executing,
causes the current thread to pause execution until t's thread
terminates.
Join ( )
Join method from Thread class is an important method and used to
impose order on execution of multiple Threads.
“You have three threads T1, T2, and T3, How do you ensure that
they finish in order T1, T2, T3 ?.
Refer ThreadPri.pdf
exampleThread.start();
exampleThread.join();
Because of join method, now, main thread will wait until Thread-0 completes
its operation or You can say main thread will join Thread-0.
Output:
Low-priority thread: 5798834241
High-priority thread: 5852293016
Synchronization
synchronization.
When two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used
by only one thread at a time.
The process by which this is achieved is called synchronization.
Monitor
Key to synchronization is the concept of the monitor
A monitor is an object that is used as a mutually exclusive
lock, or mutex.
Only one thread can own a monitor at a given time. When a
thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will
be suspended until the first thread exits the monitor.
These other threads are said to be waiting for the monitor.
Java implements synchronization through synchronized
keyword
Example
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
Example
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
Example
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
}
}
Output:
[Hello[World[Synchronized]
]
]
Example
calling sleep( ), the call( ) method allows execution to switch to
another thread.
This results in the mixed-up output of the three message strings.
In this program, nothing exists to stop all three threads from
calling the same method, on the same object, at the same time.
This is known as a race condition, because the three threads are
racing each other to complete the method.
We can’t be sure when the context switch will occur.
This can cause a program to run right one time and wrong the
next.
Synchronized methods
To serialize the access to call( ) is by adding synchronized
keyword
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
Program with Synch
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
synchronized(target) {
target.call(msg);
}
}
}
Program with Synch
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
//target.call();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
}
}
[Synchronized]
[Hello]
[World]
public class DeadlockEg {
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
} //synch2
} //synch1
} //run
}; //t1
try {
Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}//synch2
}//synch1
} //run
}; //t2
t1.start();
t2.start();
} //main
} //deadlock class
Inter-process communication
Polling
Polling is usually implemented by a loop that is used to check
some condition repeatedly.
Once the condition is true, appropriate action is taken. This
wastes CPU time.
producer has to wait until the consumer is finished before it
generates more data.
consumer would waste many CPU cycles while it waited for
the producer to produce.
Once the producer was finished, it would start polling,
wasting more CPU cycles waiting for the consumer to finish
Inter-process communication
Java includes has inter-process communication mechanism
through the wait( ), notify( ), and notifyAll( ) methods.
wait( ) tells the calling thread to give up the monitor and go to
sleep until some other thread enters the same monitor and calls
notify( ).
notify( ) wakes up a thread that called wait( ) on the same
object.
notifyAll( ) wakes up all the threads that called wait( ) on the
same object. One of the threads will be granted access.
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
Producer consumer problem
Refer PC.pdf
Deadlock
Deadlock occurs when two threads have a circular dependency
on a pair of synchronized objects.
Suppose one thread enters the monitor on object X and
another thread enters the monitor on object Y.
If the thread in X tries to call any synchronized method on Y,
it will block as expected.
However, if the thread in Y, in turn, tries to call any
synchronized method on X, the thread waits forever, because
to access X, it would have to release its own lock on Y so that
the first thread could complete
Deadlock program
Refer Deadlock.pdf
Output
MainThread entered A.foo
RacingThread entered B.bar
RacingThread trying to callA.last()
MainThread trying to call B.last()
Suspend and resume
final void suspend( )
final void resume( )
Refer suspend resume.pdf
class Q {
int n;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Q1 {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
class PCWaitNotify {
public static void main(String args[]) {
Q1 q = new Q1();
new Producer1(q);
new Consumer1(q);
System.out.println("Press Control-C to stop.");
}
}
FileReader,FileWriter,
BufferedReader,BufferedWriter
DataInputStream, DataOutputStream
DataOutputStream and DataInputStream
DataOutputStream and DataInputStream enable you to
write or read primitive data to or from a stream.
They implement the DataOutput and DataInput
interfaces, respectively.
These interfaces define methods that convert primitive values
to or from a sequence of bytes.
These streams make it easy to store binary data, such as
integers or floating-point values, in a file.
DataOutputStream
DataOutputStream(OutputStream outputStream)
final void writeDouble(double value) throws IOException
final void writeBoolean(boolean value) throws IOException
final void writeInt(int value) throws IOException
DataInputStream
DataInputStream(InputStream inputStream)
double readDouble( ) throws IOException
boolean readBoolean( ) throws IOException
int readInt( ) throws IOException
Example
class DataIODemo {
public static void main(String args[]) throws IOException {
FileOutputStream fout = new FileOutputStream("Test.dat");
DataOutputStream out = new DataOutputStream(fout);
out.writeDouble(98.6);
out.writeInt(1000);
out.writeBoolean(true);
out.close();
FileInputStream fin = new FileInputStream("Test.dat");
DataInputStream in = new DataInputStream(fin);
double d = in.readDouble();
int i = in.readInt();
boolean b = in.readBoolean();
System.out.println("Here are the values: " +
d + " " + i + " " + b);
in.close();
}
}
Reader and Writer
Reader is an abstract class that defines Java’s model of
streaming character input. It implements the Closeable and
Readable interfaces.
Writer is an abstract class that defines streaming character
output. It implements the Closeable, Flushable, and
Appendable interfaces
FileReader and FileWriter
The FileReader class creates a Reader that you can use to
read the contents of a file. Its two most commonly used
constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
FileWriter creates a Writer that you can use to write to a
file. Its most commonly used constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
Reader methods
Writer Methods
File Reader Example
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
File Writer Example
class FileWriterDemo {
public static void main(String args[]) throws IOException {
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt");
for (int i=0; i < buffer.length; i += 2) {
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new FileWriter("file2.txt");
f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
f2.close();
}
}
BufferedWriter Class
Java BufferedWriter class is used to provide buffering for
Writer instances. It makes the performance fast. It
inherits Writer class. The buffering characters are used for
providing the efficient writing of single arrays, characters,
and strings.
Constructor Description
int size;
int n = size/40;
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}
catch(Exception e) {
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}//end of catch
}//end of main
}//end of main class
class MyClass implements Serializable {
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;
}
}
Serialization
Serialization
Serialization is the process of writing the state of an object to
a byte stream.
The output of a program is saved to a persistent storage area,
such as a file.
We can also restore these objects by using the process of
deserialization.
RMI
RMI- Remote method inovocation
A Java object on one machine can call a method present on
other machine
Object may is supplied as an argument to that remote method.
The sending machine serializes the object and transmits it.
The receiving machine deserializes it.
ObjectOutputStream
ObjectOutputStream
The ObjectOutputStream class extends the OutputStream
class and implements the ObjectOutput interface.
It is responsible for writing objects to a stream.
A constructor of this class is
ObjectOutputStream(OutputStream outStream) throws IOException
The ObjectOutput interface extends the DataOutput
interface and supports object serialization.
void close( )
void flush( )
void writeObject(Object obj)
final void writeObject(Object obj)
ObjectInputStream
The ObjectInputStream class extends the InputStream class
and implements the ObjectInput interface.
ObjectInputStream is responsible for reading objects from a
stream.
Aconstructor of this class is
ObjectInputStream(InputStream inStream) throws IOException
The ObjectInput interface extends the DataInput interface and
defines the methods
int available( )
void close( )
Object readObject( )
final Object readObject( )
Serialization deserialization Eg
Serialization deserialization Eg refer serial.pdf
Lambda Expressions
Lambda Expressions
Lambda expression facilitates functional programming, and
simplifies the development a lot.
A Java lambda expression is thus a function which can be
created without belonging to any class.
Java lambda expressions are commonly used to implement
simple event listeners / callbacks
Characteristics
Optional type declaration − No need to declare the type of a
parameter. The compiler can inference the same from the value of
the parameter.
Optional parenthesis around parameter − No need to
declare a single parameter in parenthesis. For multiple parameters,
parentheses are required.
Optional curly braces − No need to use curly braces in
expression body if the body contains a single statement.
Optional return keyword − The compiler automatically
returns the value if the body has a single expression to return the
value. Curly braces are required to indicate that expression
returns a value.
Syntax
(argument-list) -> {body}
Argument-list: It can be empty or non-empty as well.
Arrow-token: It is used to link arguments-list and body of
expression.
Body: It contains expressions and statements for lambda expression.
() -> {
//Body of no parameter lambda
}
(p1) -> {
//Body of single parameter lambda
}
(p1,p2) -> {
//Body of multiple parameter lambda
}
Example
class Test
{
public static void main(String args[])
{
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
}
}
Treeset for user defined objects
The elements in TreeSet must be of a Comparable type.
String and Wrapper classes are Comparable by default.
To add user-defined objects in TreeSet, you need to
implement the Comparable interface.
Refer TreesetComparable.pdf
Hashset
HashSet extends AbstractSet and
implements the Set interface. It creates a
collection that uses a hash table for storage.
A hash table stores information by using a
mechanism called hashing. In hashing, the
informational content of a key is used to
determine a unique value, called its hash
code.
Program
public class HashSetPgm {
public static void main(String args[]){
HashSet<String> hs=new HashSet();
hs.add("S");
hs.add("A");
hs.add("N");
hs.add("J");
hs.add("A");
hs.add("N");
Iterator<String> i=hs.iterator();
while(i.hasNext()) A
{ S
System.out.println(i.next()); J
} N
}
}
DeQue
Java Deque Interface is a linear collection that supports
element insertion and removal at both ends. Deque is an
acronym for "double ended queue".
Unlike Queue, we can add or remove elements from both
sides.
Null elements are not allowed in the ArrayDeque.
ArrayDeque has no capacity restrictions.
ArrayDeque is faster than LinkedList and Stack.
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity)
{
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayDequeExample {
public static void main(String[] args) {
Deque<Book> set=new ArrayDeque<Book>();
set.add(b1);
set.add(b2);
set.add(b3);
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Map
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair
is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Classes
HashMap HashMap is the implementation of Map, but it
doesn't maintain any order.
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
System.out.println("Actual ArrayList:"+arrl);
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
arrl.addAll(list);
Collections.swap(list, 2, 5);
System.out.println("Results after swap operation:");
for(String str: list){
System.out.println(str);
}
Output:
Results after swap operation:
Java
Cric
Movie
Watch
Glass
Play
Girl
Collection comparator pgm
interface Comparator<T>
This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than
obj2. Otherwise, a negative value is returned.
The method can throw a ClassCastException if the types of the objects are not compatible for
comparison.
By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in
reverse order, you can create a comparator that reverses the outcome of a comparison.
Comparator in array list
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
105 Jai 21
101 Vijay 23
106 Ajay 27
public class MyArrayListSort {
@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
The easiest way to remove duplicate entries from the given array is, create TreeSet object and add array entries to the TreeSet.
Since the set doesnot support duplicate entries, you will get only unique elements left with TreeSet.
Output:
[five, four, one, three, two]
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
@Override
public int compare(Empl e1, Empl e2) {
return e1.getName().compareTo(e2.getName());
}
}
@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() > e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
Output:
[BLACK, BLUE, BROWN, GREEN, ORANGE, RED, WHITE, YELLOW]
sub set: [GREEN, ORANGE, RED]
sub set: [GREEN, ORANGE, RED, WHITE]
sub set: [ORANGE, RED, WHITE]
@Override
public int compare(Emp e1, Emp e2) {
if(e1.getEmpId() == e2.getEmpId()){
return 0;
} if(e1.getEmpId() < e2.getEmpId()){
return 1;
} else {
return -1;
}
}
}
class Emp {
ts.add("RED");
ts.add("ORANGE");
ts.add("BLUE");
ts.add("GREEN");
System.out.println(ts);
@Override
return str1.compareTo(str2);
Output:
import java.util.*;
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
public class TreeSetExample {
//Creating Books
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
101
Data Communications & Networking Forouzan Mc Graw Hill
4
121 Let us C Yashwant Kanetkar BPB 8
The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the
correct method.
If no element exists in the Map, it will throw a ‘NoSuchElementException’.
HashMap stores only object references. That is why, it is impossible to use primitive data types like double or int. Use
wrapper class (like Integer or Double) instead.
Output
{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}
Value of second: SECOND INSERTED
Is HashMap empty? false
{second=SECOND INSERTED, first=FIRST INSERTED}
Size of the HashMap: 2
if(hm.containsValue("SECOND INSERTED")){
System.out.println("The hashmap contains value SECOND INSERTED");
} else {
System.out.println("The hashmap does not contains value SECOND INSERTED");
}
hm.clear();
Generic classes and methods
Generics in JAVA
Using generics, it is possible to create a single class, for
example, that automatically works with different types of
data.
A class, interface, or method that operates on a
parameterized type is called generic, as in generic class or
generic method.
Generic class and methods
public class Box<T> { public static void main(String[] args) {
private T t; Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
public void add(T t) {
this.t = t; integerBox.add(new Integer(10));
} stringBox.add(new String("Hello World"));
Wildcard.pdf
Generic methods
it is possible to declare a generic method that uses one or
more type parameters of its own
it is possible to create a generic method that is enclosed
within a non-generic class.
GenMeth.pdf
Generics
Generic constructors – GenCons.pdf
Generic interfaces – GenInt.pdf
class Stats<T> {
Stats(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // Error!!!
return sum / nums.length;
}
}
With Bounded type
class BoundsDemo {
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Average is 3.0
Average is 3.3
// Use a generic constructor.
class GenCons {
void showval() {
System.out.println("val: " + val);
}
}
class GenConsDemo {
T[] vals;
MyClass(T[] o) { vals = o; }
public T min() {
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) < 0) v = vals[i];
return v;
}
}
class GenIFDemo {
Integer nums[] = { 1, 2, 3, 4, 5 };
if(isIn(2, nums))
System.out.println("2 is in nums");
if(!isIn(7, nums))
System.out.println("7 is not in nums");
System.out.println();
if(isIn("two", strs))
System.out.println("two is in strs");
if(!isIn("seven", strs))
System.out.println("seven is not in strs");
void showTypes() {
System.out.println("Type of T is " +
ob1.getClass().getName());
System.out.println("Type of V is " +
ob2.getClass().getName());
}
T getob1() {
return ob1;
}
V getob2() {
return ob2;
}
}
// Demonstrate TwoGen.
class SimpGen {
public static void main(String args[]) {
TwoGen<Integer, String> tgObj =
new TwoGen<Integer, String>(88, "Generics");
// Show the types.
tgObj.showTypes();
// Obtain and show values.
int v = tgObj.getob1();
System.out.println("value: " + v);
String str = tgObj.getob2();
System.out.println("value: " + str);
}
}
Type of T is java.lang.Integer
Type of V is java.lang.String
value: 88
value: Generics
class Stats<T extends Number> {
T[] nums; // array of Number or subclass
// Pass the constructor a reference to
// an array of type Number or subclass.
Stats(T[] o) {
nums = o;
}
class WildcardDemo {
public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
if(iob.sameAvg(dob))
System.out.println("are the same.");
else
System.out.println("differ.");
System.out.print("Averages of iob and fob ");
if(iob.sameAvg(fob))
System.out.println("are the same.");
else
System.out.println("differ.");
}
}
---------------------------------------------------------------------------