0% found this document useful (0 votes)
21 views358 pages

Java All

Java arrays can store multiple elements of the same type. Arrays allow accessing its elements through indices and can be one or multi-dimensional. Arrays can be passed to methods, returned from methods, and iterated over using for loops.

Uploaded by

Good Boy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views358 pages

Java All

Java arrays can store multiple elements of the same type. Arrays allow accessing its elements through indices and can be one or multi-dimensional. Arrays can be passed to methods, returned from methods, and iterated over using for loops.

Uploaded by

Good Boy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 358

Arrays

 Java provides a data structure, the array, which stores a fixed-size


sequential collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.
 Instead of declaring individual variables, such as number0, number1,
..., and number99, you declare one array variable such as numbers and
use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.
Declaring Array Variables
 To use an array in a program, you must declare a variable to
reference the array, and you must specify the type of array
the variable can reference.
 Here is the syntax for declaring an array variable
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Creating Arrays
 You can create an array by using the new operator with the
following syntax
 arrayRefVar = new dataType[arraySize];
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the
variable arrayRefVar.
Creating Arrays
 Declaring an array variable, creating an array, and assigning
the reference of the array to the variable can be combined in
one statement, as shown below
 dataType[] arrayRefVar = new dataType[arraySize];
 Alternatively you can create arrays as follows
 dataType[] arrayRefVar = {value0, value1, ..., valuek};
 The array elements are accessed through the index. Array
indices are 0-based; that is, they start from 0 to
arrayRefVar.length-1.
Example
 Following statement declares an array variable, myList,
creates an array of 10 elements of double type and assigns its
reference to myList
double[] myList = new double[10];
Processing
public class TestArray {
Arrays
// Finding the largest element
public static void main(String[] args) {
double max = myList[0];
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
for (int i = 0; i < myList.length; i++) {
}
System.out.println(myList[i] + " ");
System.out.println("Max is " + max);
}
}
double total = 0;  Output
}
for (int i = 0; i < myList.length; i++) { 1.9
total += myList[i]; 2.9
}
3.4
System.out.println("Total is " + total);
3.5
Total is 11.7
Max is 3.5
The enhanced for Loops
public class TestArray {

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


double[] myList = {1.9, 2.9, 3.4, 3.5};
1.9
// Print all the array elements 2.9
for (double element: myList) { 3.4
System.out.println(element); 3.5
}
}
}
Passing Arrays to Methods
public static void printArray(int[ ] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

Can be called as:


printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {


result[j] = list[i];
}
return result;
}
Arrays
 Java provides a data structure, the array, which stores a fixed-
size sequential collection of elements of the same type.
 An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of
the same type.
 Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable
such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables
 To use an array in a program, you must declare a
variable to reference the array, and you must specify
the type of array the variable can reference.
 Here is the syntax for declaring an array variable
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred
way.
Creating Arrays
 You can create an array by using the new
operator with the following syntax
 arrayRefVar = new dataType[arraySize];
 It creates an array using new
dataType[arraySize].
 It assigns the reference of the newly created
array to the variable arrayRefVar.
Creating Arrays
 Declaring an array variable, creating an array, and
assigning the reference of the array to the variable
can be combined in one statement, as shown below
 dataType[] arrayRefVar = new dataType[arraySize];
 Alternatively you can create arrays as follows
 dataType[] arrayRefVar = {value0, value1, ..., valuek};
 The array elements are accessed through the
index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.
Example
 Following statement declares an array variable,
myList, creates an array of 10 elements of double type
and assigns its reference to myList
double[] myList = new double[10];
Processing Arrays
public class TestArray {

public static void main(String[] args) { // Finding the largest element


double[] myList = {1.9, 2.9, 3.4, 3.5}; double max = myList[0];
for (int i = 1; i < myList.length; i++) {
for (int i = 0; i < myList.length; i++) { if (myList[i] > max) max = myList[i];
System.out.println(myList[i] + " "); }
} System.out.println("Max is " + max);
double total = 0; }  Output
for (int i = 0; i < myList.length; i++) { } 1.9
total += myList[i]; 2.9
}
3.4
System.out.println("Total is " + total);
3.5
Total is 11.7
Max is 3.5
The enhanced for Loops
public class TestArray {

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


double[] myList = {1.9, 2.9, 3.4, 3.5}; Out
put
// Print all the array elements 1.9
for (double element: myList) { 2.9
System.out.println(element);
3.4
}
3.5
}
}
Passing Arrays to Methods
public static void printArray(int[ ] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

Can be called as:


printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--)


{
result[j] = list[i];
}
return result;
}
Multidimensional Arrays
 In Java, multidimensional arrays are actually arrays of arrays
 To declare a multidimensional array variable, specify each
additional index using another set of square brackets
Two Dimensional Arrays
 int twoD[][] = new int[4][5];
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} 01234
} 56789
} 10 11 1213 14
15 16 17 18 19
Two Dimensional Arrays – differing size
Output:
class TwoDAgain { 0
public static void main(String args[]) {
12
int twoD[][] = new int[4][];
345
6789
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3]; for(i=0; i<4; i++) {
twoD[3] = new int[4]; for(j=0; j<i+1; j++)
int i, j, k = 0; System.out.print(twoD[i][j] + " ");
for(i=0; i<4; i++)
System.out.println();
for(j=0; j<i+1; j++) {
}//end of for
twoD[i][j] = k;
}//end of main
k++;
} }//end of class
00000
Three dimensional array 00000
class ThreeDMatrix { 00000
public static void main(String args[]) { 00000
int threeD[][][] = new int[3][4][5];
int i, j, k; 00000
for(i=0; i<3; i++) 01234
for(j=0; j<4; j++) 02468
for(k=0; k<5; k++) 0 3 6 9 12
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) { 00000
for(j=0; j<4; j++) { 02468
for(k=0; k<5; k++) 0 4 8 12 16
0 6 12 18 24
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}//end of for
Multidimensional Arrays
 In Java, multidimensional arrays are actually
arrays of arrays
 To declare a multidimensional array variable,
specify each additional index using another set of
square brackets
Two Dimensional Arrays
 int twoD[][] = new int[4][5];
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} 01234
} 56789
} 10 11 12 13 14
15 16 17 18 19
Two Dimensional Arrays – differing size
Output:
class TwoDAgain { 0
public static void main(String args[]) {
12
int twoD[][] = new int[4][];
345
6789
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3]; for(i=0; i<4; i++) {
twoD[3] = new int[4]; for(j=0; j<i+1; j++)
int i, j, k = 0; System.out.print(twoD[i][j] + "
for(i=0; i<4; i++) ");
for(j=0; j<i+1; j++) { System.out.println();
twoD[i][j] = k; }//end of for
k++;
}//end of main
}
}//end of class
Three dimensional array 00000
00000
class ThreeDMatrix {
00000
public static void main(String args[]) {
00000
int threeD[][][] = new int[3][4][5];
int i, j, k;
00000
for(i=0; i<3; i++) 01234
for(j=0; j<4; j++) 02468
for(k=0; k<5; k++) 0 3 6 9 12
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) { 00000
for(j=0; j<4; j++) { 02468
for(k=0; k<5; k++) 0 4 8 12 16
System.out.print(threeD[i][j][k] + 0" ");
6 12 18 24
System.out.println();
}
System.out.println();
}//end of for
public static void main(String[] args) {
Date sDate = new Date();
long sTime = sDate.getTime();
System.out.println("Start Time for StringBuffer: " + new Timestamp(sTime));
StringBuffer s = new StringBuffer("AA");
for (int i=0; i< 10000; i++){
s.append(i);
}
Date eDate = new Date();
long eTime = eDate.getTime();
System.out.println("End Time for StringBuffer: " + new Timestamp(eTime));
System.out.println("Time taken to Execute StringBuffer process " + (eTime-sTime) +
"ms");

Date strDate = new Date();


long strTime = strDate.getTime();
System.out.println("Start Time for String: " + new Timestamp(strTime));
String str = new String("AA");
for (int i=0; i< 10000; i++){
str+=i;
}
Date eStrDate = new Date();
long eStrTime = eStrDate.getTime();
System.out.println("End Time for String: " + new Timestamp(eStrTime));
System.out.println("Time taken to Execute String process " + (eStrTime-strTime) +
"ms");
}

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

Start Time for String: 2019-07-22 13:58:03.182


End Time for String: 2019-07-22 13:58:03.471
Time taken to Execute String process 289ms
___________________________________________________________________________
public static void main(String[] args) {
int N = 77777777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = N; i > 0 ; i--) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}

{
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.

 The Java platform provides the String class to


create and manipulate strings.
 The most direct way to create a string is to write

 String greeting = "Hello world!";
 Whenever it encounters a string literal in your
code, the compiler creates a String object with its
value in this case, "Hello world!'.
Example
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
String Length
public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
Concatenating Strings
 string1.concat(string2);
 "My name is ".concat("Zara");
 "Hello," + " world" + "!“
public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
String functions
 char charAt(int index)
 Returns the character at the specified index.

public class Test {

public static void main(String args[]) {


String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}

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.

 static String copyValueOf(char[] data, int offset, int count)


 Returns a String that represents the character sequence in the array specified.

 boolean endsWith(String suffix)


 Tests if this string ends with the specified suffix.

 boolean equals(Object anObject)


 Compares this string to the specified object.

 boolean equalsIgnoreCase(String anotherString)


 Compares this String to another String, ignoring case considerations.

 int indexOf(int ch)


 Returns the index within this string of the first occurrence of the specified character.

 int indexOf(String str)


 Returns the index within this string of the first occurrence of the specified substring.
String Functions
 String replace(char oldChar, char newChar)
 Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome");
System.out.print("Return Value :" );
System.out.println(Str.replace('o', 'T'));
System.out.print("Return Value :" );
System.out.println(Str.replace('l', 'D'));
}
}
 Return Value :WelcTme
 Return Value :WeDcome
String Functions
 int lastIndexOf(String str)
 Returns the index within this string of the rightmost
occurrence of the specified substring.
 boolean matches(String regex)
 Tells whether or not this string matches the given regular
expression.
 String replaceAll(String regex, String replacement
 Replaces each substring of this string that matches the
given regular expression with the given replacement.
 String replaceFirst(String regex, String replacement)
 Replaces the first substring of this string that matches the
given regular expression with the given replacement.
 String[] split(String regex)
 Splits this string around matches of the given regular
expression.
String Functions
 String toLowerCase()
 Converts all of the characters in this String to lower
case using the rules of the default locale.
 String toString()
 This object (which is already a string!) is itself
returned.
 String toUpperCase()
 Converts all of the characters in this String to upper
case using the rules of the default locale.
Multidimensional array in java
 Declaration
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
 Example
int[][] arr=new int[3][3];//3 row and 3 column
Initialize
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Program
class Testarray{
public static void main(String args[]){

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[]){

new Calculation().fact(5);//calling method with anonymous object


}
}
Array of objects
Public Class Account
{
Char Name[20];
int Account Type; AC[0].Name ox10 Arunkumar
int Account Number; AC[0].Account Type ox20 1
float Balance AC[0].AccountNumber ox22 1234567
AC[0].Balance ox24 10000.00
Input( );
Deposit (int x ); AC[1].Name ox40 Arun
Withdraw (int x ); AC[1].Account Type ox60 2
Enquire ( ); AC[1].AccountNumber ox62 1234568
}; AC[1].Balance ox64 10000.00
Account AC[0];
Account AC[1]; AC[2].Name ox70 Kumar
Account AC[2]; AC[2].Account Type ox90 3
AC[2].AccountNumber ox92 1234569
AC[2].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 AC[] =new Account[3]
this.account type=act;
AC[0] = new Account (“Arun”,1, 1234, 100.00)
this.account number=acn;
AC[1] =new Account(“ar”,2, 123, 100.00)
this.balance=bal;
AC[2] =new Account(“arn”,2, 12, 100.00)
}
For(int i=0;i<3;i++)
Public void deposit( int x)
AC[i].Deposit(500);
{
balance +=x;
For(int i=0;i<3;i++)
}
AC[i]. Withdraw (500);
Public void withdraw(int x)
}
{
balance-=x; }
}
// Objects may be passed to methods.
class Test {
int a, b;

Test(int i, int j) {
a = i; b = j;
}

// return true if o is equal to the invoking object


boolean equals(Test o) {
if(o.a == a && o.b == b) return true; else return false;
}
}

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));
}
}

//This program generates the following output:


//ob1 == ob2: true ob1 == ob3: false
_________________________________________________________________
class Test {
int a;
Test(int i) {
a = i;
}

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 {

int stck[] = new int[10];


int tos;

// Initialize top-of-stack
Stack() {
tos = -1;
}

// Push an item onto the stack


void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

// Pop an item from the stack


int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}

}
class TestStack {

public static void main(String args[]) {

Stack mystack1 = new Stack();

Stack mystack2 = new Stack();


// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);

// pop those numbers off the stack


System.out.println("Stack in mystack1:");

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


System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");

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


System.out.println(mystack2.pop());

}
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 is used to initialize the Method is used to expose behaviour


state of an object. of an object.

Constructor must not have return Method can have return type.
type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by compiler


constructor if you don't have any in any case.
constructor.

Constructor name must be same as Method name may not be same as


the class name. class name.
Copy Constructor
void display(){
class Student{
System.out.println(id+" "+name);
int id;
}
String name;
Student(int i,String n){
public static void main(String args[]){
id = i;
Student s1 = new Student(111,"Karan");
name = n;
}
Student s2 = new Student(s1);
s1.display();
Student(Student s){
s2.display();
id = s.id;
}
name =s.name;
}
}
Method Overloading
 If a class has multiple methods having same
name but different in parameters, it is known
as Method Overloading.
 If we have to perform only one operation, having
same name of the methods increases the readability
of the program.
 There are two ways to overload the method in
java
 By changing number of arguments
 By changing the data type
changing no. of arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
changing data type of arguments
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
overload java main() method
class TestOverloading4{
public static void main(String[] args){
System.out.println("main with String[]");
}
public static void main(String args){
System.out.println("main with String");
}
public static void main(){
System.out.println("main without args");}
}
 Jvm will call only main with string array
Static
 Static members are used to work individually
without the help of objects
 It can be used by itself, without reference to a
specific instance
 You can declare both methods and variables to
be static.
 you can declare a static block that gets executed
exactly once, when the class is first loaded
 Static variable
 Static methods
 Static class
 Static blocks
Static
 When objects of its class are declared, no copy of
a static variable is made.
 Instead, all instances of the class share the same
static variable.
 Methods declared as static have several
restrictions:
 They can only call other static methods.
 They cannot refer to this or super in any way.
Program
class UseStatic {
static int a = 3; static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
output
 As soon as the UseStatic class is loaded, all of the static
statements are run.
 First, a is set to 3, then the static block executes, which
prints a message and then initializes b to a * 4 or 12.
 Then main( ) is called, which calls meth( ), passing 42 to x.
 The three println( ) statements refer to the two static
variables a and b, as well as to the local variable x.
Static block initialized.
x = 42
a=3
b = 12
Accessing static
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}

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;
}
}

// Here, Box is extended to include weight.


class BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
The output from this program is shown here:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Inheritance
 Inheritance can be defined as the process where one class
acquires the properties (methods and fields) of another.
With the use of inheritance, the information is made
manageable in a hierarchical order.
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
Example
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Types of inheritance
Inheritance example
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
Inheritance example
class SimpleInheritance {
System.out.println("Contents of
public static void main(String args[]) {
subOb: ");
A superOb = new A();
subOb.showij();
B subOb = new B();
subOb.showk();
superOb.i = 10;
System.out.println();
superOb.j = 20;
System.out.println("Sum of i, j and k in
System.out.println("Contents of superOb: subOb:");
");
subOb.sum();
superOb.showij();
}
System.out.println();
}
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
Member access
 Subclass includes all of the members of its
superclass, it cannot access those members of the
superclass that have been declared as private
Example
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double
m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}

Super box program (Refer PDF)


Example for super.member
super.member
Here, member can be either a method or an instance variable.
class A { class UseSuper {
int i; public static void main(String
} args[]){
class B extends A { B subOb = new B(1, 2);
int i; // this i hides the i in A subOb.show();
B(int a, int b) { }
super.i = a; // i in A }
i = b; // i in B This program displays the following:
} i in superclass: 1
void show() { i in subclass: 2
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
Multilevel
 Consider three classes called A, B, and C, C can be
a subclass of B, which is a subclass of A.
 When this type of situation occurs, each subclass
inherits all of the traits found in all of its super classes.
In this case, C inherits all aspects of B and A.
 Example
 BoxWeight is used as a superclass to create the
subclass called Shipment.
 Shipment inherits all of the traits of BoxWeight and
Box, and adds a field called cost, which holds the cost of
shipping such a parcel.
Constructors in Inheritance
 In a class hierarchy, constructors are called in
order of derivation, from superclass to subclass.
 super( ) must be the first statement executed in a
subclass’ constructor.
 This order is the same whether or not super( ) is
used.
 If super( ) is not used, then the default or
parameterless constructor of each superclass will be
executed.
Constructors in Inheritance Example
class A {
class C extends B {
A() {
C() {
System.out.println("Inside A's
constructor."); System.out.println("Inside C's constructor.");
} }
} }
class B extends A { class CallingCons {
B() { public static void main(String args[]) {
System.out.println("Inside B's C c = new C();
constructor."); }
} }
} Output:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
class Box {
private double width;
private double height;
private 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;
}
}
// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
// Add shipping costs.
class Shipment extends BoxWeight {
double cost;
// construct clone of an object
Shipment(Shipment ob) { // pass object to constructor
super(ob);
cost = ob.cost;
}
// constructor when all parameters are specified
Shipment(double w, double h, double d,
double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
// default constructor
Shipment() {
super();
cost = -1;
}
// constructor used when cube is created
Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =
new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "
+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
The output of this program is shown here:
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
Volume of shipment2 is 24.0
Weight of shipment2 is 0.76
Shipping cost: $1.28
// A complete implementation of BoxWeight.
class Box {
private double width;
private double height;
private 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;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
This program generates the following output:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
Volume of mybox3 is -1.0
Weight of mybox3 is -1.0
Volume of myclone is 3000.0
Weight of myclone is 34.3
Volume of mycube is 27.0
Weight of mycube is 2.0
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
The output from the program is shown here:
Inside Area for Rectangle.
Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0
Polymorphism
 dynamic method dispatch- Dynamic method
dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather
than compile time.
 Through dynamic method dispatch only Java
implements run-time polymorphism.

Applying overriding (refer figure.pdf)


Methodology
 When an overridden method is called through a superclass
reference, Java determines which version of that method
to execute based upon the type of the object being
referred to at the time the call occurs.
 Thus, this determination is made at run time. When
different types of objects are referred to, different
versions of an overridden method will be called.
 It is the type of the object being referred to (not the type
of the reference variable) that determines which version
of an overridden method will be executed.
 Therefore, if a superclass contains a method that is
overridden by a subclass, then when different types of
objects are referred to through a superclass reference
variable, different versions of the method are executed.
Example class Dispatch {
class A { public static void main(String args[]) {
void callme() { A a = new A(); // object of type A
System.out.println("Inside A's callme B b = new B(); // object of type B
method");
C c = new C(); // object of type C
}
A r; // obtain a reference of type A
}
r = a; // r refers to an A object
class B extends A {
r.callme(); // calls A's version of callme
void callme() {
r = b; // r refers to a B object
System.out.println("Inside B's callme
r.callme(); // calls B's version of callme
method");
r = c; // r refers to a C object
}
r.callme(); // calls C's version of callme
}
}
class C extends A {
}
void callme() {
Inside A’s callme method
System.out.println("Inside C's callme
method"); Inside B’s callme method
} Inside C’s callme method
}
Abstract Class
 The superclass that declares the structure of a
given abstraction without providing a complete
implementation of every method is called as abstract
class.
 That is, sometimes you will want to create a
superclass that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each
subclass to fill in the details.
 Such a class determines the nature of the
methods that the subclasses must implement. One
way this situation can occur is when a superclass is
unable to create a meaningful implementation for a
method.
Example
 Figure class is an abstract class
 The definition of area( ) is simply a placeholder.
 It will not compute and display the area of any type
of object
 class Triangle is sub class of figure. It has no
meaning if area( ) is not defined.
 A subclass mustoverride them, it cannot simply use
the version defined in the superclass.
 To declare an abstract method, use this general
form:
abstract type name(parameter-list);
Refer AbstractFigure.pdf
Final prevents overriding
Methods declared as final cannot be overridden.
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Final prevents inheritance
 Sometimes you will want to prevent a class from
being inherited. To do this, precede the class
declaration with final.
final class A {
// ...
}

// The following class is illegal.


class B extends A { // ERROR! Can't subclass A
// ...
}
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
interface IntStack {
void push(int item); // store an item
int pop(); // retrieve an item
}
// An implementation of IntStack that uses fixed storage.
class FixedStack implements IntStack {
private int stck[];
private int tos;
// allocate and initialize stack
FixedStack(int size) {
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
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 IFTest {
public static void main(String args[]) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}

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());
}
}

Class uses both Fixed stack and dynamic stack

/* Create an interface variable and


access stacks through it.
*/
class IFTest3 {
public static void main(String args[]) {
IntStack mystack; // create an interface reference variable
DynStack ds = new DynStack(5);
FixedStack fs = new FixedStack(8);
mystack = ds; // load dynamic stack
// push some numbers onto the stack
for(int i=0; i<12; i++) mystack.push(i);
mystack = fs; // load fixed stack
for(int i=0; i<8; i++) mystack.push(i);
mystack = ds;
System.out.println("Values in dynamic stack:");
for(int i=0; i<12; i++)
System.out.println(mystack.pop());
mystack = fs;
System.out.println("Values in fixed stack:");
for(int i=0; i<8; i++)
System.out.println(mystack.pop());
}
}
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();
}
}
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();

{ //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();
X = Y = null;
System.gc();
System.runFinalization();
}
E.showNextId();//Output of this line

} //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

Who is going to run garbage collector?


ü JVM in frequent time
ü User also can invoke the System.gc method to run
garbage
 Eg. Employee E = new Employee();
Name, empid, age
E

Heap Memory

 E = null

Name, empid, age


E

Heap Memory

 Since E is made null, no reference is there for the


employee object created so its eligible for garbage
Garbage collector Example
public class Test
{
public static void main(String[] args) throws
InterruptedException
{
Test t1 = new Test();
Test t2 = new Test();
t1 = null;
System.gc();
t2 = null;
Runtime.getRuntime().gc();
} protected void finalize() throws Throwable
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " +
this);
}
Finalize ( )
 The finalize() method called by Garbage Collector
not JVM. Although Garbage Collector is one of the
module of JVM.
 Object class finalize() method has empty
implementation, thus it is recommended to
override finalize() method to dispose of system
resources or to perform other cleanup.
 The finalize() method is never invoked more than
once for any given object.
compareTo()
Compares this Number object to the argument.

public class Test {

public static void main(String args[]) {


Integer x = 5;

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.

public class Test {

public static void main(String args[]) {


Integer x = 5;
Integer y = 10;
Integer z =5;
Short a = 5;

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

public class Test {

public static void main(String args[]) {


Integer x = 5;

System.out.println(x.toString());
}
}

Output
5
12

parseInt()
This method is used to get the primitive data type of a
certain String.

public class Test {

public static void main(String args[]) {


int x =Integer.parseInt("9");
double c = Double.parseDouble("5");

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.");
}
}

New thread: Thread[One,5,main]


New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.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 ThreadDemo {
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.");
}
}
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Child Thread: 3
Main Thread: 4
Child Thread: 2
Child Thread: 1
Main Thread: 3
Exiting child thread.
Main Thread: 2
Main Thread: 1
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
}

// 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 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.");
}
}

New thread: Thread[One,5,main]


New thread: Thread[Two,5,main]
One: 5
Two: 5
One: 4
Two: 4
One: 3
Two: 3
Two: 2
One: 2
Two: 1
One: 1
One exiting.
Two exiting.
Main thread exiting.
BUILD SUCCESSFUL (total time: 10 seconds)
Multithreading
Multithreading
 A multithreaded program contains two or more parts that
can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution.
 Multithreading enables you to write very efficient programs
that make maximum use of the CPU, because idle time can
be kept to a minimum.
 The Java run-time system depends on threads for many
things, and all the class libraries are designed with
multithreading
Java Thread
 Thread states – ready, running, suspended, resumed,
blocked.
 Thread priorities - A thread can voluntarily relinquish control or
A thread can be preempted by a higher-priority thread.
 Synchronization - interprocess synchronization: monitor
 Messaging - communicate with each other
Multithreading
 Java’s multithreading system is built upon the Thread class,
its methods, and its companion interface, Runnable.
 getName - Obtain a thread’s name.
 getPriority - Obtain a thread’s priority.
 isAlive - Determine if a thread is still running.
 join -Wait for a thread to terminate.
 run - Entry point for the thread.
 sleep - Suspend a thread for a period of time.
 Start - Start a thread by calling its run method.
Creating a Thread
 You can implement the Runnable interface.
 You can extend the Thread class, itself.
 Refer CreateThread.pdf

 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 ?.

 By calling T1.join() from T2 and T2.join() from T3. In this case


thread, T1 will finish first, followed by T2 and T3.
 The primary use of Thread.join() is to wait for another thread and
start execution once that Thread has completed execution or died.
 Join is also a blocking method, which blocks until the thread on
which join has called die or specified waiting time is over.
 Refer SimpleJoin.pdf
Thread Priority
 MIN_PRIORITY - 1
 MAX_PRIORITY - 10
 NORM_PRIORITY – 5

 Refer ThreadPri.pdf

 volatile Java variable means: The value of this variable will


never be cached thread-locally: all reads and writes will go
straight to "main memory"; Access to the variable acts as
though it is enclosed in a synchronized block,
public class JoinDemo {

public static void main(String args[]) throws InterruptedException{

System.out.println(Thread.currentThread().getName() + " is Started");

Thread exampleThread = new Thread(){


public void run(){
try {
System.out.println(Thread.currentThread().getName() + " is Started");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " is Completed");
} catch (InterruptedException ex) {
System.out.println(ex);
//Logger.getLogger(Join.class.getName()).log(Level.SEVERE, null, ex);
}
}
};

exampleThread.start();
exampleThread.join();

System.out.println(Thread.currentThread().getName() + " is Completed");


}

/* If you look at above example, the first main thread is started


and then it creates another thread, whose name is "Thread-0"
and started it. Since Thread-0 sleep for 2 seconds,
it requires at least 2 seconds to complete and in between main
thread called join method on the Thread-0 object.

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.

If you look at output, it confirms this theory.*/


// Demonstrate thread priorities.
class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORIT
Y);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " +
lo.click);
System.out.println("High-priority thread: " +
hi.click);
}
}

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

public void run() {


synchronized(target) { // synchronized block
target.call(msg);
}
}
Program with Synch

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 {

public static void main(String[] args) {


final String resource1 = "SSSSSS";

final String resource2 = "VVVVVV";

// t1 tries to lock resource1 then resource2


Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(100);} catch (Exception e) {}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
} //synch2
} //synch1
} //run
}; //t1

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");

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 Consumer implements Runnable {


Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println
("Press Control-C to stop.");
}
}

With wait and notify


class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedExceptio
n caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedExceptio
n caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
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 Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to
stop.");
}
}
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 = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread
Interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to
finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread
Interrupted");
}
System.out.println("Main thread exiting.");
}
}
package Multithreading;

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;
}

synchronized void put(int n) {


while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer1 implements Runnable {


Q1 q;
Producer1(Q1 q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


int i = 0;
while(true) {
q.put(i++);
}//while
}//run
}//class

class Consumer1 implements Runnable {


Q1 q;
Consumer1(Q1 q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {


while(true) {
q.get();
}//while
}//run
}//class

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.

BufferedWriter(Writ It is used to create a buffered character output


er wrt) stream that uses the default size for an output
buffer.

BufferedWriter(Writ It is used to create a buffered character output


er wrt, int size) stream that uses the specified size for an output
buffer.
BufferedWriter Class
Method Description

void newLine() It is used to add a new line by writing a line


separator.

void write(int c) It is used to write a single character.

void write(char[] cbuf, int It is used to write a portion of an array of


off, int len) characters.

void write(String s, int off, It is used to write a portion of a string.


int len)
void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream


BufferedWriter
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome.");
buffer.close();
System.out.println("Success");
}
}
BufferedReader
 Java BufferedReader class is used to read the text from a
character-based input stream. It can be used to read data line
by line by readLine() method. It makes the performance fast.
It inherits Reader class.

Constructor Description

BufferedReader(Reade It is used to create a buffered character input


r rd) stream that uses the default size for an input
buffer.
BufferedReader(Reade It is used to create a buffered character input
r rd, int size) stream that uses the specified size for an
input buffer.
BufferedReader
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, It is used for reading characters into a portion of
int off, int len) an array.
boolean It is used to test the input stream support for the mark
markSupported() and reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be
read.
long skip(long n) It is used for skipping the characters.
void reset() It repositions the stream at a position the mark method
was last called on this input stream.

void mark(int It is used for marking the present position in a stream.


readAheadLimit)
void close() It closes the input stream and releases any of the
system resources associated with the stream.
BufferedReader
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Java I/O streams
Java I/O
 Data is retrieved from an input source. The results of a
program are sent to an output destination.
 Devices are all handled by the same abstraction: the stream.
 A stream is a logical entity that either produces or consumes
information.
 A stream is linked to a physical device by the Java I/O
system.
 All streams behave in the same manner, even if the actual
physical devices they are linked to differ.
Java io classes
Java io interfaces
File
 File class does not operate on streams.
class FileDemo {
static void p(String s) {
System.out.println(s); File Name: COPYRIGHT
} Path: /java/COPYRIGHT
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT"); Abs Path: /java/COPYRIGHT
p("File Name: " + f1.getName()); Parent: /java
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
exists
p("Parent: " + f1.getParent()); is writeable
p(f1.exists() ? "exists" : "does not exist");
is readable
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable"); is not a directory
p("is " + (f1.isDirectory() ? "" : "not" + " a directory")); is normal file
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute"); is absolute
p("File last modified: " + f1.lastModified()); File last modified: 812465204000
p("File size: " + f1.length() + " Bytes");
}
File size: 695 Bytes
}
The Stream Classes
 Java’s stream-based I/O is built upon four abstract classes:
InputStream, OutputStream, Reader, and Writer.
 InputStream and OutputStream are designed for byte
streams. Reader and Writer are designed for character
streams.
 The byte stream classes and the character stream classes form
separate hierarchies.
Streams
 InputStream is an abstract class that defines Java’s model of
streaming byte input. It implements the Closeable interface.
Most of the methods in this class will throw an
IOException on error conditions.
 OutputStream is an abstract class that defines streaming
byte output. It implements the Closeable and Flushable
interfaces. Most of the methods in this class return void and
throw an IOException in the case of errors.
Input stream
Outputstream
Read example
 Example program class FileInputStreamDemo.pdf
Print Writter
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
The output:
This is a string
-7
4.5E-7
Input output
class CopyFile {
public static void main(String args[]) throws IOException } catch(ArrayIndexOutOfBoundsException e) {
{ System.out.println("Usage: CopyFile From To");
int i; return;
FileInputStream fin;
}
FileOutputStream fout;
try {
try {
do {
try {
fin = new FileInputStream(args[0]); i = fin.read();
} catch(FileNotFoundException e) { if(i != -1) fout.write(i);
System.out.println("Input File Not Found"); } while(i != -1);
return; } catch(IOException e) {
} System.out.println("File Error");
try {
}
fout = new FileOutputStream(args[1]);
fin.close();
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output fout.close();
File"); }
return; }
}
class FileInputStreamDemo {
public static void main(String args[]) throws IOException {

int size;

InputStream f = new FileInputStream("FileInputStreamDemo.java");

System.out.println("Total Available Bytes: " + (size = f.available()));

int n = size/40;

System.out.println("First " + n + " bytes of the file one read() at a


time");

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


System.out.print((char) f.read());
}

System.out.println("\nStill Available: " + f.available());

System.out.println("Reading the next " + n + " with one read(b[])");

byte b[] = new byte[n];


if (f.read(b) != n) {
System.err.println("couldn't read " + n + " bytes.");
}

System.out.println(new String(b, 0, n));


System.out.println("\nStill Available: " + (size = f.available()));
System.out.println("Skipping half of remaining bytes with skip()");
f.skip(size/2);

System.out.println("Still Available: " + f.available());


System.out.println("Reading " + n/2 + " into the end of array");
if (f.read(b, n/2, n/2) != n/2) {
System.err.println("couldn't read " + n/2 + " bytes.");
}

System.out.println(new String(b, 0, b.length));


System.out.println("\nStill Available: " + f.available());
f.close();
}
}
Total Available Bytes: 1433
First 35 bytes of the file one read() at a time
// Demonstrate FileInputStream.
im
Still Available: 1398
Reading the next 35 with one read(b[])
port java.io.*;
class FileInputS
Still Available: 1363
Skipping half of remaining bytes with skip()
Still Available: 682
Reading 17 into the end of array
port java.io.*;
read(b) != n) {
S
Still Available: 665
public class SerializationDemo {
public static void main(String args[]) {
try {
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(IOException e) {
System.out.println("Exception during serialization: " + e);
System.exit(0);
}

// 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);

arrL.forEach(n -> System.out.println(n));

arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });


}
}
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));
}
30
} 300
interface Addable{
int add(int a,int b);
}

public class LambdaExpressionExample6 {


public static void main(String[] args) {

// Lambda expression without return keyword.


Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));

// Lambda expression with return keyword. 30


300
Addable ad2=(int a,int b)->{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}
Collections
Collections
 Implementation of fundamental collections (dynamic arrays,
linked lists, trees, and hash tables) are highly efficient.
 Several standard implementations (such as LinkedList,
HashSet, and TreeSet) of these interfaces are provided that
you may use as-is.
 You may also implement your own collection.
 Algorithms operate on collections and are defined as static
methods within the Collections class.
 An iterator offers a general-purpose, standardized way of
accessing the elements within a collection,
The Collection Interfaces
 Collection - Enables you to work with groups of objects; it is at
the top of the collections hierarchy.
 Deque - Extends Queue to handle a double-ended queue
 List - Extends Collection to handle sequences (lists of objects).
 NavigableSet - Extends SortedSet to handle retrieval of
elements based on closest-match searches.
 Queue - Extends Collection to handle special types of lists in
which elements are removed only from the head.
 Set - Extends Collection to handle sets, which must contain
unique elements.
 SortedSet - Extends Set to handle sorted sets.
 In addition to the collection interfaces, collections also use the
Comparator, RandomAccess, Iterator, and ListIterator
interfaces
Collection classes
ArrayList
class ArrayListDemo { System.out.println("Contents of al: " + al);
public static void main(String args[]) { al.remove("F");
ArrayList<String> al = new ArrayList<String>(); al.remove(2);
System.out.println("Initial size of al: " + System.out.println("Size of al after deletions: " +
al.size()); al.size());
al.add("C"); System.out.println("Contents of al: " + al);
al.add("A"); }
al.add("E"); }
al.add("B"); The output from this program is shown here:
al.add("D"); Initial size of al: 0
al.add("F"); Size of al after additions: 7
al.add(1, "A2"); Contents of al: [C, A2, A, E, B, D, F]
System.out.println("Size of al after additions: " + Size of al after deletions: 5
al.size()); Contents of al: [C, A2, E, B, D]
Linked List
class LinkedListDemo { // Remove first and last elements.
public static void main(String args[]) { ll.removeFirst();
// Create a linked list. ll.removeLast();
LinkedList<String> ll = new LinkedList<String>(); System.out.println("ll after deleting first and last: "
// Add elements to the linked list. + ll);
ll.add("F"); // Get and set a value.
ll.add("B"); String val = ll.get(2);
ll.add("D"); ll.set(2, val + " Changed");
ll.add("E"); System.out.println("ll after change: " + ll);
ll.add("C"); }
ll.addLast("Z"); }
ll.addFirst("A"); The output from this program is shown here:
ll.add(1, "A2"); Original contents of ll: [A, A2, F, B, D, E, C, Z]
System.out.println("Original contents of ll: " + ll); Contents of ll after deletion: [A, A2, D, E, C, Z]
ll.remove("F"); ll after deleting first and last: [A2, D, E, C]
ll.remove(2); ll after change: [A2, D, E Changed, C]
System.out.println("Contents of ll after deletion: "+ ll);
Treeset
Treeset
 Java TreeSet class implements the Set interface that uses a
tree for storage
 The objects of the TreeSet class are stored in ascending order.
 Java TreeSet class access and retrieval times are quiet fast.
 Java TreeSet class doesn't allow null element.
 Java TreeSet class is non synchronized.
 Java TreeSet class maintains ascending order.
Treeset
class TreeSetDemo {
public static void main(String args[]) {
TreeSet<String> ts = new TreeSet<String>();
ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D");
System.out.println(ts);
System.out.println("First element : " + ts.first());
System.out.println("Last element : " + ts.last());
String n="D";
System.out.println("Element just greater than " + n + " : " + ts.higher(n));
System.out.println("Element just lower than " + n + " : " + ts.lower(n));
System.out.println("Head Set: "+ts.headSet(n));
System.out.println("Head Set: "+ts.tailSet(n));
}
}
[A, B, C, D, E, F] First element : A Last element : F
Element just greater than D : E
Element just lower than D : C
Head Set: [A, B, C] Tail Set: [D, E, F]
TreeSet with Iterator
import java.util.*;
class TreeSet2{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add(“A");
set.add(“C");
set.add(“B");
System.out.println("Traversing element through Iterator in descending order");
Iterator i=set.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}

}
}
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>();

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications ","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

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.

LinkedHashMap LinkedHashMap is the implementation of Map. It


inherits HashMap class. It maintains insertion order.

TreeMap TreeMap is the implementation of Map and


SortedMap. It maintains ascending order.
Map Example
 import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"A");
map.put(101,"V");
map.put(102,"R");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
} 100 A
101 V
102 R
public class MyHashMapCopy {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
HashMap<String, String> subMap = new HashMap<String, String>();
subMap.put("s1", "S1 VALUE");
subMap.put("s2", "S2 VALUE");
hm.putAll(subMap);
//subMap.putAll(hm);
System.out.println(hm);
// System.out.println(subMap);
} {third=THIRD INSERTED, first=FIRST INSERTED, second=SECOND INSERTED}
} {third=THIRD INSERTED, first=FIRST INSERTED, s1=S1 VALUE, second=SECOND
INSERTED, s2=S2 VALUE}
public class HashMapSearch {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
if(hm.containsKey("first")){
System.out.println("The hashmap contains key first");
} else {
System.out.println("The hashmap does not contains key first");
}
if(hm.containsKey("fifth")){
System.out.println("The hashmap contains key fifth");
} else {
System.out.println("The hashmap does not contains key fifth");
}
}
{third=THIRD INSERTED, first=FIRST INSERTED, second=SECOND INSERTED}
} The hashmap contains key first
The hashmap does not contains key fifth
How to copy or clone a ArrayList?
ArrayList<String> copy = (ArrayList<String>) arrl.clone();
How to add all elements of a list to ArrayList?

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);

How to delete all elements from my ArrayList?


arrl.clear();
How to find does ArrayList contains all list elements or not?
ArrayList<String> arrl = new ArrayList<String>();
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
List<String> list = new ArrayList<String>();
list.add("Second");
list.add("Random");
System.out.println("Does ArrayList contains all list elements?:
"
+arrl.containsAll(list));->true
list.add("one");
System.out.println("Does ArrayList contains all list elements?:
"
+arrl.containsAll(list));-> false
How to copy ArrayList to array?
ArrayList<String> arrl = new ArrayList<String>();
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
System.out.println("Actual ArrayList:"+arrl);
String[] strArr = new String[arrl.size()];
arrl.toArray(strArr);
System.out.println("Created Array content:");
for(String str:strArr){
System.out.println(str);
How to get sub list from ArrayList?
ArrayList<String> arrl = new ArrayList<String>();
//adding elements to the end
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
arrl.add("Click");
System.out.println("Actual ArrayList:"+arrl);
List<String> list = arrl.subList(2, 4);
System.out.println("Sub List: "+list);
Output:
Actual ArrayList:[First, Second, Third, Random, Click]
Sub List: [Third, Random]

How to reverse ArrayList content?


Collections.reverse(list);
How to shuffle elements in ArrayList?
Collections.shuffle(list);
How to swap two elements in a ArrayList?
list.add("Java");
list.add("Cric");
list.add("Play");
list.add("Watch");
list.add("Glass");
list.add("Movie");
list.add("Girl");

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

Comparator is a generic interface that has this declaration:

interface Comparator<T>

Here, T specifies the type of objects being compared.


int compare(T obj1, T obj2)

obj1 and obj2 are the objects to be compared.

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;
}

public int compareTo(Student st){


if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

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 {

public static void main(String a[]){

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


list.add(new Empl("Ram",3000));
list.add(new Empl("John",6000));
list.add(new Empl("Crish",2000));
list.add(new Empl("Tom",2400));
Collections.sort(list,new MySalaryComp());
System.out.println("Sorted list entries: ");
for(Empl e:list){
System.out.println(e);
}
}
}

class MySalaryComp implements Comparator<Empl>{

@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}

class Empl{

private String name;


private int salary;

public Empl(String n, int s){


this.name = n;
this.salary = s;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}

Sorted list entries:


Name: John-- Salary: 6000
Name: Ram-- Salary: 3000
Name: Tom-- Salary: 2400
Name: Crish-- Salary: 2000
Treeset pgms

Write a program to remove duplicate entries from an array.

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.

public static void main(String a[]){


String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
}

Output:
[five, four, one, three, two]

How to create a TreeSet with comparator?

public class MySetWithCompr {

public static void main(String a[]){

TreeSet<String> ts = new TreeSet<String>(new MyComp());


ts.add("RED");
ts.add("ORANGE");
ts.add("BLUE");
ts.add("GREEN");
System.out.println(ts);
}
}

class MyComp implements Comparator<String>{

@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}

Create TreeSet with comparator by user define objects.


public class MyCompUserDefine {

public static void main(String a[]){


//By using name comparator (String comparison)
TreeSet<Empl> nameComp = new TreeSet<Empl>(new MyNameComp());
nameComp.add(new Empl("Ram",3000));
nameComp.add(new Empl("John",6000));
nameComp.add(new Empl("Crish",2000));
nameComp.add(new Empl("Tom",2400));
for(Empl e:nameComp){
System.out.println(e);
}
System.out.println("===========================");
//By using salary comparator (int comparison)
TreeSet<Empl> salComp = new TreeSet<Empl>(new MySalaryComp());
salComp.add(new Empl("Ram",3000));
salComp.add(new Empl("John",6000));
salComp.add(new Empl("Crish",2000));
salComp.add(new Empl("Tom",2400));
for(Empl e:salComp){
System.out.println(e);
}
}
}

class MyNameComp implements Comparator<Empl>{

@Override
public int compare(Empl e1, Empl e2) {
return e1.getName().compareTo(e2.getName());
}
}

class MySalaryComp implements Comparator<Empl>{

@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() > e2.getSalary()){
return 1;
} else {
return -1;
}
}
}

class Empl{

private String name;


private int salary;

public Empl(String n, int s){


this.name = n;
this.salary = s;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}
Output:
Name: Crish-- Salary: 2000
Name: John-- Salary: 6000
Name: Ram-- Salary: 3000
Name: Tom-- Salary: 2400
===========================
Name: Crish-- Salary: 2000
Name: Tom-- Salary: 2400
Name: Ram-- Salary: 3000
Name: John-- Salary: 6000

How to get subset from sorted set?

public class MySetSublist {

public static void main(String a[]){

TreeSet<String> ts = new TreeSet<String>(new MyStrComp());


ts.add("RED");
ts.add("ORANGE");
ts.add("BLUE");
ts.add("GREEN");
ts.add("WHITE");
ts.add("BROWN");
ts.add("YELLOW");
ts.add("BLACK");
System.out.println(ts);
Set<String> subSet = ts.subSet("GREEN", "WHITE");
System.out.println("sub set: "+subSet);
subSet = ts.subSet("GREEN", true, "WHITE", true);
System.out.println("sub set: "+subSet);
subSet = ts.subSet("GREEN", false, "WHITE", true);
System.out.println("sub set: "+subSet);
}
}

class MyStrComp implements Comparator<String>{

@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]

How to get least value element from a set?


public class MyLeastElementInSet {

public static void main(String a[]){

TreeSet<Empl1> salComp = new TreeSet<Empl1>(new MySalCompr());


salComp.add(new Empl1("Ram",3000));
salComp.add(new Empl1("John",6000));
salComp.add(new Empl1("Crish",2000));
salComp.add(new Empl1("Tom",2400));
System.out.println("Least salary emp: "+salComp.first());
}
}

How to get highest value element from a set?


System.out.println("Highest salary emp: "+salComp.last());
How to avoid duplicate user defined objects in TreeSet?
public class MyUserDuplicates {

public static void main(String a[]){

Set<Emp> ts = new TreeSet<Emp>(new EmpComp());


ts.add(new Emp(201,"John",40000));
ts.add(new Emp(302,"Krish",44500));
ts.add(new Emp(146,"Tom",20000));
ts.add(new Emp(543,"Abdul",10000));
ts.add(new Emp(12,"Dinesh",50000));
//adding duplicate entry
ts.add(new Emp(146,"Tom",20000));
//check duplicate entry is there or not
for(Emp e:ts){
System.out.println(e);
}
}
}

class EmpComp implements Comparator<Emp>{

@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 {

private int empId;


private String empName;
private int empSal;

public Emp(int id, String name, int sal){


this.empId = id;
this.empName = name;
this.empSal = sal;
}

public int getEmpId() {


return empId;
}

public void setEmpId(int empId) {


this.empId = empId;
}

public String getEmpName() {


return empName;
}

public void setEmpName(String empName) {


this.empName = empName;
}

public int getEmpSal() {


return empSal;
}
public void setEmpSal(int empSal) {
this.empSal = empSal;
}

public String toString(){


return empId+" : "+empName+" : "+empSal;
}
}
For simple strings

public class MySetWithCompr {

public static void main(String a[]){

TreeSet<String> ts = new TreeSet<String>(new MyComp());

ts.add("RED");

ts.add("ORANGE");

ts.add("BLUE");

ts.add("GREEN");

System.out.println(ts);

class MyComp implements Comparator<String>{

@Override

public int compare(String str1, String str2) {

return str1.compareTo(str2);

Output:

[BLUE, GREEN, ORANGE, RED]


For user defined types

import java.util.*;

class Book implements Comparable<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 int compareTo(Book b) {

if(id>b.id){

return 1;

}else if(id<b.id){

return -1;

}else{

return 0;

}
public class TreeSetExample {

public static void main(String[] args) {

Set<Book> set=new TreeSet<Book>();

//Creating Books

Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(233,"Operating System","Galvin","Wiley",6);

Book b3=new Book(101,"Data Communications & Networking","Forouzan


","Mc Graw Hill",4);

//Adding Books to TreeSet

set.add(b1);

set.add(b2);

set.add(b3);

//Traversing TreeSet

for(Book b:set){

System.out.println(b.id+" "+b.name+" "

+b.author+" "+b.publisher+" "+b.quantity);

101
Data Communications & Networking Forouzan Mc Graw Hill
4
121 Let us C Yashwant Kanetkar BPB 8

233 Operating System Galvin Wiley 6


Hash Map pgms
A HashMap basically designates unique keys to corresponding values that can be retrieved at any given point.

 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.

Hash Map Basic Operations

public class MyBasicHashMap {

public static void main(String a[]){


HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
//getting value for the given key from hashmap
System.out.println("Value of second: "+hm.get("second"));
System.out.println("Is HashMap empty? "+hm.isEmpty());
hm.remove("third");
System.out.println(hm);
System.out.println("Size of the HashMap: "+hm.size());
}
}

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

How to copy Map content to another HashMap?

public class MyHashMapCopy {

public static void main(String a[]){


HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
HashMap<String, String> subMap = new HashMap<String, String>();
subMap.put("s1", "S1 VALUE");
subMap.put("s2", "S2 VALUE");
hm.putAll(subMap);
System.out.println(hm);
}
}

{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}


{s2=S2 VALUE, s1=S1 VALUE, second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}

How to search a key in HashMap?

public static void main(String a[]){


HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
if(hm.containsKey("first")){
System.out.println("The hashmap contains key first");
} else {
System.out.println("The hashmap does not contains key first");
}
if(hm.containsKey("fifth")){
System.out.println("The hashmap contains key fifth");
} else {
System.out.println("The hashmap does not contains key fifth");
}
}

{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}


The hashmap contains key first
The hashmap does not contains key fifth

How to search a value in HashMap?

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");
}

How to get all keys from HashMap?

public class MyHashMapKeys {

public static void main(String a[]){


HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println(key);
}
}

{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}


second
third
first

How to delete all elements from HashMap?

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"));

public T get() { System.out.printf("Integer Value :%d\n\n", integerBox.get());


return t; System.out.printf("String Value :%s\n", stringBox.get());
} }
}
Generic demo
class Gen<T> { class GenDemo {
T ob; // declare an object of type T public static void main(String args[]) {
Gen(T o) { Gen<Integer> iOb;
ob = o; iOb = new Gen<Integer>(88);
}
T getob() { iOb.showType();
return ob; int v = iOb.getob();
} System.out.println("value: " + v);
void showType() { System.out.println();
System.out.println("Type of T is " + Gen<String> strOb = new
ob.getClass().getName()); Gen<String>("Generics Test");
} strOb.showType();
} String str = strOb.getob();
System.out.println("value: " + str);
}
}
Generics
 Generics Work Only with Objects
 Gen<int> strOb = new Gen<int>(53); // Error, can't use
primitive type
 Generic Types Differ Based on Their Type Arguments
 iOb = strOb; // Wrong!
Generics
 TwoGeneric.pdf
Generics
 Till the previous examples the type parameters could be
replaced by any class type
 but sometimes it is useful to limit the types that can be
passed to a type parameter.
 Limiting the type to be only for numbers not the string or
char.
 Example refer BoundedType.pdf
Generics
 Bounded types -When specifying a type parameter, you can
create an upper bound that declares the superclass from
which all type arguments must be derived.
 This is accomplished through the use of an extends clause
when specifying the type parameter, as shown here:
 <T extends superclass>
Generics
 Wild card.
Integer inums[] = { 1, 2, 3, 4, 5 };
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Integer> iob = new Stats<Integer>(inums);
Stats<Double> dob = new Stats<Double>(dnums);
if(iob.sameAvg(dob))
System.out.println("Averages are the same.");
else
System.out.println("Averages differ.");
___________________________________________________________
boolean sameAvg(Stats<T> ob) {
if(average() == ob.average())
return true;
return false;
}
Generics
 To create a generic sameAvg( ) method, you must use another feature of Java
generics: the wildcard argument.
 The wildcard argument is specified by the ?, and it represents an unknown type.
 Using a wildcard, here is one way to write the sameAvg( ) method:

boolean sameAvg(Stats<?> ob) {


if(average() == ob.average())
return true;
return false;
}

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> {

T[] nums; // nums is an array of type T


// Pass the constructor a reference to
// an array of type T.

Stats(T[] o) {
nums = o;
}

// Return type double in all cases.

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 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;
}

// Return type double in all cases.


double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}
}

class BoundsDemo {

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);

// This won't compile because String is not asubclass of Number.


// String strs[] = { "1", "2", "3", "4", "5" };
// Stats<String> strob = new Stats<String>(strs);
// double x = strob.average();
// System.out.println("strob average is " + v);
}
}

The output is shown here:

Average is 3.0
Average is 3.3
// Use a generic constructor.

class GenCons {

private double val;

<T extends Number> GenCons(T arg) {


val = arg.doubleValue();
}

void showval() {
System.out.println("val: " + val);
}

}
class GenConsDemo {

public static void main(String args[]) {

GenCons test = new GenCons(100);


GenCons test2 = new GenCons(123.5F);
test.showval();
test2.showval();
}
}

The output is shown here:


val: 100.0
val: 123.5
interface MinMax<T extends Comparable<T>> {
T min();
T max();
}

// Now, implement MinMax

class MyClass<T extends Comparable<T>> implements


MinMax<T> {

T[] vals;

MyClass(T[] o) { vals = o; }

// Return the minimum value in vals.

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;
}

// Return the maximum value in vals.


public T max() {
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 {

public static void main(String args[]) {

Integer inums[] = {3, 6, 2, 8, 6 };


Character chs[] = {'b', 'r', 'p', 'w' };

MyClass<Integer> iob = new MyClass<Integer>(inums);

MyClass<Character> cob = new MyClass<Character>(chs);

System.out.println("Max value in inums: " + iob.max());

System.out.println("Min value in inums: " + iob.min());

System.out.println("Max value in chs: " + cob.max());

System.out.println("Min value in chs: " + cob.min());


}
}
The output is shown here:
Max value in inums: 8
Min value in inums: 2
Max value in chs: w
Min value in chs: b
class GenMethDemo {

static <T, V extends T> boolean isIn(T x, V[] y) {


for(int i=0; i < y.length; i++)
if(x.equals(y[i])) return true;
return false;
}

public static void main(String args[]) {

// Use isIn() on Integers.

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();

// Use isIn() on Strings.

String strs[] = { "one", "two", "three", "four", "five" };

if(isIn("two", strs))
System.out.println("two is in strs");

if(!isIn("seven", strs))
System.out.println("seven is not in strs");

// Oops! Won't compile! Types must be compatible.


// if(isIn("two", nums))
// System.out.println("two is in strs");
}
}

The output from the program is shown here:


2 is in nums
7 is not in nums
two is in strs
seven is not in strs
// A simple generic class with two type
// parameters: T and V.

class TwoGen<T, V> {


T ob1;
V ob2;
// Pass the constructor a reference to
// an object of type T and an object of type V.

TwoGen(T o1, V o2) {


ob1 = o1;
ob2 = o2;
}
// Show types of T and V.

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);
}
}

The output from this program is shown here:

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;
}

// Return type double in all cases.


double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}

// Determine if two averages are the same.


// Notice the use of the wildcard.

boolean sameAvg(Stats<?> ob) {


if(average() == ob.average())
return true;
return false;
}
}

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);

Float fnums[] = { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F };


Stats<Float> fob = new Stats<Float>(fnums);
double x = fob.average();
System.out.println("fob average is " + x);

// See which arrays have same average.


System.out.print("Averages of iob and dob ");

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.");
}
}

---------------------------------------------------------------------------

The output is shown here:

iob average is 3.0


dob average is 3.3
fob average is 3.0
Averages of iob and dob differ.
Averages of iob and fob are the same.

You might also like