SlideShare a Scribd company logo
1 of 151
Download to read offline
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.
2.
3.
4.
5.
6.
7.
8.
9.

How to compile a java file?
How to run a class file?
How to debug a java file?
How to set classpath?
How to view current classpath?
How to set destination of the class file?
How to run a compiled class file?
How to check version of java running on your system?
How to set classpath when class files are in .jar file?

Saikat Banerjee

Page 1
Problem Description:
How to compile a java file?

Solution:
Following example demonstrates how to compile a java file using javac command.
c:jdkdemoapp> 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:javaMyClasse1;C:javaMyClass2
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.

Saikat Banerjee

Page 2
Demo.java will debug.

Problem Description:
How to set classpath?

Solution:
Following example demonstrates how to set classpath.
C:> java -classpath C:javaDemoClasses 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 FilesJavajre1.6.0_03libextQTJava.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.

Saikat Banerjee

Page 3
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:jdkdemoapp>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:javamyclasses.jar utility.testapp.main

Saikat Banerjee

Page 4
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.

Saikat Banerjee

Page 5
-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.

Saikat Banerjee

Page 6
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.

Saikat Banerjee

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

Saikat Banerjee

Page 8
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

Saikat Banerjee

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

Saikat Banerjee

Page 10
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

Saikat Banerjee

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

Saikat Banerjee

Page 12
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.

Saikat Banerjee

Page 13
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
24 26
44 46
64 66

8 10 12 14 16 18 20 22
28 30 32 34 36 38 40 42
48 50 52 54 56 58 60 62
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?

Saikat Banerjee

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

Saikat Banerjee

Page 15
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.

Saikat Banerjee

Page 16
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]);
}
}
}

Saikat Banerjee

Page 17
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" };

Saikat Banerjee

Page 18
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

Saikat Banerjee

Page 19
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

Saikat Banerjee

Page 20
+ ": [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]

Saikat Banerjee

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

Saikat Banerjee

Page 22
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]

Saikat Banerjee

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

Saikat Banerjee

Page 24
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

Saikat Banerjee

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

Saikat Banerjee

Page 26
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 : "

Saikat Banerjee

Page 27
+ 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){

Saikat Banerjee

Page 28
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
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth
shortMonth

=
=
=
=
=
=
=
=
=
=
=
=

Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

Saikat Banerjee

Page 29
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
weekday
weekday
weekday
weekday

=
=
=
=
=

Monday
Tuesday
Wednesday
Thursday
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 "

Saikat Banerjee

Page 30
+ cl.getTime().toString() );
}
}

Result:
The above code sample will produce the following result.
today is Mon
date after a
date after 7
date after 3

Jun 22 02:47:02 IST 2009
month will be Wed Jul 22 02:47:02 IST 2009
hrs will be Wed Jul 22 09:47:02 IST 2009
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.

Saikat Banerjee

Page 31
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

Saikat Banerjee

Page 32
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)

Saikat Banerjee

Page 33
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;

Saikat Banerjee

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

Saikat Banerjee

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

Saikat Banerjee

Page 36
}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
Disk
Disk
Disk
Disk
Disk
Disk

1
2
1
3
1
2
1

from
from
from
from
from
from
from

A
A
C
A
B
B
A

to
to
to
to
to
to
to

C
B
B
C
A
C
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: %dn",
counter, fibonacci(counter));
}
}
}

Result:
The above code sample will produce the following result.
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci

of
of
of
of
of
of
of
of

0
1
2
3
4
5
6
7

is:
is:
is:
is:
is:
is:
is:
is:

Saikat Banerjee

0
1
1
2
3
5
8
13

Page 37
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! = %dn", 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);

Saikat Banerjee

Page 38
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) {

Saikat Banerjee

Page 39
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
Saikat Banerjee

Page 40
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?

Saikat Banerjee

Page 41
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.

Saikat Banerjee

Page 42
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

Saikat Banerjee

Page 43
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.

Saikat Banerjee

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

Saikat Banerjee

Page 45
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?

Saikat Banerjee

Page 46
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("aString1n");
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 copiedn");
out1.close();
InputStream in = new FileInputStream

Saikat Banerjee

Page 47
(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("aString1n");
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);

Saikat Banerjee

Page 48
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 ?

Saikat Banerjee

Page 49
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 ?

Saikat Banerjee

Page 50
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:abcdefghi";
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.

Saikat Banerjee

Page 51
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?

Saikat Banerjee

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

Saikat Banerjee

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

Saikat Banerjee

Page 54
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

Saikat Banerjee

Page 55
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)

Saikat Banerjee

Page 56
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 ?

Saikat Banerjee

Page 57
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.

Saikat Banerjee

Page 58
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.

Saikat Banerjee

Page 59
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.

Saikat Banerjee

Page 60
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?

Saikat Banerjee

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

Saikat Banerjee

Page 62
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?

Saikat Banerjee

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

Saikat Banerjee

Page 64
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;

Saikat Banerjee

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

Saikat Banerjee

Page 66
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;

Saikat Banerjee

Page 67
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

Saikat Banerjee

Page 68
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;

Saikat Banerjee

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

Saikat Banerjee

Page 70
}

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;

Saikat Banerjee

Page 71
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

Saikat Banerjee

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

Saikat Banerjee

Page 73
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[])

Saikat Banerjee

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

Saikat Banerjee

Page 75
}

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 .

Saikat Banerjee

Page 76
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

Saikat Banerjee

Page 77
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples
Java programming-examples

More Related Content

What's hot

Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in javaJayasankarPR2
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handlingNahian Ahmed
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
Java package
Java packageJava package
Java packageCS_GDRCST
 

What's hot (20)

JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java threads
Java threadsJava threads
Java threads
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Methods in java
Methods in javaMethods in java
Methods in java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Java interface
Java interfaceJava interface
Java interface
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java package
Java packageJava package
Java package
 
Java packages
Java packagesJava packages
Java packages
 
Java &amp; advanced java
Java &amp; advanced javaJava &amp; advanced java
Java &amp; advanced java
 
Java swing
Java swingJava swing
Java swing
 
OOP java
OOP javaOOP java
OOP java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 

Viewers also liked

Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritancejwjablonski
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programsJames Brotsos
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 iimjobs and hirist
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manualLaura Popovici
 

Viewers also liked (20)

Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritance
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Hibernate Advance Interview Questions
Hibernate Advance Interview QuestionsHibernate Advance Interview Questions
Hibernate Advance Interview Questions
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Java practical
Java practicalJava practical
Java practical
 

Similar to Java programming-examples

Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
JavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeJavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeFederico Tomassetti
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxfredharris32
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxingGeetha Manohar
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxDrYogeshDeshmukh1
 
Basics java programing
Basics java programingBasics java programing
Basics java programingDarshan Gohel
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxsmile790243
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
Bt0074, oops with java
Bt0074, oops with javaBt0074, oops with java
Bt0074, oops with javasmumbahelp
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
01-ch01-1-println.ppt java introduction one
01-ch01-1-println.ppt java introduction one01-ch01-1-println.ppt java introduction one
01-ch01-1-println.ppt java introduction onessuser656672
 
Sql exception and class notfoundexception
Sql exception and class notfoundexceptionSql exception and class notfoundexception
Sql exception and class notfoundexceptionRohit Singh
 

Similar to Java programming-examples (20)

Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
JavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeJavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java code
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Article link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docxArticle link httpiveybusinessjournal.compublicationmanaging-.docx
Article link httpiveybusinessjournal.compublicationmanaging-.docx
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Java mcq
Java mcqJava mcq
Java mcq
 
Unit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptxUnit No 5 Files and Database Connectivity.pptx
Unit No 5 Files and Database Connectivity.pptx
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Bt0074, oops with java
Bt0074, oops with javaBt0074, oops with java
Bt0074, oops with java
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Java
JavaJava
Java
 
01-ch01-1-println.ppt java introduction one
01-ch01-1-println.ppt java introduction one01-ch01-1-println.ppt java introduction one
01-ch01-1-println.ppt java introduction one
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Sql exception and class notfoundexception
Sql exception and class notfoundexceptionSql exception and class notfoundexception
Sql exception and class notfoundexception
 

More from Mumbai Academisc (20)

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Ieee java projects list
Ieee java projects list Ieee java projects list
Ieee java projects list
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects list
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects list
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai Academics
 
Web based development
Web based developmentWeb based development
Web based development
 
Jdbc
JdbcJdbc
Jdbc
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Java tutorial part 2
Java tutorial part 2Java tutorial part 2
Java tutorial part 2
 
Engineering
EngineeringEngineering
Engineering
 
Jsp
JspJsp
Jsp
 

Recently uploaded

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Java programming-examples

  • 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. 2. 3. 4. 5. 6. 7. 8. 9. How to compile a java file? How to run a class file? How to debug a java file? How to set classpath? How to view current classpath? How to set destination of the class file? How to run a compiled class file? How to check version of java running on your system? How to set classpath when class files are in .jar file? Saikat Banerjee Page 1
  • 2. Problem Description: How to compile a java file? Solution: Following example demonstrates how to compile a java file using javac command. c:jdkdemoapp> 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:javaMyClasse1;C:javaMyClass2 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. Saikat Banerjee Page 2
  • 3. Demo.java will debug. Problem Description: How to set classpath? Solution: Following example demonstrates how to set classpath. C:> java -classpath C:javaDemoClasses 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 FilesJavajre1.6.0_03libextQTJava.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. Saikat Banerjee Page 3
  • 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:jdkdemoapp>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:javamyclasses.jar utility.testapp.main Saikat Banerjee Page 4
  • 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. Saikat Banerjee Page 5
  • 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. Saikat Banerjee Page 6
  • 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. Saikat Banerjee Page 7
  • 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]); Saikat Banerjee Page 8
  • 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 Saikat Banerjee Page 9
  • 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"); } } Saikat Banerjee Page 10
  • 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 Saikat Banerjee Page 11
  • 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"); Saikat Banerjee Page 12
  • 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. Saikat Banerjee Page 13
  • 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 24 26 44 46 64 66 8 10 12 14 16 18 20 22 28 30 32 34 36 38 40 42 48 50 52 54 56 58 60 62 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? Saikat Banerjee Page 14
  • 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); Saikat Banerjee Page 15
  • 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. Saikat Banerjee Page 16
  • 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]); } } } Saikat Banerjee Page 17
  • 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" }; Saikat Banerjee Page 18
  • 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 Saikat Banerjee Page 19
  • 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 Saikat Banerjee Page 20
  • 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] Saikat Banerjee Page 21
  • 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"); Saikat Banerjee Page 22
  • 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] Saikat Banerjee Page 23
  • 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)); } } Saikat Banerjee Page 24
  • 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 Saikat Banerjee Page 25
  • 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); } } Saikat Banerjee Page 26
  • 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 : " Saikat Banerjee Page 27
  • 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){ Saikat Banerjee Page 28
  • 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 shortMonth shortMonth shortMonth shortMonth shortMonth shortMonth shortMonth shortMonth shortMonth shortMonth shortMonth = = = = = = = = = = = = Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Saikat Banerjee Page 29
  • 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 weekday weekday weekday weekday = = = = = Monday Tuesday Wednesday Thursday 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 " Saikat Banerjee Page 30
  • 31. + cl.getTime().toString() ); } } Result: The above code sample will produce the following result. today is Mon date after a date after 7 date after 3 Jun 22 02:47:02 IST 2009 month will be Wed Jul 22 02:47:02 IST 2009 hrs will be Wed Jul 22 09:47:02 IST 2009 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. Saikat Banerjee Page 31
  • 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 Saikat Banerjee Page 32
  • 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) Saikat Banerjee Page 33
  • 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; Saikat Banerjee Page 34
  • 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[]) { Saikat Banerjee Page 35
  • 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); Saikat Banerjee Page 36
  • 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 Disk Disk Disk Disk Disk Disk 1 2 1 3 1 2 1 from from from from from from from A A C A B B A to to to to to to to C B B C A C 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: %dn", counter, fibonacci(counter)); } } } Result: The above code sample will produce the following result. Fibonacci Fibonacci Fibonacci Fibonacci Fibonacci Fibonacci Fibonacci Fibonacci of of of of of of of of 0 1 2 3 4 5 6 7 is: is: is: is: is: is: is: is: Saikat Banerjee 0 1 1 2 3 5 8 13 Page 37
  • 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! = %dn", 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); Saikat Banerjee Page 38
  • 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) { Saikat Banerjee Page 39
  • 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 Saikat Banerjee Page 40
  • 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? Saikat Banerjee Page 41
  • 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. Saikat Banerjee Page 42
  • 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 Saikat Banerjee Page 43
  • 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. Saikat Banerjee Page 44
  • 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()); Saikat Banerjee Page 45
  • 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? Saikat Banerjee Page 46
  • 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("aString1n"); 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 copiedn"); out1.close(); InputStream in = new FileInputStream Saikat Banerjee Page 47
  • 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("aString1n"); 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); Saikat Banerjee Page 48
  • 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 ? Saikat Banerjee Page 49
  • 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 ? Saikat Banerjee Page 50
  • 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:abcdefghi"; 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. Saikat Banerjee Page 51
  • 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? Saikat Banerjee Page 52
  • 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())); } } Saikat Banerjee Page 53
  • 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 { Saikat Banerjee Page 54
  • 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 Saikat Banerjee Page 55
  • 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) Saikat Banerjee Page 56
  • 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 ? Saikat Banerjee Page 57
  • 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. Saikat Banerjee Page 58
  • 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. Saikat Banerjee Page 59
  • 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. Saikat Banerjee Page 60
  • 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? Saikat Banerjee Page 61
  • 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; } Saikat Banerjee Page 62
  • 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? Saikat Banerjee Page 63
  • 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); Saikat Banerjee Page 64
  • 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; Saikat Banerjee Page 65
  • 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 { Saikat Banerjee Page 66
  • 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; Saikat Banerjee Page 67
  • 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 Saikat Banerjee Page 68
  • 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; Saikat Banerjee Page 69
  • 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); } Saikat Banerjee Page 70
  • 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; Saikat Banerjee Page 71
  • 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 Saikat Banerjee Page 72
  • 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"); Saikat Banerjee Page 73
  • 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[]) Saikat Banerjee Page 74
  • 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)); } Saikat Banerjee Page 75
  • 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 . Saikat Banerjee Page 76
  • 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 Saikat Banerjee Page 77