Java programming-examples

151
Saikat Banerjee Page 1 Java Programming Examples Find the best practical and ready to use Java Programming Examples. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. These examples would be very useful for your projects and learning. Java Basics Examples Example - Home Example - Environment Example - Strings Example - Arrays Example - Date & Time Example - Methods Example - Files Example - Directories Example - Exceptions Example - Data Structure Example - Collections Example - Networking Example - Threading Example - Applets Example - Simple GUI Example - JDBC Example - Regular Exp Java Environment - Programming Examples Learn how to play with Environment in Java programming. Here are most commonly used examples: 1. How to compile a java file? 2. How to run a class file? 3. How to debug a java file? 4. How to set classpath? 5. How to view current classpath? 6. How to set destination of the class file? 7. How to run a compiled class file? 8. How to check version of java running on your system? 9. How to set classpath when class files are in .jar file?

Transcript of Java programming-examples

Page 1: Java programming-examples

Saikat Banerjee Page 1

Java Programming Examples

Find the best practical and ready to use Java Programming Examples.

Java runs on a variety of platforms, such as Windows, Mac OS, and the

various versions of UNIX.

These examples would be very useful for your projects and learning.

Java Basics Examples

Example - Home

Example - Environment

Example - Strings

Example - Arrays

Example - Date & Time

Example - Methods

Example - Files

Example - Directories

Example - Exceptions

Example - Data Structure

Example - Collections

Example - Networking

Example - Threading

Example - Applets

Example - Simple GUI

Example - JDBC

Example - Regular Exp

Java Environment - Programming Examples

Learn how to play with Environment in Java programming. Here are most commonly used examples:

1. How to compile a java file?

2. How to run a class file?

3. How to debug a java file?

4. How to set classpath?

5. How to view current classpath?

6. How to set destination of the class file?

7. How to run a compiled class file?

8. How to check version of java running on your system?

9. How to set classpath when class files are in .jar file?

Page 2: Java programming-examples

Saikat Banerjee Page 2

Problem Description:

How to compile a java file?

Solution:

Following example demonstrates how to compile a java file using javac command.

c:\jdk\demoapp> javac First.java

Result:

The above code sample will produce the following result.

First.java compile successfully.

Problem Description:

How to set multiple classpath?

Solution:

Following example demonstrates how to set multiple classpath. Multiple class paths are separated by a

semicolon.

c:> java -classpath C:\java\MyClasse1;C:\java\MyClass2

utility.testapp.main

Result:

The above code sample will produce the following result.

Class path set.

Problem Description:

How to set destination of the class file?

Solution:

Following example demonstrates how to debug a java file using =g option with javac command.

c:> javac demo.java -g

Result:

The above code sample will produce the following result.

Page 3: Java programming-examples

Saikat Banerjee Page 3

Demo.java will debug.

Problem Description:

How to set classpath?

Solution:

Following example demonstrates how to set classpath.

C:> java -classpath C:\java\DemoClasses utility.demoapp.main

Result:

The above code sample will produce the following result.

Class path set.

Problem Description:

How to view current classpath?

Solution:

Following example demonstrates how to view current classpath using echo command.

C:> echo %CLASSPATH%

Result:

The above code sample will produce the following result.

.;C:\Program Files\Java\jre1.6.0_03\lib\ext\QTJava.zip

Problem Description:

How to set destination of the class file?

Solution:

Following example demonstrates how to set destination of the class file that will be created after compiling a

java file using -d option with javac command.

c:> javac demo.java -d c:\myclasses

Result:

The above code sample will produce the following result.

Page 4: Java programming-examples

Saikat Banerjee Page 4

Demo application executed.

Problem Description:

How to run a class file?

Solution:

Following example demonstrates how to run a class file from command prompt using java command.

c:\jdk\demoapp>java First

Result:

The above code sample will produce the following result.

Demo application executed.

Problem Description:

How to check version of java running on your system?

Solution:

Following example demonstrates how to check version of java installed on your system using version argument

with java command.

java -version

Result:

The above code sample will produce the following result.

java version "1.6.0_13"

Java(TM) SE Runtime Environment (build 1.6.0_13-b03)

Java HotSpot(TM) Client VM (build 11.3-b02, mixed mode, sharing)

Problem Description:

How to set classpath when class files are in .jar file?

Solution:

Following example demonstrates how to set class path when classes are stored in a .jar or .zip file.

c:> java -classpath C:\java\myclasses.jar utility.testapp.main

Page 5: Java programming-examples

Saikat Banerjee Page 5

Result:

The above code sample will produce the following result.

Class path set.

Java String - Programming Examples

Learn how to play with strings in Java programming. Here are most commonly used examples:

1. How to compare strings?

2. How to search last occurance of a substring inside a substring?

3. How to remove a particular character from a string?

4. How to replace a substring inside a string by another one ?

5. How to reverse a String?

6. How to search a word inside a string?

7. How to split a string into a number of substrings ?

8. How to convert a string totally into upper case?

9. How to match regions in a string?

10. How to compare performance of two strings?

11. How to optimize string creation?

12. How to format strings?

13. How to concatenate two strings?

14. How to get unicode of strings?

15. How to buffer strings?

Problem Description:

How to compare two strings ?

Solution:

Following example compares two strings by using str compareTo (string) , str compareToIgnoreCase(String)

and str compareTo(object string) of string class and returns the ascii difference of first odd characters of

compared strings .

public class StringCompareEmp{

public static void main(String args[]){

String str = "Hello World";

String anotherString = "hello world";

Object objStr = str;

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

System.out.println( str.compareToIgnoreCase(anotherString) );

System.out.println( str.compareTo(objStr.toString()));

}

}

Result:

The above code sample will produce the following result.

Page 6: Java programming-examples

Saikat Banerjee Page 6

-32

0

0

Problem Description:

How to search the last position of a substring ?

Solution:

This example shows how to determine the last position of a substring inside a string with the help of

strOrig.lastIndexOf(Stringname) method.

public class SearchlastString {

public static void main(String[] args) {

String strOrig = "Hello world ,Hello Reader";

int lastIndex = strOrig.lastIndexOf("Hello");

if(lastIndex == - 1){

System.out.println("Hello not found");

}else{

System.out.println("Last occurrence of Hello

is at index "+ lastIndex);

}

}

}

Result:

The above code sample will produce the following result.

Last occurrence of Hello is at index 13

Problem Description:

How to remove a particular character from a string ?

Solution:

Following example shows hoe to remove a character from a particular position from a string with the help of

removeCharAt(string,position) method.

public class Main {

public static void main(String args[]) {

String str = "this is Java";

System.out.println(removeCharAt(str, 3));

}

public static String removeCharAt(String s, int pos) {

return s.substring(0, pos) + s.substring(pos + 1);

}

}

Result:

The above code sample will produce the following result.

Page 7: Java programming-examples

Saikat Banerjee Page 7

thi is Java

Problem Description:

How to replace a substring inside a string by another one ?

Solution:

This example describes how replace method of java String class can be used to replace character or substring

by new one.

public class StringReplaceEmp{

public static void main(String args[]){

String str="Hello World";

System.out.println( str.replace( 'H','W' ) );

System.out.println( str.replaceFirst("He", "Wa") );

System.out.println( str.replaceAll("He", "Ha") );

}

}

Result:

The above code sample will produce the following result.

Wello World

Wallo World

Hallo World

Problem Description:

How to reverse a String?

Solution:

Following example shows how to reverse a String after taking it from command line argument .The program

buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the

buffer into a String with the help of toString() method.

public class StringReverseExample{

public static void main(String[] args){

String string="abcdef";

String reverse = new StringBuffer(string).

reverse().toString();

System.out.println("\nString before reverse:

"+string);

System.out.println("String after reverse:

"+reverse);

}

}

Result:

The above code sample will produce the following result.

Page 8: Java programming-examples

Saikat Banerjee Page 8

String before reverse:abcdef

String after reverse:fedcba

Problem Description:

How to search a word inside a string ?

Solution:

This example shows how we can search a word within a String object using indexOf() method which returns a

position index of a word within the string if found. Otherwise it returns -1.

public class SearchStringEmp{

public static void main(String[] args) {

String strOrig = "Hello readers";

int intIndex = strOrig.indexOf("Hello");

if(intIndex == - 1){

System.out.println("Hello not found");

}else{

System.out.println("Found Hello at index "

+ intIndex);

}

}

}

Result:

The above code sample will produce the following result.

Found Hello at index 0

Problem Description:

How to split a string into a number of substrings ?

Solution:

Following example splits a string into a number of substrings with the help of str split(string) method and then

prints the substrings.

public class JavaStringSplitEmp{

public static void main(String args[]){

String str = "jan-feb-march";

String[] temp;

String delimeter = "-";

temp = str.split(delimeter);

for(int i =0; i < temp.length ; i++){

System.out.println(temp[i]);

System.out.println("");

str = "jan.feb.march";

delimeter = "\\.";

temp = str.split(delimeter);

}

for(int i =0; i < temp.length ; i++){

System.out.println(temp[i]);

Page 9: Java programming-examples

Saikat Banerjee Page 9

System.out.println("");

temp = str.split(delimeter,2);

for(int j =0; j < temp.length ; j++){

System.out.println(temp[i]);

}

}

}

}

Result:

The above code sample will produce the following result.

jan

feb

march

jan

jan

jan

feb.march

feb.march

feb.march

Problem Description:

How to convert a string totally into upper case?

Solution:

Following example changes the case of a string to upper case by using String toUpperCase() method.

public class StringToUpperCaseEmp {

public static void main(String[] args) {

String str = "string abc touppercase ";

String strUpper = str.toUpperCase();

System.out.println("Original String: " + str);

System.out.println("String changed to upper case: "

+ strUpper);

}

}

Result:

The above code sample will produce the following result.

Original String: string abc touppercase

String changed to upper case: STRING ABC TOUPPERCASE

Page 10: Java programming-examples

Saikat Banerjee Page 10

Problem Description:

How to match regions in strings ?

Solution:

Following example determines region matchs in two strings by using regionMatches() method.

public class StringRegionMatch{

public static void main(String[] args){

String first_str = "Welcome to Microsoft";

String second_str = "I work with Microsoft";

boolean match = first_str.

regionMatches(11, second_str, 12, 9);

System.out.println("first_str[11 -19] == "

+ "second_str[12 - 21]:-"+ match);

}

}

Result:

The above code sample will produce the following result.

first_str[11 -19] == second_str[12 - 21]:-true

Problem Description:

How to compare performance of string creation ?

Solution:

Following example compares the performance of two strings created in two different ways.

public class StringComparePerformance{

public static void main(String[] args){

long startTime = System.currentTimeMillis();

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

String s1 = "hello";

String s2 = "hello";

}

long endTime = System.currentTimeMillis();

System.out.println("Time taken for creation"

+ " of String literals : "+ (endTime - startTime)

+ " milli seconds" );

long startTime1 = System.currentTimeMillis();

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

String s3 = new String("hello");

String s4 = new String("hello");

}

long endTime1 = System.currentTimeMillis();

System.out.println("Time taken for creation"

+ " of String objects : " + (endTime1 - startTime1)

+ " milli seconds");

}

}

Page 11: Java programming-examples

Saikat Banerjee Page 11

Result:

The above code sample will produce the following result.The result may vary.

Time taken for creation of String literals : 0 milli seconds

Time taken for creation of String objects : 16 milli seconds

Problem Description:

How to optimize string creation ?

Solution:

Following example optimizes string creation by using String.intern() method.

public class StringOptimization{

public static void main(String[] args){

String variables[] = new String[50000];

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

variables[i] = "s"+i;

}

long startTime0 = System.currentTimeMillis();

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

variables[i] = "hello";

}

long endTime0 = System.currentTimeMillis();

System.out.println("Creation time"

+ " of String literals : "+ (endTime0 - startTime0)

+ " ms" );

long startTime1 = System.currentTimeMillis();

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

variables[i] = new String("hello");

}

long endTime1 = System.currentTimeMillis();

System.out.println("Creation time of"

+ " String objects with 'new' key word : "

+ (endTime1 - startTime1)

+ " ms");

long startTime2 = System.currentTimeMillis();

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

variables[i] = new String("hello");

variables[i] = variables[i].intern();

}

long endTime2 = System.currentTimeMillis();

System.out.println("Creation time of"

+ " String objects with intern(): "

+ (endTime2 - startTime2)

+ " ms");

}

}

Result:

The above code sample will produce the following result.The result may vary.

Creation time of String literals : 0 ms

Creation time of String objects with 'new' key word : 31 ms

Page 12: Java programming-examples

Saikat Banerjee Page 12

Creation time of String objects with intern(): 16 ms

Problem Description:

How to format strings ?

Solution:

Following example returns a formatted string value by using a specific locale, format and arguments in format()

method

import java.util.*;

public class StringFormat{

public static void main(String[] args){

double e = Math.E;

System.out.format("%f%n", e);

System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);

}

}

Result:

The above code sample will produce the following result.

2.718282

2,7183

Problem Description:

How to optimize string concatenation ?

Solution:

Following example shows performance of concatenation by using "+" operator and StringBuffer.append()

method.

public class StringConcatenate{

public static void main(String[] args){

long startTime = System.currentTimeMillis();

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

String result = "This is"

+ "testing the"

+ "difference"+ "between"

+ "String"+ "and"+ "StringBuffer";

}

long endTime = System.currentTimeMillis();

System.out.println("Time taken for string"

+ "concatenation using + operator : "

+ (endTime - startTime)+ " ms");

long startTime1 = System.currentTimeMillis();

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

StringBuffer result = new StringBuffer();

result.append("This is");

result.append("testing the");

Page 13: Java programming-examples

Saikat Banerjee Page 13

result.append("difference");

result.append("between");

result.append("String");

result.append("and");

result.append("StringBuffer");

}

long endTime1 = System.currentTimeMillis();

System.out.println("Time taken for String concatenation"

+ "using StringBuffer : "

+ (endTime1 - startTime1)+ " ms");

}

}

Result:

The above code sample will produce the following result.The result may vary.

Time taken for stringconcatenation using + operator : 0 ms

Time taken for String concatenationusing StringBuffer : 16 ms

Problem Description:

How to determine the Unicode code point in string ?

Solution:

This example shows you how to use codePointBefore() method to return the character (Unicode code point)

before the specified index.

public class StringUniCode{

public static void main(String[] args){

String test_string="Welcome to Sbdsi.saikat";

System.out.println("String under test is = "+test_string);

System.out.println("Unicode code point at"

+" position 5 in the string is = "

+ test_string.codePointBefore(5));

}

}

Result:

The above code sample will produce the following result.

String under test is = Welcome to Sbdsi.saikat

Unicode code point at position 5 in the string is =111

Problem Description:

How to buffer strings ?

Solution:

Following example buffers strings and flushes it by using emit() method.

Page 14: Java programming-examples

Saikat Banerjee Page 14

public class StringBuffer{

public static void main(String[] args) {

countTo_N_Improved();

}

private final static int MAX_LENGTH=30;

private static String buffer = "";

private static void emit(String nextChunk) {

if(buffer.length() + nextChunk.length() > MAX_LENGTH) {

System.out.println(buffer);

buffer = "";

}

buffer += nextChunk;

}

private static final int N=100;

private static void countTo_N_Improved() {

for (int count=2; count<=N; count=count+2) {

emit(" " + count);

}

}

}

Result:

The above code sample will produce the following result.

2 4 6 8 10 12 14 16 18 20 22

24 26 28 30 32 34 36 38 40 42

44 46 48 50 52 54 56 58 60 62

64 66 68 70 72 74 76 78 80 82

Java Arrays - Programming Examples

Learn how to play with arrays in Java programming. Here are most commonly used examples:

1. How to sort an array and search an element inside it?

2. How to sort an array and insert an element inside it?

3. How to determine the upper bound of a two dimentional array?

4. How to reverse an array?

5. How to write an array of strings to the output console?

6. How to search the minimum and the maximum element in an array?

7. How to merge two arrays?

8. How to fill (initialize at once) an array?

9. How to extend an array after initialisation?

10. How to sort an array and search an element inside it?

11. How to remove an element of array?

12. How to remove one array from another array?

13. How to find common elements from arrays?

14. How to find an object or a string in an Array?

15. How to check if two arrays are equal or not?

16. How to compare two arrays?

Problem Description:

How to sort an array and search an element inside it?

Page 15: Java programming-examples

Saikat Banerjee Page 15

Solution:

Following example shows how to use sort () and binarySearch () method to accomplish the task. The user

defined method printArray () is used to display the output:

import java.util.Arrays;

public class MainClass {

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

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray("Sorted array", array);

int index = Arrays.binarySearch(array, 2);

System.out.println("Found 2 @ " + index);

}

private static void printArray(String message, int array[]) {

System.out.println(message

+ ": [length: " + array.length + "]");

for (int i = 0; i < array.length; i++) {

if(i != 0){

System.out.print(", ");

}

System.out.print(array[i]);

}

System.out.println();

}

}

Result:

The above code sample will produce the following result.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5

Problem Description:

How to sort an array and insert an element inside it?

Solution:

Following example shows how to use sort () method and user defined method insertElement ()to accomplish

the task.

import java.util.Arrays;

public class MainClass {

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

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray("Sorted array", array);

int index = Arrays.binarySearch(array, 1);

System.out.println("Didn't find 1 @ "

+ index);

int newIndex = -index - 1;

array = insertElement(array, 1, newIndex);

Page 16: Java programming-examples

Saikat Banerjee Page 16

printArray("With 1 added", array);

}

private static void printArray(String message, int array[]) {

System.out.println(message

+ ": [length: " + array.length + "]");

for (int i = 0; i < array.length; i++) {

if (i != 0){

System.out.print(", ");

}

System.out.print(array[i]);

}

System.out.println();

}

private static int[] insertElement(int original[],

int element, int index) {

int length = original.length;

int destination[] = new int[length + 1];

System.arraycopy(original, 0, destination, 0, index);

destination[index] = element;

System.arraycopy(original, index, destination, index

+ 1, length - index);

return destination;

}

}

Result:

The above code sample will produce the following result.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Didn't find 1 @ -6

With 1 added: [length: 11]

-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

Problem Description:

How to determine the upper bound of a two dimentional array ?

Solution:

Following example helps to determine the upper bound of a two dimentional array with the use of

arrayname.length.

public class Main {

public static void main(String args[]) {

String[][] data = new String[2][5];

System.out.println("Dimension 1: " + data.length);

System.out.println("Dimension 2: " + data[0].length);

}

}

Result:

The above code sample will produce the following result.

Page 17: Java programming-examples

Saikat Banerjee Page 17

Dimension 1: 2

Dimension 2: 5

Problem Description:

How to reverse an array list ?

Solution:

Following example reverses an array list by using Collections.reverse(ArrayList)method.

import java.util.ArrayList;

import java.util.Collections;

public class Main {

public static void main(String[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add("A");

arrayList.add("B");

arrayList.add("C");

arrayList.add("D");

arrayList.add("E");

System.out.println("Before Reverse Order: " + arrayList);

Collections.reverse(arrayList);

System.out.println("After Reverse Order: " + arrayList);

}

}

Result:

The above code sample will produce the following result.

Before Reverse Order: [A, B, C, D, E]

After Reverse Order: [E, D, C, B, A]

Problem Description:

How to write an array of strings to the output console ?

Solution:

Following example demonstrates writing elements of an array to the output console through looping.

public class Welcome {

public static void main(String[] args){

String[] greeting = new String[3];

greeting[0] = "This is the greeting";

greeting[1] = "for all the readers from";

greeting[2] = "Java Source .";

for (int i = 0; i < greeting.length; i++){

System.out.println(greeting[i]);

}

}

}

Page 18: Java programming-examples

Saikat Banerjee Page 18

Result:

The above code sample will produce the following result.

This is the greeting

For all the readers From

Java source .

Problem Description:

How to search the minimum and the maximum element in an array ?

Solution:

This example shows how to search the minimum and maximum element in an array by using Collection.max()

and Collection.min() methods of Collection class .

import java.util.Arrays;

import java.util.Collections;

public class Main {

public static void main(String[] args) {

Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};

int min = (int) Collections.min(Arrays.asList(numbers));

int max = (int) Collections.max(Arrays.asList(numbers));

System.out.println("Min number: " + min);

System.out.println("Max number: " + max);

}

}

Result:

The above code sample will produce the following result.

Min number: 1

Max number: 9

Problem Description:

How to merge two arrays ?

Solution:

This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2)

method of List class and Arrays.toString () method of Array class.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String args[]) {

String a[] = { "A", "E", "I" };

Page 19: Java programming-examples

Saikat Banerjee Page 19

String b[] = { "O", "U" };

List list = new ArrayList(Arrays.asList(a));

list.addAll(Arrays.asList(b));

Object[] c = list.toArray();

System.out.println(Arrays.toString(c));

}

}

Result:

The above code sample will produce the following result.

[A, E, I, O, U]

Problem Description:

How to fill (initialize at once) an array ?

Solution:

This example fill (initialize all the elements of the array in one short) an array by using

Array.fill(arrayname,value) method and Array.fill(arrayname ,starting index ,ending index ,value) method of

Java Util class.

import java.util.*;

public class FillTest {

public static void main(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

for (int i=0, n=array.length; i < n; i++) {

System.out.println(array[i]);

}

System.out.println();

Arrays.fill(array, 3, 6, 50);

for (int i=0, n=array.length; i< n; i++) {

System.out.println(array[i]);

}

}

}

Result:

The above code sample will produce the following result.

100

100

100

100

100

100

100

100

100

50

Page 20: Java programming-examples

Saikat Banerjee Page 20

50

50

Problem Description:

How to extend an array after initialisation?

Solution:

Following example shows how to extend an array after initialization by creating an new array.

public class Main {

public static void main(String[] args) {

String[] names = new String[] { "A", "B", "C" };

String[] extended = new String[5];

extended[3] = "D";

extended[4] = "E";

System.arraycopy(names, 0, extended, 0, names.length);

for (String str : extended){

System.out.println(str);

}

}

}

Result:

The above code sample will produce the following result.

A

B

C

D

E

Problem Description:

How to sort an array and search an element inside it?

Solution:

Following example shows how to use sort () and binarySearch () method to accomplish the task. The user

defined method printArray () is used to display the output:

import java.util.Arrays;

public class MainClass {

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

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray("Sorted array", array);

int index = Arrays.binarySearch(array, 2);

System.out.println("Found 2 @ " + index);

}

private static void printArray(String message, int array[]) {

System.out.println(message

Page 21: Java programming-examples

Saikat Banerjee Page 21

+ ": [length: " + array.length + "]");

for (int i = 0; i < array.length; i++) {

if(i != 0){

System.out.print(", ");

}

System.out.print(array[i]);

}

System.out.println();

}

}

Result:

The above code sample will produce the following result.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5

Problem Description:

How to remove an element of array?

Solution:

Following example shows how to remove an element from array.

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList objArray = new ArrayList();

objArray.clear();

objArray.add(0,"0th element");

objArray.add(1,"1st element");

objArray.add(2,"2nd element");

System.out.println("Array before removing an

element"+objArray);

objArray.remove(1);

objArray.remove("0th element");

System.out.println("Array after removing an

element"+objArray);

}

}

Result:

The above code sample will produce the following result.

Array before removing an element[0th element,

1st element, 2nd element]

Array after removing an element[0th element]

Page 22: Java programming-examples

Saikat Banerjee Page 22

Problem Description:

How to remove one array from another array?

Solution:

Following example uses Removeall method to remove one array from another.

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList objArray = new ArrayList();

ArrayList objArray2 = new ArrayList();

objArray2.add(0,"common1");

objArray2.add(1,"common2");

objArray2.add(2,"notcommon");

objArray2.add(3,"notcommon1");

objArray.add(0,"common1");

objArray.add(1,"common2");

objArray.add(2,"notcommon2");

System.out.println("Array elements of array1" +objArray);

System.out.println("Array elements of array2" +objArray2);

objArray.removeAll(objArray2);

System.out.println("Array1 after removing

array2 from array1"+objArray);

}

}

Result:

The above code sample will produce the following result.

Array elements of array1[common1, common2, notcommon2]

Array elements of array2[common1, common2, notcommon,

notcommon1]

Array1 after removing array2 from array1[notcommon2]

Problem Description:

How to find common elements from arrays?

Solution:

Following example shows how to find common elements from two arrays and store them in an array.

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList objArray = new ArrayList();

ArrayList objArray2 = new ArrayList();

objArray2.add(0,"common1");

objArray2.add(1,"common2");

objArray2.add(2,"notcommon");

objArray2.add(3,"notcommon1");

Page 23: Java programming-examples

Saikat Banerjee Page 23

objArray.add(0,"common1");

objArray.add(1,"common2");

objArray.add(2,"notcommon2");

System.out.println("Array elements of array1"+objArray);

System.out.println("Array elements of array2"+objArray2);

objArray.retainAll(objArray2);

System.out.println("Array1 after retaining common

elements of array2 & array1"+objArray);

}

}

Result:

The above code sample will produce the following result.

Array elements of array1[common1, common2, notcommon2]

Array elements of array2[common1, common2, notcommon,

notcommon1]

Array1 after retaining common elements of array2 & array1

[common1, common2]

Problem Description:

How to find an object or a string in an Array?

Solution:

Following example uses Contains method to search a String in the Array.

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList objArray = new ArrayList();

ArrayList objArray2 = new ArrayList();

objArray2.add(0,"common1");

objArray2.add(1,"common2");

objArray2.add(2,"notcommon");

objArray2.add(3,"notcommon1");

objArray.add(0,"common1");

objArray.add(1,"common2");

System.out.println("Array elements of array1"+objArray);

System.out.println("Array elements of array2"+objArray2);

System.out.println("Array 1 contains String common2?? "

+objArray.contains("common1"));

System.out.println("Array 2 contains Array1?? "

+objArray2.contains(objArray) );

}

}

Result:

The above code sample will produce the following result.

Array elements of array1[common1, common2]

Array elements of array2[common1, common2, notcommon, notcommon1]

Page 24: Java programming-examples

Saikat Banerjee Page 24

Array 1 contains String common2?? true

Array 2 contains Array1?? false

Problem Description:

How to check if two arrays are equal or not?

Solution:

Following example shows how to use equals () method of Arrays to check if two arrays are equal or not.

import java.util.Arrays;

public class Main {

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

int[] ary = {1,2,3,4,5,6};

int[] ary1 = {1,2,3,4,5,6};

int[] ary2 = {1,2,3,4};

System.out.println("Is array 1 equal to array 2?? "

+Arrays.equals(ary, ary1));

System.out.println("Is array 1 equal to array 3?? "

+Arrays.equals(ary, ary2));

}

}

Result:

The above code sample will produce the following result.

Is array 1 equal to array 2?? true

Is array 1 equal to array 3?? false

Problem Description:

How to compare two arrays?

Solution:

Following example uses equals method to check whether two arrays are or not.

import java.util.Arrays;

public class Main {

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

int[] ary = {1,2,3,4,5,6};

int[] ary1 = {1,2,3,4,5,6};

int[] ary2 = {1,2,3,4};

System.out.println("Is array 1 equal to array 2?? "

+Arrays.equals(ary, ary1));

System.out.println("Is array 1 equal to array 3?? "

+Arrays.equals(ary, ary2));

}

}

Page 25: Java programming-examples

Saikat Banerjee Page 25

Result:

The above code sample will produce the following result.

Is array 1 equal to array 2?? true

Is array 1 equal to array 3?? false

Java Date & Time - Programming Examples

Learn how to play with data and time in Java programming. Here are most commonly used examples:

1. How to format time in AM-PM format?

2. How to display name of a month in (MMM) format ?

3. How to display hour and minute?

4. How to display current date and time?

5. How to format time in 24 hour format?

6. How to format time in MMMM format?

7. How to format seconds?

8. How to display name of the months in short format?

9. How to display name of the weekdays?

10. How to add time to Date?

11. How to display time in different country's format?

12. How to display time in different languages?

13. How to roll through hours & months?

14. How to find which week of the year?

15. How to display date in different formats ?

Problem Description:

How to format time in AM-PM format?

Solution:

This example formats the time by using SimpleDateFormat("HH-mm-ss a") constructor and sdf.format(date)

method of SimpleDateFormat class.

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main{

public static void main(String[] args){

Date date = new Date();

String strDateFormat = "HH:mm:ss a";

SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

System.out.println(sdf.format(date));

}

}

Result:

The above code sample will produce the following result.The result will change depending upon the current

system time

Page 26: Java programming-examples

Saikat Banerjee Page 26

06:40:32 AM

Problem Description:

How to display name of a month in (MMM) format ?

Solution:

This example shows how to display the current month in the (MMM) format with the help of

Calender.getInstance() method of Calender class and fmt.format() method of Formatter class.

import java.util.Calendar;

import java.util.Formatter;

public class MainClass{

public static void main(String args[]){

Formatter fmt = new Formatter();

Calendar cal = Calendar.getInstance();

fmt = new Formatter();

fmt.format("%tB %tb %tm", cal, cal, cal);

System.out.println(fmt);

}

}

Result:

The above code sample will produce the following result.

October Oct 10

Problem Description:

How to display hour and minute ?

Solution:

This example demonstrates how to display the hour and minute of that moment by using Calender.getInstance()

of Calender class.

import java.util.Calendar;

import java.util.Formatter;

public class MainClass{

public static void main(String args[]){

Formatter fmt = new Formatter();

Calendar cal = Calendar.getInstance();

fmt = new Formatter();

fmt.format("%tl:%tM", cal, cal);

System.out.println(fmt);

}

}

Page 27: Java programming-examples

Saikat Banerjee Page 27

Result:

The above code sample will produce the following result.The result will chenge depending upon the current

system time.

03:20

Problem Description:

How to display current date and time?

Solution:

This example shows how to display the current date and time using Calender.getInstance() method of Calender

class and fmt.format() method of Formatter class.

import java.util.Calendar;

import java.util.Formatter;

public class MainClass{

public static void main(String args[]){

Formatter fmt = new Formatter();

Calendar cal = Calendar.getInstance();

fmt = new Formatter();

fmt.format("%tc", cal);

System.out.println(fmt);

}

}

Result:

The above code sample will produce the following result.The result will change depending upon the current

system date and time

Wed Oct 15 20:37:30 GMT+05:30 2008

Problem Description:

How to format time in 24 hour format?

Solution:

This example formats the time into 24 hour format (00:00-24:00) by using sdf.format(date) method of

SimpleDateFormat class.

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {

public static void main(String[] args) {

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("h");

System.out.println("hour in h format : "

Page 28: Java programming-examples

Saikat Banerjee Page 28

+ sdf.format(date));

}

}

Result:

The above code sample will produce the following result.

hour in h format : 8

Problem Description:

How to format time in MMMM format?

Solution:

This example formats the month with the help of SimpleDateFormat(�MMMM�) constructor and

sdf.format(date) method of SimpleDateFormat class.

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main{

public static void main(String[] args){

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("MMMM");

System.out.println("Current Month in MMMM format : "

+ sdf.format(date));

}

}

Result:

The above code sample will produce the following result.The result will change depending upon the current

system date

Current Month in MMMM format : May

Problem Description:

How to format seconds?

Solution:

This example formats the second by using SimpleDateFormat(�ss�) constructor and sdf.format(date) method

of SimpleDateFormat class.

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main{

public static void main(String[] args){

Page 29: Java programming-examples

Saikat Banerjee Page 29

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("ss");

System.out.println("seconds in ss format : "

+ sdf.format(date));

}

}

Result:

The above code sample will produce the following result.The result will change depending upon the current

system time.

seconds in ss format : 14

Problem Description:

How to display name of the months in short format?

Solution:

This example displays the names of the months in short form with the help of

DateFormatSymbols().getShortMonths() method of DateFormatSymbols class.

import java.text.SimpleDateFormat;

import java.text.DateFormatSymbols;

public class Main {

public static void main(String[] args) {

String[] shortMonths = new DateFormatSymbols()

.getShortMonths();

for (int i = 0; i < (shortMonths.length-1); i++) {

String shortMonth = shortMonths[i];

System.out.println("shortMonth = " + shortMonth);

}

}

}

Result:

The above code sample will produce the following result.

shortMonth = Jan

shortMonth = Feb

shortMonth = Mar

shortMonth = Apr

shortMonth = May

shortMonth = Jun

shortMonth = Jul

shortMonth = Aug

shortMonth = Sep

shortMonth = Oct

shortMonth = Nov

shortMonth = Dec

Page 30: Java programming-examples

Saikat Banerjee Page 30

Problem Description:

How to display name of the weekdays ?

Solution:

This example displays the names of the weekdays in short form with the help of

DateFormatSymbols().getWeekdays() method of DateFormatSymbols class.

import java.text.SimpleDateFormat;

import java.text.DateFormatSymbols;

public class Main {

public static void main(String[] args) {

String[] weekdays = new DateFormatSymbols().getWeekdays();

for (int i = 2; i < (weekdays.length-1); i++) {

String weekday = weekdays[i];

System.out.println("weekday = " + weekday);

}

}

}

Result:

The above code sample will produce the following result.

weekday = Monday

weekday = Tuesday

weekday = Wednesday

weekday = Thursday

weekday = Friday

Problem Description:

How to add time(Days, years , seconds) to Date?

Solution:

The following examples shows us how to add time to a date using add() method of Calender.

import java.util.*;

public class Main {

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

Date d1 = new Date();

Calendar cl = Calendar. getInstance();

cl.setTime(d1);

System.out.println("today is " + d1.toString());

cl. add(Calendar.MONTH, 1);

System.out.println("date after a month will be "

+ cl.getTime().toString() );

cl. add(Calendar.HOUR, 70);

System.out.println("date after 7 hrs will be "

+ cl.getTime().toString() );

cl. add(Calendar.YEAR, 3);

System.out.println("date after 3 years will be "

Page 31: Java programming-examples

Saikat Banerjee Page 31

+ cl.getTime().toString() );

}

}

Result:

The above code sample will produce the following result.

today is Mon Jun 22 02:47:02 IST 2009

date after a month will be Wed Jul 22 02:47:02 IST 2009

date after 7 hrs will be Wed Jul 22 09:47:02 IST 2009

date after 3 years will be Sun Jul 22 09:47:02 IST 2012

Problem Description:

How to display time in different country's format?

Solution:

Following example uses Locale class & DateFormat class to disply date in different Country's format.

import java.text.DateFormat;

import java.util.*;

public class Main {

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

Date d1 = new Date();

System.out.println("today is "+ d1.toString());

Locale locItalian = new Locale("it","ch");

DateFormat df = DateFormat.getDateInstance

(DateFormat.FULL, locItalian);

System.out.println("today is in Italian Language

in Switzerland Format : "+ df.format(d1));

}

}

Result:

The above code sample will produce the following result.

today is Mon Jun 22 02:37:06 IST 2009

today is in Italian Language in Switzerlandluned�,

22. giugno 2009

Problem Description:

How to display time in different languages?

Solution:

This example uses DateFormat class to display time in Italian.

Page 32: Java programming-examples

Saikat Banerjee Page 32

import java.text.DateFormat;

import java.util.*;

public class Main {

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

Date d1 = new Date();

System.out.println("today is "+ d1.toString());

Locale locItalian = new Locale("it");

DateFormat df = DateFormat.getDateInstance

(DateFormat.FULL, locItalian);

System.out.println("today is "+ df.format(d1));

}

}

Result:

The above code sample will produce the following result.

today is Mon Jun 22 02:33:27 IST 2009

today is luned� 22 giugno 2009

Problem Description:

How to roll through hours & months?

Solution:

This example shows us how to roll through monrhs (without changing year) or hrs(without changing month or

year) using roll() method of Class calender.

import java.util.*;

public class Main {

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

Date d1 = new Date();

Calendar cl = Calendar. getInstance();

cl.setTime(d1);

System.out.println("today is "+ d1.toString());

cl. roll(Calendar.MONTH, 100);

System.out.println("date after a month will be "

+ cl.getTime().toString() );

cl. roll(Calendar.HOUR, 70);

System.out.println("date after 7 hrs will be "

+ cl.getTime().toString() );

}

}

Result:

The above code sample will produce the following result.

today is Mon Jun 22 02:44:36 IST 2009

date after a month will be Thu Oct 22 02:44:36 IST 2009

date after 7 hrs will be Thu Oct 22 00:44:36 IST 2009

Page 33: Java programming-examples

Saikat Banerjee Page 33

Problem Description:

How to find which week of the year, month?

Solution:

The following example displays week no of the year & month.

import java.util.*;

public class Main {

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

Date d1 = new Date();

Calendar cl = Calendar. getInstance();

cl.setTime(d1);

System.out.println("today is "

+ cl.WEEK_OF_YEAR+ " week of the year");

System.out.println("today is a "+cl.DAY_OF_MONTH +

"month of the year");

System.out.println("today is a "+cl.WEEK_OF_MONTH

+"week of the month");

}

}

Result:

The above code sample will produce the following result.

today is 30 week of the year

today is a 5month of the year

today is a 4week of the month

Problem Description:

How to display date in different formats ?

Solution:

This example displays the names of the weekdays in short form with the help of

DateFormatSymbols().getWeekdays() method of DateFormatSymbols class.

import java.text.*;

import java.util.*;

public class Main {

public static void main(String[] args) {

Date dt = new Date(1000000000000L);

DateFormat[] dtformat = new DateFormat[6];

dtformat[0] = DateFormat.getInstance();

dtformat[1] = DateFormat.getDateInstance();

dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);

dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL);

dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG);

dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);

for(DateFormat dateform : dtformat)

Page 34: Java programming-examples

Saikat Banerjee Page 34

System.out.println(dateform.format(dt));

}

}

Result:

The above code sample will produce the following result.

9/9/01 7:16 AM

Sep 9, 2001

Sep 9, 2001

Sunday, September 9, 2001

September 9, 2001

9/9/01

Java Method - Programming Examples

Learn how to play with methods in Java programming. Here are most commonly used examples:

1. How to overload methods?

2. How to use method overloading for printing different types of array?

3. How to use method for solving Tower of Hanoi problem?

4. How to use method for calculating Fibonacci series?

5. How to use method for calculating Factorial of a number?

6. How to use method overriding in Inheritance for subclasses?

7. How to display Object class using instanceOf keyword?

8. How to use break to jump out of a loop in a method?

9. How to use continue in a method?

10. How to use Label in a method?

11. How to use enum & switch statement ?

12. How to make enum constructor, instance variable & method?

13. How to use for and foreach loop for printing values of an array ?

14. How to make a method take variable lentgth argument as an input?

15. How to use variable arguments as an input when dealing with method overloading?

Problem Description:

How to overload methods ?

Solution:

This example displays the way of overloading a method depending on type and number of parameters.

class MyClass {

int height;

MyClass() {

System.out.println("bricks");

height = 0;

}

MyClass(int i) {

System.out.println("Building new House that is "

+ i + " feet tall");

height = i;

Page 35: Java programming-examples

Saikat Banerjee Page 35

}

void info() {

System.out.println("House is " + height

+ " feet tall");

}

void info(String s) {

System.out.println(s + ": House is "

+ height + " feet tall");

}

}

public class MainClass {

public static void main(String[] args) {

MyClass t = new MyClass(0);

t.info();

t.info("overloaded method");

//Overloaded constructor:

new MyClass();

}

}

Result:

The above code sample will produce the following result.

Building new House that is 0 feet tall.

House is 0 feet tall.

Overloaded method: House is 0 feet tall.

bricks

Problem Description:

How to use method overloading for printing different types of array ?

Solution:

This example displays the way of using overloaded method for printing types of array (integer, double and

character).

public class MainClass {

public static void printArray(Integer[] inputArray) {

for (Integer element : inputArray){

System.out.printf("%s ", element);

System.out.println();

}

}

public static void printArray(Double[] inputArray) {

for (Double element : inputArray){

System.out.printf("%s ", element);

System.out.println();

}

}

public static void printArray(Character[] inputArray) {

for (Character element : inputArray){

System.out.printf("%s ", element);

System.out.println();

}

}

public static void main(String args[]) {

Page 36: Java programming-examples

Saikat Banerjee Page 36

Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };

Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4,

5.5, 6.6, 7.7 };

Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");

printArray(integerArray);

System.out.println("\nArray doubleArray contains:");

printArray(doubleArray);

System.out.println("\nArray characterArray contains:");

printArray(characterArray);

}

}

Result:

The above code sample will produce the following result.

Array integerArray contains:

1

2

3

4

5

6

Array doubleArray contains:

1.1

2.2

3.3

4.4

5.5

6.6

7.7

Array characterArray contains:

H

E

L

L

O

Problem Description:

How to use method for solving Tower of Hanoi problem?

Solution:

This example displays the way of using method for solving Tower of Hanoi problem( for 3 disks).

public class MainClass {

public static void main(String[] args) {

int nDisks = 3;

doTowers(nDisks, 'A', 'B', 'C');

}

public static void doTowers(int topN, char from,

char inter, char to) {

if (topN == 1){

System.out.println("Disk 1 from "

+ from + " to " + to);

Page 37: Java programming-examples

Saikat Banerjee Page 37

}else {

doTowers(topN - 1, from, to, inter);

System.out.println("Disk "

+ topN + " from " + from + " to " + to);

doTowers(topN - 1, inter, from, to);

}

}

}

Result:

The above code sample will produce the following result.

Disk 1 from A to C

Disk 2 from A to B

Disk 1 from C to B

Disk 3 from A to C

Disk 1 from B to A

Disk 2 from B to C

Disk 1 from A to C

Problem Description:

How to use method for calculating Fibonacci series?

Solution:

This example shows the way of using method for calculating Fibonacci Series upto n numbers.

public class MainClass {

public static long fibonacci(long number) {

if ((number == 0) || (number == 1))

return number;

else

return fibonacci(number - 1) + fibonacci(number - 2);

}

public static void main(String[] args) {

for (int counter = 0; counter <= 10; counter++){

System.out.printf("Fibonacci of %d is: %d\n",

counter, fibonacci(counter));

}

}

}

Result:

The above code sample will produce the following result.

Fibonacci of 0 is: 0

Fibonacci of 1 is: 1

Fibonacci of 2 is: 1

Fibonacci of 3 is: 2

Fibonacci of 4 is: 3

Fibonacci of 5 is: 5

Fibonacci of 6 is: 8

Fibonacci of 7 is: 13

Page 38: Java programming-examples

Saikat Banerjee Page 38

Fibonacci of 8 is: 21

Fibonacci of 9 is: 34

Fibonacci of 10 is: 55

Problem Description:

How to use method for calculating Factorial of a number?

Solution:

This example shows the way of using method for calculating Factorial of 9(nine) numbers.

public class MainClass {

public static void main(String args[]) {

for (int counter = 0; counter <= 10; counter++){

System.out.printf("%d! = %d\n", counter,

factorial(counter));

}

}

public static long factorial(long number) {

if (number <= 1)

return 1;

else

return number * factorial(number - 1);

}

}

Result:

The above code sample will produce the following result.

0! = 1

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

6! = 720

7! = 5040

8! = 40320

9! = 362880

10! = 3628800

Problem Description:

How to use method overriding in Inheritance for subclasses ?

Solution:

This example demonstrates the way of method overriding by subclasses with different number and type of

parameters.

public class Findareas{

public static void main (String []agrs){

Figure f= new Figure(10 , 10);

Page 39: Java programming-examples

Saikat Banerjee Page 39

Rectangle r= new Rectangle(9 , 5);

Figure figref;

figref=f;

System.out.println("Area is :"+figref.area());

figref=r;

System.out.println("Area is :"+figref.area());

}

}

class Figure{

double dim1;

double dim2;

Figure(double a , double b) {

dim1=a;

dim2=b;

}

Double area() {

System.out.println("Inside area for figure.");

return(dim1*dim2);

}

}

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a ,b);

}

Double area() {

System.out.println("Inside area for rectangle.");

return(dim1*dim2);

}

}

Result:

The above code sample will produce the following result.

Inside area for figure.

Area is :100.0

Inside area for rectangle.

Area is :45.0

Problem Description:

How to display Object class using instanceOf keyword?

Solution:

This example makes displayObjectClass() method to display the Class of the Object that is passed in this

method as an argument.

import java.util.ArrayList;

import java.util.Vector;

public class Main {

public static void main(String[] args) {

Object testObject = new ArrayList();

displayObjectClass(testObject);

}

public static void displayObjectClass(Object o) {

Page 40: Java programming-examples

Saikat Banerjee Page 40

if (o instanceof Vector)

System.out.println("Object was an instance

of the class java.util.Vector");

else if (o instanceof ArrayList)

System.out.println("Object was an instance of

the class java.util.ArrayList");

else

System.out.println("Object was an instance of the "

+ o.getClass());

}

}

Result:

The above code sample will produce the following result.

Object was an instance of the class java.util.ArrayList

Problem Description:

How to use break to jump out of a loop in a method?

Solution:

This example uses the 'break' to jump out of the loop.

public class Main {

public static void main(String[] args) {

int[] intary = { 99,12,22,34,45,67,5678,8990 };

int no = 5678;

int i = 0;

boolean found = false;

for ( ; i < intary.length; i++) {

if (intary[i] == no) {

found = true;

break;

}

}

if (found) {

System.out.println("Found the no: " + no

+ " at index: " + i);

}

else {

System.out.println(no + "not found in the array");

}

}

}

Result:

The above code sample will produce the following result.

Found the no: 5678 at index: 6

Java Files - Programming Examples

Page 41: Java programming-examples

Saikat Banerjee Page 41

Learn how to play with Files in Java programming. Here are most commonly used examples:

1. How to compare paths of two files?

2. How to create a new file?

3. How to get last modification date of a file?

4. How to create a file in a specified directory?

5. How to check a file exist or not?

6. How to make a file read-only?

7. How to renaming a file ?

8. How to get a file's size in bytes?

9. How to change the last modification time of a file ?

10. How to create a temporary file?

11. How to append a string in an existing file?

12. How to copy one file into another file?

13. How to delete a file?

14. How to read a file?

15. How to write to a file?

Problem Description:

How to compare paths of two files ?

Solution:

This example shows how to compare paths of two files in a same directory by the use of

filename.compareTo(another filename) method of File class.

import java.io.File;

public class Main {

public static void main(String[] args) {

File file1 = new File("C:/File/demo1.txt");

File file2 = new File("C:/java/demo1.txt");

if(file1.compareTo(file2) == 0) {

System.out.println("Both paths are same!");

} else {

System.out.println("Paths are not same!");

}

}

}

Result:

The above code sample will produce the following result.

Paths are not same!

Problem Description:

How to create a new file?

Page 42: Java programming-examples

Saikat Banerjee Page 42

Solution:

This example demonstrates the way of creating a new file by using File() constructor and file.createNewFile()

method of File class.

import java.io.File;

import java.io.IOException;

public class Main {

public static void main(String[] args) {

try{

File file = new File("C:/myfile.txt");

if(file.createNewFile())

System.out.println("Success!");

else

System.out.println

("Error, file already exists.");

}

catch(IOException ioe) {

ioe.printStackTrace();

}

}

}

Result:

The above code sample will produce the following result (if "myfile.txt does not exist before)

Success!

Problem Description:

How to get last modification date of a file ?

Solution:

This example shows how to get the last modification date of a file using file.lastModified() method of File

class.

import java.io.File;

import java.util.Date;

public class Main {

public static void main(String[] args) {

File file = new File("Main.java");

Long lastModified = file.lastModified();

Date date = new Date(lastModified);

System.out.println(date);

}

}

Result:

The above code sample will produce the following result.

Page 43: Java programming-examples

Saikat Banerjee Page 43

Tue 12 May 10:18:50 PDF 2009

Problem Description:

How to create a file in a specified directory ?

Solution:

This example demonstrates how to create a file in a specified directory using File.createTempFile() method of

File class.

import java.io.File;

public class Main {

public static void main(String[] args)

throws Exception {

File file = null;

File dir = new File("C:/");

file = File.createTempFile

("JavaTemp", ".javatemp", dir);

System.out.println(file.getPath());

}

}

Result:

The above code sample will produce the following result.

C:\JavaTemp37056.javatemp

Problem Description:

How to check a file exist or not?

Solution:

This example shows how to check a file�s existence by using file.exists() method of File class.

import java.io.File;

public class Main {

public static void main(String[] args) {

File file = new File("C:/java.txt");

System.out.println(file.exists());

}

}

Result:

The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).

true

Page 44: Java programming-examples

Saikat Banerjee Page 44

Problem Description:

How to make a file read-only?

Solution:

This example demonstrates how to make a file read-only by using file.setReadOnly() and file.canWrite()

methods of File class .

import java.io.File;

public class Main {

public static void main(String[] args) {

File file = new File("C:/java.txt");

System.out.println(file.setReadOnly());

System.out.println(file.canWrite());

}

}

Result:

The above code sample will produce the following result.To test the example,first create a file 'java.txt' in 'C'

drive.

true

false

Problem Description:

How to rename a file?

Solution:

This example demonstrates how to renaming a file using oldName.renameTo(newName) method of File class.

import java.io.File;

public class Main {

public static void main(String[] args) {

File oldName = new File("C:/program.txt");

File newName = new File("C:/java.txt");

if(oldName.renameTo(newName)) {

System.out.println("renamed");

} else {

System.out.println("Error");

}

}

}

Result:

The above code sample will produce the following result.To test this example, first create a file 'program.txt' in

'C' drive.

Page 45: Java programming-examples

Saikat Banerjee Page 45

renamed

Problem Description:

How to get a file�s size in bytes ?

Solution:

This example shows how to get a file's size in bytes by using file.exists() and file.length() method of File class.

import java.io.File;

public class Main {

public static long getFileSize(String filename) {

File file = new File(filename);

if (!file.exists() || !file.isFile()) {

System.out.println("File doesn\'t exist");

return -1;

}

return file.length();

}

public static void main(String[] args) {

long size = getFileSize("c:/java.txt");

System.out.println("Filesize in bytes: " + size);

}

}

Result:

The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in

'C' drive.The size may vary depending upon the size of the file.

File size in bytes: 480

Problem Description:

How to change the last modification time of a file ?

Solution:

This example shows how to change the last modification time of a file with the help of

fileToChange.lastModified() and fileToChange setLastModified() methods of File class .

import java.io.File;

import java.util.Date;

public class Main {

public static void main(String[] args)

throws Exception {

File fileToChange = new File

("C:/myjavafile.txt");

fileToChange.createNewFile();

Date filetime = new Date

(fileToChange.lastModified());

Page 46: Java programming-examples

Saikat Banerjee Page 46

System.out.println(filetime.toString());

System.out.println

(fileToChange.setLastModified

(System.currentTimeMillis()));

filetime = new Date

(fileToChange.lastModified());

System.out.println(filetime.toString());

}

}

Result:

The above code sample will produce the following result.The result may vary depending upon the system time.

Sat Oct 18 19:58:20 GMT+05:30 2008

true

Sat Oct 18 19:58:20 GMT+05:30 2008

Problem Description:

How to create a temporary file?

Solution:

This example shows how to create a temporary file using createTempFile() method of File class.

import java.io.*;

public class Main {

public static void main(String[] args)

throws Exception {

File temp = File.createTempFile

("pattern", ".suffix");

temp.deleteOnExit();

BufferedWriter out = new BufferedWriter

(new FileWriter(temp));

out.write("aString");

System.out.println("temporary file created:");

out.close();

}

}

Result:

The above code sample will produce the following result.

temporary file created:

Problem Description:

How to append a string in an existing file?

Page 47: Java programming-examples

Saikat Banerjee Page 47

Solution:

This example shows how to append a string in an existing file using filewriter method.

import java.io.*;

public class Main {

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

try {

BufferedWriter out = new BufferedWriter

(new FileWriter("filename"));

out.write("aString1\n");

out.close();

out = new BufferedWriter(new FileWriter

("filename",true));

out.write("aString2");

out.close();

BufferedReader in = new BufferedReader

(new FileReader("filename"));

String str;

while ((str = in.readLine()) != null) {

System.out.println(str);

}

}

in.close();

catch (IOException e) {

System.out.println("exception occoured"+ e);

}

}

}

Result:

The above code sample will produce the following result.

aString1

aString2

Problem Description:

How to copy one file into another file?

Solution:

This example shows how to copy contents of one file into another file using read & write methods of

BufferedWriter class.

import java.io.*;

public class Main {

public static void main(String[] args)

throws Exception {

BufferedWriter out1 = new BufferedWriter

(new FileWriter("srcfile"));

out1.write("string to be copied\n");

out1.close();

InputStream in = new FileInputStream

Page 48: Java programming-examples

Saikat Banerjee Page 48

(new File("srcfile"));

OutputStream out = new FileOutputStream

(new File("destnfile"));

byte[] buf = new byte[1024];

int len;

while ((len = in.read(buf)) > 0) {

out.write(buf, 0, len);

}

in.close();

out.close();

BufferedReader in1 = new BufferedReader

(new FileReader("destnfile"));

String str;

while ((str = in1.readLine()) != null) {

System.out.println(str);

}

in.close();

}

}

Result:

The above code sample will produce the following result.

string to be copied

Problem Description:

How to delete a file?

Solution:

This example shows how to delete a file using delete() method of File class.

import java.io.*;

public class Main {

public static void main(String[] args) {

try {

BufferedWriter out = new BufferedWriter

(new FileWriter("filename"));

out.write("aString1\n");

out.close();

boolean success = (new File

("filename")).delete();

if (success) {

System.out.println("The file has

been successfully deleted");

}

BufferedReader in = new BufferedReader

(new FileReader("filename"));

String str;

while ((str = in.readLine()) != null) {

System.out.println(str);

}

in.close();

}

catch (IOException e) {

System.out.println("exception occoured"+ e);

Page 49: Java programming-examples

Saikat Banerjee Page 49

System.out.println("File does not exist

or you are trying to read a file that

has been deleted");

}

}

}

}

Result:

The above code sample will produce the following result.

The file has been successfully deleted

exception occouredjava.io.FileNotFoundException:

filename (The system cannot find the file specified)

File does not exist or you are trying to read a

file that has been deleted

Problem Description:

How to read a file?

Solution:

This example shows how to read a file using readLine method of BufferedReader class.

import java.io.*;

public class Main {

public static void main(String[] args) {

try {

BufferedReader in = new BufferedReader

(new FileReader("c:\\filename"));

String str;

while ((str = in.readLine()) != null) {

System.out.println(str);

}

System.out.println(str);

}

catch (IOException e) {

}

}

}

}

Result:

The above code sample will produce the following result.

aString

Problem Description:

How to write into a file ?

Page 50: Java programming-examples

Saikat Banerjee Page 50

Solution:

This example shows how to write to a file using write method of BufferedWriter.

import java.io.*;

public class Main {

public static void main(String[] args) {

try {

BufferedWriter out = new

BufferedWriter(new FileWriter("outfilename"));

out.write("aString");

out.close();

System.out.println

("File created successfully");

}

catch (IOException e) {

}

}

}

Result:

The above code sample will produce the following result.

File created successfully.

Java Directory - Programming Examples

Learn how to accsess directories in Java programming. Here are most commonly used examples:

1. How to create directories recursively?

2. How to delete a directory?

3. How to get the fact that a directory is empty or not?

4. How to get a directory is hidden or not?

5. How to print the directory hierarchy?

6. How to print the last modification time of a directory?

7. How to get the parent directory of a file?

8. How to search all files inside a directory?

9. How to get the size of a directory?

10. How to traverse a directory?

11. How to find current working directory?

12. How to display root directories in the system?

13. How to search for a file in a directory?

14. How to display all the files in a directory?

15. How to display all the directories in a directory?

Problem Description:

How to create directories recursively ?

Page 51: Java programming-examples

Saikat Banerjee Page 51

Solution:

Following example shows how to create directories recursively with the help of file.mkdirs() methods of File

class.

import java.io.File;

public class Main {

public static void main(String[] args) {

String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";

File file = new File(directories);

boolean result = file.mkdirs();

System.out.println("Status = " + result);

}

}

Result:

The above code sample will produce the following result.

Status = true

Problem Description:

How to delete a directory?

Solution:

Following example demonstares how to delete a directory after deleting its files and directories by the use

ofdir.isDirectory(),dir.list() and deleteDir() methods of File class.

import java.io.File;

public class Main {

public static void main(String[] argv) throws Exception {

deleteDir(new File("c:\\temp"));

}

public static boolean deleteDir(File dir) {

if (dir.isDirectory()) {

String[] children = dir.list();

for (int i = 0; i < children.length; i++) {

boolean success = deleteDir

(new File(dir, children[i]));

if (!success) {

return false;

}

}

}

return dir.delete();

System.out.println("The directory is deleted.");

}

}

Result:

The above code sample will produce the following result.

Page 52: Java programming-examples

Saikat Banerjee Page 52

The directory is deleted.

Problem Description:

How to get the fact that a directory is empty or not?

Solution:

Following example gets the size of a directory by using file.isDirectory(),file.list() and file.getPath() methodsof

File class.

import java.io.File;

public class Main {

public static void main(String[] args) {

File file = new File("/data");

if (file.isDirectory()) {

String[] files = file.list();

if (files.length > 0) {

System.out.println("The " + file.getPath() +

" is not empty!");

}

}

}

}

Result:

The above code sample will produce the following result.

The D://Java/file.txt is not empty!

Problem Description:

How to get a directory is hidden or not?

Solution:

Following example demonstrates how to get the fact that a file is hidden or not by using file.isHidden() method

of File class.

import java.io.File;

public class Main {

public static void main(String[] args) {

File file = new File("C:/Demo.txt");

System.out.println(file.isHidden());

}

}

Problem Description:

How to print the directory hierarchy?

Page 53: Java programming-examples

Saikat Banerjee Page 53

Solution:

Following example shows how to print the hierarchy of a specified directory using file.getName() and

file.listFiles() method of File class.

import java.io.File;

import java.io.IOException;

public class FileUtil {

public static void main(String[] a)throws IOException{

showDir(1, new File("d:\\Java"));

}

static void showDir(int indent, File file)

throws IOException {

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

System.out.print('-');

System.out.println(file.getName());

if (file.isDirectory()) {

File[] files = file.listFiles();

for (int i = 0; i < files.length; i++)

showDir(indent + 4, files[i]);

}

}

}

Result:

The above code sample will produce the following result.

-Java

-----codes

---------string.txt

---------array.txt

-----tutorial

Problem Description:

How to print the last modification time of a directory?

Solution:

Following example demonstrates how to get the last modification time of a directory with the help of

file.lastModified() method of File class.

import java.io.File;

import java.util.Date;

public class Main {

public static void main(String[] args) {

File file = new File("C://FileIO//demo.txt");

System.out.println("last modifed:" +

new Date(file.lastModified()));

}

}

Page 54: Java programming-examples

Saikat Banerjee Page 54

Result:

The above code sample will produce the following result.

last modifed:10:20:54

The above code sample will produce the following result (as Demo.txt is hidden).

True

Problem Description:

How to get the parent directory of a file?

Solution:

Following example shows how to get the parent directory of a file by the use of file.getParent() method of File

class.

import java.io.File;

public class Main {

public static void main(String[] args) {

File file = new File("C:/File/demo.txt");

String strParentDirectory = file.getParent();

System.out.println("Parent directory is : "

+ strParentDirectory);

}

}

Result:

The above code sample will produce the following result.

Parent directory is : File

Problem Description:

How to search all files inside a directory?

Solution:

Following example demonstrares how to search and get a list of all files under a specified directory by using

dir.list() method of File class.

import java.io.File;

public class Main {

Page 55: Java programming-examples

Saikat Banerjee Page 55

public static void main(String[] argv)

throws Exception {

File dir = new File("directoryName");

String[] children = dir.list();

if (children == null) {

System.out.println("does not exist or

is not a directory");

}

else {

for (int i = 0; i < children.length; i++) {

String filename = children[i];

System.out.println(filename);

}

}

}

}

Result:

The above code sample will produce the following result.

sdk

---vehicles

------body.txt

------color.txt

------engine.txt

---ships

------shipengine.txt

Problem Description:

How to get the size of a directory?

Solution:

Following example shows how to get the size of a directory with the help of FileUtils.sizeofDirectory(File

Name) method of FileUtils class.

import java.io.File;

import org.apache.commons.io.FileUtils;

public class Main {

public static void main(String[] args) {

long size = FileUtils.sizeOfDirectory

(new File("C:/Windows"));

System.out.println("Size: " + size + " bytes");

}

}

Result:

The above code sample will produce the following result.

Size: 2048 bytes

Page 56: Java programming-examples

Saikat Banerjee Page 56

Java Exception - Programming Examples

Learn how to play with exception in Java programming. Here are most commonly used examples:

1. How to use finally block for catching exceptions?

2. How to use handle the exception heiarchies?

3. How to use handle the exception methods?

4. How to use handle the runtime exceptions?

5. How to use handle the empty stack exception ?

6. How to use catch to handle the exception?

7. How to use catch to handle chained exception?

8. How to use handle the exception with overloaded methods ?

9. How to handle the checked exceptions?

10. How to pass arguments while throwing checked exception?

11. How to handle multiple exceptions (devide by zero)?

12. How to handle multiple exceptions (Array out of bound)?

13. How to use handle the exception with overloaded methods ?

14. How to print stack of the Exception?

15. How to use exceptions with thread?

16. How to create user defined Exception?

Problem Description:

How to use finally block for catching exceptions?

Solution:

This example shows how to use finally block to catch runtime exceptions (Illegal Argument Exception) by the

use of e.getMessage().

public class ExceptionDemo2 {

public static void main(String[] argv) {

new ExceptionDemo2().doTheWork();

}

public void doTheWork() {

Object o = null;

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

try {

o = makeObj(i);

}

catch (IllegalArgumentException e) {

System.err.println

("Error: ("+ e.getMessage()+").");

return;

}

finally {

System.err.println("All done");

if (o==null)

System.exit(0);

}

System.out.println(o);

}

}

public Object makeObj(int type)

throws IllegalArgumentException {

if (type == 1)

Page 57: Java programming-examples

Saikat Banerjee Page 57

throw new IllegalArgumentException

("Don't like type " + type);

return new Object();

}

}

Result:

The above code sample will produce the following result.

All done

java.lang.Object@1b90b39

Error: (Don't like type 1).

All done

Problem Description:

How to handle the exception hierarchies?

Solution:

This example shows how to handle the exception hierarchies by extending Exception class ?

class Animal extends Exception {

}

class Mammel extends Animal {

}

public class Human {

public static void main(String[] args) {

try {

throw new Mammel();

}

catch (Mammel m) {

System.err.println("It is mammel");

}

catch (Annoyance a) {

System.err.println("It is animal");

}

}

}

Result:

The above code sample will produce the following result.

It is mammel

Problem Description:

How to use handle the exception methods ?

Page 58: Java programming-examples

Saikat Banerjee Page 58

Solution:

This example shows how to handle the exception methods by using System.err.println() method of System

class .

public static void main(String[] args) {

try {

throw new Exception("My Exception");

} catch (Exception e) {

System.err.println("Caught Exception");

System.err.println("getMessage():" + e.getMessage());

System.err.println("getLocalizedMessage():"

+ e.getLocalizedMessage());

System.err.println("toString():" + e);

System.err.println("printStackTrace():");

e.printStackTrace();

}

}

Result:

The above code sample will produce the following result.

Caught Exception

getMassage(): My Exception

gatLocalisedMessage(): My Exception

toString():java.lang.Exception: My Exception

print StackTrace():

java.lang.Exception: My Exception

at ExceptionMethods.main(ExceptionMeyhods.java:12)

Problem Description:

How to handle the runtime exceptions ?

Solution:

This example shows how to handle the runtime exception in a java programs.

public class NeverCaught {

static void f() {

throw new RuntimeException("From f()");

}

static void g() {

f();

}

public static void main(String[] args) {

g();

}

}

Result:

The above code sample will produce the following result.

Page 59: Java programming-examples

Saikat Banerjee Page 59

From f()

Problem Description:

How to handle the empty stack exception ?

Solution:

This example shows how to handle the empty stack exception by using s.empty(),s.pop() methods of Stack

class and System.currentTimeMillis()method of Date class .

import java.util.Date;

import java.util.EmptyStackException;

import java.util.Stack;

public class ExceptionalTest {

public static void main(String[] args) {

int count = 1000000;

Stack s = new Stack();

System.out.println("Testing for empty stack");

long s1 = System.currentTimeMillis();

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

if (!s.empty())

s.pop();

long s2 = System.currentTimeMillis();

System.out.println((s2 - s1) + " milliseconds");

System.out.println("Catching EmptyStackException");

s1 = System.currentTimeMillis();

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

try {

s.pop();

}

catch (EmptyStackException e) {

}

}

s2 = System.currentTimeMillis();

System.out.println((s2 - s1) + " milliseconds");

}

}

Result:

The above code sample will produce the following result.

Testing for empty stack

16 milliseconds

Catching EmptyStackException

3234 milliseconds

Problem Description:

How to use catch to handle the exception?

Solution:

This example shows how to use catch to handle the exception.

Page 60: Java programming-examples

Saikat Banerjee Page 60

public class Main{

public static void main (String args[]) {

int array[]={20,20,40};

int num1=15,num2=10;

int result=10;

try{

result = num1/num2;

System.out.println("The result is" +result);

for(int i =5;i >=0; i--) {

System.out.println

("The value of array is" +array[i]);

}

}

catch (Exception e) {

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

}

}

}

Result:

The above code sample will produce the following result.

The result is1

Exception occoured : java.lang.ArrayIndexOutOfBoundsException: 5

Problem Description:

How to use catch to handle chained exception?

Solution:

This example shows how to handle chained exception using multiple catch blocks.

public class Main{

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

int n=20,result=0;

try{

result=n/0;

System.out.println("The result is"+result);

}

catch(ArithmeticException ex){

System.out.println

("Arithmetic exception occoured: "+ex);

try {

throw new NumberFormatException();

}

catch(NumberFormatException ex1) {

System.out.println

("Chained exception thrown manually : "+ex1);

}

}

}

}

Result:

The above code sample will produce the following result.

Page 61: Java programming-examples

Saikat Banerjee Page 61

Arithmetic exception occoured :

java.lang.ArithmeticException: / by zero

Chained exception thrown manually :

java.lang.NumberFormatException

Problem Description:

How to handle the exception with overloaded methods ?

Solution:

This example shows how to handle the exception with overloaded methods. You need to have a try catch block

in each method or where the are used.

public class Main {

double method(int i) throws Exception{

return i/0;

}

boolean method(boolean b) {

return !b;

}

static double method(int x, double y) throws Exception {

return x + y ;

}

static double method(double x, double y) {

return x + y - 3;

}

public static void main(String[] args) {

Main mn = new Main();

try{

System.out.println(method(10, 20.0));

System.out.println(method(10.0, 20));

System.out.println(method(10.0, 20.0));

System.out.println(mn.method(10));

}

catch (Exception ex){

System.out.println("exception occoure: "+ ex);

}

}

}

Result:

The above code sample will produce the following result.

30.0

27.0

27.0

exception occoure: java.lang.ArithmeticException: / by zero

Java Data Structure - Programming Examples

Learn how to play with data structure in Java programming. Here are most commonly used examples:

1. How to print summation of n numbers?

2. How to get the first and the last element of a linked list?

Page 62: Java programming-examples

Saikat Banerjee Page 62

3. How to add an element at first and last position of a linked list?

4. How to convert an infix expression to postfix expression?

5. How to implement Queue?

6. How to reverse a string using stack?

7. How to search an element inside a linked list?

8. How to implement stack?

9. How to swap two elements in a vector?

10. How to update a linked list?

11. How to get the maximum element from a vector?

12. How to execute binary search on a vector?

13. How to get elements of a LinkedList?

14. How to delete many elements from a linkedList?

Problem Description:

How to print summation of n numbers?

Solution:

Following example demonstrates how to add first n natural numbers by using the concept of stack .

import java.io.IOException;

public class AdditionStack {

static int num;

static int ans;

static Stack theStack;

public static void main(String[] args)

throws IOException {

num = 50;

stackAddition();

System.out.println("Sum=" + ans);

}

public static void stackAddition() {

theStack = new Stack(10000);

ans = 0;

while (num > 0) {

theStack.push(num);

--num;

}

while (!theStack.isEmpty()) {

int newN = theStack.pop();

ans += newN;

}

}

}

class Stack {

private int maxSize;

private int[] data;

private int top;

public Stack(int s) {

maxSize = s;

data = new int[maxSize];

top = -1;

}

public void push(int p) {

data[++top] = p;

}

Page 63: Java programming-examples

Saikat Banerjee Page 63

public int pop() {

return data[top--];

}

public int peek() {

return data[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

Result:

The above code sample will produce the following result.

Sum=1225

Problem Description:

How to get the first and the last element of a linked list ?

Solution:

Following example shows how to get the first and last element of a linked list with the help of

linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList lList = new LinkedList();

lList.add("100");

lList.add("200");

lList.add("300");

lList.add("400");

lList.add("500");

System.out.println("First element of LinkedList is :

" + lList.getFirst());

System.out.println("Last element of LinkedList is :

" + lList.getLast());

}

}

Result:

The above code sample will produce the following result.

First element of LinkedList is :100

Last element of LinkedList is :500

Problem Description:

How to add an element at first and last position of a linked list?

Page 64: Java programming-examples

Saikat Banerjee Page 64

Solution:

Following example shows how to add an element at the first and last position of a linked list by using addFirst()

and addLast() method of Linked List class.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList lList = new LinkedList();

lList.add("1");

lList.add("2");

lList.add("3");

lList.add("4");

lList.add("5");

System.out.println(lList);

lList.addFirst("0");

System.out.println(lList);

lList.addLast("6");

System.out.println(lList);

}

}

Result:

The above code sample will produce the following result.

1, 2, 3, 4, 5

0, 1, 2, 3, 4, 5

0, 1, 2, 3, 4, 5, 6

Problem Description:

How to convert an infix expression to postfix expression?

Solution:

Following example demonstrates how to convert an infix to postfix expression by using the concept of stack.

import java.io.IOException;

public class InToPost {

private Stack theStack;

private String input;

private String output = "";

public InToPost(String in) {

input = in;

int stackSize = input.length();

theStack = new Stack(stackSize);

}

public String doTrans() {

for (int j = 0; j < input.length(); j++) {

char ch = input.charAt(j);

switch (ch) {

case '+':

case '-':

gotOper(ch, 1);

Page 65: Java programming-examples

Saikat Banerjee Page 65

break;

case '*':

case '/':

gotOper(ch, 2);

break;

case '(':

theStack.push(ch);

break;

case ')':

gotParen(ch);

break;

default:

output = output + ch;

break;

}

}

while (!theStack.isEmpty()) {

output = output + theStack.pop();

}

System.out.println(output);

return output;

}

public void gotOper(char opThis, int prec1) {

while (!theStack.isEmpty()) {

char opTop = theStack.pop();

if (opTop == '(') {

theStack.push(opTop);

break;

}

else {

int prec2;

if (opTop == '+' || opTop == '-')

prec2 = 1;

else

prec2 = 2;

if (prec2 < prec1) {

theStack.push(opTop);

break;

}

else

output = output + opTop;

}

}

theStack.push(opThis);

}

public void gotParen(char ch){

while (!theStack.isEmpty()) {

char chx = theStack.pop();

if (chx == '(')

break;

else

output = output + chx;

}

}

public static void main(String[] args)

throws IOException {

String input = "1+2*4/5-7+3/6";

String output;

InToPost theTrans = new InToPost(input);

output = theTrans.doTrans();

System.out.println("Postfix is " + output + '\n');

}

class Stack {

private int maxSize;

private char[] stackArray;

Page 66: Java programming-examples

Saikat Banerjee Page 66

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top--];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

}

Result:

The above code sample will produce the following result.

124*5/+7-36/+

Postfix is 124*5/+7-36/+

Problem Description:

How to implement Queue ?

Solution:

Following example shows how to implement a queue in an employee structure.

import java.util.LinkedList;

class GenQueue {

private LinkedList list = new LinkedList();

public void enqueue(E item) {

list.addLast(item);

}

public E dequeue() {

return list.poll();

}

public boolean hasItems() {

return !list.isEmpty();

}

public int size() {

return list.size();

}

public void addItems(GenQueue q) {

while (q.hasItems())

list.addLast(q.dequeue());

}

}

public class GenQueueTest {

Page 67: Java programming-examples

Saikat Banerjee Page 67

public static void main(String[] args) {

GenQueue empList;

empList = new GenQueue();

GenQueue hList;

hList = new GenQueue();

hList.enqueue(new HourlyEmployee("T", "D"));

hList.enqueue(new HourlyEmployee("G", "B"));

hList.enqueue(new HourlyEmployee("F", "S"));

empList.addItems(hList);

System.out.println("The employees' names are:");

while (empList.hasItems()) {

Employee emp = empList.dequeue();

System.out.println(emp.firstName + " "

+ emp.lastName);

}

}

}

class Employee {

public String lastName;

public String firstName;

public Employee() {

}

public Employee(String last, String first) {

this.lastName = last;

this.firstName = first;

}

public String toString() {

return firstName + " " + lastName;

}

}

class HourlyEmployee extends Employee {

public double hourlyRate;

public HourlyEmployee(String last, String first) {

super(last, first);

}

}

Result:

The above code sample will produce the following result.

The employees' name are:

T D

G B

F S

Problem Description:

How to reverse a string using stack ?

Solution:

Following example shows how to reverse a string using stack with the help of user defined method

StringReverserThroughStack().

import java.io.IOException;

Page 68: Java programming-examples

Saikat Banerjee Page 68

public class StringReverserThroughStack {

private String input;

private String output;

public StringReverserThroughStack(String in) {

input = in;

}

public String doRev() {

int stackSize = input.length();

Stack theStack = new Stack(stackSize);

for (int i = 0; i < input.length(); i++) {

char ch = input.charAt(i);

theStack.push(ch);

}

output = "";

while (!theStack.isEmpty()) {

char ch = theStack.pop();

output = output + ch;

}

return output;

}

public static void main(String[] args)

throws IOException {

String input = "Java Source and Support";

String output;

StringReverserThroughStack theReverser =

new StringReverserThroughStack(input);

output = theReverser.doRev();

System.out.println("Reversed: " + output);

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int max) {

maxSize = max;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top--];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

}

}

Result:

The above code sample will produce the following result.

JavaStringReversal

Reversed:lasreveRgnirtSavaJ

Page 69: Java programming-examples

Saikat Banerjee Page 69

Problem Description:

How to search an element inside a linked list ?

Solution:

Following example demonstrates how to search an element inside a linked list using

linkedlistname.indexof(element) to get the first position of the element and

linkedlistname.Lastindexof(elementname) to get the last position of the element inside the linked list.

import java.util.LinkedList;

public class Main {

public static void main(String[] args) {

LinkedList lList = new LinkedList();

lList.add("1");

lList.add("2");

lList.add("3");

lList.add("4");

lList.add("5");

lList.add("2");

System.out.println("First index of 2 is:"+

lList.indexOf("2"));

System.out.println("Last index of 2 is:"+

lList.lastIndexOf("2"));

}

}

Result:

The above code sample will produce the following result.

First index of 2 is: 1

Last index of 2 is: 5

Problem Description:

How to implement stack?

Solution:

Following example shows how to implement stack by creating user defined push() method for entering

elements and pop() method for retriving elements from the stack.

public class MyStack {

private int maxSize;

private long[] stackArray;

private int top;

public MyStack(int s) {

maxSize = s;

stackArray = new long[maxSize];

top = -1;

}

public void push(long j) {

stackArray[++top] = j;

Page 70: Java programming-examples

Saikat Banerjee Page 70

}

public long pop() {

return stackArray[top--];

}

public long peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

public boolean isFull() {

return (top == maxSize - 1);

}

public static void main(String[] args) {

MyStack theStack = new MyStack(10);

theStack.push(10);

theStack.push(20);

theStack.push(30);

theStack.push(40);

theStack.push(50);

while (!theStack.isEmpty()) {

long value = theStack.pop();

System.out.print(value);

System.out.print(" ");

}

System.out.println("");

}

}

Result:

The above code sample will produce the following result.

50 40 30 20 10

Problem Description:

How to swap two elements in a vector ?

Solution:

Following example .

import java.util.Collections;

import java.util.Vector;

public class Main {

public static void main(String[] args) {

Vector v = new Vector();

v.add("1");

v.add("2");

v.add("3");

v.add("4");

v.add("5");

System.out.println(v);

Collections.swap(v, 0, 4);

System.out.println("After swapping");

System.out.println(v);

}

Page 71: Java programming-examples

Saikat Banerjee Page 71

}

Result:

The above code sample will produce the following result.

1 2 3 4 5

After swapping

5 2 3 4 1

Problem Description:

How to update a linked list ?

Solution:

Following example demonstrates how to update a linked list by using listname.add() and listname.set() methods

of LinkedList class.

import java.util.LinkedList;

public class MainClass {

public static void main(String[] a) {

LinkedList officers = new LinkedList();

officers.add("B");

officers.add("B");

officers.add("T");

officers.add("H");

officers.add("P");

System.out.println(officers);

officers.set(2, "M");

System.out.println(officers);

}

}

Result:

The above code sample will produce the following result.

BBTHP

BBMHP

Problem Description:

How to get the maximum element from a vector ?

Solution:

Following example demonstrates how to get the maximum element of a vector by using v.add() method of

Vector class and Collections.max() method of Collection class.

import java.util.Collections;

Page 72: Java programming-examples

Saikat Banerjee Page 72

import java.util.Vector;

public class Main {

public static void main(String[] args) {

Vector v = new Vector();

v.add(new Double("3.4324"));

v.add(new Double("3.3532"));

v.add(new Double("3.342"));

v.add(new Double("3.349"));

v.add(new Double("2.3"));

Object obj = Collections.max(v);

System.out.println("The max element is:"+obj);

}

}

Result:

The above code sample will produce the following result.

The max element is: 3.4324

Problem Description:

How to execute binary search on a vector ?

Solution:

Following example how to execute binary search on a vector with the help of v.add() method of Vector class

and sort.Collection() method of Collection class.

import java.util.Collections;

import java.util.Vector;

public class Main {

public static void main(String[] args) {

Vector v = new Vector();

v.add("X");

v.add("M");

v.add("D");

v.add("A");

v.add("O");

Collections.sort(v);

System.out.println(v);

int index = Collections.binarySearch(v, "D");

System.out.println("Element found at : " + index);

}

}

Result:

The above code sample will produce the following result.

[A, D, M, O, X]

Element found at : 1

Page 73: Java programming-examples

Saikat Banerjee Page 73

Problem Description:

How to get elements of a LinkedList?

Solution:

Following example demonstrates how to get elements of LinkedList using top() & pop() methods.

import java.util.*;

public class Main {

private LinkedList list = new LinkedList();

public void push(Object v) {

list.addFirst(v);

}

public Object top() {

return list.getFirst();

}

public Object pop() {

return list.removeFirst();

}

public static void main(String[] args) {

Main stack = new Main();

for (int i = 30; i < 40; i++)

stack.push(new Integer(i));

System.out.println(stack.top());

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

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

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

}

}

Result:

The above code sample will produce the following result.

39

39

38

37

Problem Description:

How to delete many elements from a linkedList?

Solution:

Following example demonstrates how to delete many elements of linkedList using Clear() method.

import java.util.*;

public class Main {

public static void main(String[] args) {

LinkedList lList = new LinkedList();

lList.add("1");

lList.add("8");

Page 74: Java programming-examples

Saikat Banerjee Page 74

lList.add("6");

lList.add("4");

lList.add("5");

System.out.println(lList);

lList.subList(2, 4).clear();

System.out.println(lList);

}

}

Result:

The above code sample will produce the following result.

[one, two, three, four, five]

[one, two, three, Replaced, five]

Java Collection - Programming Examples

Learn how to play with collections in Java programming. Here are most commonly used examples:

1. How to convert an array into a collection?

2. How to compare elements in a collection?

3. How to convert a collection into an array?

4. How to print a collection?

5. How to make a collection read-only?

6. How to remove a specific element from a collection?

7. How to reverse a collection?

8. How to shuffle the elements of a collection?

9. How to get the size of a collection?

10. How to iterate through elements of HashMap?

11. How to use different types of Collections?

12. How to use enumeration to display contents of HashTable?

13. How to get Set view of Keys from Java Hashtable?

14. How to find min & max of a List?

15. How to find a sublist in a List?

16. How to replace an element in a list?

17. How to rotate elements of the List?

Problem Description:

How to convert an array into a collection?

Solution:

Following example demonstrates to convert an array into a collection Arrays.asList(name) method of Java Util

class.

import java.util.*;

import java.io.*;

public class ArrayToCollection{

public static void main(String args[])

Page 75: Java programming-examples

Saikat Banerjee Page 75

throws IOException{

BufferedReader in = new BufferedReader

(new InputStreamReader(System.in));

System.out.println("How many elements

you want to add to the array: ");

int n = Integer.parseInt(in.readLine());

String[] name = new String[n];

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

name[i] = in.readLine();

}

List list = Arrays.asList(name);

System.out.println();

for(String li: list){

String str = li;

System.out.print(str + " ");

}

}

}

Result:

The above code sample will produce the following result.

How many elements you want to add to the array:

red white green

red white green

Problem Description:

How to compare elements in a collection ?

Solution:

Following example compares the element of a collection by converting a string into a treeset using

Collection.min() and Collection.max() methods of Collection class.

import java.util.Collections;

import java.util.Set;

import java.util.TreeSet;

class MainClass {

public static void main(String[] args) {

String[] coins = { "Penny", "nickel", "dime",

"Quarter", "dollar" };

Set set = new TreeSet();

for (int i = 0; i < coins.length; i++)

set.add(coins[i]);

System.out.println(Collections.min(set));

System.out.println(Collections.min(set,

String.CASE_INSENSITIVE_ORDER));

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

System.out.print(-);

System.out.println(Collections.max(set));

System.out.println(Collections.max(set,

String.CASE_INSENSITIVE_ORDER));

}

Page 76: Java programming-examples

Saikat Banerjee Page 76

}

Result:

The above code sample will produce the following result.

Penny

dime

----------

nickle

Quarter

Problem Description:

How to change a collection to an array?

Solution:

Following example shows how to convert a collection to an array by using list.add() and list.toArray() method

of Java Util class.

import java.util.*;

public class CollectionToArray{

public static void main(String[] args){

List list = new ArrayList();

list.add("This ");

list.add("is ");

list.add("a ");

list.add("good ");

list.add("program.");

String[] s1 = list.toArray(new String[0]);

for(int i = 0; i < s1.length; ++i){

String contents = s1[i];

System.out.print(contents);

}

}

}

Result:

The above code sample will produce the following result.

This is a good program.

Problem Description:

How to print a collection?

Solution:

Following example how to print a collection by using tMap.keySet(),tMap.values() and tMap.firstKey()

methods of Java Util class .

Page 77: Java programming-examples

Saikat Banerjee Page 77

import java.util.*;

public class TreeExample{

public static void main(String[] args) {

System.out.println("Tree Map Example!\n");

TreeMap tMap = new TreeMap();

tMap.put(1, "Sunday");

tMap.put(2, "Monday");

tMap.put(3, "Tuesday");

tMap.put(4, "Wednesday");

tMap.put(5, "Thursday");

tMap.put(6, "Friday");

tMap.put(7, "Saturday");

System.out.println("Keys of tree map: "

+ tMap.keySet());

System.out.println("Values of tree map: "

+ tMap.values());

System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");

System.out.println("First key: " + tMap.firstKey()

+ " Value: "

+ tMap.get(tMap.firstKey()) + "\n");

System.out.println("Last key: " + tMap.lastKey()

+ " Value: "+ tMap.get(tMap.lastKey()) + "\n");

System.out.println("Removing first data: "

+ tMap.remove(tMap.firstKey()));

System.out.println("Now the tree map Keys: "

+ tMap.keySet());

System.out.println("Now the tree map contain: "

+ tMap.values() + "\n");

System.out.println("Removing last data: "

+ tMap.remove(tMap.lastKey()));

System.out.println("Now the tree map Keys: "

+ tMap.keySet());

System.out.println("Now the tree map contain: "

+ tMap.values());

}

}

Result:

The above code sample will produce the following result.

C:\collection>javac TreeExample.java

C:\collection>java TreeExample

Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]

Values of tree map: [Sunday, Monday, Tuesday, Wednesday,

Thursday, Friday, Saturday]

Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

Removing first data: Sunday

Now the tree map Keys: [2, 3, 4, 5, 6, 7]

Now the tree map contain: [Monday, Tuesday, Wednesday,

Thursday, Friday, Saturday]

Removing last data: Saturday

Page 78: Java programming-examples

Saikat Banerjee Page 78

Now the tree map Keys: [2, 3, 4, 5, 6]

Now the tree map contain: [Monday, Tuesday, Wednesday,

Thursday, Friday]

C:\collection>

Problem Description:

How to make a collection read-only ?

Solution:

Following example shows how to make a collection read-only by using Collections.unmodifiableList() method

of Collection class.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;

public class Main {

public static void main(String[] argv)

throws Exception {

List stuff = Arrays.asList(new String[] { "a", "b" });

List list = new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

list.set(0, "new value");

}

catch (UnsupportedOperationException e) {

}

Set set = new HashSet(stuff);

set = Collections.unmodifiableSet(set);

Map map = new HashMap();

map = Collections.unmodifiableMap(map);

System.out.println("Collection is read-only now.");

}

}

Result:

The above code sample will produce the following result.

Collection is read-only now.

Problem Description:

How to remove a specific element from a collection?

Page 79: Java programming-examples

Saikat Banerjee Page 79

Solution:

Following example demonstrates how to remove a certain element from a collection with the help of

collection.remove() method of Collection class.

import java.util.*;

public class CollectionTest {

public static void main(String [] args) {

System.out.println( "Collection Example!\n" );

int size;

HashSet collection = new HashSet ();

String str1 = "Yellow", str2 = "White", str3 =

"Green", str4 = "Blue";

Iterator iterator;

collection.add(str1);

collection.add(str2);

collection.add(str3);

collection.add(str4);

System.out.print("Collection data: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() + " ");

}

System.out.println();

collection.remove(str2);

System.out.println("After removing [" + str2 + "]\n");

System.out.print("Now collection data: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() + " ");

}

System.out.println();

size = collection.size();

System.out.println("Collection size: " + size + "\n");

}

}

Result:

The above code sample will produce the following result.

Collection Example!

Collection data: Blue White Green Yellow

After removing [White]

Now collection data: Blue Green Yellow

Collection size: 3

Problem Description:

How to reverse a collection ?

Page 80: Java programming-examples

Saikat Banerjee Page 80

Solution:

Following example demonstratres how to reverse a collection with the help of listIterator() and

Collection.reverse() methods of Collection and Listiterator class .

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.ListIterator;

class UtilDemo3 {

public static void main(String[] args) {

String[] coins = { "A", "B", "C", "D", "E" };

List l = new ArrayList();

for (int i = 0; i < coins.length; i++)

l.add(coins[i]);

ListIterator liter = l.listIterator();

System.out.println("Before reversal");

while (liter.hasNext())

System.out.println(liter.next());

Collections.reverse(l);

liter = l.listIterator();

System.out.println("After reversal");

while (liter.hasNext())

System.out.println(liter.next());

}

}

Result:

The above code sample will produce the following result.

Before reversal

A

B

C

D

E

After reversal

E

D

C

B

A

Problem Description:

How to shuffle the elements of a collection ?

Solution:

Following example how to shuffle the elements of a collection with the help of Collections.shuffle() method of

Collections class.

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

Page 81: Java programming-examples

Saikat Banerjee Page 81

public class Main {

public static void main(String[] argv)

throws Exception {

String[] alpha = { "A", "E", "I", "O", "U" };

List list = new ArrayList(alpha);

Collections.shuffle(list);

System.out.println("list");

}

}

Result:

The above code sample will produce the following result.

I

O

A

U

E

Problem Description:

How to get size of a collection?

Solution:

Following example shows how to get the size of a collection by the use of collection.add() to add new data and

collection.size() to get the size of the collection of Collections class.

import java.util.*;

public class CollectionTest {

public static void main(String [] args) {

System.out.println( "Collection Example!\n" );

int size;

HashSet collection = new HashSet ();

String str1 = "Yellow", str2 = "White", str3 =

"Green", str4 = "Blue";

Iterator iterator;

collection.add(str1);

collection.add(str2);

collection.add(str3);

collection.add(str4);

System.out.print("Collection data: ");

iterator = collection.iterator();

while (iterator.hasNext()){

System.out.print(iterator.next() + " ");

}

System.out.println();

size = collection.size();

if (collection.isEmpty()){

System.out.println("Collection is empty");

}

else{

System.out.println( "Collection size: " + size);

}

System.out.println();

Page 82: Java programming-examples

Saikat Banerjee Page 82

}

}

Result:

The above code sample will produce the following result.

Collection Example!

Collection data: Blue White Green Yellow

Collection size: 4

Problem Description:

How to iterate through elements of HashMap?

Solution:

Following example uses iterator Method of Collection class to iterate through the HashMap.

import java.util.*;

public class Main {

public static void main(String[] args) {

HashMap< String, String> hMap =

new HashMap< String, String>();

hMap.put("1", "1st");

hMap.put("2", "2nd");

hMap.put("3", "3rd");

Collection cl = hMap.values();

Iterator itr = cl.iterator();

while (itr.hasNext()) {

System.out.println(itr.next());

}

}

}

Result:

The above code sample will produce the following result.

3rd

2nd

1st

Problem Description:

How to use different types of Collections?

Solution:

Following example uses different types of collection classes and adds an element in those collections.

Page 83: Java programming-examples

Saikat Banerjee Page 83

import java.util.Map;

import java.util.Set;

import java.util.SortedMap;

import java.util.SortedSet;

import java.util.TreeMap;

import java.util.TreeSet;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.LinkedHashSet;

import java.util.LinkedList;

import java.util.List;

public class Main {

public static void main(String[] args) {

List lnkLst = new LinkedList();

lnkLst.add("element1");

lnkLst.add("element2");

lnkLst.add("element3");

lnkLst.add("element4");

displayAll(lnkLst);

List aryLst = new ArrayList();

aryLst.add("x");

aryLst.add("y");

aryLst.add("z");

aryLst.add("w");

displayAll(aryLst);

Set hashSet = new HashSet();

hashSet.add("set1");

hashSet.add("set2");

hashSet.add("set3");

hashSet.add("set4");

displayAll(hashSet);

SortedSet treeSet = new TreeSet();

treeSet.add("1");

treeSet.add("2");

treeSet.add("3");

treeSet.add("4");

displayAll(treeSet);

LinkedHashSet lnkHashset = new LinkedHashSet();

lnkHashset.add("one");

lnkHashset.add("two");

lnkHashset.add("three");

lnkHashset.add("four");

displayAll(lnkHashset);

Map ma p1 = new HashMap();

map1.put("key1", "J");

map1.put("key2", "K");

map1.put("key3", "L");

map1.put("key4", "M");

displayAll(map1.keySet());

displayAll(map1.values());

SortedMap map2 = new TreeMap();

map2.put("key1", "JJ");

map2.put("key2", "KK");

map2.put("key3", "LL");

map2.put("key4", "MM");

displayAll(map2.keySet());

displayAll(map2.values());

LinkedHashMap map3 = new LinkedHashMap();

Page 84: Java programming-examples

Saikat Banerjee Page 84

map3.put("key1", "JJJ");

map3.put("key2", "KKK");

map3.put("key3", "LLL");

map3.put("key4", "MMM");

displayAll(map3.keySet());

displayAll(map3.values());

}

static void displayAll(Collection col) {

Iterator itr = col.iterator();

while (itr.hasNext()) {

String str = (String) itr.next();

System.out.print(str + " ");

}

System.out.println();

}

}

Result:

The above code sample will produce the following result.

element1 element2 element3 element4

x y z w

set1 set2 set3 set4

1 2 3 4

one two three four

key4 key3 key2 key1

M L K J

key1 key2 key3 key4

JJ KK LL MM

key1 key2 key3 key4

JJJ KKK LLL MMM

Problem Description:

How to use enumeration to display contents of HashTable?

Solution:

Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the

contents of the HashTable.

import java.util.Enumeration;

import java.util.Hashtable;

public class Main {

public static void main(String[] args) {

Hashtable ht = new Hashtable();

ht.put("1", "One");

ht.put("2", "Two");

ht.put("3", "Three");

Enumeration e = ht.elements();

While (e.hasMoreElements()){

System.out.println(e.nextElement());

}

}

}

Page 85: Java programming-examples

Saikat Banerjee Page 85

Result:

The above code sample will produce the following result.

Three

Two

One

Problem Description:

How to set view of Keys from Java Hashtable?

Solution:

Following example uses keys() method to get Enumeration of Keys of the Hashtable.

import java.util.Enumeration;

import java.util.Hashtable;

public class Main {

public static void main(String[] args) {

Hashtable ht = new Hashtable();

ht.put("1", "One");

ht.put("2", "Two");

ht.put("3", "Three");

Enumeration e = ht.keys();

while (e.hasMoreElements()){

System.out.println(e.nextElement());

}

}

}

Result:

The above code sample will produce the following result.

3

2

1

Problem Description:

How to find min & max of a List?

Solution:

Following example uses min & max Methods to find minimum & maximum of the List.

import java.util.*;

public class Main {

public static void main(String[] args) {

List list = Arrays.asList("one Two three Four five six

Page 86: Java programming-examples

Saikat Banerjee Page 86

one three Four".split(" "));

System.out.println(list);

System.out.println("max: " + Collections.max(list));

System.out.println("min: " + Collections.min(list));

}

}

Result:

The above code sample will produce the following result.

[one, Two, three, Four, five, six, one, three, Four]

max: three

min: Four

Problem Description:

How to find a sublist in a List?

Solution:

Following example uses indexOfSubList() & lastIndexOfSubList() to check whether the sublist is there in the

list or not & to find the last occurance of the sublist in the list.

import java.util.*;

public class Main {

public static void main(String[] args) {

List list = Arrays.asList("one Two three Four five

six one three Four".split(" "));

System.out.println("List :"+list);

List sublist = Arrays.asList("three Four".split(" "));

System.out.println("SubList :"+sublist);

System.out.println("indexOfSubList: "

+ Collections.indexOfSubList(list, sublist));

System.out.println("lastIndexOfSubList: "

+ Collections.lastIndexOfSubList(list, sublist));

}

}

Result:

The above code sample will produce the following result.

List :[one, Two, three, Four, five, six, one, three, Four]

SubList :[three, Four]

indexOfSubList: 2

lastIndexOfSubList: 7

Problem Description:

How to replace an element in a list

Page 87: Java programming-examples

Saikat Banerjee Page 87

Solution:

Following example uses replaceAll() method to replace all the occurance of an element with a different element

in a list.

import java.util.*;

public class Main {

public static void main(String[] args) {

List list = Arrays.asList("one Two three Four five six

one three Four".split(" "));

System.out.println("List :"+list);

Collections.replaceAll(list, "one", "hundread");

System.out.println("replaceAll: " + list);

}

}

Result:

The above code sample will produce the following result.

List :[one, Two, three, Four, five, six, one, three, Four]

replaceAll: [hundread, Two, three, Four, five, six,

hundread, three, Four]

Problem Description:

How to rotate elements of the List?

Solution:

Following example uses rotate() method to rotate elements of the list depending on the 2nd argument of the

method.

import java.util.*;

public class Main {

public static void main(String[] args) {

List list = Arrays.asList("one Two three Four five

six".split(" "));

System.out.println("List :"+list);

Collections.rotate(list, 3);

System.out.println("rotate: " + list);

}

}

Result:

The above code sample will produce the following result.

List :[one, Two, three, Four, five, six]

rotate: [Four, five, six, one, Two, three]

Page 88: Java programming-examples

Saikat Banerjee Page 88

Java Network - Programming Examples

Learn how to modify networks in Java programming. Here are most commonly used examples:

1. How to change the host name to its specific IP address?

2. How to get connected with web server?

3. How to check a file is modified at a server or not?

4. How to create a multithreaded server?

5. How to get the file size from the server?

6. How to make a socket displaying message to a single client?

7. How to make a srever to allow the connection to the socket 6123?

8. How to get the parts of an URL?

9. How to get the date of URL connection?

10. How to read and download a webpage?

11. How to find hostname from IP Address?

12. How to determine IP Address & hostname of Local Computer?

13. How to check whether a port is being used or not?

14. How to find proxy settings of a System?

15. How to create a socket at a specific port?

Problem Description:

How to split a string into a number of substrings ?

Solution:

Following example shows how to change the host name to its specific IP address with the help of

InetAddress.getByName() method of net.InetAddress class.

import java.net.InetAddress;

import java.net.UnknownHostException;

public class GetIP {

public static void main(String[] args) {

InetAddress address = null;

try {

address = InetAddress.getByName

("www.javatutorial.com");

}

catch (UnknownHostException e) {

System.exit(2);

}

System.out.println(address.getHostName() + "="

+ address.getHostAddress());

System.exit(0);

}

}

Result:

The above code sample will produce the following result.

Page 89: Java programming-examples

Saikat Banerjee Page 89

http://www.sbdsisaikat.com = 123.14.2.35

Problem Description:

How to get connected with web server?

Solution:

Following example demonstrates how to get connected with web server by using sock.getInetAddress() method

of net.Socket class.

import java.net.InetAddress;

import java.net.Socket;

public class WebPing {

public static void main(String[] args) {

try {

InetAddress addr;

Socket sock = new Socket("www.javatutorial.com", 80);

addr = sock.getInetAddress();

System.out.println("Connected to " + addr);

sock.close();

} catch (java.io.IOException e) {

System.out.println("Can't connect to " + args[0]);

System.out.println(e);

}

}

}

Result:

The above code sample will produce the following result.

Connected to http://www.sbdsisaikat.com/102.32.56.14

Problem Description:

How to check a file is modified at a server or not?

Solution:

Following example shows How to check a file is modified at a server or not.

import java.net.URL;

import java.net.URLConnection;

public class Main {

public static void main(String[] argv)

throws Exception {

URL u = new URL("http://127.0.0.1/java.bmp");

URLConnection uc = u.openConnection();

uc.setUseCaches(false);

long timestamp = uc.getLastModified();

Page 90: Java programming-examples

Saikat Banerjee Page 90

System.out.println("The last modification time

of java.bmp is :"+timestamp);

}

}

Result:

The above code sample will produce the following result.

The last modification time of java.bmp is :24 May 2009 12:14:50

Problem Description:

How to create a multithreaded server?

Solution:

Following example demonstrates how to create a multithreaded server by using ssock.accept() method of

Socket class and MultiThreadServer(socketname) method of ServerSocket class.

import java.io.IOException;

import java.io.PrintStream;

import java.net.ServerSocket;

import java.net.Socket;

public class MultiThreadServer implements Runnable {

Socket csocket;

MultiThreadServer(Socket csocket) {

this.csocket = csocket;

}

public static void main(String args[])

throws Exception {

ServerSocket ssock = new ServerSocket(1234);

System.out.println("Listening");

while (true) {

Socket sock = ssock.accept();

System.out.println("Connected");

new Thread(new MultiThreadServer(sock)).start();

}

}

public void run() {

try {

PrintStream pstream = new PrintStream

(csocket.getOutputStream());

for (int i = 100; i >= 0; i--) {

pstream.println(i +

" bottles of beer on the wall");

}

pstream.close();

csocket.close();

}

catch (IOException e) {

System.out.println(e);

}

}

}

Page 91: Java programming-examples

Saikat Banerjee Page 91

Result:

The above code sample will produce the following result.

Listening

Connected

Problem Description:

How to get the file size from the server?

Solution:

Following example demonstrates How to get the file size from the server.

import java.net.URL;

import java.net.URLConnection;

public class Main {

public static void main(String[] argv)

throws Exception {

int size;

URL url = new URL("http://www.server.com");

URLConnection conn = url.openConnection();

size = conn.getContentLength();

if (size < 0)

System.out.println("Could not determine file size.");

else

System.out.println("The size of the file is = "

+size + "bytes");

conn.getInputStream().close();

}

}

Result:

The above code sample will produce the following result.

The size of The file is = 16384 bytes

Problem Description:

How to make a socket displaying message to a single client?

Solution:

Following example demonstrates how to make a socket displaying message to a single client with the help of

ssock.accept() method of Socket class.

import java.io.PrintStream;

import java.net.ServerSocket;

import java.net.Socket;

Page 92: Java programming-examples

Saikat Banerjee Page 92

public class BeerServer {

public static void main(String args[])

throws Exception {

ServerSocket ssock = new ServerSocket(1234);

System.out.println("Listening");

Socket sock = ssock.accept();

ssock.close();

PrintStream ps = new PrintStream

(sock.getOutputStream());

for (int i = 10; i >= 0; i--) {

ps.println(i +

" from Java Source and Support.");

}

ps.close();

sock.close();

}

}

Result:

The above code sample will produce the following result.

Listening

10 from Java Source and Support

9 from Java Source and Support

8 from Java Source and Support

7 from Java Source and Support

6 from Java Source and Support

5 from Java Source and Support

4 from Java Source and Support

3 from Java Source and Support

2 from Java Source and Support

1 from Java Source and Support

0 from Java Source and Support

Problem Description:

How to make a srever to allow the connection to the socket 6123?

Solution:

Following example shows how to make a srever to allow the connection to the socket 6123 by using

server.accept() method of ServerSocket class andb sock.getInetAddress() method of Socket class.

import java.io.IOException;

import java.net.InetAddress;

import java.net.ServerSocket;

import java.net.Socket;

public class SocketDemo {

public static void main(String[] args) {

try {

ServerSocket server = new ServerSocket(6123);

while (true) {

System.out.println("Listening");

Socket sock = server.accept();

InetAddress addr = sock.getInetAddress();

System.out.println("Connection made to "

Page 93: Java programming-examples

Saikat Banerjee Page 93

+ addr.getHostName()

+ " (" + addr.getHostAddress() + ")");

pause(5000);

sock.close();

}

}

catch (IOException e) {

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

}

}

private static void pause(int ms) {

try {

Thread.sleep(ms);

}

catch (InterruptedException e) {

}

}

}

Result:

The above code sample will produce the following result.

Listening

Terminate batch job (Y/N)? n

Connection made to 112.63.21.45

Problem Description:

How to get the parts of an URL?

Solution:

Following example shows how to get the parts of an URL with the help of url.getProtocol() ,url.getFile()

method etc. of net.URL class.

import java.net.URL;

public class Main {

public static void main(String[] args)

throws Exception {

URL url = new URL(args[0]);

System.out.println("URL is " + url.toString());

System.out.println("protocol is "

+ url.getProtocol());

System.out.println("file name is " + url.getFile());

System.out.println("host is " + url.getHost());

System.out.println("path is " + url.getPath());

System.out.println("port is " + url.getPort());

System.out.println("default port is "

+ url.getDefaultPort());

}

}

Result:

The above code sample will produce the following result.

Page 94: Java programming-examples

Saikat Banerjee Page 94

URL is http://www.server.com

protocol is TCP/IP

file name is java_program.txt

host is 122.45.2.36

path is

port is 2

default port is 1

Problem Description:

How to get the date of URL connection?

Solution:

Following example demonstrates how to get the date of URL connection by using httpCon.getDate() method of

HttpURLConnection class.

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Date;

public class Main{

public static void main(String args[])

throws Exception {

URL url = new URL("http://www.google.com");

HttpURLConnection httpCon =

(HttpURLConnection) url.openConnection();

long date = httpCon.getDate();

if (date == 0)

System.out.println("No date information.");

else

System.out.println("Date: " + new Date(date));

}

}

Result:

The above code sample will produce the following result.

Date:05.26.2009

Problem Description:

How to read and download a webpage?

Solution:

Following example shows how to read and download a webpage URL() constructer of net.URL class.

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.InputStreamReader;

import java.net.URL;

Page 95: Java programming-examples

Saikat Banerjee Page 95

public class Main {

public static void main(String[] args)

throws Exception {

URL url = new URL("http://www.google.com");

BufferedReader reader = new BufferedReader

(new InputStreamReader(url.openStream()));

BufferedWriter writer = new BufferedWriter

(new FileWriter("data.html"));

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

writer.write(line);

writer.newLine();

}

reader.close();

writer.close();

}

}

Result:

The above code sample will produce the following result.

Welcome to Java Tutorial

Here we have plenty of examples for you!

Come and Explore Java!

Problem Description:

How to find hostname from IP Address?

Solution:

Following example shows how to change the host name to its specific IP address with the help of

InetAddress.getByName() method of net.InetAddress class.

import java.net.InetAddress;

public class Main {

public static void main(String[] argv) throws Exception {

InetAddress addr = InetAddress.getByName("74.125.67.100");

System.out.println("Host name is: "+addr.getHostName());

System.out.println("Ip address is: "+ addr.getHostAddress());

}

}

Result:

The above code sample will produce the following result.

http://www.sbdsisaikat.com = 123.14.2.35

Page 96: Java programming-examples

Saikat Banerjee Page 96

Problem Description:

How to determine IP Address & hostname of Local Computer?

Solution:

Following example shows how to find local IP Address & Hostname of the system using getLocalAddress()

method of InetAddress class.

import java.net.InetAddress;

public class Main {

public static void main(String[] args)

throws Exception {

InetAddress addr = InetAddress.getLocalHost();

System.out.println("Local HostAddress:

"+addr.getHostAddress());

String hostname = addr.getHostName();

System.out.println("Local host name: "+hostname);

}

}

Result:

The above code sample will produce the following result.

Local HostAddress: 192.168.1.4

Local host name: saikat

Problem Description:

How to check whether a port is being used or not?

Solution:

Following example shows how to check whether any port is being used as a server or not by creating a socket

object.

import java.net.*;

import java.io.*;

public class Main {

public static void main(String[] args) {

Socket Skt;

String host = "localhost";

if (args.length > 0) {

host = args[0];

}

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

try {

System.out.println("Looking for "+ i);

Skt = new Socket(host, i);

System.out.println("There is a server on port "

+ i + " of " + host);

Page 97: Java programming-examples

Saikat Banerjee Page 97

}

catch (UnknownHostException e) {

System.out.println("Exception occured"+ e);

break;

}

catch (IOException e) {

}

}

}

}

Result:

The above code sample will produce the following result.

Looking for 0

Looking for 1

Looking for 2

Looking for 3

Looking for 4. . .

Problem Description:

How to find proxy settings of a System?

Solution:

Following example shows how to find proxy settings & create a proxy connection on a system using put

method of systemSetting & getResponse method of HttpURLConnection class.

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.Properties;

import java.net.InetSocketAddress;

import java.net.Proxy;

import java.net.ProxySelector;

import java.net.URI;

public class Main{

public static void main(String s[])

throws Exception{

try {

Properties systemSettings =

System.getProperties();

systemSettings.put("proxySet", "true");

systemSettings.put("http.proxyHost",

"proxy.mycompany1.local");

systemSettings.put("http.proxyPort", "80");

URL u = new URL("http://www.google.com");

HttpURLConnection con = (HttpURLConnection)

u.openConnection();

System.out.println(con.getResponseCode() +

" : " + con.getResponseMessage());

System.out.println(con.getResponseCode() ==

HttpURLConnection.HTTP_OK);

}

catch (Exception e) {

e.printStackTrace();

Page 98: Java programming-examples

Saikat Banerjee Page 98

System.out.println(false);

}

System.setProperty("java.net.useSystemProxies",

"true");

Proxy proxy = (Proxy) ProxySelector.getDefault().

select(new URI("http://www.yahoo.com/")).iterator().

next();;

System.out.println("proxy hostname : " + proxy.type());

InetSocketAddress addr = (InetSocketAddress)

proxy.address();

if (addr == null) {

System.out.println("No Proxy");

}

else {

System.out.println("proxy hostname : "

+ addr.getHostName());

System.out.println("proxy port : "

+ addr.getPort());

}

}

}

Result:

The above code sample will produce the following result.

200 : OK

true

proxy hostname : HTTP

proxy hostname : proxy.mycompany1.local

proxy port : 80

Problem Description:

How to create a socket at a specific port?

Solution:

Following example shows how to sing Socket constructor of Socket class.And also get Socket details using

getLocalPort() getLocalAddress , getInetAddress() & getPort() methods.

import java.io.IOException;

import java.net.InetAddress;

import java.net.Socket;

import java.net.SocketException;

import java.net.UnknownHostException;

public class Main {

public static void main(String[] args) {

try {

InetAddress addr =

InetAddress.getByName("74.125.67.100");

Socket theSocket = new Socket(addr, 80);

System.out.println("Connected to "

+ theSocket.getInetAddress()

+ " on port " + theSocket.getPort() + " from port "

+ theSocket.getLocalPort() + " of "

+ theSocket.getLocalAddress());

Page 99: Java programming-examples

Saikat Banerjee Page 99

}

catch (UnknownHostException e) {

System.err.println("I can't find " + e );

}

catch (SocketException e) {

System.err.println("Could not connect to " +e );

}

catch (IOException e) {

System.err.println(e);

}

}

}

Result:

The above code sample will produce the following result.

Connected to /74.125.67.100 on port 80 from port

2857 of /192.168.1.4

Java Threading - Programming Examples

Learn how to use threads in Java programming. Here are most commonly used examples:

1. How to check a thread is alive or not?

2. How to check a thread has stop or not?

3. How to solve deadlock using thread?

4. How to get the priorities of running threads?

5. How to monitor a thread's status?

6. How to get the name of a running thread?

7. How to solve the producer consumer problem using thread?

8. How to set the priority of a thread?

9. How to stop a thread?

10. How to suspend a thread for a while?

11. How to get the Id of the running thread?

12. How to check priority level of a thread?

13. How to display all running Thread?

14. How to display thread status?

15. How to interrupt a running Thread?

Problem Description:

How to check a thread is alive or not?

Solution:

Following example demonstrates how to check a thread is alive or not by extending Threda class and using

currentThread() method.

public class TwoThreadAlive extends Thread {

public void run() {

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

Page 100: Java programming-examples

Saikat Banerjee Page 100

printMsg();

}

}

public void printMsg() {

Thread t = Thread.currentThread();

String name = t.getName();

System.out.println("name=" + name);

}

public static void main(String[] args) {

TwoThreadAlive tt = new TwoThreadAlive();

tt.setName("Thread");

System.out.println("before start(),

tt.isAlive()=" + tt.isAlive());

tt.start();

System.out.println("just after start(),

tt.isAlive()=" + tt.isAlive());

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

tt.printMsg();

}

System.out.println("The end of main(),

tt.isAlive()=" + tt.isAlive());

}

}

Result:

The above code sample will produce the following result.

before start(),tt.isAlive()=false

just after start(), tt.isAlive()=true

name=main

name=main

name=main

name=main

name=main

name=Thread

name=Thread

name=Thread

name=Thread

name=Thread

name=Thread

name=Thread

name=main

name=main

The end of main().tt.isAlive()=false

Problem Description:

How to check a thread has stop or not?

Solution:

Following example demonstrates how to check a thread has stop or not by checking with isAlive() method.

public class Main {

public static void main(String[] argv)

throws Exception {

Page 101: Java programming-examples

Saikat Banerjee Page 101

Thread thread = new MyThread();

thread.start();

if (thread.isAlive()) {

System.out.println("Thread has not finished");

}

else {

System.out.println("Finished");

}

long delayMillis = 5000;

thread.join(delayMillis);

if (thread.isAlive()) {

System.out.println("thread has not finished");

}

else {

System.out.println("Finished");

}

thread.join();

}

}

class MyThread extends Thread {

boolean stop = false;

public void run() {

while (true) {

if (stop) {

return;

}

}

}

}

Result:

The above code sample will produce the following result.

Thread has not finished

Finished

Problem Description:

How to solve deadlock using thread?

Solution:

Following example demonstrates how to solve deadlock using the concept of thread.

import java.util.*;

import java.util.concurrent.*;

import java.util.concurrent.locks.*;

public class DeadlockDetectingLock extends ReentrantLock {

private static List deadlockLocksRegistry

= new ArrayList();

private static synchronized void

registerLock(DeadlockDetectingLock ddl) {

if (!deadlockLocksRegistry.contains(ddl))

deadlockLocksRegistry.add(ddl);

}

private static synchronized void

Page 102: Java programming-examples

Saikat Banerjee Page 102

unregisterLock(DeadlockDetectingLock ddl) {

if (deadlockLocksRegistry.contains(ddl))

deadlockLocksRegistry.remove(ddl);

}

private List hardwaitingThreads = new ArrayList();

private static synchronized void

markAsHardwait(List l, Thread t) {

if (!l.contains(t))

l.add(t);

}

private static synchronized void

freeIfHardwait(List l, Thread t) {

if (l.contains(t))

l.remove(t);

}

private static Iterator getAllLocksOwned(Thread t) {

DeadlockDetectingLock current;

ArrayList results = new ArrayList();

Iterator itr = deadlockLocksRegistry.iterator();

while (itr.hasNext()) {

current = (DeadlockDetectingLock) itr.next();

if (current.getOwner() == t)

results.add(current);

}

return results.iterator();

}

private static Iterator

getAllThreadsHardwaiting(DeadlockDetectingLock l) {

return l.hardwaitingThreads.iterator();

}

private static synchronized boolean canThreadWaitOnLock

(Thread t,DeadlockDetectingLock l) {

Iterator locksOwned = getAllLocksOwned(t);

while (locksOwned.hasNext()) {

DeadlockDetectingLock current

= (DeadlockDetectingLock) locksOwned.next();

if (current == l)

return false;

Iterator waitingThreads

= getAllThreadsHardwaiting(current);

while (waitingThreads.hasNext()) {

Thread otherthread = (Thread) waitingThreads.next();

if (!canThreadWaitOnLock(otherthread, l)) {

return false;

}

}

}

return true;

}

public DeadlockDetectingLock() {

this(false, false);

}

public DeadlockDetectingLock(boolean fair) {

this(fair, false);

}

private boolean debugging;

public DeadlockDetectingLock(boolean fair, boolean debug) {

Page 103: Java programming-examples

Saikat Banerjee Page 103

super(fair);

debugging = debug;

registerLock(this);

}

public void lock() {

if (isHeldByCurrentThread()) {

if (debugging)

System.out.println("Already Own Lock");

super.lock();

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

return;

}

markAsHardwait(hardwaitingThreads,

Thread.currentThread());

if (canThreadWaitOnLock(Thread.currentThread(), this)) {

if (debugging)

System.out.println("Waiting For Lock");

super.lock();

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

if (debugging)

System.out.println("Got New Lock");

}

else {

throw new DeadlockDetectedException("DEADLOCK");

}

}

public void lockInterruptibly() throws InterruptedException {

lock();

}

locks.

public class DeadlockDetectingCondition implements Condition {

Condition embedded;

protected DeadlockDetectingCondition(ReentrantLock lock,

Condition embedded) {

this.embedded = embedded;

}

Public void await() throws InterruptedException {

try {

markAsHardwait(hardwaitingThreads,

Thread.currentThread());

embedded.await();

}

finally {

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

}

}

public void awaitUninterruptibly() {

markAsHardwait(hardwaitingThreads,

Thread.currentThread());

embedded.awaitUninterruptibly();

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

}

public long awaitNanos(long nanosTimeout)

throws InterruptedException {

try {

Page 104: Java programming-examples

Saikat Banerjee Page 104

markAsHardwait(hardwaitingThreads,

Thread.currentThread());

return embedded.awaitNanos(nanosTimeout);

}

finally {

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

}

}

public boolean await(long time, TimeUnit unit)

throws InterruptedException {

try {

markAsHardwait(hardwaitingThreads,

Thread.currentThread());

return embedded.await(time, unit);

}

finally {

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

}

}

public boolean awaitUntil(Date deadline)

throws InterruptedException {

try {

markAsHardwait(hardwaitingThreads,

Thread.currentThread());

return embedded.awaitUntil(deadline);

}

finally {

freeIfHardwait(hardwaitingThreads,

Thread.currentThread());

}

}

public void signal() {

embedded.signal();

}

public void signalAll() {

embedded.signalAll();

}

}

public Condition newCondition() {

return new DeadlockDetectingCondition(this,

super.newCondition());

}

private static Lock a = new DeadlockDetectingLock(false, true);

private static Lock b = new DeadlockDetectingLock(false, true);

private static Lock c = new DeadlockDetectingLock(false, true);

private static Condition wa = a.newCondition();

private static Condition wb = b.newCondition();

private static Condition wc = c.newCondition();

private static void delaySeconds(int seconds) {

try {

Thread.sleep(seconds * 1000);

}

catch (InterruptedException ex) {

}

}

private static void awaitSeconds(Condition c, int seconds) {

Page 105: Java programming-examples

Saikat Banerjee Page 105

try {

c.await(seconds, TimeUnit.SECONDS);

}

catch (InterruptedException ex) {

}

}

private static void testOne() {

new Thread(new Runnable() {

public void run() {

System.out.println("thread one grab a");

a.lock();

delaySeconds(2);

System.out.println("thread one grab b");

b.lock();

delaySeconds(2);

a.unlock();

b.unlock();

}

}).start();

new Thread(new Runnable() {

public void run() {

System.out.println("thread two grab b");

b.lock();

delaySeconds(2);

System.out.println("thread two grab a");

a.lock();

delaySeconds(2);

a.unlock();

b.unlock();

}

}).start();

}

private static void testTwo() {

new Thread(new Runnable() {

public void run() {

System.out.println("thread one grab a");

a.lock();

delaySeconds(2) ;

System.out.println("thread one grab b");

b.lock();

delaySeconds(10);

a.unlock();

b.unlock();

}

}).start();

new Thread(new Runnable() {

public void run() {

System.out.println("thread two grab b");

b.lock();

delaySeconds(2);

System.out.println("thread two grab c");

c.lock();

delaySeconds(10);

b.unlock();

c.unlock();

}

}).start();

new Thread(new Runnable() {

public void run() {

System.out.println("thread three grab c");

c.lock();

delaySeconds(4);

System.out.println("thread three grab a");

Page 106: Java programming-examples

Saikat Banerjee Page 106

a.lock();

delaySeconds(10);

c.unlock();

a.unlock();

}

}).start();

}

private static void testThree() {

new Thread(new Runnable() {

public void run() {

System.out.println("thread one grab b");

b.lock();

System.out.println("thread one grab a");

a.lock();

delaySeconds(2);

System.out.println("thread one waits on b");

awaitSeconds(wb, 10);

a.unlock();

b.unlock();

}

}).start();

new Thread(new Runnable() {

public void run() {

delaySeconds(1);

System.out.println("thread two grab b");

b.lock();

System.out.println("thread two grab a");

a.lock();

delaySeconds(10);

b.unlock();

c.unlock();

}

}).start();

}

public static void main(String args[]) {

int test = 1;

if (args.length > 0)

test = Integer.parseInt(args[0]);

switch (test) {

case 1:

testOne();

break;

case 2:

testTwo();

break;

case 3:

testThree();

break;

default:

System.err.println("usage: java

DeadlockDetectingLock [ test# ]");

}

delaySeconds(60);

System.out.println("--- End Program ---");

System.exit(0);

}

}

class DeadlockDetectedException extends RuntimeException {

public DeadlockDetectedException(String s) {

super(s);

}

}

Page 107: Java programming-examples

Saikat Banerjee Page 107

Result:

The above code sample will produce the following result.

thread one grab a

Waiting For Lock

Got New Lock

thread two grab b

Waiting For Lock

Got New Lock

thread one grab b

Waiting For Lock

thread two grab a

Exception in thread "Thread-1"

DeadlockDetectedException:DEADLOCK

at DeadlockDetectingLock.

lock(DealockDetectingLock.java:152)

at java.lang.Thread.run(Thread.java:595)

Problem Description:

How to get the priorities of running threads?

Solution:

Following example prints the priority of the running threads by using setPriority() method .

public class SimplePriorities extends Thread {

private int countDown = 5;

private volatile double d = 0;

public SimplePriorities(int priority) {

setPriority(priority);

start();

}

public String toString() {

return super.toString() + ": " + countDown;

}

public void run() {

while(true) {

for(int i = 1; i < 100000; i++)

d = d + (Math.PI + Math.E) / (double)i;

System.out.println(this);

if(--countDown == 0) return;

}

}

public static void main(String[] args) {

new SimplePriorities(Thread.MAX_PRIORITY);

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

new SimplePriorities(Thread.MIN_PRIORITY);

}

}

Result:

The above code sample will produce the following result.

Thread[Thread-0,10,main]: 5

Page 108: Java programming-examples

Saikat Banerjee Page 108

Thread[Thread-0,10,main]: 4

Thread[Thread-0,10,main]: 3

Thread[Thread-0,10,main]: 2

Thread[Thread-0,10,main]: 1

Thread[Thread-1,1,main]: 5

Thread[Thread-1,1,main]: 4

Thread[Thread-1,1,main]: 3

Thread[Thread-1,1,main]: 2

Thread[Thread-1,1,main]: 1

Thread[Thread-2,1,main]: 5

Thread[Thread-2,1,main]: 4

Thread[Thread-2,1,main]: 3

Thread[Thread-2,1,main]: 2

Thread[Thread-2,1,main]: 1

.

.

.

Problem Description:

How to monitor a thread's status?

Solution:

Following example demonstrates how to monitor a thread's status by extending Thread class and using

currentThread.getName() method.

class MyThread extends Thread{

boolean waiting= true;

boolean ready= false;

MyThread() {

}

public void run() {

String thrdName = Thread.currentThread().getName();

System.out.println(thrdName + " starting.");

while(waiting)

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

System.out.println("waiting...");

startWait();

try {

Thread.sleep(1000);

}

catch(Exception exc) {

System.out.println(thrdName + " interrupted.");

}

System.out.println(thrdName + " terminating.");

}

synchronized void startWait() {

try {

while(!ready) wait();

}

catch(InterruptedException exc) {

System.out.println("wait() interrupted");

}

}

synchronized void notice() {

ready = true;

notify();

}

}

public class Main {

Page 109: Java programming-examples

Saikat Banerjee Page 109

public static void main(String args[])

throws Exception{

MyThread thrd = new MyThread();

thrd.setName("MyThread #1");

showThreadStatus(thrd);

thrd.start();

Thread.sleep(50);

showThreadStatus(thrd);

thrd.waiting = false;

Thread.sleep(50);

showThreadStatus(thrd);

thrd.notice();

Thread.sleep(50);

showThreadStatus(thrd);

while(thrd.isAlive())

System.out.println("alive");

showThreadStatus(thrd);

}

static void showThreadStatus(Thread thrd) {

System.out.println(thrd.getName()+"

Alive:="+thrd.isAlive()+"

State:=" + thrd.getState() );

}

}

Result:

The above code sample will produce the following result.

main Alive=true State:=running

Problem Description:

How to get the name of a running thread?

Solution:

Following example shows How to get the name of a running thread .

public class TwoThreadGetName extends Thread {

public void run() {

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

printMsg();

}

}

public void printMsg() {

Thread t = Thread.currentThread();

String name = t.getName();

System.out.println("name=" + name);

}

public static void main(String[] args) {

TwoThreadGetName tt = new TwoThreadGetName();

tt.start();

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

tt.printMsg();

}

}

}

Page 110: Java programming-examples

Saikat Banerjee Page 110

Result:

The above code sample will produce the following result.

name=main

name=main

name=main

name=main

name=main

name=thread

name=thread

name=thread

name=thread

Problem Description:

How to solve the producer consumer problem using thread?

Solution:

Following example demonstrates how to solve the producer consumer problem using thread.

public class ProducerConsumerTest {

public static void main(String[] args) {

CubbyHole c = new CubbyHole();

Producer p1 = new Producer(c, 1);

Consumer c1 = new Consumer(c, 1);

p1.start();

c1.start();

}

}

class CubbyHole {

private int contents;

private boolean available = false;

public synchronized int get() {

while (available == false) {

try {

wait();

}

catch (InterruptedException e) {

}

}

available = false;

notifyAll();

return contents;

}

public synchronized void put(int value) {

while (available == true) {

try {

wait();

}

catch (InterruptedException e) {

}

}

contents = value;

available = true;

notifyAll();

}

}

Page 111: Java programming-examples

Saikat Banerjee Page 111

class Consumer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Consumer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

}

public void run() {

int value = 0;

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

value = cubbyhole.get();

System.out.println("Consumer #"

+ this.number

+ " got: " + value);

}

}

}

class Producer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Producer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

}

public void run() {

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

cubbyhole.put(i);

System.out.println("Producer #" + this.number

+ " put: " + i);

try {

sleep((int)(Math.random() * 100));

} catch (InterruptedException e) { }

}

}

}

Result:

The above code sample will produce the following result.

Producer #1 put: 0

Consumer #1 got: 0

Producer #1 put: 1

Consumer #1 got: 1

Producer #1 put: 2

Consumer #1 got: 2

Producer #1 put: 3

Consumer #1 got: 3

Producer #1 put: 4

Consumer #1 got: 4

Producer #1 put: 5

Consumer #1 got: 5

Producer #1 put: 6

Consumer #1 got: 6

Producer #1 put: 7

Consumer #1 got: 7

Producer #1 put: 8

Consumer #1 got: 8

Producer #1 put: 9

Page 112: Java programming-examples

Saikat Banerjee Page 112

Consumer #1 got: 9

Problem Description:

How to set the priority of a thread?

Solution:

Following example how to set the priority of a thread with the help of.

public class Main {

public static void main(String[] args)

throws Exception {

Thread thread1 = new Thread(new TestThread(1));

Thread thread2 = new Thread(new TestThread(2));

thread1.setPriority(Thread.MAX_PRIORITY);

thread2.setPriority(Thread.MIN_PRIORITY);

thread1.start();

thread2.start();

thread1.join();

thread2.join();

System.out.println("The priority has been set.");

}

}

Result:

The above code sample will produce the following result.

The priority has been set.

Problem Description:

How to stop a thread for a while?

Solution:

Following example demonstates how to stop a thread by creating an user defined method run() taking the help

of Timer classes' methods.

import java.util.Timer;

import java.util.TimerTask;

class CanStop extends Thread {

private volatile boolean stop = false;

private int counter = 0;

public void run() {

while (!stop && counter < 10000) {

System.out.println(counter++);

}

if (stop)

System.out.println("Detected stop");

}

public void requestStop() {

stop = true;

Page 113: Java programming-examples

Saikat Banerjee Page 113

}

}

public class Stopping {

public static void main(String[] args) {

final CanStop stoppable = new CanStop();

stoppable.start();

new Timer(true).schedule(new TimerTask() {

public void run() {

System.out.println("Requesting stop");

stoppable.requestStop();

}

}, 350);

}

}

Result:

The above code sample will produce the following result.

Detected stop

Problem Description:

How to suspend a thread for a while?

Solution:

Following example shows how to suspend a thread for a while by creating sleepingThread() method.

public class SleepingThread extends Thread {

private int countDown = 5;

private static int threadCount = 0;

public SleepingThread() {

super("" + ++threadCount);

start();

}

public String toString() {

return "#" + getName() + ": " + countDown;

}

public void run() {

while (true) {

System.out.println(this);

if (--countDown == 0)

return;

try {

sleep(100);

}

catch (InterruptedException e) {

throw new RuntimeException(e);

}

}

}

public static void main(String[] args)

throws InterruptedException {

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

new SleepingThread().join();

System.out.println("The thread has been suspened.");

}

}

Page 114: Java programming-examples

Saikat Banerjee Page 114

Result:

The above code sample will produce the following result.

The thread has been suspened.

Problem Description:

How to get the Id of the running thread?

Solution:

Following example demonstrates how to get the Id of a running thread using getThreadId() method.

public class Main extends Object implements Runnable {

private ThreadID var;

public Main(ThreadID v) {

this.var = v;

}

public void run() {

try {

print("var getThreadID =" + var.getThreadID());

Thread.sleep(2000);

print("var getThreadID =" + var.getThreadID());

} catch (InterruptedException x) {

}

}

private static void print(String msg) {

String name = Thread.currentThread().getName();

System.out.println(name + ": " + msg);

}

public static void main(String[] args) {

ThreadID tid = new ThreadID();

Main shared = new Main(tid);

try {

Thread threadA = new Thread(shared, "threadA");

threadA.start();

Thread.sleep(500);

Thread threadB = new Thread(shared, "threadB");

threadB.start();

Thread.sleep(500);

Thread threadC = new Thread(shared, "threadC");

threadC.start();

} catch (InterruptedException x) {

}

}

}

class ThreadID extends ThreadLocal {

private int nextID;

Page 115: Java programming-examples

Saikat Banerjee Page 115

public ThreadID() {

nextID = 10001;

}

private synchronized Integer getNewID() {

Integer id = new Integer(nextID);

nextID++;

return id;

}

protected Object initialValue() {

print("in initialValue()");

return getNewID();

}

public int getThreadID() {

Integer id = (Integer) get();

return id.intValue();

}

private static void print(String msg) {

String name = Thread.currentThread().getName();

System.out.println(name + ": " + msg);

}

}

Result:

The above code sample will produce the following result.

threadA: in initialValue()

threadA: var getThreadID =10001

threadB: in initialValue()

threadB: var getThreadID =10002

threadC: in initialValue()

threadC: var getThreadID =10003

threadA: var getThreadID =10001

threadB: var getThreadID =10002

threadC: var getThreadID =10003

Problem Description:

How to check priority level of a thread?

Solution:

Following example demonstrates how to check priority level of a thread using getPriority() method of a Thread.

public class Main extends Object {

private static Runnable makeRunnable() {

Runnable r = new Runnable() {

public void run() {

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

Thread t = Thread.currentThread();

System.out.println("in run() - priority="

+ t.getPriority()+ ", name=" + t.getName());

try {

Thread.sleep(2000);

Page 116: Java programming-examples

Saikat Banerjee Page 116

}

catch (InterruptedException x) {

}

}

}

};

return r;

}

public static void main(String[] args) {

System.out.println("in main() - Thread.currentThread().

getPriority()=" + Thread.currentThread().getPriority());

System.out.println("in main() - Thread.currentThread()

.getName()="+ Thread.currentThread().getName());

Thread threadA = new Thread(makeRunnable(), "threadA");

threadA.start();

try {

Thread.sleep(3000);

}

catch (InterruptedException x) {

}

System.out.println("in main() - threadA.getPriority()="

+ threadA.getPriority());

}

}

Result:

The above code sample will produce the following result.

in main() - Thread.currentThread().getPriority()=5

in main() - Thread.currentThread().getName()=main

in run() - priority=5, name=threadA

in run() - priority=5, name=threadA

in main() - threadA.getPriority()=5

in run() - priority=5, name=threadA

in run() - priority=5, name=threadA

in run() - priority=5, name=threadA

Problem Description:

How to display all running Thread?

Solution:

Following example demonstrates how to display names of all the running threads using getName() method.

public class Main extends Thread {

public static void main(String[] args) {

Main t1 = new Main();

t1.setName("thread1");

t1.start();

ThreadGroup currentGroup =

Thread.currentThread().getThreadGroup();

int noThreads = currentGroup.activeCount();

Thread[] lstThreads = new Thread[noThreads];

currentGroup.enumerate(lstThreads);

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

System.out.println("Thread No:" + i + " = "

+ lstThreads[i].getName());

Page 117: Java programming-examples

Saikat Banerjee Page 117

}

}

Result:

The above code sample will produce the following result.

Thread No:0 = main

Thread No:1 = thread1

Problem Description:

How to display thread status?

Solution:

Following example demonstrates how to display different status of thread using isAlive() & getStatus()

methods of Thread.

class MyThread extends Thread{

boolean waiting= true;

boolean ready= false;

MyThread() {

}

public void run() {

String thrdName = Thread.currentThread().getName();

System.out.println(thrdName + " starting.");

while(waiting)

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

System.out.println("waiting...");

startWait();

try {

Thread.sleep(1000);

}

catch(Exception exc) {

System.out.println(thrdName + " interrupted.");

}

System.out.println(thrdName + " terminating.");

}

synchronized void startWait() {

try {

while(!ready) wait();

}

catch(InterruptedException exc) {

System.out.println("wait() interrupted");

}

}

synchronized void notice() {

ready = true;

notify();

}

}

public class Main {

public static void main(String args[])

throws Exception{

MyThread thrd = new MyThread();

thrd.setName("MyThread #1");

showThreadStatus(thrd);

Page 118: Java programming-examples

Saikat Banerjee Page 118

thrd.start();

Thread.sleep(50);

showThreadStatus(thrd);

thrd.waiting = false;

Thread.sleep(50);

showThreadStatus(thrd);

thrd.notice();

Thread.sleep(50);

showThreadStatus(thrd);

while(thrd.isAlive())

System.out.println("alive");

showThreadStatus(thrd);

}

static void showThreadStatus(Thread thrd) {

System.out.println(thrd.getName()+" Alive:"

+thrd.isAlive()+" State:" + thrd.getState() );

}

}

Result:

The above code sample will produce the following result.

MyThread #1 Alive:false State:NEW

MyThread #1 starting.

waiting:true

waiting:true

alive

alive

MyThread #1 terminating.

alive

MyThread #1 Alive:false State:TERMINATED

Problem Description:

How to interrupt a running Thread?

Solution:

Following example demonstrates how to interrupt a running thread interrupt() method of thread and check if a

thread is interrupted using isInterrupted() method.

public class GeneralInterrupt extends Object

implements Runnable {

public void run() {

try {

System.out.println("in run() -

about to work2()");

work2();

System.out.println("in run() -

back from work2()");

}

catch (InterruptedException x) {

System.out.println("in run() -

interrupted in work2()");

return;

}

System.out.println("in run() -

Page 119: Java programming-examples

Saikat Banerjee Page 119

doing stuff after nap");

System.out.println("in run() -

leaving normally");

}

public void work2() throws InterruptedException {

while (true) {

if (Thread.currentThread().isInterrupted()) {

System.out.println("C isInterrupted()="

+ Thread.currentThread().isInterrupted());

Thread.sleep(2000);

System.out.println("D isInterrupted()="

+ Thread.currentThread().isInterrupted());

}

}

}

public void work() throws InterruptedException {

while (true) {

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

int j = i * 2;

}

System.out.println("A isInterrupted()="

+ Thread.currentThread().isInterrupted());

if (Thread.interrupted()) {

System.out.println("B isInterrupted()="

+ Thread.currentThread().isInterrupted());

throw new InterruptedException();

}

}

}

public static void main(String[] args) {

GeneralInterrupt si = new GeneralInterrupt();

Thread t = new Thread(si);

t.start();

try {

Thread.sleep(2000);

}

catch (InterruptedException x) {

}

System.out.println("in main() -

interrupting other thread");

t.interrupt();

System.out.println("in main() - leaving");

}

}

Result:

The above code sample will produce the following result.

in run() - about to work2()

in main() - interrupting other thread

in main() - leaving

C isInterrupted()=true

in run() - interrupted in work2()

Java Applet - Programming Examples

Learn how to play with Applets in Java programming. Here are most commonly used examples:

1. How to create a basic Applet?

Page 120: Java programming-examples

Saikat Banerjee Page 120

2. How to create a banner using Applet?

3. How to display clock using Applet?

4. How to create different shapes using Applet?

5. How to fill colors in shapes using Applet?

6. How to goto a link using Applet?

7. How to create an event listener in Applet?

8. How to display image using Applet?

9. How to open a link in a new window using Applet?

10. How to play sound using Applet?

11. How to read a file using Applet?

12. How to write to a file using Applet?

13. How to use swing applet in JAVA?

Problem Description:

How to create a basic Applet?

Solution:

Following example demonstrates how to create a basic Applet by extrnding Applet Class.You will need to

embed another HTML code to run this program.

import java.applet.*;

import java.awt.*;

public class Main extends Applet{

public void paint(Graphics g){

g.drawString("Welcome in Java Applet.",40,20);

}

}

Now compile the above code and call the generated class in your HTML code as follows:

<HTML>

<HEAD>

</HEAD>

<BODY>

<div >

<APPLET CODE="Main.class" WIDTH="800" HEIGHT="500">

</APPLET>

</div>

</BODY>

</HTML>

Result:

The above code sample will produce the following result in a java enabled web browser.

Welcome in Java Applet.

Problem Description:

How to create a banner using Applet?

Page 121: Java programming-examples

Saikat Banerjee Page 121

Solution:

Following example demonstrates how to play a sound using an applet image using Thread class. It also uses

drawRect(), fillRect() , drawString() methods of Graphics class.

import java.awt.*;

import java.applet.*;

public class SampleBanner extends Applet

implements Runnable{

String str = "This is a simple Banner ";

Thread t ;

boolean b;

public void init() {

setBackground(Color.gray);

setForeground(Color.yellow);

}

public void start() {

t = new Thread(this);

b = false;

t.start();

}

public void run () {

char ch;

for( ; ; ) {

try {

repaint();

Thread.sleep(250);

ch = str.charAt(0);

str = str.substring(1, str.length());

str = str + ch;

}

catch(InterruptedException e) {}

}

}

public void paint(Graphics g) {

g.drawRect(1,1,300,150);

g.setColor(Color.yellow);

g.fillRect(1,1,300,150);

g.setColor(Color.red);

g.drawString(str, 1, 150);

}

}

Result:

The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Problem Description:

How to display clock using Applet?

Solution:

Following example demonstrates how to display a clock using valueOf() mehtods of String Class. & using

Calender class to get the second, minutes & hours.

Page 122: Java programming-examples

Saikat Banerjee Page 122

import java.awt.*;

import java.applet.*;

import java.applet.*;

import java.awt.*;

import java.util.*;

public class ClockApplet extends Applet implements Runnable{

Thread t,t1;

public void start(){

t = new Thread(this);

t.start();

}

public void run(){

t1 = Thread.currentThread();

while(t1 == t){

repaint();

try{

t1.sleep(1000);

}

catch(InterruptedException e){}

}

}

public void paint(Graphics g){

Calendar cal = new GregorianCalendar();

String hour = String.valueOf(cal.get(Calendar.HOUR));

String minute = String.valueOf(cal.get(Calendar.MINUTE));

String second = String.valueOf(cal.get(Calendar.SECOND));

g.drawString(hour + ":" + minute + ":" + second, 20, 30);

}

}

Result:

The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Problem Description:

How to create different shapes using Applet?

Solution:

Following example demonstrates how to create an applet which will have a line, an Oval & a Rectangle using

drawLine(), drawOval(, drawRect() methods of Graphics clas.

import java.applet.*;

import java.awt.*;

public class Shapes extends Applet{

int x=300,y=100,r=50;

public void paint(Graphics g){

g.drawLine(30,300,200,10);

g.drawOval(x-r,y-r,100,100);

g.drawRect(400,50,200,100);

}

}

Page 123: Java programming-examples

Saikat Banerjee Page 123

Result:

The above code sample will produce the following result in a java enabled web browser.

A line , Oval & a Rectangle will be drawn in the browser.

Problem Description:

How to fill colors in shapes using Applet?

Solution:

Following example demonstrates how to create an applet which will have fill color in a rectangle using

setColor(), fillRect() methods of Graphics class to fill color in a Rectangle.

import java.applet.*;

import java.awt.*;

public class fillColor extends Applet{

public void paint(Graphics g){

g.drawRect(300,150,200,100);

g.setColor(Color.yellow);

g.fillRect( 300,150, 200, 100 );

g.setColor(Color.magenta);

g.drawString("Rectangle",500,150);

}

}

Result:

The above code sample will produce the following result in a java enabled web browser.

A Rectangle with yellow color filled in it willl be drawn in the browser.

Problem Description:

How to goto a link using Applet?

Solution:

Following example demonstrates how to go to a particular webpage from an applet using showDocument()

method of AppletContext class.

import java.applet.*;

import java.awt.*;

import java.net.*;

import java.awt.event.*;

public class tesURL extends Applet implements ActionListener{

public void init(){

String link = "yahoo";

Button b = new Button(link);

b.addActionListener(this);

Page 124: Java programming-examples

Saikat Banerjee Page 124

add(b);

}

public void actionPerformed(ActionEvent ae){

Button src = (Button)ae.getSource();

String link = "http://www."+src.getLabel()+".com";

try{

AppletContext a = getAppletContext();

URL u = new URL(link);

a.showDocument(u,"_self");

}

catch (MalformedURLException e){

System.out.println(e.getMessage());

}

}

}

Result:

The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Problem Description:

How to create an event listener in Applet?

Solution:

Following example demonstrates how to create a basic Applet having buttons to add & subtract two nos.

Methods usded here are addActionListener() to listen to an event(click on a button) & Button() construxtor to

create a button.

import java.applet.*;

import java.awt.event.*;

import java.awt.*;

public class EventListeners extends Applet

implements ActionListener{

TextArea txtArea;

String Add, Subtract;

int i = 10, j = 20, sum =0,Sub=0;

public void init(){

txtArea = new TextArea(10,20);

txtArea.setEditable(false);

add(txtArea,"center");

Button b = new Button("Add");

Button c = new Button("Subtract");

b.addActionListener(this);

c.addActionListener(this);

add(b);

add(c);

}

public void actionPerformed(ActionEvent e){

sum = i + j;

txtArea.setText("");

txtArea.append("i = "+ i + "\t" + "j = " + j + "\n");

Button source = (Button)e.getSource();

if(source.getLabel() == "Add"){

Page 125: Java programming-examples

Saikat Banerjee Page 125

txtArea.append("Sum : " + sum + "\n");

}

if(i >j){

Sub = i - j;

}

else{

Sub = j - i;

}

if(source.getLabel() == "Subtract"){

txtArea.append("Sub : " + Sub + "\n");

}

}

}

Result:

The above code sample will produce the following result in a java enabled web browser.

View in Browser.

Java Simple GUI - Programming Examples

Learn how to play with Simple GUI in Java programming. Here are most commonly used examples:

1. How to display text in different fonts?

2. How to draw a line using GUI?

3. How to display a message in a new frame?

4. How to draw a polygon using GUI?

5. How to display string in a rectangle?

6. How to display different shapes using GUI?

7. How to draw a solid rectange using GUI?

8. How to create a transparent cursor?

9. How to check whether antialiasing is enabled or not?

10. How to display colours in a frame?

11. How to display a pie chart using a frame?

12. How to draw text using GUI?

Problem Description:

How to display text in different fonts?

Solution:

Following example demonstrates how to display text in different fonts using setFont() method of Font class.

import java.awt.*;

import java.awt.event.*

import javax.swing.*

public class Main extends JPanel {

String[] type = { "Serif","SansSerif"};

Page 126: Java programming-examples

Saikat Banerjee Page 126

int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,

Font.ITALIC + Font.BOLD };

String[] stylenames =

{ "Plain", "Italic", "Bold", "Bold & Italic" };

public void paint(Graphics g) {

for (int f = 0; f < type.length; f++) {

for (int s = 0; s < styles.length; s++) {

Font font = new Font(type[f], styles[s], 18);

g.setFont(font);

String name = type[f] + " " + stylenames[s];

g.drawString(name, 20, (f * 4 + s + 1) * 20);

}

}

}

public static void main(String[] a) {

JFrame f = new JFrame();

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

}

);

f.setContentPane(new Main());

f.setSize(400,400);

f.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

Different font names are displayed in a frame.

Problem Description:

How to draw a line using GUI?

Solution:

Following example demonstrates how to draw a line using draw() method of Graphics2D class with Line2D

object as an argument.

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.Line2D;

import javax.swing.JApplet;

import javax.swing.JFrame;

public class Main extends JApplet {

public void init() {

setBackground(Color.white);

setForeground(Color.white);

}

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

Page 127: Java programming-examples

Saikat Banerjee Page 127

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setPaint(Color.gray);

int x = 5;

int y = 7;

g2.draw(new Line2D.Double(x, y, 200, 200));

g2.drawString("Line", x, 250);

}

public static void main(String s[]) {

JFrame f = new JFrame("Line");

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

JApplet applet = new Main();

f.getContentPane().add("Center", applet);

applet.init();

f.pack();

f.setSize(new Dimension(300, 300));

f.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

Line is displayed in a frame.

Problem Description:

How to display a message in a new frame?

Solution:

Following example demonstrates how to display message in a new frame by creating a frame using JFrame() &

using JFrames getContentPanel(), setSize() & setVisible() methods to display this frame.

import java.awt.*;

import java.awt.font.FontRenderContext;

import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2.setFont(new Font("Serif", Font.PLAIN, 48));

paintHorizontallyCenteredText(g2, "Java Source", 200, 75);

paintHorizontallyCenteredText(g2, "and", 200, 125);

paintHorizontallyCenteredText(g2, "Support", 200, 175);

}

protected void paintHorizontallyCenteredText(Graphics2D g2,

String s, float centerX, float baselineY) {

FontRenderContext frc = g2.getFontRenderContext();

Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);

Page 128: Java programming-examples

Saikat Banerjee Page 128

float width = (float) bounds.getWidth();

g2.drawString(s, centerX - width / 2, baselineY);

}

public static void main(String[] args) {

JFrame f = new JFrame();

f.getContentPane().add(new Main());

f.setSize(450, 350);

f.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

JAVA and J2EE displayed in a new Frame.

Problem Description:

How to draw a polygon using GUI?

Solution:

Following example demonstrates how to draw a polygon by creating Polygon() object. addPoint() &

drawPolygon() method is used to draw the Polygon.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Main extends JPanel {

public void paintComponent(Graphics g) {

super.paintComponent(g);

Polygon p = new Polygon();

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

p.addPoint((int)

(100 + 50 * Math.cos(i * 2 * Math.PI / 5)),

(int) (100 + 50 * Math.sin(i * 2 * Math.PI / 5)));

g.drawPolygon(p);

}

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setTitle("Polygon");

frame.setSize(350, 250);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

Container contentPane = frame.getContentPane();

contentPane.add(new Main());

frame.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

Page 129: Java programming-examples

Saikat Banerjee Page 129

Polygon is displayed in a frame.

Problem Description:

How to display string in a rectangle?

Solution:

Following example demonstrates how to display each character in a rectangle by drawing a rectangle around

each character using drawRect() method.

import java.awt.*;

import javax.swing.*

public class Main extends JPanel {

public void paint(Graphics g) {

g.setFont(new Font("",0,100));

FontMetrics fm = getFontMetrics(new Font("",0,100));

String s = "message";

int x = 5;

int y = 5;

for (int i = 0; i < s.length(); i++) {

char c = s.charAt(i);

int h = fm.getHeight();

int w = fm.charWidth(c);

g.drawRect(x, y, w, h);

g.drawString(String.valueOf(c), x, y + h);

x = x + w;

}

}

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setContentPane(new Main());

frame.setSize(500, 700);

frame.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

Each character is displayed in a rectangle.

Problem Description:

How to display different shapes using GUI?

Solution:

Following example demonstrates how to display different shapes using Arc2D, Ellipse2D, Rectangle2D,

RoundRectangle2D classes.

import java.awt.Shape;

Page 130: Java programming-examples

Saikat Banerjee Page 130

import java.awt.geom.*;

public class Main {

public static void main(String[] args) {

int x1 = 1, x2 = 2, w = 3, h = 4,

x = 5, y = 6,

y1 = 1, y2 = 2, start = 3;

Shape line = new Line2D.Float(x1, y1, x2, y2);

Shape arc = new Arc2D.Float(x, y, w, h, start, 1, 1);

Shape oval = new Ellipse2D.Float(x, y, w, h);

Shape rectangle = new Rectangle2D.Float(x, y, w, h);

Shape roundRectangle = new RoundRectangle2D.Float

(x, y, w, h, 1, 2);

System.out.println("Different shapes are created:");

}

}

Result:

The above code sample will produce the following result.

Different shapes are created.

Problem Description:

How to draw a solid rectangle using GUI?

Solution:

Following example demonstrates how to display a solid rectangle using fillRect() method of Graphics class.

import java.awt.Graphics;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public static void main(String[] a) {

JFrame f = new JFrame();

f.setSize(400, 400);

f.add(new Main());

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

public void paint(Graphics g) {

g.fillRect (5, 15, 50, 75);

}

}

Result:

The above code sample will produce the following result.

Solid rectangle is created.

Page 131: Java programming-examples

Saikat Banerjee Page 131

Problem Description:

How to create a transparent cursor?

Solution:

Following example demonstrates how to create a transparent cursor by using createCustomCursor() method

with "invisiblecursor" as an argument.

import java.awt.*;

import java.awt.image.MemoryImageSource;

public class Main {

public static void main(String[] argv) throws Exception {

int[] pixels = new int[16 * 16];

Image image = Toolkit.getDefaultToolkit().createImage(

new MemoryImageSource(16, 16, pixels, 0, 16));

Cursor transparentCursor = Toolkit.getDefaultToolkit().

createCustomCursor(image, new Point(0, 0),

"invisibleCursor");

System.out.println("Transparent Cursor created.");

}

}

Result:

The above code sample will produce the following result.

Transparent Cursor created.

Problem Description:

How to check whether antialiasing is enabled or not?

Solution:

Following example demonstrates how to check if antialiasing is turned on or not using RenderingHints Class.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JComponent;

import javax.swing.JFrame;

public class Main {

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.add(new MyComponent());

frame.setSize(300, 300);

frame.setVisible(true);

}

}

class MyComponent extends JComponent {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

RenderingHints rh = g2d.getRenderingHints();

Page 132: Java programming-examples

Saikat Banerjee Page 132

boolean bl = rh.containsValue

(RenderingHints.VALUE_ANTIALIAS_ON);

System.out.println(bl);

g2.setRenderingHint(RenderingHints.

KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

}

}

Result:

The above code sample will produce the following result.

False

False

False

Problem Description:

How to display colours in a frame?

Solution:

Following example displays how to a display all the colors in a frame using setRGB method of image class.

import java.awt.Graphics;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import javax.swing.JFrame;

public class Main extends JComponent {

BufferedImage image;

public void initialize() {

int width = getSize().width;

int height = getSize().height;

int[] data = new int[width * height];

int index = 0;

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

int red = (i * 255) / (height - 1);

for (int j = 0; j < width; j++) {

int green = (j * 255) / (width - 1);

int blue = 128;

data[index++] = (red < < 16) | (green < < 8) | blue;

}

}

image = new BufferedImage

(width, height, BufferedImage.TYPE_INT_RGB);

image.setRGB(0, 0, width, height, data, 0, width);

}

public void paint(Graphics g) {

if (image == null)

initialize();

g.drawImage(image, 0, 0, this);

}

public static void main(String[] args) {

JFrame f = new JFrame("Display Colours");

f.getContentPane().add(new Main());

f.setSize(300, 300);

Page 133: Java programming-examples

Saikat Banerjee Page 133

f.setLocation(100, 100);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

f.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

Displays all the colours in a frame.

Problem Description:

How to display a pie chart using a frame?

Solution:

Following example displays how to a display a piechart by making Slices class & creating arc depending on the

slices.

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Rectangle;

import javax.swing.JComponent;

import javax.swing.JFrame;

class Slice {

double value;

Color color;

public Slice(double value, Color color) {

this.value = value;

this.color = color;

}

}

class MyComponent extends JComponent {

Slice[] slices = { new Slice(5, Color.black),

new Slice(33, Color.green),

new Slice(20, Color.yellow), new Slice(15, Color.red) };

MyComponent() {}

public void paint(Graphics g) {

drawPie((Graphics2D) g, getBounds(), slices);

}

void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {

double total = 0.0D;

for (int i = 0; i < slices.length; i++) {

total += slices[i].value;

}

double curValue = 0.0D;

int startAngle = 0;

for (int i = 0; i < slices.length; i++) {

startAngle = (int) (curValue * 360 / total);

Page 134: Java programming-examples

Saikat Banerjee Page 134

int arcAngle = (int) (slices[i].value * 360 / total);

g.setColor(slices[i].color);

g.fillArc(area.x, area.y, area.width, area.height,

startAngle, arcAngle);

curValue += slices[i].value;

}

}

}

public class Main {

public static void main(String[] argv) {

JFrame frame = new JFrame();

frame.getContentPane().add(new MyComponent());

frame.setSize(300, 200);

frame.setVisible(true);

}

}

Result:

The above code sample will produce the following result.

Displays a piechart in a frame.

Problem Description:

How to draw text using GUI?

Solution:

Following example demonstrates how to draw text drawString(), setFont() methods of Graphics class.

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel{

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

Font font = new Font("Serif", Font.PLAIN, 96);

g2.setFont(font);

g2.drawString("Text", 40, 120);

}

public static void main(String[] args) {

JFrame f = new JFrame();

f.getContentPane().add(new Main());

f.setSize(300, 200);

f.setVisible(true);

}

}

Page 135: Java programming-examples

Saikat Banerjee Page 135

Result:

The above code sample will produce the following result.

Text is displayed in a frame.

Java JDBC - Programming Examples

Learn how to use JDBC in Java programming. Here are most commonly used examples:

1. How to establishing a connection with Database?

2. How to Create, edit & alter table using Java?

3. How to display contents of table ?

4. How to update, edit & delete rows ?

5. How to search in the database using java commands?

6. How to sort elements of a column using java commands?

7. How to combine data from more than one tables?

8. How to use commit statement in Java?

9. How to us prepared statement in Java?

10. How to set & rollback to a savepoint ?

11. How to execute a batch of SQL statements using java?

12. How to use different row methods in java?

13. How to use different column methods in java?

Problem Description:

How to connect to a database using JDBC? Assume that database name is testDb and it has table named

employee which has 2 records.

Solution:

Following example uses getConnection, createStatement & executeQuery methods to connect to a database &

execute queries.

import java.sql.*;

public class jdbcConn {

public static void main(String[] args) {

try {

Class.forName("org.apache.derby.jdbc.ClientDriver");

}

catch(ClassNotFoundException e) {

System.out.println("Class not found "+ e);

}

System.out.println("JDBC Class found");

int no_of_rows = 0;

try {

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","username",

"password");

Page 136: Java programming-examples

Saikat Banerjee Page 136

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery

("SELECT * FROM employee");

while (rs.next()) {

no_of_rows++;

}

System.out.println("There are "+ no_of_rows

+ " record in the table");

}

catch(SQLException e){

System.out.println("SQL exception occured" + e);

}

}

}

Result:

The above code sample will produce the following result.The result may vary. You will get ClassNotfound

exception if your JDBC driver is not installed properly.

JDBC Class found

There are 2 record in the table

Problem Description:

How to edit(Add or update) columns of a Table and how to delete a table?

Solution:

Following example uses create, alter & drop SQL commands to create, edit or delete table

import java.sql.*;

public class jdbcConn {

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

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","username",

"password");

Statement stmt = con.createStatement();

String query ="CREATE TABLE employees

(id INTEGER PRIMARY KEY,

first_name CHAR(50),last_name CHAR(75))";

stmt.execute(query);

System.out.println("Employee table created");

String query1 = "aLTER TABLE employees ADD

address CHAR(100) ";

String query2 = "ALTER TABLE employees DROP

COLUMN last_name";

stmt.execute(query1);

stmt.execute(query2);

System.out.println("Address column added to the table

& last_name column removed from the table");

String query3 = "drop table employees";

stmt.execute(query3);

System.out.println("Employees table removed");

}

}

Page 137: Java programming-examples

Saikat Banerjee Page 137

Result:

The above code sample will produce the following result.The result may vary.

Employee table created

Address column added to the table & last_name

column removed from the table

Employees table removed from the database

Problem Description:

How to retrieve contents of a table using JDBC connection?

Solution:

Following example uses getString,getInt & executeQuery methods to fetch & display the contents of the table.

import java.sql.*;

public class jdbcResultSet {

public static void main(String[] args) {

try {

Class.forName("org.apache.derby.jdbc.ClientDriver");

}

catch(ClassNotFoundException e) {

System.out.println("Class not found "+ e);

}

try {

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","username",

"password");

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery

("SELECT * FROM employee");

System.out.println("id name job");

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String job = rs.getString("job");

System.out.println(id+" "+name+" "+job);

}

}

catch(SQLException e){

System.out.println("SQL exception occured" + e);

}

}

}

Result:

The above code sample will produce the following result.The result may vary.

id name job

1 alok trainee

2 ravi trainee

Page 138: Java programming-examples

Saikat Banerjee Page 138

Problem Description:

How to update(delete, insert or update) contents of a table using JDBC connection?

Solution:

Following method uses update, delete & insert SQL commands to edit or delete row contents.

import java.sql.*;

public class updateTable {

public static void main(String[] args) {

try {

Class.forName("org.apache.derby.jdbc.ClientDriver");

}

catch(ClassNotFoundException e) {

System.out.println("Class not found "+ e);

}

try {

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","username",

"password");

Statement stmt = con.createStatement();

String query1="update emp set name='ravi' where id=2";

String query2 = "delete from emp where id=1";

String query3 = "insert into emp values

(1,'ronak','manager')";

stmt.execute(query1);

stmt.execute(query2);

stmt.execute(query3);

ResultSet rs = stmt.executeQuery("SELECT * FROM emp");

System.out.println("id name job");

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String job = rs.getString("job");

System.out.println(id+" "+name+" "+job);

}

}

catch(SQLException e){

System.out.println("SQL exception occured" + e);

}

}

}

Result:

The above code sample will produce the following result.The result may vary.

id name job

2 ravi trainee

1 ronak manager

Problem Description:

How to Search contents of a table?

Page 139: Java programming-examples

Saikat Banerjee Page 139

Solution:

Following method uses where & like sql Commands to search through the database.

import java.sql.*;

public class jdbcConn {

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

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","username",

"password");

Statement stmt = con.createStatement();

String query[] ={"SELECT * FROM emp where id=1",

"select name from emp where name like 'ravi_'",

"select name from emp where name like 'ravi%'"};

for(String q : query){

ResultSet rs = stmt.executeQuery(q);

System.out.println("Names for query "+q+" are");

while (rs.next()) {

String name = rs.getString("name");

System.out.print(name+" ");

}

System.out.println();

}

}

}

Result:

The above code sample will produce the following result.The result may vary.

Names for query SELECT * FROM emp where id=1 are

ravi

Names for query select name from emp where name like 'ravi_' are

ravi2 ravi3

Names for query select name from emp where name like 'ravi%' are

ravi ravi2 ravi3 ravi123 ravi222

Problem Description:

How to sort contents of a table?

Solution:

Following example uses Order by SQL command to sort the table.

import java.sql.*;

public class jdbcConn {

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

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection con = DriverManager.getConnection

("jdbc:derby://localhost:1527/testDb","name","pass");

Statement stmt = con.createStatement();

Page 140: Java programming-examples

Saikat Banerjee Page 140

String query = "select * from emp order by name";

String query1="select * from emp order by name, job";

ResultSet rs = stmt.executeQuery(query);

System.out.println("Table contents sorted by Name");

System.out.println("Id Name Job");

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String job = rs.getString("job");

System.out.println(id + " " + name+" "+job);

}

rs = stmt.executeQuery(query1);

System.out.println("Table contents after sorted

by Name & job");

System.out.println("Id Name Job");

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String job = rs.getString("job");

System.out.println(id + " " + name+" "+job);

}

}

}

Result:

The above code sample will produce the following result.The result may vary.

Table contents after sorting by Name

Id Name Job

1 ravi trainee

5 ravi MD

4 ravi CEO

2 ravindra CEO

2 ravish trainee

Table contents after sorting by Name & job

Id Name Job

4 ravi CEO

5 ravi MD

1 ravi trainee

2 ravindra CEO

2 ravish trainee

Problem Description:

How to join contents of more than one table & display?

Solution:

Following example uses inner join sql command to combine data from two tables. To display the contents of

the table getString() method of resultset is used.

import java.sql.*;

public class jdbcConn {

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

Class.forName("org.apache.derby.jdbc.ClientDriver");

Connection con = DriverManager.getConnection

Page 141: Java programming-examples

Saikat Banerjee Page 141

("jdbc:derby://localhost:1527/testDb","username",

"password");

Statement stmt = con.createStatement();

String query ="SELECT fname,lname,isbn from author

inner join books on author.AUTHORID = books.AUTHORID";

ResultSet rs = stmt.executeQuery(query);

System.out.println("Fname Lname ISBN");

while (rs.next()) {

String fname = rs.getString("fname");

String lname = rs.getString("lname");

int isbn = rs.getInt("isbn");

System.out.println(fname + " " + lname+" "+isbn);

}

System.out.println();

System.out.println();

}

}

Result:

The above code sample will produce the following result.The result may vary.

Fname Lname ISBN

john grisham 123

jeffry archer 113

jeffry archer 112

jeffry archer 122

Java Regular Expression - Programming Examples

Learn how to use regular expression in Java programming. Here are most commonly used examples:

1. How to reset the pattern of a regular expression?

2. How to match duplicate words in a regular expression?

3. How to find every occurance of a word?

4. How to know the last index of a perticular word in a string?

5. How to print all the strings that match a given pattern from a file?

6. How to remove the white spaces?

7. How to match phone numbers in a list to a certain pattern?

8. How to count a group of words in a string?

9. How to search a perticular word in a string?

10. How to split a regular expression?

11. How to count replace first occourance of a String?

12. How to check check whether date is in proper format or not?

13. How to validate an email address format?

14. How to replace all occurings of a string?

15. How to make first character of each word in Uppercase?

Problem Description:

How to reset the pattern of a regular expression?

Page 142: Java programming-examples

Saikat Banerjee Page 142

Solution:

Following example demonstrates how to reset the pattern of a regular expression by using Pattern.compile() of

Pattern class and m.find() method of Matcher class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Resetting {

public static void main(String[] args)

throws Exception {

Matcher m = Pattern.compile("[frb][aiu][gx]").

matcher("fix the rug with bags");

while (m.find())

System.out.println(m.group());

m.reset("fix the rig with rags");

while (m.find())

System.out.println(m.group());

}

}

Result:

The above code sample will produce the following result.

fix

rug

bag

fix

rig

rag

Problem Description:

How to match duplicate words in a regular expression?

Solution:

Following example shows how to search duplicate words in a regular expression by using p.matcher() method

and m.group() method of regex.Matcher class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String args[])

throws Exception {

String duplicatePattern = "\\b(\\w+) \\1\\b";

Pattern p = Pattern.compile(duplicatePattern);

int matches = 0;

String phrase = " this is a test ";

Matcher m = p.matcher(phrase);

String val = null;

while (m.find()) {

val = ":" + m.group() + ":";

matches++;

}

Page 143: Java programming-examples

Saikat Banerjee Page 143

if(val>0)

System.out.println("The string

has matched with the pattern.");

else

System.out.println("The string

has not matched with the pattern.");

}

}

Result:

The above code sample will produce the following result.

The string has matched with the pattern.

Problem Description:

How to find every occurance of a word?

Solution:

Following example demonstrates how to find every occurance of a word with the help of Pattern.compile()

method and m.group() method.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String args[])

throws Exception {

String candidate = "this is a test, A TEST.";

String regex = "\\ba\\w*\\b";

Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(candidate);

String val = null;

System.out.println("INPUT: " + candidate);

System.out.println("REGEX: " + regex + "\r\n");

while (m.find()) {

val = m.group();

System.out.println("MATCH: " + val);

}

if (val == null) {

System.out.println("NO MATCHES: ");

}

}

}

Result:

The above code sample will produce the following result.

INPUT: this is a test ,A TEST.

REGEX: \\ba\\w*\\b

MATCH: a test

MATCH: A TEST

Page 144: Java programming-examples

Saikat Banerjee Page 144

Problem Description:

How to know the last index of a perticular word in a string?

Solution:

Following example demonstrates how to know the last index of a perticular word in a string by using

Patter.compile() method of Pattern class and matchet.find() method of Matcher class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String args[]) {

String candidateString = "This is a Java example.

This is another Java example.";

Pattern p = Pattern.compile("Java");

Matcher matcher = p.matcher(candidateString);

matcher.find();

int nextIndex = matcher.end();

System.out.print("The last index of Java is:");

System.out.println(nextIndex);

}

}

Result:

The above code sample will produce the following result.

The last index of Java is: 42

Problem Description:

How to print all the strings that match a given pattern from a file?

Solution:

Following example shows how to print all the strings that match a given pattern from a file with the help of

Patternname.matcher() method of Util.regex class.

import java.util.regex.*;

import java.io.*;

public class ReaderIter {

public static void main(String[] args)

throws IOException {

Pattern patt = Pattern.compile("[A-Za-z][a-z]+");

BufferedReader r = new BufferedReader

(new FileReader("ReaderIter.java"));

String line;

while ((line = r.readLine()) != null) {

Matcher m = patt.matcher(line);

while (m.find()) {

System.out.println(m.group(0));

int start = m.start(0);

int end = m.end(0);

Page 145: Java programming-examples

Saikat Banerjee Page 145

Use CharacterIterator.substring(offset, end);

System.out.println(line.substring(start, end));

}

}

}

}

Result:

The above code sample will produce the following result.

Ian

Darwin

http

www

darwinsys

com

All

rights

reserved

Software

written

by

Ian

Darwin

and

others

Problem Description:

How to remove the white spaces?

Solution:

Following example demonstrates how to remove the white spaces with the help matcher.replaceAll(stringname)

method of Util.regex.Pattern class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String[] argv)

throws Exception {

String ExString = "This is a Java program.

This is another Java Program.";

String result=removeDuplicateWhitespace(ExString);

System.out.println(result);

}

public static CharSequence

removeDuplicateWhitespace(CharSequence inputStr) {

String patternStr = "\\s+";

String replaceStr = " ";

Pattern pattern = Pattern.compile(patternStr);

Matcher matcher = pattern.matcher(inputStr);

return matcher.replaceAll(replaceStr);

}

}

Page 146: Java programming-examples

Saikat Banerjee Page 146

Result:

The above code sample will produce the following result.

ThisisaJavaprogram.ThisisanotherJavaprogram.

Problem Description:

How to match phone numbers in a list?

Solution:

Following example shows how to match phone numbers in a list to a perticlar pattern by using

phone.matches(phoneNumberPattern) method .

public class MatchPhoneNumber {

public static void main(String args[]) {

isPhoneValid("1-999-585-4009");

isPhoneValid("999-585-4009");

isPhoneValid("1-585-4009");

isPhoneValid("585-4009");

isPhoneValid("1.999-585-4009");

isPhoneValid("999 585-4009");

isPhoneValid("1 585 4009");

isPhoneValid("111-Java2s");

}

public static boolean isPhoneValid(String phone) {

boolean retval = false;

String phoneNumberPattern =

"(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";

retval = phone.matches(phoneNumberPattern);

String msg = "NO MATCH: pattern:" + phone

+ "\r\n regex: " + phoneNumberPattern;

if (retval) {

msg = " MATCH: pattern:" + phone

+ "\r\n regex: " + phoneNumberPattern;

}

System.out.println(msg + "\r\n");

return retval;

}

}

Result:

The above code sample will produce the following result.

MATCH: pattern:1-999-585-4009

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

MATCH: pattern:999-585-4009

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

MATCH: pattern:1-585-4009

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

NOMATCH: pattern:1.999-585-4009

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

NOMATCH: pattern:999 585-4009

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

NOMATCH: pattern:1 585 4009

Page 147: Java programming-examples

Saikat Banerjee Page 147

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

NOMATCH: pattern:111-Java2s

regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

Problem Description:

How to count a group of words in a string?

Solution:

Following example demonstrates how to count a group of words in a string with the help of

matcher.groupCount() method of regex.Matcher class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class MatcherGroupCountExample {

public static void main(String args[]) {

Pattern p = Pattern.compile("J(ava)");

String candidateString = "This is Java.

This is a Java example.";

Matcher matcher = p.matcher(candidateString);

int numberOfGroups = matcher.groupCount();

System.out.println("numberOfGroups =" + numberOfGroups);

}

}

Result:

The above code sample will produce the following result.

numberOfGroups =3

Problem Description:

How to search a perticular word in a string?

Solution:

Following example demonstrates how to search a perticular word in a string with the help of matcher.start()

method of regex.Matcher class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String args[]) {

Pattern p = Pattern.compile("j(ava)");

String candidateString = "This is a java program.

This is another java program.";

Matcher matcher = p.matcher(candidateString);

int nextIndex = matcher.start(1);

System.out.println(candidateString);

System.out.println("The index for java is:"

+ nextIndex);

Page 148: Java programming-examples

Saikat Banerjee Page 148

}

}

Result:

The above code sample will produce the following result.

This is a java program. This is another java program.

The index for java is: 11

Problem Description:

How to split a regular expression?

Solution:

Following example demonstrates how to split a regular expression by using Pattern.compile() method and

patternname.split() method of regex.Pattern class.

import java.util.regex.Pattern;

public class PatternSplitExample {

public static void main(String args[]) {

Pattern p = Pattern.compile(" ");

String tmp = "this is the Java example";

String[] tokens = p.split(tmp);

for (int i = 0; i < tokens.length; i++) {

System.out.println(tokens[i]);

}

}

}

Result:

The above code sample will produce the following result.

this

is

the

Java

example

Problem Description:

How to count replace first occourance of a String?

Solution:

Following example demonstrates how to replace first occourance of a String in a String using replaceFirst()

method of a Matcher class.

import java.util.regex.Matcher;

Page 149: Java programming-examples

Saikat Banerjee Page 149

import java.util.regex.Pattern;

public class Main {

public static void main(String args[]) {

Pattern p = Pattern.compile("hello");

String instring = "hello hello hello.";

System.out.println("initial String: "+ instring);

Matcher m = p.matcher(instring);

String tmp = m.replaceFirst("Java");

System.out.println("String after replacing 1st Match: "

+tmp);

}

}

Result:

The above code sample will produce the following result.

initial String: hello hello hello.

String after replacing 1st Match: Java hello hello.

Problem Description:

How to check check whether date is in proper format or not?

Solution:

Following example demonstrates how to check whether the date is in a proper format or not using matches

method of String class.

public class Main {

public static void main(String[] argv) {

boolean isDate = false;

String date1 = "8-05-1988";

String date2 = "08/04/1987" ;

String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";

isDate = date1.matches(datePattern);

System.out.println("Date :"+ date1+": matches with

the this date Pattern:"+datePattern+"Ans:"+isDate);

isDate = date2.matches(datePattern);

System.out.println("Date :"+ date2+": matches with

the this date Pattern:"+datePattern+"Ans:"+isDate);

}

}

Result:

The above code sample will produce the following result.

Date :8-05-1988: matches with the this date Pattern:

\d{1,2}-\d{1,2}-\d{4}Ans:true

Date :08/04/1987: matches with the this date Pattern:

\d{1,2}-\d{1,2}-\d{4}Ans:false

Page 150: Java programming-examples

Saikat Banerjee Page 150

Problem Description:

How to validate an email address format?

Solution:

Following example demonstrates how to validate e-mail address using matches() method of String class.

public class Main {

public static void main(String[] args) {

String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\

@([\\w]+\\.)+[\\w]+[\\w]$";

String email1 = "[email protected]";

Boolean b = email1.matches(EMAIL_REGEX);

System.out.println("is e-mail: "+email1+" :Valid = " + b);

String email2 = "user^domain.co.in";

b = email2.matches(EMAIL_REGEX);

System.out.println("is e-mail: "+email2

+" :Valid = " + b);

}

}

Result:

The above code sample will produce the following result.

is e-mail: [email protected] :Valid = true

is e-mail: user^domain.co.in :Valid = false

Problem Description:

How to replace all occurings of a string?

Solution:

Following example demonstrates how to replace all occouranc of a String in a String using replaceAll() method

of Matcher class.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String args[]) {

Pattern p = Pattern.compile("hello");

String instring = "hello hello hello.";

System.out.println("initial String: "+ instring);

Matcher m = p.matcher(instring);

String tmp = m.replaceAll("Java");

System.out.println("String after replacing 1st Match: "

+tmp);

}

}

Page 151: Java programming-examples

Saikat Banerjee Page 151

Result:

The above code sample will produce the following result.

initial String: hello hello hello.

String after replacing 1st Match: Java Java Java.

Problem Description:

How to make first character of each word in Uppercase?

Solution:

Following example demonstrates how to convert first letter of each word in a string into an uppercase letter

Using toUpperCase(), appendTail() methods.

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Main {

public static void main(String[] args) {

String str = "this is a java test";

System.out.println(str);

StringBuffer stringbf = new StringBuffer();

Matcher m = Pattern.compile("([a-z])([a-z]*)",

Pattern.CASE_INSENSITIVE).matcher(str);

while (m.find()) {

m.appendReplacement(stringbf,

m.group(1).toUpperCase() + m.group(2).toLowerCase());

}

System.out.println(m.appendTail(stringbf).toString());

}

}

Result:

The above code sample will produce the following result.

this is a java test

This Is A Java Test