You are on page 1of 157

JAVA PROGRAMS

JAVA PROGRAMS
[1]: JAVA STRING - Programming Examples

[2]: JAVA ARRAYS-Programming Examples

[3]: JAVA DATE & TIME-Programming Example

[4]: JAVA METHODS-Programming Examples

[5]: JAVA FILES -Programming Examples

[6]: JAVA DIRECTORY -Programming Examples

[7]: JAVA EXCEPTION - Programming Examples

[8]: JAVA DATA STRUCTURE - Programming Examples

[9]: JAVA COLLECTION - Programming Examples

[10]: JAVA THREADING -Programming Examples

[11]: JAVA APPLET - Programming Examples

[12]: JAVA SIMPLE GUI - Programming Examples

[13]: JAVA JDBC - Programming Examples

[14]: JAVA REGULAR EXPRESSION - Programming Examples

[15]: JAVA NETWORK - Programming Examples

[16]: TCS JAVA Programs Assignment

[17]: SOME MORE IMPORTANT PROGRAMS

durgesh.tripathi2@gmail.com Page 1
JAVA PROGRAMS

[1]: JAVA STRING - PROGRAMMING EXAMPLES

[1]: 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.
-32
0
0

[2]: 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

[3]: How to remove a particular character from a string?

durgesh.tripathi2@gmail.com Page 2
JAVA PROGRAMS

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.
thi is Java

[4]: 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

[5]: 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.
String before reverse:abcdef

durgesh.tripathi2@gmail.com Page 3
JAVA PROGRAMS

String after reverse:fedcba

[6]: 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

[7]: 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]);
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

durgesh.tripathi2@gmail.com Page 4
JAVA PROGRAMS

march

jan

jan
jan
feb.march

feb.march
feb.march

[8]: 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

[9]: 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

[10]: 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();

durgesh.tripathi2@gmail.com Page 5
JAVA PROGRAMS

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

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

[11]: 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");

durgesh.tripathi2@gmail.com Page 6
JAVA PROGRAMS

}
}

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
Creation time of String objects with intern(): 16 ms

[12]: 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

[13]: 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");
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");
}

durgesh.tripathi2@gmail.com Page 7
JAVA PROGRAMS

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

[14]: 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 TutorialsPoint";
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 TutorialsPoint
Unicode code point at position 5 in the string is =111

[15]: How to buffer strings?

Solution: Following example buffers strings and flushes it by using emit()


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

durgesh.tripathi2@gmail.com Page 8
JAVA PROGRAMS

2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82

[2]: JAVA ARRAYS-PROGRAMMING EXAMPLES:


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

[2]: 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;

durgesh.tripathi2@gmail.com Page 9
JAVA PROGRAMS

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

[3]: 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.
Dimension 1: 2
Dimension 2: 5

durgesh.tripathi2@gmail.com Page 10
JAVA PROGRAMS

[4]: 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]

[5]: 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]);
}
}
}

Result: The above code sample will produce the following result.
This is the greeting
For all the readers From
Java source .

[6]: 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;

durgesh.tripathi2@gmail.com Page 11
JAVA PROGRAMS

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

[7]: 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" };
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]

[8]: 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);

durgesh.tripathi2@gmail.com Page 12
JAVA PROGRAMS

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

[9]: 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

[10]: 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 };

durgesh.tripathi2@gmail.com Page 13
JAVA PROGRAMS

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

[11]: 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]

[11]: 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 {

durgesh.tripathi2@gmail.com Page 14
JAVA PROGRAMS

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]

[12]: 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");
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]

[13]: How to find an object or a string in an Array?

durgesh.tripathi2@gmail.com Page 15
JAVA PROGRAMS

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]
Array 1 contains String common2?? true
Array 2 contains Array1?? False

[14]: 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

[15]: How to compare two arrays?

Solution: Following example uses equals method to check whether two


arrays are or not.

durgesh.tripathi2@gmail.com Page 16
JAVA PROGRAMS

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

[3]: JAVA DATE & TIME PROGRAMMING


EXAMPLE:
[1]: 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
06:40:32 AM

[2]: 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.

durgesh.tripathi2@gmail.com Page 17
JAVA PROGRAMS

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

[3]: 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);
}
}

Result: The above code sample will produce the following result.The result
will chenge depending upon the current system time.
03:20

[4]: 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);
}
}

durgesh.tripathi2@gmail.com Page 18
JAVA PROGRAMS

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

[5]: 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 : " + sdf.format(date));
}
}

Result: The above code sample will produce the following result.
hour in h format : 8

[6]: 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

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

durgesh.tripathi2@gmail.com Page 19
JAVA PROGRAMS

public static void main(String[] args){


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

[8]: How to display name of the months in short format?

Solution: This example displays the names of the months in short form
with the help of DateFormatSymbols().getShortMonths() method of
DateFormatSymbols class.
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;

public class Main {


public static void main(String[] args) {
String[] shortMonths = new DateFormatSymbols()
.getShortMonths();
for (int i = 0; i < (shortMonths.length-1); i++) {
String shortMonth = shortMonths[i];
System.out.println("shortMonth = " + shortMonth);
}
}
}

Result: The above code sample will produce the following result.
shortMonth = Jan
shortMonth = Feb
shortMonth = Mar
shortMonth = Apr
shortMonth = May
shortMonth = Jun
shortMonth = Jul
shortMonth = Aug
shortMonth = Sep
shortMonth = Oct
shortMonth = Nov
shortMonth = Dec

[9]: 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();

durgesh.tripathi2@gmail.com Page 20
JAVA PROGRAMS

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


String weekday = weekdays[i];
System.out.println("weekday = " + weekday);
}
}
}

Result: The above code sample will produce the following result.
weekday = Monday
weekday = Tuesday
weekday = Wednesday
weekday = Thursday
weekday = Friday

[10]: 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 " + cl.getTime().toString() );
}
}

Result: The above code sample will produce the following result.
today is Mon Jun 22 02:47:02 IST 2009
date after a month will be Wed Jul 22 02:47:02 IST 2009
date after 7 hrs will be Wed Jul 22 09:47:02 IST 2009
date after 3 years will be Sun Jul 22 09:47:02 IST 2012

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

durgesh.tripathi2@gmail.com Page 21
JAVA PROGRAMS

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

[12]: How to display time in different languages?

Solution: This example uses DateFormat class to display time in Italian.


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

[13]: 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

durgesh.tripathi2@gmail.com Page 22
JAVA PROGRAMS

[14]: 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

[15]: 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)


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

durgesh.tripathi2@gmail.com Page 23
JAVA PROGRAMS

September 9, 2001
9/9/01

[4]: JAVA METHODS PROGRAMMING


EXAMPLES:
[1]: 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;
}
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 {

durgesh.tripathi2@gmail.com Page 24
JAVA PROGRAMS

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

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

durgesh.tripathi2@gmail.com Page 25
JAVA PROGRAMS

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

[3]: 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);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}

Result: The above code sample will produce the following result.
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C

[4]: 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))

durgesh.tripathi2@gmail.com Page 26
JAVA PROGRAMS

return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
}
}

Result: The above code sample will produce the following result.
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55

[5]: How to use method for calculating Factorial of a number?

Solution: This example shows the way of using method for calculating
Factorial of 9(nine) numbers.
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter, factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}

Result: The above code sample will produce the following result.
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

durgesh.tripathi2@gmail.com Page 27
JAVA PROGRAMS

[6]: 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);
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

[7]: 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) {
if (o instanceof Vector)

durgesh.tripathi2@gmail.com Page 28
JAVA PROGRAMS

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

[8]: 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

[9]: How to use continue in a method?

Solution: This example uses continue statement to jump out of a loop in a


method.
public class Main {
public static void main(String[] args) {
StringBuffer searchstr = new StringBuffer( "hello how are you. ");
int length = searchstr.length();
int count = 0;
for (int i = 0; i < length; i++) {
if (searchstr.charAt(i) != 'h')
continue;
count++;
searchstr.setCharAt(i, 'h');
}
System.out.println("Found " + count + " h's in the string.");
System.out.println(searchstr);

durgesh.tripathi2@gmail.com Page 29
JAVA PROGRAMS

}
}

Result: The above code sample will produce the following result.
Found 2 h's in the string.
hello how are you.

[10]: How to use method overloading for printing different types


of array?

Solution: This example shows how to jump to a particular label when


break or continue statements occour in a loop.
public class Main {
public static void main(String[] args) {
String strSearch = "This is the string in which you have to search for a
substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() - substring.length();
testlbl:
for (int i = 0; i < = max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) != substring.charAt(k++){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("Found the substring .");
}
else {
System.out.println("did not find the substing in the string.");
}
}
}

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

[11]: How to use enum & switch statement?

Solution: This example displays how to check which enum member is


selected using Switch statements.
enum Car {
lamborghini,tata,audi,fiat,honda
}
public class Main {
public static void main(String args[]){
Car c;
c = Car.tata;

durgesh.tripathi2@gmail.com Page 30
JAVA PROGRAMS

switch(c) {
case lamborghini:
System.out.println("You choose lamborghini!");
break;
case tata:
System.out.println("You choose tata!");
break;
case audi:
System.out.println("You choose audi!");
break;
case fiat:
System.out.println("You choose fiat!");
break;
case honda:
System.out.println("You choose honda!");
break;
default:
System.out.println("I don't know your car.");
break;
}
}
}

Result: The above code sample will produce the following result.
You choose tata!

[12]: How to use enum constructor, instance variable & method?

Solution: This example initializes enum using a costructor & getPrice()


method & display values of enums.
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println(c + " costs " + c.getPrice() + " thousand dollars.");
}
}

Result: The above code sample will produce the following result.
All car prices:
lamborghini costs 900 thousand dollars.
tata costs 2 thousand dollars.
audi costs 50 thousand dollars.
fiat costs 15 thousand dollars.
honda costs 12 thousand dollars.

durgesh.tripathi2@gmail.com Page 31
JAVA PROGRAMS

[13]: How to use for and foreach loops to display elements of an


array.
Solution: This example displays an integer array using for loop & foreach
loops.
public class Main {
public static void main(String[] args) {
int[] intary = { 1,2,3,4};
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a){
System.out.println("Display an array using for loop");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachDisplay(int[] data){
System.out.println("Display an array using for each loop");
for (int a : data) {
System.out.print(a+ " ");
}
}
}

Result: The above code sample will produce the following result.
Display an array using for loop
1234
Display an array using for each loop
1234

[14]: How to make a method take variable lentgth argument as an


input?

Solution: This example creates sumvarargs() method which takes


variable no of int numbers as an argument and returns the sum of these
arguments as an output.
public class Main {
static int sumvarargs(int... intArrays){
int sum, i;
sum=0;
for(i=0; i< intArrays.length; i++) {
sum += intArrays[i];
}
return(sum);
}
public static void main(String args[]){
int sum=0;
sum = sumvarargs(new int[]{10,12,33});
System.out.println("The sum of the numbers is: " + sum);
}
}

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

durgesh.tripathi2@gmail.com Page 32
JAVA PROGRAMS

The sum of the numbers is: 55

[15]: How to use variable arguments as an input when dealing


with method overloading?

Solution: This example displays how to overload methods which have


variable arguments as an input.
public class Main {
static void vaTest(int ... no) {
System.out.print("vaTest(int ...): " + "Number of args: " + no.length +"
Contents: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
static void vaTest(boolean ... bl) {
System.out.print("vaTest(boolean ...) " + "Number of args: " + bl.length + "
Contents: ");
for(boolean b : bl)
System.out.print(b + " ");
System.out.println();
}
static void vaTest(String msg, int ... no) {
System.out.print("vaTest(String, int ...): " + msg +"no. of arguments: "+
no.length +" Contents: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
public static void main(String args[]){
vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}

Result: The above code sample will produce the following result.
vaTest(int ...): Number of args: 3 Contents: 1 2 3
vaTest(String, int ...): Testing: no. of arguments: 2
Contents: 10 20
vaTest(boolean ...) Number of args: 3 Contents:
true false false

[5]: JAVA FILES - PROGRAMMING EXAMPLES

[1]: How to compare paths of two files?

durgesh.tripathi2@gmail.com Page 33
JAVA PROGRAMS

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!

[2]: How to create a new file?


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!

[3]: 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;

durgesh.tripathi2@gmail.com Page 34
JAVA PROGRAMS

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.
Tue 12 May 10:18:50 PDF 2009

[4]: 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

[5]: 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

durgesh.tripathi2@gmail.com Page 35
JAVA PROGRAMS

[6]: 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

[7]: 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.
Renamed

[8]: 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;
}

durgesh.tripathi2@gmail.com Page 36
JAVA PROGRAMS

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

[9]: 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());
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

[10]: 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:");

durgesh.tripathi2@gmail.com Page 37
JAVA PROGRAMS

out.close();
}
}

Result: The above code sample will produce the following result.
temporary file created:

[11]: How to append a string in an existing file?

Solution: This example shows how to append a string in an existing file


using filewriter method.
import java.io.*;

public class Main {


public static void main(String[] args) throws Exception {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
out.write("aString1\n");
out.close();
out = new BufferedWriter(new FileWriter("filename",true));
out.write("aString2");
out.close();
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
}
in.close();
catch (IOException e) {
System.out.println("exception occoured"+ e);
}
}
}

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

[12]: How to copy one file into another file?

Solution: This example shows how to copy contents of one file into
another file using read & write methods of BufferedWriter class.
import java.io.*;

public class Main {


public static void main(String[] args)
throws Exception {
BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
InputStream in = new FileInputStream(new File("srcfile"));
OutputStream out = new FileOutputStream(new File("destnfile"));
byte[] buf = new byte[1024];
int len;

durgesh.tripathi2@gmail.com Page 38
JAVA PROGRAMS

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

[13]: How to delete a file?

Solution: This example shows how to delete a file using delete() method
of File class.
import java.io.*;

public class Main {


public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
out.write("aString1\n");
out.close();
boolean success = (new File("filename")).delete();
if (success) {
System.out.println("The file has been successfully deleted");
}
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (IOException e) {
System.out.println("exception occoured"+ e);
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

[14]: How to read a file?


durgesh.tripathi2@gmail.com Page 39
JAVA PROGRAMS

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

[15]: How to write into a file?

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.

[6]: JAVA DIRECTORY - PROGRAMMING


EXAMPLES

durgesh.tripathi2@gmail.com Page 40
JAVA PROGRAMS

[1]: How to create directories recursively?

Solution: Following example shows how to create directories recursively


with the help of file.mkdirs() methods of File class.
import java.io.File;

public class Main {


public static void main(String[] args) {
String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
File file = new File(directories);
boolean result = file.mkdirs();
System.out.println("Status = " + result);
}
}

Result: The above code sample will produce the following result.
Status = true

[2]: 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.
The directory is deleted.

[3]: 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;

durgesh.tripathi2@gmail.com Page 41
JAVA PROGRAMS

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!

[4]: 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());
}
}

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

[5]: How to print the directory hierarchy?

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

durgesh.tripathi2@gmail.com Page 42
JAVA PROGRAMS

}
}

Result: The above code sample will produce the following result.
-Java
-----codes
---------string.txt
---------array.txt
-----tutorial

[6]: 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()));
}
}

Result: The above code sample will produce the following result.
last modifed:10:20:54

[7]: 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

[8]: 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;

durgesh.tripathi2@gmail.com Page 43
JAVA PROGRAMS

public class Main {


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

[9]: 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

[10]: How to traverse a directory?

Solution: Following example demonstratres how to traverse a directory


with the help of dir.isDirectory() and dir.list() methods of File class.
import java.io.File;

public class Main {


public static void main(String[] argv)
throws Exception {
System.out.println("The Directory is traversed.");

durgesh.tripathi2@gmail.com Page 44
JAVA PROGRAMS

visitAllDirsAndFiles(C://Java);
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}

Result: The above code sample will produce the following result.
The Directory is traversed.

[11]: How to find current working directory?

Solution: Following example shows how to get current directory using


getProperty() method.
class Main {
public static void main(String[] args) {
String curDir = System.getProperty("user.dir");
System.out.println("You currently working in :" + curDir+ ": Directory");
}
}

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

You currently working in :C:\Documents and Settings\user\


My Documents\NetBeansProjects\TestApp: Directory

[12]: How to display root directories in the system?

Solution: Following example shows how to find root directories in your


system using listRoots() method of File class.
import java.io.*;

class Main{
public static void main(String[] args){
File[] roots = File.listRoots();
System.out.println("Root directories in your system are:");
for (int i=0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}
}
}

Result: The above code sample will produce the following result. The
result may vary depending on the system & operating system. If you are
using Unix system you will get a single root '/'.
Root directories in your system are:

durgesh.tripathi2@gmail.com Page 45
JAVA PROGRAMS

C:\
D:\
E:\
F:\
G:\
H:\

[13]: How to search for a file in a directory?

Solution: Following example shows how to search for a particular file in a


directory by making a Filefiter. Following example displays all the files
having file names starting with 'b'.
import java.io.*;

class Main {
public static void main(String[] args) {
File dir = new File("C:");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("b");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir 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.
Build
build.xml

[14]: How to display all the files in a directory?

Solution: Following example shows how to display all the filess contained
in a directory using list method of File class.
import java.io.*;

class Main {
public static void main(String[] args) {
File dir = new File("C:");
String[] children = dir.list();
if (children == null) {
System.out.println( "Either dir 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);
}

durgesh.tripathi2@gmail.com Page 46
JAVA PROGRAMS

}
}
}

Result: The above code sample will produce the following result.
build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test

[15]: How to display all the directories in a directory?

Solution: Following example shows how to display all the directories


contained in a directory making a filter which list method of File class.
import java.io.*;

class Main {
public static void main(String[] args) {
File dir = new File("F:");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("Either dir does not exist or is not a directory");
}
else {
for (int i=0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}

Result: The above code sample will produce the following result.
14
F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh final
F:\hhhh
F:\mov
F:\msdownld.tmp
F:\New Folder
F:\ravi
F:\ravi3

durgesh.tripathi2@gmail.com Page 47
JAVA PROGRAMS

F:\RECYCLER
F:\System Volume Information
F:\temp
F:\work

[7]: JAVA EXCEPTION - PROGRAMMING


EXAMPLES

[1]: 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)
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

durgesh.tripathi2@gmail.com Page 48
JAVA PROGRAMS

[2]: 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 mammal

[3]: How to use handle the exception methods?

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)

[4]: How to handle the runtime exceptions?

durgesh.tripathi2@gmail.com Page 49
JAVA PROGRAMS

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.
From f()

[5]: 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

durgesh.tripathi2@gmail.com Page 50
JAVA PROGRAMS

[6]: How to use catch to handle the exception?

Solution: This example shows how to use catch to handle the exception.
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

[7]: 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.
Arithmetic exception occoured :
java.lang.ArithmeticException: / by zero
Chained exception thrown manually :
java.lang.NumberFormatException

[8]: How to handle the exception with overloaded methods?

durgesh.tripathi2@gmail.com Page 51
JAVA PROGRAMS

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

[9]: How to handle checked exception?

Solution: This example shows how to handle checked exception using


catch block.
public class Main {
public static void main (String args[]) {
try{
throw new Exception("throwing an exception");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Result: The above code sample will produce the following result.
throwing an exception

[10]: How to pass arguments while throwing checked exception?

durgesh.tripathi2@gmail.com Page 52
JAVA PROGRAMS

Solution: This example shows how to pass arguments while throwing an


exception & how to use these arguments while catching an exception
using getMessage() method of Exception class.
public class Main{
public static void main (String args[]) {
try {
throw new Exception("throwing an exception");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Result: The above code sample will produce the following result.
throwing an exception

[11]: How to use handle multiple exceptions (devided by zero)?

Solution: This example shows how to handle multiple exceptions while


deviding by zero?
public class Main {
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=0;
int result=0;
try {
result = num1/num2;
System.out.println("The result is" +result);
for(int i =2;i >=0; i--){
System.out.println("The value of array is" +array[i]);
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error�. Array is out of Bounds"+e);
}
catch (ArithmeticException e) {
System.out.println("Can't be divided by Zero"+e);
}
}
}

Result: The above code sample will produce the following result.
Can't be divided by Zerojava.lang.ArithmeticException: / by zero

[12]: How to handle multiple exceptions while array is out of


bound?

Solution: This example shows how to handle multiple exception methods


by using System.err.println() method of System class .
public class Main {

durgesh.tripathi2@gmail.com Page 53
JAVA PROGRAMS

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 (ArrayIndexOutOfBoundsException e) {
System.out.println("Array is out of Bounds"+e);
}
catch (ArithmeticException e) {
System.out.println ("Can't divide by Zero"+e);
}
}
}

Result: The above code sample will produce the following result.
The result is1
Array is out of Boundsjava.lang.ArrayIndexOutOfBoundsException : 5

[13]: 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 they 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);
}
}
}

durgesh.tripathi2@gmail.com Page 54
JAVA PROGRAMS

Result: The above code sample will produce the following result.
30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException: / by zero

[14]: How to print stack of the Exception?

Solution: This example shows how to print stack of the exception using
printStack() method of the exception class.
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) {
e.printStackTrace();
}
}}

Result: The above code sample will produce the following result.
The result is1
java.lang.ArrayIndexOutOfBoundsException: 5
at testapp.Main.main(Main.java:28)

[15]: How to use exceptions with thread?

Solution: This example shows how to handle the exception while dealing
with threads.
class MyThread extends Thread{
public void run(){
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
class Main {
public static void main(String[] args){
MyThread t = new MyThread();
t.start();
try{
Thread.sleep(1000);
}
catch (Exception x){
System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}

durgesh.tripathi2@gmail.com Page 55
JAVA PROGRAMS

[16]: How to create user defined Exception?

Solution: This example shows how to create user defined exception by


extending Exception Class.
class WrongInputException extends Exception {
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong input");
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}

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

[8]: JAVA DATA STRUCTURE - PROGRAMMING


EXAMPLES

[1]: 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;

durgesh.tripathi2@gmail.com Page 56
JAVA PROGRAMS

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

[2]: 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 :

durgesh.tripathi2@gmail.com Page 57
JAVA PROGRAMS

" + 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

[3]: How to add an element at first and last position of a linked


list?

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

[4]: 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);
}

durgesh.tripathi2@gmail.com Page 58
JAVA PROGRAMS

public String doTrans() {


for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);
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 {

durgesh.tripathi2@gmail.com Page 59
JAVA PROGRAMS

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

[5]: 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());
}
}

durgesh.tripathi2@gmail.com Page 60
JAVA PROGRAMS

public class GenQueueTest {


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:
TD
GB
FS

[6]: 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;

public class StringReverserThroughStack {


private String input;
private String output;
public StringReverserThroughStack(String in) {
input = in;
}

durgesh.tripathi2@gmail.com Page 61
JAVA PROGRAMS

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

[7]: 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;

durgesh.tripathi2@gmail.com Page 62
JAVA PROGRAMS

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

[8]: 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;
}
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);

durgesh.tripathi2@gmail.com Page 63
JAVA PROGRAMS

System.out.print(" ");
}
System.out.println("");
}
}

Result: The above code sample will produce the following result.
50 40 30 20 10

[9]: 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);
}
}

Result: The above code sample will produce the following result.
12345
After swapping
52341

[10]: 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.

durgesh.tripathi2@gmail.com Page 64
JAVA PROGRAMS

BBTHP
BBMHP

[11]: 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;
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

[12]: 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

durgesh.tripathi2@gmail.com Page 65
JAVA PROGRAMS

[13]: 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

[14]: 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");
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]

durgesh.tripathi2@gmail.com Page 66
JAVA PROGRAMS

[9]: JAVA COLLECTION - PROGRAMMING


EXAMPLES

[1]: 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[])
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 + " ");
}

durgesh.tripathi2@gmail.com Page 67
JAVA PROGRAMS

}
}

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

[2]: 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));
}
}

Result: The above code sample will produce the following result.
Penny
dime
----------
nickle
Quarter

[3]: 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]);

durgesh.tripathi2@gmail.com Page 68
JAVA PROGRAMS

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.

[4]: 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 .
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

durgesh.tripathi2@gmail.com Page 69
JAVA PROGRAMS

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


Now the tree map Keys: [2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesday,
Thursday, Friday]

C:\collection>

[5]: How to make a collection read-only?

Solution: Following example shows how to make a collection read-only by


using Collections.unmodifiableList() method of Collection class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {


public static void main(String[] argv)
throws Exception {
List stuff = Arrays.asList(new String[] { "a", "b" });
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);
try {
list.set(0, "new value");
}
catch (UnsupportedOperationException e) {
}
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
Map map = new HashMap();
map = Collections.unmodifiableMap(map);
System.out.println("Collection is read-only now.");
}
}

Result: The above code sample will produce the following result.
Collection is read-only now.

[6]: How to remove a specific element from a collection?

Solution: Following example demonstrates how to remove a certain


element from a collection with the help of collection.remove() method of
Collection class.
import java.util.*;

public class CollectionTest {

durgesh.tripathi2@gmail.com Page 70
JAVA PROGRAMS

public static void main(String [] args) {


System.out.println( "Collection Example!\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
collection.remove(str2);
System.out.println("After removing [" + str2 + "]\n");
System.out.print("Now collection data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("Collection size: " + size + "\n");
}
}

Result: The above code sample will produce the following result.
Collection Example!

Collection data: Blue White Green Yellow

After removing [White]

Now collection data: Blue Green Yellow

Collection size: 3

[7]: How to reverse a collection?

Solution: Following example demonstratres how to reverse a collection


with the help of listIterator() and Collection.reverse() methods of Collection
and Listiterator class .
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

class UtilDemo3 {
public static void main(String[] args) {
String[] coins = { "A", "B", "C", "D", "E" };
List l = new ArrayList();
for (int i = 0; i < coins.length; i++)
l.add(coins[i]);
ListIterator liter = l.listIterator();

durgesh.tripathi2@gmail.com Page 71
JAVA PROGRAMS

System.out.println("Before reversal");
while (liter.hasNext())
System.out.println(liter.next());
Collections.reverse(l);
liter = l.listIterator();
System.out.println("After reversal");
while (liter.hasNext())
System.out.println(liter.next());
}
}

Result: The above code sample will produce the following result.
Before reversal
A
B
C
D
E
After reversal
E
D
C
B
A

[8]: How to shuffle the elements of a collection?

Solution: Following example how to shuffle the elements of a collection


with the help of Collections.shuffle() method of Collections class.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {


public static void main(String[] argv)
throws Exception {
String[] alpha = { "A", "E", "I", "O", "U" };
List list = new ArrayList(alpha);
Collections.shuffle(list);
System.out.println("list");
}
}

Result: The above code sample will produce the following result.
I
O
A
U
E

[9]: How to get size of a collection?

Solution: Following example shows how to get the size of a collection by


the use of collection.add() to add new data and collection.size() to get the
size of the collection of Collections class.
durgesh.tripathi2@gmail.com Page 72
JAVA PROGRAMS

import java.util.*;

public class CollectionTest {


public static void main(String [] args) {
System.out.println( "Collection Example!\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 =
"Green", str4 = "Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
System.out.println( "Collection size: " + size);
}
System.out.println();
}
}

Result: The above code sample will produce the following result.
Collection Example!

Collection data: Blue White Green Yellow


Collection size: 4

[10]: How to iterate through elements of HashMap?

Solution: Following example uses iterator Method of Collection class to


iterate through the HashMap.
import java.util.*;

public class Main {


public static void main(String[] args) {
HashMap< String, String> hMap =
new HashMap< String, String>();
hMap.put("1", "1st");
hMap.put("2", "2nd");
hMap.put("3", "3rd");
Collection cl = hMap.values();
Iterator itr = cl.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

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

durgesh.tripathi2@gmail.com Page 73
JAVA PROGRAMS

3rd
2nd
1st

[11]: How to use different types of Collections?

Solution: Following example uses different types of collection classes and


adds an element in those collections.
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;

public class Main {


public static void main(String[] args) {
List lnkLst = new LinkedList();
lnkLst.add("element1");
lnkLst.add("element2");
lnkLst.add("element3");
lnkLst.add("element4");
displayAll(lnkLst);
List aryLst = new ArrayList();
aryLst.add("x");
aryLst.add("y");
aryLst.add("z");
aryLst.add("w");
displayAll(aryLst);
Set hashSet = new HashSet();
hashSet.add("set1");
hashSet.add("set2");
hashSet.add("set3");
hashSet.add("set4");
displayAll(hashSet);
SortedSet treeSet = new TreeSet();
treeSet.add("1");
treeSet.add("2");
treeSet.add("3");
treeSet.add("4");
displayAll(treeSet);
LinkedHashSet lnkHashset = new LinkedHashSet();
lnkHashset.add("one");
lnkHashset.add("two");
lnkHashset.add("three");
lnkHashset.add("four");
displayAll(lnkHashset);
Map ma p1 = new HashMap();
map1.put("key1", "J");
map1.put("key2", "K");

durgesh.tripathi2@gmail.com Page 74
JAVA PROGRAMS

map1.put("key3", "L");
map1.put("key4", "M");
displayAll(map1.keySet());
displayAll(map1.values());
SortedMap map2 = new TreeMap();
map2.put("key1", "JJ");
map2.put("key2", "KK");
map2.put("key3", "LL");
map2.put("key4", "MM");
displayAll(map2.keySet());
displayAll(map2.values());
LinkedHashMap map3 = new LinkedHashMap();
map3.put("key1", "JJJ");
map3.put("key2", "KKK");
map3.put("key3", "LLL");
map3.put("key4", "MMM");
displayAll(map3.keySet());
displayAll(map3.values());
}
static void displayAll(Collection col) {
Iterator itr = col.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.print(str + " ");
}
System.out.println();
}
}

Result: The above code sample will produce the following result.
element1 element2 element3 element4
xyzw
set1 set2 set3 set4
1234
one two three four
key4 key3 key2 key1
MLKJ
key1 key2 key3 key4
JJ KK LL MM
key1 key2 key3 key4
JJJ KKK LLL MMM

[12]: How to use enumeration to display contents of HashTable?

Solution: Following example uses hasMoreElements & nestElement


Methods of Enumeration Class to display the contents of the HashTable.
import java.util.Enumeration;
import java.util.Hashtable;

public class Main {


public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.elements();
While (e.hasMoreElements()){
System.out.println(e.nextElement());

durgesh.tripathi2@gmail.com Page 75
JAVA PROGRAMS

}
}
}

Result: The above code sample will produce the following result.
Three
Two
One

[13]: How to set view of Keys from Java Hashtable?

Solution: Following example uses keys() method to get Enumeration of


Keys of the Hashtable.
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}

Result: The above code sample will produce the following result.
3
2
1

[14]: How to find min & max of a List?

Solution: Following example uses min & max Methods to find minimum &
maximum of the List.
import java.util.*;

public class Main {


public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split("
"));
System.out.println(list);
System.out.println("max: " + Collections.max(list));
System.out.println("min: " + Collections.min(list));
}
}

Result: The above code sample will produce the following result.
[one, Two, three, Four, five, six, one, three, Four]
max: three
min: Four

durgesh.tripathi2@gmail.com Page 76
JAVA PROGRAMS

[15]: How to find a sublist in a List?

Solution: Following example uses indexOfSubList() & lastIndexOfSubList()


to check whether the sublist is there in the list or not & to find the last
occurance of the sublist in the list.
import java.util.*;

public class Main {


public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split("
"));
System.out.println("List :"+list);
List sublist = Arrays.asList("three Four".split(" "));
System.out.println("SubList :"+sublist);
System.out.println("indexOfSubList: " + Collections.indexOfSubList(list,
sublist));
System.out.println("lastIndexOfSubList: " +
Collections.lastIndexOfSubList(list, sublist));
}
}

Result: The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
SubList :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7

[16]: How to replace an element in a list

Solution: Following example uses replaceAll() method to replace all the


occurance of an element with a different element in a list.
import java.util.*;

public class Main {


public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split("
"));
System.out.println("List :"+list);
Collections.replaceAll(list, "one", "hundread");
System.out.println("replaceAll: " + list);
}
}

Result: The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six,
hundread, three, Four]

[17]: How to rotate elements of the List?

durgesh.tripathi2@gmail.com Page 77
JAVA PROGRAMS

Solution: Following example uses rotate() method to rotate elements of


the list depending on the 2nd argument of the method.
import java.util.*;

public class Main {


public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six".split(" "));
System.out.println("List :"+list);
Collections.rotate(list, 3);
System.out.println("rotate: " + list);
}
}

Result: The above code sample will produce the following result.
List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]

[10]: JAVA THREADING - PROGRAMMING


EXAMPLES
[1]: How to check a thread is alive or not?

Solution: Following example demonstrates how to check a thread is alive


or not by extending Threda class and using currentThread() method.
public class TwoThreadAlive extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}

public void printMsg() {


Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}

public static void main(String[] args) {


TwoThreadAlive tt = new TwoThreadAlive();

durgesh.tripathi2@gmail.com Page 78
JAVA PROGRAMS

tt.setName("Thread");
System.out.println("before start(),
tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),
tt.isAlive()=" + tt.isAlive());
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
System.out.println("The end of main(),
tt.isAlive()=" + tt.isAlive());
}
}

Result: The above code sample will produce the following result.
before start(),tt.isAlive()=false
just after start(), tt.isAlive()=true
name=main
name=main
name=main
name=main
name=main
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=main
name=main
The end of main().tt.isAlive()=false

[2]: How to check a thread has stop or not?

Solution: Following example demonstrates how to check a thread has


stop or not by checking with isAlive() method.
public class Main {
public static void main(String[] argv)
throws Exception {
Thread thread = new MyThread();
thread.start();
if (thread.isAlive()) {
System.out.println("Thread has not finished");
}
else {
System.out.println("Finished");
}
long delayMillis = 5000;
thread.join(delayMillis);
if (thread.isAlive()) {
System.out.println("thread has not finished");
}
else {

durgesh.tripathi2@gmail.com Page 79
JAVA PROGRAMS

System.out.println("Finished");
}
thread.join();
}
}

class MyThread extends Thread {


boolean stop = false;
public void run() {
while (true) {
if (stop) {
return;
}
}
}
}

Result: The above code sample will produce the following result.
Thread has not finished
Finished

[3]: How to get the priorities of running threads?

Solution: Following example prints the priority of the running threads by


using setPriority() method .
public class SimplePriorities extends Thread {
private int countDown = 5;
private volatile double d = 0;
public SimplePriorities(int priority) {
setPriority(priority);
start();
}
public String toString() {
return super.toString() + ": " + countDown;
}
public void run() {
while(true) {
for(int i = 1; i < 100000; i++)
d = d + (Math.PI + Math.E) / (double)i;
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
new SimplePriorities(Thread.MAX_PRIORITY);
for(int i = 0; i < 5; i++)
new SimplePriorities(Thread.MIN_PRIORITY);
}
}

Result: The above code sample will produce the following result.
Thread[Thread-0,10,main]: 5
Thread[Thread-0,10,main]: 4
Thread[Thread-0,10,main]: 3
Thread[Thread-0,10,main]: 2
Thread[Thread-0,10,main]: 1
Thread[Thread-1,1,main]: 5
Thread[Thread-1,1,main]: 4

durgesh.tripathi2@gmail.com Page 80
JAVA PROGRAMS

Thread[Thread-1,1,main]: 3
Thread[Thread-1,1,main]: 2
Thread[Thread-1,1,main]: 1
Thread[Thread-2,1,main]: 5
Thread[Thread-2,1,main]: 4
Thread[Thread-2,1,main]: 3
Thread[Thread-2,1,main]: 2
Thread[Thread-2,1,main]: 1
.
.
.

[4]: How to monitor a thread's status?

Solution: Following example demonstrates how to monitor a thread's


status by extending Thread class and using currentThread.getName()
method.
class MyThread extends Thread{
boolean waiting= true;
boolean ready= false;
MyThread() {
}
public void run() {
String thrdName = Thread.currentThread().getName();
System.out.println(thrdName + " starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
}
catch(Exception exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
}
catch(InterruptedException exc) {
System.out.println("wait() interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
}
}
public class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;

durgesh.tripathi2@gmail.com Page 81
JAVA PROGRAMS

Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+"
Alive:="+thrd.isAlive()+"
State:=" + thrd.getState() );
}
}

Result: The above code sample will produce the following result.
main Alive=true State:=running

[5]: How to get the name of a running thread?

Solution: Following example shows How to get the name of a running


thread .
public class TwoThreadGetName extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args) {
TwoThreadGetName tt = new TwoThreadGetName();
tt.start();
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
}
}

Result: The above code sample will produce the following result.
name=main
name=main
name=main
name=main
name=main
name=thread
name=thread
name=thread
name=thread

[6]: How to solve the producer consumer problem using thread?

durgesh.tripathi2@gmail.com Page 82
JAVA PROGRAMS

Solution: Following example demonstrates how to solve the producer


consumer problem using thread.
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}

class Consumer extends Thread {


private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #"
+ this.number
+ " got: " + value);
}
}
}

class Producer extends Thread {


private CubbyHole cubbyhole;
private int number;

durgesh.tripathi2@gmail.com Page 83
JAVA PROGRAMS

public Producer(CubbyHole c, int number) {


cubbyhole = c;
this.number = number;
}

public void run() {


for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number
+ " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

Result: The above code sample will produce the following result.
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9

[7]: How to set the priority of a thread?

Solution: Following example how to set the priority of a thread with the
help of.
public class Main {
public static void main(String[] args)
throws Exception {
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("The priority has been set.");
}
}

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

durgesh.tripathi2@gmail.com Page 84
JAVA PROGRAMS

The priority has been set.

[8]: How to stop a thread for a while?

Solution: Following example demonstates how to stop a thread by


creating an user defined method run() taking the help of Timer classes'
methods.
import java.util.Timer;
import java.util.TimerTask;

class CanStop extends Thread {


private volatile boolean stop = false;
private int counter = 0;
public void run() {
while (!stop && counter < 10000) {
System.out.println(counter++);
}
if (stop)
System.out.println("Detected stop");
}
public void requestStop() {
stop = true;
}
}
public class Stopping {
public static void main(String[] args) {
final CanStop stoppable = new CanStop();
stoppable.start();
new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("Requesting stop");
stoppable.requestStop();
}
}, 350);
}
}

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

[9]: How to suspend a thread for a while?

Solution: Following example shows how to suspend a thread for a while


by creating sleepingThread() method.
public class SleepingThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread() {
super("" + ++threadCount);
start();
}
public String toString() {
return "#" + getName() + ": " + countDown;
}
public void run() {

durgesh.tripathi2@gmail.com Page 85
JAVA PROGRAMS

while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
throws InterruptedException {
for (int i = 0; i < 5; i++)
new SleepingThread().join();
System.out.println("The thread has been suspened.");
}
}

Result: The above code sample will produce the following result.
The thread has been suspened.

[10]: How to get the Id of the running thread?

Solution: Following example demonstrates how to get the Id of a running


thread using getThreadId() method.
public class Main extends Object implements Runnable {
private ThreadID var;

public Main(ThreadID v) {
this.var = v;
}

public void run() {


try {
print("var getThreadID =" + var.getThreadID());
Thread.sleep(2000);
print("var getThreadID =" + var.getThreadID());
} catch (InterruptedException x) {
}
}

private static void print(String msg) {


String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}

public static void main(String[] args) {


ThreadID tid = new ThreadID();
Main shared = new Main(tid);

try {
Thread threadA = new Thread(shared, "threadA");
threadA.start();

Thread.sleep(500);

Thread threadB = new Thread(shared, "threadB");

durgesh.tripathi2@gmail.com Page 86
JAVA PROGRAMS

threadB.start();

Thread.sleep(500);

Thread threadC = new Thread(shared, "threadC");


threadC.start();
} catch (InterruptedException x) {
}
}
}

class ThreadID extends ThreadLocal {


private int nextID;

public ThreadID() {
nextID = 10001;
}

private synchronized Integer getNewID() {


Integer id = new Integer(nextID);
nextID++;
return id;
}

protected Object initialValue() {


print("in initialValue()");
return getNewID();
}

public int getThreadID() {


Integer id = (Integer) get();
return id.intValue();
}

private static void print(String msg) {


String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
}

Result: The above code sample will produce the following result.
threadA: in initialValue()
threadA: var getThreadID =10001
threadB: in initialValue()
threadB: var getThreadID =10002
threadC: in initialValue()
threadC: var getThreadID =10003
threadA: var getThreadID =10001
threadB: var getThreadID =10002
threadC: var getThreadID =10003

[11]: How to check priority level of a thread?

Solution: Following example demonstrates how to check priority level of a


thread using getPriority() method of a Thread.
public class Main extends Object {
private static Runnable makeRunnable() {

durgesh.tripathi2@gmail.com Page 87
JAVA PROGRAMS

Runnable r = new Runnable() {


public void run() {
for (int i = 0; i < 5; i++) {
Thread t = Thread.currentThread();
System.out.println("in run() - priority="
+ t.getPriority()+ ", name=" + t.getName());
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
}
}
};
return r;
}
public static void main(String[] args) {
System.out.println("in main() - Thread.currentThread().
getPriority()=" + Thread.currentThread().getPriority());
System.out.println("in main() - Thread.currentThread()
.getName()="+ Thread.currentThread().getName());
Thread threadA = new Thread(makeRunnable(), "threadA");
threadA.start();
try {
Thread.sleep(3000);
}
catch (InterruptedException x) {
}
System.out.println("in main() - threadA.getPriority()="
+ threadA.getPriority());
}
}

Result: The above code sample will produce the following result.
in main() - Thread.currentThread().getPriority()=5
in main() - Thread.currentThread().getName()=main
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in main() - threadA.getPriority()=5
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA

[12]: How to display all running Thread?

Solution: Following example demonstrates how to display names of all


the running threads using getName() method.
public class Main extends Thread {
public static void main(String[] args) {
Main t1 = new Main();
t1.setName("thread1");
t1.start();
ThreadGroup currentGroup =
Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++)
System.out.println("Thread No:" + i + " = "

durgesh.tripathi2@gmail.com Page 88
JAVA PROGRAMS

+ lstThreads[i].getName());
}
}

Result: The above code sample will produce the following result.
Thread No:0 = main
Thread No:1 = thread1

[13]: How to display thread status?

Solution: Following example demonstrates how to display different status


of thread using isAlive() & getStatus() methods of Thread.
class MyThread extends Thread{
boolean waiting= true;
boolean ready= false;
MyThread() {
}
public void run() {
String thrdName = Thread.currentThread().getName();
System.out.println(thrdName + " starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
}
catch(Exception exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
}
catch(InterruptedException exc) {
System.out.println("wait() interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
}
}
public class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);

durgesh.tripathi2@gmail.com Page 89
JAVA PROGRAMS

showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+" Alive:"
+thrd.isAlive()+" State:" + thrd.getState() );
}
}

Result: The above code sample will produce the following result.
MyThread #1 Alive:false State:NEW
MyThread #1 starting.
waiting:true
waiting:true
alive
alive
MyThread #1 terminating.
alive
MyThread #1 Alive:false State:TERMINATED

[14]: How to interrupt a running Thread?

Solution: Following example demonstrates how to interrupt a running


thread interrupt() method of thread and check if a thread is interrupted
using isInterrupted() method.
public class GeneralInterrupt extends Object
implements Runnable {
public void run() {
try {
System.out.println("in run() -
about to work2()");
work2();
System.out.println("in run() -
back from work2()");
}
catch (InterruptedException x) {
System.out.println("in run() -
interrupted in work2()");
return;
}
System.out.println("in run() -
doing stuff after nap");
System.out.println("in run() -
leaving normally");
}
public void work2() throws InterruptedException {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("C isInterrupted()="
+ Thread.currentThread().isInterrupted());
Thread.sleep(2000);
System.out.println("D isInterrupted()="
+ Thread.currentThread().isInterrupted());
}
}
}
public void work() throws InterruptedException {

durgesh.tripathi2@gmail.com Page 90
JAVA PROGRAMS

while (true) {
for (int i = 0; i < 100000; i++) {
int j = i * 2;
}
System.out.println("A isInterrupted()="
+ Thread.currentThread().isInterrupted());
if (Thread.interrupted()) {
System.out.println("B isInterrupted()="
+ Thread.currentThread().isInterrupted());
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
GeneralInterrupt si = new GeneralInterrupt();
Thread t = new Thread(si);
t.start();
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
System.out.println("in main() -
interrupting other thread");
t.interrupt();
System.out.println("in main() - leaving");
}
}

Result: The above code sample will produce the following result.
in run() - about to work2()
in main() - interrupting other thread
in main() - leaving
C isInterrupted()=true
in run() - interrupted in work2()

[11]: JAVA APPLET - PROGRAMMING


EXAMPLES
[1]: How to create a basic Applet?

Solution: Following example demonstrates how to create a basic Applet


by extrnding Applet Class.You will need to embed another HTML code to
run this program.
import java.applet.*;
import java.awt.*;

public class Main extends Applet{


public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}

durgesh.tripathi2@gmail.com Page 91
JAVA PROGRAMS

Now compile the above code and call the generated class in your HTML
code as follows:

<HTML>
<HEAD>
</HEAD>
<BODY>
<div >
<APPLET CODE="Main.class" WIDTH="800" HEIGHT="500">
</APPLET>
</div>
</BODY>
</HTML>

Result: The above code sample will produce the following result in a java
enabled web browser.
Welcome in Java Applet.

[2]: How to create a banner using Applet?

Solution: Following example demonstrates how to play a sound using an


applet image using Thread class. It also uses drawRect(), fillRect() ,
drawString() methods of Graphics class.
import java.awt.*;
import java.applet.*;

public class SampleBanner extends Applet


implements Runnable{
String str = "This is a simple Banner ";
Thread t ;
boolean b;
public void init() {
setBackground(Color.gray);
setForeground(Color.yellow);
}
public void start() {
t = new Thread(this);
b = false;
t.start();
}
public void run () {
char ch;
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
}
catch(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);

durgesh.tripathi2@gmail.com Page 92
JAVA PROGRAMS

g.drawString(str, 1, 150);
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[3]: How to display clock using Applet?

Solution: Following example demonstrates how to display a clock using


valueOf() mehtods of String Class. & using Calender class to get the
second, minutes & hours.
import java.awt.*;
import java.applet.*;

import java.applet.*;
import java.awt.*;
import java.util.*;

public class ClockApplet extends Applet implements Runnable{


Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}
public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[4]: How to create different shapes using Applet?

Solution: Following example demonstrates how to create an applet which


will have a line, an Oval & a Rectangle using drawLine(), drawOval(,
drawRect() methods of Graphics clas.
import java.applet.*;

durgesh.tripathi2@gmail.com Page 93
JAVA PROGRAMS

import java.awt.*;

public class Shapes extends Applet{


int x=300,y=100,r=50;
public void paint(Graphics g){
g.drawLine(30,300,200,10);
g.drawOval(x-r,y-r,100,100);
g.drawRect(400,50,200,100);
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
A line , Oval & a Rectangle will be drawn in the browser.

[5]: How to fill colors in shapes using Applet?

Solution: Following example demonstrates how to create an applet which


will have fill color in a rectangle using setColor(), fillRect() methods of
Graphics class to fill color in a Rectangle.
import java.applet.*;
import java.awt.*;

public class fillColor extends Applet{


public void paint(Graphics g){
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
A Rectangle with yellow color filled in it willl be drawn in the browser.

[6]: How to goto a link using Applet?

Solution: Following example demonstrates how to go to a particular


webpage from an applet using showDocument() method of AppletContext
class.
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;

public class tesURL extends Applet implements ActionListener{


public void init(){
String link = "yahoo";
Button b = new Button(link);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){

durgesh.tripathi2@gmail.com Page 94
JAVA PROGRAMS

Button src = (Button)ae.getSource();


String link = "http://www."+src.getLabel()+".com";
try{
AppletContext a = getAppletContext();
URL u = new URL(link);
a.showDocument(u,"_self");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[7]: How to create an event listener in Applet?

Solution: Following example demonstrates how to create a basic Applet


having buttons to add & subtract two nos. Methods usded here are
addActionListener() to listen to an event(click on a button) & Button()
construxtor to create a button.
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class EventListeners extends Applet


implements ActionListener{
TextArea txtArea;
String Add, Subtract;
int i = 10, j = 20, sum =0,Sub=0;
public void init(){
txtArea = new TextArea(10,20);
txtArea.setEditable(false);
add(txtArea,"center");
Button b = new Button("Add");
Button c = new Button("Subtract");
b.addActionListener(this);
c.addActionListener(this);
add(b);
add(c);
}
public void actionPerformed(ActionEvent e){
sum = i + j;
txtArea.setText("");
txtArea.append("i = "+ i + "\t" + "j = " + j + "\n");
Button source = (Button)e.getSource();
if(source.getLabel() == "Add"){
txtArea.append("Sum : " + sum + "\n");
}
if(i >j){
Sub = i - j;
}
else{
Sub = j - i;
}
if(source.getLabel() == "Subtract"){
txtArea.append("Sub : " + Sub + "\n");

durgesh.tripathi2@gmail.com Page 95
JAVA PROGRAMS

}
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[8]: How to display image using Applet?

Solution: Following example demonstrates how to display image using


getImage() method. It also uses addImage() method of MediaTracker class.
import java.applet.*;
import java.awt.*;

public class appletImage extends Applet{


Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(), "demoimg.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[9]: How to open a link in a new window using Applet?

Solution: Following example demonstrates how to go open a particular


webpage from an applet in a new window using showDocument() with
second argument as "_blank" .
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;

public class testURL_NewWindow extends Applet


implements ActionListener{
public void init(){
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
String link = "http://www."+source.getLabel()+".com";
try {

durgesh.tripathi2@gmail.com Page 96
JAVA PROGRAMS

AppletContext a = getAppletContext();
URL url = new URL(link);
a.showDocument(url,"_blank");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[10]: How to play sound using Applet?

Solution: Following example demonstrates how to play a sound using an


applet image using getAudioClip(), play() & stop() methods of AudioClip()
class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class PlaySoundApplet extends Applet


implements ActionListener{
Button play,stop;
AudioClip audioClip;
public void init(){
play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "Sound.wav");
}
public void actionPerformed(ActionEvent ae){
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop "){
audioClip.play();
}
else if(source.getLabel() == " Stop "){
audioClip.stop();
}
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[11]: How to read a file using Applet?

Solution: Following example demonstrates how to read a file using an


Applet using openStream() method of URL.

durgesh.tripathi2@gmail.com Page 97
JAVA PROGRAMS

import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class readFileApplet extends Applet{
String fileToRead = "test1.txt";
StringBuffer strBuff;
TextArea txtArea;
Graphics g;
public void init(){
txtArea = new TextArea(100, 100);
txtArea.setEditable(false);
add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");
if (prHtml != null) fileToRead = new String(prHtml);
readFile();
}
public void readFile(){
String line;
URL url = null;
try{
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e){}
try{
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader
(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null){
strBuff.append(line + "\n");
}
txtArea.append("File Name : " + fileToRead + "\n");
txtArea.append(strBuff.toString());
}
catch(IOException e){
e.printStackTrace();
}
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[12]: How to write to a file using Applet?

Solution: Following example demonstrates how to write to a a file by


making textarea for writing in a browser using TextArea() making Labels &
then creating file using File() constructor.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import java.net.*;

public class WriteFile extends Applet{


Button write = new Button("WriteToFile");

durgesh.tripathi2@gmail.com Page 98
JAVA PROGRAMS

Label label1 = new Label("Enter the file name:");


TextField text = new TextField(20);
Label label2 = new Label("Write your text:");
TextArea area = new TextArea(10,20);
public void init(){
add(label1);
label1.setBackground(Color.lightGray);
add(text);
add(label2);
label2.setBackground(Color.lightGray);
add(area);
add(write,BorderLayout.CENTER);
write.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e){
new WriteText();
}
}
);
}
public class WriteText {
WriteText(){
try {
String str = text.getText();
if(str.equals("")){
JOptionPane.showMessageDialog(null,
"Please enter the file name!");
text.requestFocus();
}
else{
File f = new File(str);
if(f.exists()){
BufferedWriter out = new
BufferedWriter(new FileWriter(f,true));
if(area.getText().equals("")){
JOptionPane.showMessageDialog
(null,"Please enter your text!");
area.requestFocus();
}
else{
out.write(area.getText());
if(f.canWrite()){
JOptionPane.showMessageDialog(null,
"Text is written in "+str);
text.setText("");
area.setText("");
text.requestFocus();
}
else{
JOptionPane.showMessageDialog(null,
"Text isn't written in "+str);
}
out.close();
}
}
else{
JOptionPane.showMessageDialog
(null,"File not found!");
text.setText("");
text.requestFocus();
}
}
}
catch(Exception x){

durgesh.tripathi2@gmail.com Page 99
JAVA PROGRAMS

x.printStackTrace();
}
}
}
}

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[13]: How to use swing applet in JAVA?

Solution: Following example demonstrates how to go use Swing Applet in


JAVA by implementing ActionListener & by creating JLabels.
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class SApplet extends Applet implements ActionListener {


TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, sum = 0;
public void init(){
label1 = new Label("please enter number : ");
add(label1);
label1.setBackground(Color.yellow);
label1.setForeground(Color.magenta);
input = new TextField(5);
add(input);
label2 = new Label("Sum : ");
add(label2);
label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
output = new TextField(20);
add(output);
b1 = new Button("Add");
add(b1);
b1.addActionListener(this);
lbl = new JLabel("Swing Applet Example. ");
add(lbl);
setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae){
try{
num = Integer.parseInt(input.getText());
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the second Text Box : " + output.getText());
}
catch(NumberFormatException e){
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}

durgesh.tripathi2@gmail.com Page 100


JAVA PROGRAMS

Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.

[12]: JAVA SIMPLE GUI - PROGRAMMING


EXAMPLES

[1]: How to display text in different fonts?

Solution: Following example demonstrates how to display text in different


fonts using setFont() method of Font class.
import java.awt.*;
import java.awt.event.*
import javax.swing.*

public class Main extends JPanel {


String[] type = { "Serif","SansSerif"};
int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD,
Font.ITALIC + Font.BOLD };
String[] stylenames =
{ "Plain", "Italic", "Bold", "Bold & Italic" };
public void paint(Graphics g) {
for (int f = 0; f < type.length; f++) {
for (int s = 0; s < styles.length; s++) {
Font font = new Font(type[f], styles[s], 18);
g.setFont(font);
String name = type[f] + " " + stylenames[s];
g.drawString(name, 20, (f * 4 + s + 1) * 20);
}
}
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}

durgesh.tripathi2@gmail.com Page 101


JAVA PROGRAMS

Result: The above code sample will produce the following result.
Different font names are displayed in a frame.

[2]: How to draw a line using GUI?

Solution: Following example demonstrates how to draw a line using


draw() method of Graphics2D class with Line2D object as an argument.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Main extends JApplet {
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
int x = 5;
int y = 7;
g2.draw(new Line2D.Double(x, y, 200, 200));
g2.drawString("Line", x, 250);
}
public static void main(String s[]) {
JFrame f = new JFrame("Line");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JApplet applet = new Main();
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(300, 300));
f.setVisible(true);
}
}

Result: The above code sample will produce the following result.
Line is displayed in a frame.

[3]: How to display a message in a new frame?

Solution: Following example demonstrates how to display message in a


new frame by creating a frame using JFrame() & using JFrames
getContentPanel(), setSize() & setVisible() methods to display this frame.
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

durgesh.tripathi2@gmail.com Page 102


JAVA PROGRAMS

public class Main extends JPanel {


public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Serif", Font.PLAIN, 48));
paintHorizontallyCenteredText(g2, "Java Source", 200, 75);
paintHorizontallyCenteredText(g2, "and", 200, 125);
paintHorizontallyCenteredText(g2, "Support", 200, 175);
}
protected void paintHorizontallyCenteredText(Graphics2D g2,
String s, float centerX, float baselineY) {
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
float width = (float) bounds.getWidth();
g2.drawString(s, centerX - width / 2, baselineY);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(450, 350);
f.setVisible(true);
}
}

Result: The above code sample will produce the following result.
JAVA and J2EE displayed in a new Frame.

[4]: How to draw a polygon using GUI?

Solution: Following example demonstrates how to draw a polygon by


creating Polygon() object. addPoint() & drawPolygon() method is used to
draw the Polygon.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JPanel {


public void paintComponent(Graphics g) {
super.paintComponent(g);
Polygon p = new Polygon();
for (int i = 0; i < 5; i++)
p.addPoint((int)
(100 + 50 * Math.cos(i * 2 * Math.PI / 5)),
(int) (100 + 50 * Math.sin(i * 2 * Math.PI / 5)));
g.drawPolygon(p);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Polygon");
frame.setSize(350, 250);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());

durgesh.tripathi2@gmail.com Page 103


JAVA PROGRAMS

frame.setVisible(true);
}
}

Result: The above code sample will produce the following result.
Polygon is displayed in a frame.

[5]: How to display string in a rectangle?

Solution: Following example demonstrates how to display each character


in a rectangle by drawing a rectangle around each character using
drawRect() method.
import java.awt.*;
import javax.swing.*

public class Main extends JPanel {


public void paint(Graphics g) {
g.setFont(new Font("",0,100));
FontMetrics fm = getFontMetrics(new Font("",0,100));
String s = "message";
int x = 5;
int y = 5;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int h = fm.getHeight();
int w = fm.charWidth(c);
g.drawRect(x, y, w, h);
g.drawString(String.valueOf(c), x, y + h);
x = x + w;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Main());
frame.setSize(500, 700);
frame.setVisible(true);
}
}

Result: The above code sample will produce the following result.
Each character is displayed in a rectangle.

[6]: How to display different shapes using GUI?

Solution: Following example demonstrates how to display different


shapes using Arc2D, Ellipse2D, Rectangle2D, RoundRectangle2D classes.
import java.awt.Shape;
import java.awt.geom.*;

public class Main {


public static void main(String[] args) {
int x1 = 1, x2 = 2, w = 3, h = 4,
x = 5, y = 6,
y1 = 1, y2 = 2, start = 3;

durgesh.tripathi2@gmail.com Page 104


JAVA PROGRAMS

Shape line = new Line2D.Float(x1, y1, x2, y2);


Shape arc = new Arc2D.Float(x, y, w, h, start, 1, 1);
Shape oval = new Ellipse2D.Float(x, y, w, h);
Shape rectangle = new Rectangle2D.Float(x, y, w, h);
Shape roundRectangle = new RoundRectangle2D.Float
(x, y, w, h, 1, 2);
System.out.println("Different shapes are created:");
}
}

Result: The above code sample will produce the following result.
Different shapes are created.

[7]: How to draw a solid rectangle using GUI?

Solution: Following example demonstrates how to display a solid


rectangle using fillRect() method of Graphics class.
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

public static void main(String[] a) {


JFrame f = new JFrame();
f.setSize(400, 400);
f.add(new Main());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}

public void paint(Graphics g) {


g.fillRect (5, 15, 50, 75);
}
}

Result: The above code sample will produce the following result.
Solid rectangle is created.

[8]: How to create a transparent cursor?

Solution: Following example demonstrates how to create a transparent


cursor by using createCustomCursor() method with "invisiblecursor" as an
argument.
import java.awt.*;
import java.awt.image.MemoryImageSource;

public class Main {


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

durgesh.tripathi2@gmail.com Page 105


JAVA PROGRAMS

int[] pixels = new int[16 * 16];


Image image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(16, 16, pixels, 0, 16));
Cursor transparentCursor = Toolkit.getDefaultToolkit().
createCustomCursor(image, new Point(0, 0),
"invisibleCursor");
System.out.println("Transparent Cursor created.");
}
}

Result: The above code sample will produce the following result.
Transparent Cursor created.

[9]: How to check whether antialiasing is enabled or not?

Solution: Following example demonstrates how to check if antialiasing is


turned on or not using RenderingHints Class.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main {


public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new MyComponent());
frame.setSize(300, 300);
frame.setVisible(true);
}
}
class MyComponent extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
RenderingHints rh = g2d.getRenderingHints();
boolean bl = rh.containsValue
(RenderingHints.VALUE_ANTIALIAS_ON);
System.out.println(bl);
g2.setRenderingHint(RenderingHints.
KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
}

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

[10]: How to display colours in a frame?

Solution: Following example displays how to a display all the colors in a


frame using setRGB method of image class.
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

durgesh.tripathi2@gmail.com Page 106


JAVA PROGRAMS

import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main extends JComponent {


BufferedImage image;
public void initialize() {
int width = getSize().width;
int height = getSize().height;
int[] data = new int[width * height];
int index = 0;
for (int i = 0; i < height; i++) {
int red = (i * 255) / (height - 1);
for (int j = 0; j < width; j++) {
int green = (j * 255) / (width - 1);
int blue = 128;
data[index++] = (red < < 16) | (green < < 8) | blue;
}
}
image = new BufferedImage
(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data, 0, width);
}
public void paint(Graphics g) {
if (image == null)
initialize();
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
JFrame f = new JFrame("Display Colours");
f.getContentPane().add(new Main());
f.setSize(300, 300);
f.setLocation(100, 100);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}

Result: The above code sample will produce the following result.
Displays all the colours in a frame.

[11]: How to display a pie chart using a frame?

Solution: Following example displays how to a display a piechart by


making Slices class & creating arc depending on the slices.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

durgesh.tripathi2@gmail.com Page 107


JAVA PROGRAMS

import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;

class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = { new Slice(5, Color.black),
new Slice(33, Color.green),
new Slice(20, Color.yellow), new Slice(15, Color.red) };
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height,
startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Main {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}

Result: The above code sample will produce the following result.
Displays a piechart in a frame.

[12]: How to draw text using GUI?

Solution: Following example demonstrates how to draw text drawString(),


setFont() methods of Graphics class.
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;

durgesh.tripathi2@gmail.com Page 108


JAVA PROGRAMS

import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel{


public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Serif", Font.PLAIN, 96);
g2.setFont(font);
g2.drawString("Text", 40, 120);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new Main());
f.setSize(300, 200);
f.setVisible(true);
}
}

Result: The above code sample will produce the following result.
Text is displayed in a frame.

[13]: JAVA JDBC - PROGRAMMING EXAMPLES


[1]: How to connect to a database using JDBC? Assume that
database name is testDb and it has table named employee which
has 2 records.

durgesh.tripathi2@gmail.com Page 109


JAVA PROGRAMS

Solution: Following example uses getConnection, createStatement &


executeQuery methods to connect to a database & execute queries.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

Result: The above code sample will produce the following result.The result
may vary. You will get ClassNotfound exception if your JDBC driver is not
installed properly.
JDBC Class found
There are 2 record in the table

[2]: How to edit(Add or update) columns of a Table and how to


delete a table?

Solution: Following example uses create, alter & drop SQL commands to
create, edit or delete table
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username",
"password");
Statement stmt = con.createStatement();
String query ="CREATE TABLE employees
(id INTEGER PRIMARY KEY,
first_name CHAR(50),last_name CHAR(75))";
stmt.execute(query);
System.out.println("Employee table created");
String query1 = "aLTER TABLE employees ADD

durgesh.tripathi2@gmail.com Page 110


JAVA PROGRAMS

address CHAR(100) ";


String query2 = "ALTER TABLE employees DROP
COLUMN last_name";
stmt.execute(query1);
stmt.execute(query2);
System.out.println("Address column added to the table
& last_name column removed from the table");
String query3 = "drop table employees";
stmt.execute(query3);
System.out.println("Employees table removed");
}
}

Result: The above code sample will produce the following result.The result
may vary.
Employee table created
Address column added to the table & last_name
column removed from the table
Employees table removed from the database

[3]: How to retrieve contents of a table using JDBC connection?

Solution: Following example uses getString,getInt & executeQuery


methods to fetch & display the contents of the table.
import java.sql.*;

public class jdbcResultSet {


public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

Result: The above code sample will produce the following result.The result
may vary.
id name job

durgesh.tripathi2@gmail.com Page 111


JAVA PROGRAMS

1 alok trainee
2 ravi trainee

[4]: How to update(delete, insert or update) contents of a table


using JDBC connection?

Solution: Following method uses update, delete & insert SQL commands
to edit or delete row contents.
import java.sql.*;

public class updateTable {


public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username",
"password");
Statement stmt = con.createStatement();
String query1="update emp set name='ravi' where id=2";
String query2 = "delete from emp where id=1";
String query3 = "insert into emp values
(1,'ronak','manager')";
stmt.execute(query1);
stmt.execute(query2);
stmt.execute(query3);
ResultSet rs = stmt.executeQuery("SELECT * FROM emp");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

Result: The above code sample will produce the following result.The result
may vary.
id name job
2 ravi trainee
1 ronak manager

[5]: How to Search contents of a table?

durgesh.tripathi2@gmail.com Page 112


JAVA PROGRAMS

Solution: Following method uses where & like sql Commands to search
through the database.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username",
"password");
Statement stmt = con.createStatement();
String query[] ={"SELECT * FROM emp where id=1",
"select name from emp where name like 'ravi_'",
"select name from emp where name like 'ravi%'"};
for(String q : query){
ResultSet rs = stmt.executeQuery(q);
System.out.println("Names for query "+q+" are");
while (rs.next()) {
String name = rs.getString("name");
System.out.print(name+" ");
}
System.out.println();
}
}
}

Result: The above code sample will produce the following result.The result
may vary.
Names for query SELECT * FROM emp where id=1 are
ravi
Names for query select name from emp where name like 'ravi_' are
ravi2 ravi3
Names for query select name from emp where name like 'ravi%' are
ravi ravi2 ravi3 ravi123 ravi222

[6]: How to sort contents of a table?

Solution: Following example uses Order by SQL command to sort the


table.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement();
String query = "select * from emp order by name";
String query1="select * from emp order by name, job";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Table contents sorted by Name");
System.out.println("Id Name Job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");

durgesh.tripathi2@gmail.com Page 113


JAVA PROGRAMS

System.out.println(id + " " + name+" "+job);


}
rs = stmt.executeQuery(query1);
System.out.println("Table contents after sorted
by Name & job");
System.out.println("Id Name Job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id + " " + name+" "+job);
}
}
}

Result: The above code sample will produce the following result.The result
may vary.
Table contents after sorting by Name
Id Name Job
1 ravi trainee
5 ravi MD
4 ravi CEO
2 ravindra CEO
2 ravish trainee
Table contents after sorting by Name & job
Id Name Job
4 ravi CEO
5 ravi MD
1 ravi trainee
2 ravindra CEO
2 ravish trainee

[7]: How to join contents of more than one table & display?

Solution: Following example uses inner join sql command to combine


data from two tables. To display the contents of the table getString()
method of resultset is used.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
String query ="SELECT fname,lname,isbn from author
inner join books on author.AUTHORID = books.AUTHORID";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Fname Lname ISBN");
while (rs.next()) {
String fname = rs.getString("fname");
String lname = rs.getString("lname");
int isbn = rs.getInt("isbn");
System.out.println(fname + " " + lname+" "+isbn);
}
System.out.println();
System.out.println();
}
}

durgesh.tripathi2@gmail.com Page 114


JAVA PROGRAMS

Result: The above code sample will produce the following result.The result
may vary.
Fname Lname ISBN
john grisham 123
jeffry archer 113
jeffry archer 112
jeffry archer 122

[8]: How to commit a query?

Solution: Following example uses connection.commit() method to execute


a query.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement();
String query = "insert into emp values(2,'name1','job')";
String query1 ="insert into emp values(5,'name2','job')";
String query2 = "select * from emp";
ResultSet rs = stmt.executeQuery(query2);
int no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("No. of rows before commit
statement = "+ no_of_rows);
con.setAutoCommit(false);
stmt.execute(query1);
stmt.execute(query);
con.commit();
rs = stmt.executeQuery(query2);
no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("No. of rows after commit
statement = "+ no_of_rows);
}
}

Result: The above code sample will produce the following result.The result
may vary.
No. of rows before commit statement = 1
No. of rows after commit statement = 3

[9]: How to use Prepared Statement in java?

Solution: Following example uses PrepareStatement method to create


PreparedStatement. It also uses setInt & setString methods of
PreparedStatement to set parameters of PreparedStatement.
import java.sql.*;

durgesh.tripathi2@gmail.com Page 115


JAVA PROGRAMS

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
PreparedStatement updateemp = con.prepareStatement
("insert into emp values(?,?,?)");
updateemp.setInt(1,23);
updateemp.setString(2,"Roshan");
updateemp.setString(3, "CEO");
updateemp.executeUpdate();
Statement stmt = con.createStatement();
String query = "select * from emp";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Id Name Job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id + " " + name+" "+job);
}
}
}

Result: The above code sample will produce the following result.The result
may vary.
Id Name Job
23 Roshan CEO

[10]: How to make a Savepoint & Rollback in java?

Solution: Following example uses Rollback method of connection to


Rollback to a previously saved SavePoint
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement();
String query1 = "insert into emp values(5,'name','job')";
String query2 = "select * from emp";
con.setAutoCommit(false);
Savepoint spt1 = con.setSavepoint("svpt1");
stmt.execute(query1);
ResultSet rs = stmt.executeQuery(query2);
int no_of_rows = 0;
while (rs.next()) {
no_of_rows++;
}
System.out.println("rows before rollback statement = " + no_of_rows);
con.rollback(spt1);
con.commit();
no_of_rows = 0;
rs = stmt.executeQuery(query2);
while (rs.next()) {
no_of_rows++;
}

durgesh.tripathi2@gmail.com Page 116


JAVA PROGRAMS

System.out.println("rows after rollback statement = " + no_of_rows);


}
}

Result: The above code sample will produce the following result.The result
may vary.
rows before rollback statement = 4
rows after rollback statement = 3

[12]: How to execute multiple SQL commands on a database


simultaneously?

Solution: Following example uses addBatch & executeBatch commands to


execute multiple SQL commands simultaneously.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= " + rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= " + rs.getRow());
}
}

Result: The above code sample will produce the following result.The result
may vary.
rows before batch execution= 6
Batch executed
rows after batch execution= = 9

[13]: How to use different row methods to get no of rows in a


table, update table etc?

durgesh.tripathi2@gmail.com Page 117


JAVA PROGRAMS

Solution: Following example uses first, last,deletRow,getRow,insertRow


methods of ResultSet to delete or inser a Row & move pointer of ResultSet
to first or last Record.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "select * from emp";
ResultSet rs = stmt.executeQuery(query);
rs.last();
System.out.println("No of rows in table="+rs.getRow());
rs.moveToInsertRow();
rs.updateInt("id", 9);
rs.updateString("name","sujay");
rs.updateString("job", "trainee");
rs.insertRow();
System.out.println("Row added");
rs.first();
rs.deleteRow();
System.out.println("first row deleted");
}
}

Result: The above code sample will produce the following result.For this
code to compile your database has to be updatable. The result may vary.
No of rows in table=5
Row added
first row deleted

[14]: How to use different methods of column to Count no of


columns, get column name, get column type etc?

Solution: Following example uses getColumnCount, getColumnName,


getColumnTypeName, getColumnDisplaySize methods to get the no of
columns, name of the column or type of the column in the table.
import java.sql.*;

public class jdbcConn {


public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement();
String query = "select * from emp order by name";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("no of columns in the table= "+ rsmd.getColumnCount());
System.out.println("Name of the first column "+
rsmd.getColumnName(1));
System.out.println("Type of the second column "+
rsmd.getColumnTypeName(2));

durgesh.tripathi2@gmail.com Page 118


JAVA PROGRAMS

System.out.println("No of characters in 3rd column "+


rsmd.getColumnDisplaySize(2));
}
}

Result: The above code sample will produce the following result.The result
may vary.
no of columns in the table= 3
Name of the first columnID
Type of the second columnVARCHAR
No of characters in 3rd column20

[14]: JAVA REGULAR EXPRESSION - PROGRAMMING


EXAMPLES

[1]: How to reset the pattern of a regular expression?

Solution: Following example demonstrates how to reset the pattern of a


regular expression by using Pattern.compile() of Pattern class and m.find()
method of Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Resetting {


public static void main(String[] args)
throws Exception {
Matcher m = Pattern.compile("[frb][aiu][gx]").
matcher("fix the rug with bags");
while (m.find())
System.out.println(m.group());
m.reset("fix the rig with rags");
while (m.find())
System.out.println(m.group());
}
}

Result: The above code sample will produce the following result.
fix
rug
bag
fix
rig
rag

[2]: How to match duplicate words in a regular expression?

Solution: Following example shows how to search duplicate words in a


regular expression by using p.matcher() method and m.group() method of
regex.Matcher class.

durgesh.tripathi2@gmail.com Page 119


JAVA PROGRAMS

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String args[])
throws Exception {
String duplicatePattern = "\\b(\\w+) \\1\\b";
Pattern p = Pattern.compile(duplicatePattern);
int matches = 0;
String phrase = " this is a test ";
Matcher m = p.matcher(phrase);
String val = null;
while (m.find()) {
val = ":" + m.group() + ":";
matches++;
}
if(val>0)
System.out.println("The string has matched with the pattern.");
else
System.out.println("The string has not matched with the pattern.");
}
}

Result: The above code sample will produce the following result.
The string has matched with the pattern.

[3]: How to find every occurance of a word?

Solution: Following example demonstrates how to find every occurance of


a word with the help of Pattern.compile() method and m.group() method.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String args[])
throws Exception {
String candidate = "this is a test, A TEST.";
String regex = "\\ba\\w*\\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(candidate);
String val = null;
System.out.println("INPUT: " + candidate);
System.out.println("REGEX: " + regex + "\r\n");
while (m.find()) {
val = m.group();
System.out.println("MATCH: " + val);
}
if (val == null) {
System.out.println("NO MATCHES: ");
}
}
}

Result: The above code sample will produce the following result.
INPUT: this is a test ,A TEST.
REGEX: \\ba\\w*\\b
MATCH: a test
MATCH: A TEST

durgesh.tripathi2@gmail.com Page 120


JAVA PROGRAMS

[4]: How to know the last index of a perticular word in a string?

Solution: Following example demonstrates how to know the last index of


a perticular word in a string by using Patter.compile() method of Pattern
class and matchet.find() method of Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String args[]) {
String candidateString = "This is a Java example.
This is another Java example.";
Pattern p = Pattern.compile("Java");
Matcher matcher = p.matcher(candidateString);
matcher.find();
int nextIndex = matcher.end();
System.out.print("The last index of Java is:");
System.out.println(nextIndex);
}
}

Result: The above code sample will produce the following result.
The last index of Java is: 42

[5]: How to print all the strings that match a given pattern from a
file?

Solution: Following example shows how to print all the strings that match
a given pattern from a file with the help of Patternname.matcher() method
of Util.regex class.
import java.util.regex.*;
import java.io.*;

public class ReaderIter {


public static void main(String[] args)
throws IOException {
Pattern patt = Pattern.compile("[A-Za-z][a-z]+");
BufferedReader r = new BufferedReader
(new FileReader("ReaderIter.java"));
String line;
while ((line = r.readLine()) != null) {
Matcher m = patt.matcher(line);
while (m.find()) {
System.out.println(m.group(0));
int start = m.start(0);
int end = m.end(0);
Use CharacterIterator.substring(offset, end);
System.out.println(line.substring(start, end));
}
}
}
}

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

durgesh.tripathi2@gmail.com Page 121


JAVA PROGRAMS

http
www
darwinsys
com
All
rights
reserved
Software
written
by
Ian
Darwin
and
others

[6]: How to remove the white spaces?

Solution: Following example demonstrates how to remove the white


spaces with the help matcher.replaceAll(stringname) method of
Util.regex.Pattern class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String[] argv)
throws Exception {
String ExString = "This is a Java program.
This is another Java Program.";
String result=removeDuplicateWhitespace(ExString);
System.out.println(result);
}
public static CharSequence
removeDuplicateWhitespace(CharSequence inputStr) {
String patternStr = "\\s+";
String replaceStr = " ";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
return matcher.replaceAll(replaceStr);
}
}

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

[7]: How to match phone numbers in a list?

Solution: Following example shows how to match phone numbers in a list


to a perticlar pattern by using phone.matches(phoneNumberPattern)
method .
public class MatchPhoneNumber {
public static void main(String args[]) {
isPhoneValid("1-999-585-4009");
isPhoneValid("999-585-4009");
isPhoneValid("1-585-4009");
isPhoneValid("585-4009");

durgesh.tripathi2@gmail.com Page 122


JAVA PROGRAMS

isPhoneValid("1.999-585-4009");
isPhoneValid("999 585-4009");
isPhoneValid("1 585 4009");
isPhoneValid("111-Java2s");
}
public static boolean isPhoneValid(String phone) {
boolean retval = false;
String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";
retval = phone.matches(phoneNumberPattern);
String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " +
phoneNumberPattern;
if (retval) {
msg = " MATCH: pattern:" + phone + "\r\n regex: " +
phoneNumberPattern;
}
System.out.println(msg + "\r\n");
return retval;
}
}

Result: The above code sample will produce the following result.
MATCH: pattern:1-999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
MATCH: pattern:999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
MATCH: pattern:1-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:1.999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:999 585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:1 585 4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:111-Java2s
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}

[8]: How to count a group of words in a string?

Solution: Following example demonstrates how to count a group of words


in a string with the help of matcher.groupCount() method of regex.Matcher
class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherGroupCountExample {


public static void main(String args[]) {
Pattern p = Pattern.compile("J(ava)");
String candidateString = "This is Java.
This is a Java example.";
Matcher matcher = p.matcher(candidateString);
int numberOfGroups = matcher.groupCount();
System.out.println("numberOfGroups =" + numberOfGroups);
}
}

Result: The above code sample will produce the following result.
numberOfGroups =3

durgesh.tripathi2@gmail.com Page 123


JAVA PROGRAMS

[9]: How to search a perticular word in a string?

Solution: Following example demonstrates how to search a perticular


word in a string with the help of matcher.start() method of regex.Matcher
class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String args[]) {
Pattern p = Pattern.compile("j(ava)");
String candidateString = "This is a java program. This is another java
program.";
Matcher matcher = p.matcher(candidateString);
int nextIndex = matcher.start(1);
System.out.println(candidateString);
System.out.println("The index for java is:" + nextIndex);
}
}

Result: The above code sample will produce the following result.
This is a java program. This is another java program.
The index for java is: 11

[10]: How to split a regular expression?

Solution: Following example demonstrates how to split a regular


expression by using Pattern.compile() method and patternname.split()
method of regex.Pattern class.
import java.util.regex.Pattern;

public class PatternSplitExample {


public static void main(String args[]) {
Pattern p = Pattern.compile(" ");
String tmp = "this is the Java example";
String[] tokens = p.split(tmp);
for (int i = 0; i < tokens.length; i++) {
System.out.println(tokens[i]);
}
}
}

Result: The above code sample will produce the following result.
this
is
the
Java
Example

[11]: How to count replace first occourance of a String?

durgesh.tripathi2@gmail.com Page 124


JAVA PROGRAMS

Solution: Following example demonstrates how to replace first


occourance of a String in a String using replaceFirst() method of a Matcher
class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String args[]) {
Pattern p = Pattern.compile("hello");
String instring = "hello hello hello.";
System.out.println("initial String: "+ instring);
Matcher m = p.matcher(instring);
String tmp = m.replaceFirst("Java");
System.out.println("String after replacing 1st Match: " +tmp);
}
}

Result: The above code sample will produce the following result.
initial String: hello hello hello.
String after replacing 1st Match: Java hello hello.

[12]: How to check check whether date is in proper format or not?

Solution: Following example demonstrates how to check whether the


date is in a proper format or not using matches method of String class.
public class Main {
public static void main(String[] argv) {
boolean isDate = false;
String date1 = "8-05-1988";
String date2 = "08/04/1987" ;
String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
isDate = date1.matches(datePattern);
System.out.println("Date :"+ date1+": matches with
the this date Pattern:"+datePattern+"Ans:"+isDate);
isDate = date2.matches(datePattern);
System.out.println("Date :"+ date2+": matches with
the this date Pattern:"+datePattern+"Ans:"+isDate);
}
}

Result: The above code sample will produce the following result.
Date :8-05-1988: matches with the this date Pattern:
\d{1,2}-\d{1,2}-\d{4}Ans:true
Date :08/04/1987: matches with the this date Pattern:
\d{1,2}-\d{1,2}-\d{4}Ans:false

[13]: How to validate an email address format?

Solution: Following example demonstrates how to validate e-mail address


using matches() method of String class.

durgesh.tripathi2@gmail.com Page 125


JAVA PROGRAMS

public class Main {


public static void main(String[] args) {
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\
@([\\w]+\\.)+[\\w]+[\\w]$";
String email1 = "user@domain.com";
Boolean b = email1.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email1+" :Valid = " + b);
String email2 = "user^domain.co.in";
b = email2.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email2 +" :Valid = " + b);
}
}

Result: The above code sample will produce the following result.
is e-mail: user@domain.com :Valid = true
is e-mail: user^domain.co.in :Valid = false

[14]: How to replace all occurings of a string?

Solution: Following example demonstrates how to replace all occouranc


of a String in a String using replaceAll() method of Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String args[]) {
Pattern p = Pattern.compile("hello");
String instring = "hello hello hello.";
System.out.println("initial String: "+ instring);
Matcher m = p.matcher(instring);
String tmp = m.replaceAll("Java");
System.out.println("String after replacing 1st Match: " +tmp);
}
}

Result: The above code sample will produce the following result.
initial String: hello hello hello.
String after replacing 1st Match: Java Java Java.

[15]: How to make first character of each word in Uppercase?

Solution: Following example demonstrates how to convert first letter of


each word in a string into an uppercase letter Using toUpperCase(),
appendTail() methods.
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


public static void main(String[] args) {
String str = "this is a java test";
System.out.println(str);
StringBuffer stringbf = new StringBuffer();
Matcher m = Pattern.compile("([a-z])([a-z]*)",
Pattern.CASE_INSENSITIVE).matcher(str);
while (m.find()) {

durgesh.tripathi2@gmail.com Page 126


JAVA PROGRAMS

m.appendReplacement(stringbf,
m.group(1).toUpperCase() + m.group(2).toLowerCase());
}
System.out.println(m.appendTail(stringbf).toString());
}
}

Result: The above code sample will produce the following result.
this is a java test
This Is A Java Test

[15]: JAVA NETWORK - PROGRAMMING


EXAMPLES

[1]: How to split a string into a number of substrings?

Solution: Following example shows how to change the host name to its
specific IP address with the help of InetAddress.getByName() method of
net.InetAddress class.
import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIP {


public static void main(String[] args) {
InetAddress address = null;
try {
address = InetAddress.getByName("www.javatutorial.com");
}
catch (UnknownHostException e) {
System.exit(2);
}
System.out.println(address.getHostName() + "=" +
address.getHostAddress());
System.exit(0);
}
}

durgesh.tripathi2@gmail.com Page 127


JAVA PROGRAMS

Result: The above code sample will produce the following result.
http://www.javatutorial.com = 123.14.2.35

[2]: How to get connected with web server?

Solution: Following example demonstrates how to get connected with


web server by using sock.getInetAddress() method of net.Socket class.
import java.net.InetAddress;
import java.net.Socket;

public class WebPing {


public static void main(String[] args) {
try {
InetAddress addr;
Socket sock = new Socket("www.javatutorial.com", 80);
addr = sock.getInetAddress();
System.out.println("Connected to " + addr);
sock.close();
} catch (java.io.IOException e) {
System.out.println("Can't connect to " + args[0]);
System.out.println(e);
}
}
}

Result: The above code sample will produce the following result.
Connected to http://www,javatutorial.com/102.32.56.14

[3]: How to check a file is modified at a server or not?

Solution: Following example shows How to check a file is modified at a


server or not.
import java.net.URL;
import java.net.URLConnection;

public class Main {


public static void main(String[] argv)
throws Exception {
URL u = new URL("http://127.0.0.1/java.bmp");
URLConnection uc = u.openConnection();
uc.setUseCaches(false);
long timestamp = uc.getLastModified();
System.out.println("The last modification time of java.bmp is :"+timestamp);

}
}

Result: The above code sample will produce the following result.
The last modification time of java.bmp is :24 May 2009 12:14:50

[4]: How to create a multithreaded server?

durgesh.tripathi2@gmail.com Page 128


JAVA PROGRAMS

Solution: Following example demonstrates how to create a multithreaded


server by using ssock.accept() method of Socket class and
MultiThreadServer(socketname) method of ServerSocket class.
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThreadServer implements Runnable {


Socket csocket;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}

public static void main(String args[])


throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
PrintStream pstream = new PrintStream
(csocket.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i +
" bottles of beer on the wall");
}
pstream.close();
csocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}

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

[5]: How to get the file size from the server?

Solution: Following example demonstrates How to get the file size from
the server.
import java.net.URL;
import java.net.URLConnection;

public class Main {


public static void main(String[] argv)
throws Exception {
int size;
URL url = new URL("http://www.server.com");
URLConnection conn = url.openConnection();

durgesh.tripathi2@gmail.com Page 129


JAVA PROGRAMS

size = conn.getContentLength();
if (size < 0)
System.out.println("Could not determine file size.");
else
System.out.println("The size of the file is = " +size + "bytes");
conn.getInputStream().close();
}
}

Result: The above code sample will produce the following result.
The size of The file is = 16384 bytes

[6]: How to make a socket displaying message to a single client?

Solution: Following example demonstrates how to make a socket


displaying message to a single client with the help of ssock.accept()
method of Socket class.
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BeerServer {


public static void main(String args[])
throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
Socket sock = ssock.accept();
ssock.close();
PrintStream ps = new PrintStream(sock.getOutputStream());
for (int i = 10; i >= 0; i--) {
ps.println(i + " from Java Source and Support.");
}
ps.close();
sock.close();
}
}

Result: The above code sample will produce the following result.
Listening
10 from Java Source and Support
9 from Java Source and Support
8 from Java Source and Support
7 from Java Source and Support
6 from Java Source and Support
5 from Java Source and Support
4 from Java Source and Support
3 from Java Source and Support
2 from Java Source and Support
1 from Java Source and Support
0 from Java Source and Support

[7]: How to make a srever to allow the connection to the socket


6123?

durgesh.tripathi2@gmail.com Page 130


JAVA PROGRAMS

Solution: Following example shows how to make a srever to allow the


connection to the socket 6123 by using server.accept() method of
ServerSocket class andb sock.getInetAddress() method of Socket class.
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo {


public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(6123);
while (true) {
System.out.println("Listening");
Socket sock = server.accept();
InetAddress addr = sock.getInetAddress();
System.out.println("Connection made to "
+ addr.getHostName() + " (" + addr.getHostAddress() + ")");
pause(5000);
sock.close();
}
}
catch (IOException e) {
System.out.println("Exception detected: " + e);
}
}
private static void pause(int ms) {
try {
Thread.sleep(ms);
}
catch (InterruptedException e) {
}
}
}

Result: The above code sample will produce the following result.
Listening
Terminate batch job (Y/N)? n
Connection made to 112.63.21.45

[8]: How to get the parts of an URL?

Solution: Following example shows how to get the parts of an URL with
the help of url.getProtocol() ,url.getFile() method etc. of net.URL class.
import java.net.URL;

public class Main {


public static void main(String[] args)
throws Exception {
URL url = new URL(args[0]);
System.out.println("URL is " + url.toString());
System.out.println("protocol is " + url.getProtocol());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());

durgesh.tripathi2@gmail.com Page 131


JAVA PROGRAMS

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


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

Result: The above code sample will produce the following result.
URL is http://www.server.com
protocol is TCP/IP
file name is java_program.txt
host is 122.45.2.36
path is
port is 2
default port is 1

[9]: How to get the date of URL connection?

Solution: Following example demonstrates how to get the date of URL


connection by using httpCon.getDate() method of HttpURLConnection
class.
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

public class Main{


public static void main(String args[])
throws Exception {
URL url = new URL("http://www.google.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
long date = httpCon.getDate();
if (date == 0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(date));
}
}

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

[10]: How to read and download a webpage?

Solution: Following example shows how to read and download a webpage


URL() constructer of net.URL class.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;

public class Main {


public static void main(String[] args)
throws Exception {
URL url = new URL("http://www.google.com");
BufferedReader reader = new BufferedReader(new

durgesh.tripathi2@gmail.com Page 132


JAVA PROGRAMS

InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("data.html"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}

Result: The above code sample will produce the following result.
Welcome to Java Tutorial
Here we have plenty of examples for you!

Come and Explore Java!

[11]: How to find hostname from IP Address?

Solution: Following example shows how to change the host name to its
specific IP address with the help of InetAddress.getByName() method of
net.InetAddress class.
import java.net.InetAddress;

public class Main {


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

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


System.out.println("Host name is: "+addr.getHostName());
System.out.println("Ip address is: "+ addr.getHostAddress());
}
}

Result: The above code sample will produce the following result.
http://www.javatutorial.com = 123.14.2.35

[12]: How to determine IP Address & hostname of Local Computer?

Solution: Following example shows how to find local IP Address &


Hostname of the system using getLocalAddress() method of InetAddress
class.
import java.net.InetAddress;

public class Main {


public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress: "+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}

durgesh.tripathi2@gmail.com Page 133


JAVA PROGRAMS

Result: The above code sample will produce the following result.
Local HostAddress: 192.168.1.4
Local host name: harsh

[13]: How to check whether a port is being used or not?

Solution: Following example shows how to check whether any port is


being used as a server or not by creating a socket object.
import java.net.*;
import java.io.*;

public class Main {


public static void main(String[] args) {
Socket Skt;
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
for (int i = 0; i < 1024; i++) {
try {
System.out.println("Looking for "+ i);
Skt = new Socket(host, i);
System.out.println("There is a server on port " + i + " of " + host);
}
catch (UnknownHostException e) {
System.out.println("Exception occured"+ e);
break;
}
catch (IOException e) {
}
}
}
}

Result: The above code sample will produce the following result.
Looking for 0
Looking for 1
Looking for 2
Looking for 3
Looking for 4. . .

[14]: How to find proxy settings of a System?

Solution: Following example shows how to find proxy settings & create a
proxy connection on a system using put method of systemSetting &
getResponse method of HttpURLConnection class.
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;

public class Main{


public static void main(String s[])

durgesh.tripathi2@gmail.com Page 134


JAVA PROGRAMS

throws Exception{
try {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "proxy.mycompany1.local");
systemSettings.put("http.proxyPort", "80");
URL u = new URL("http://www.google.com");
HttpURLConnection con = (HttpURLConnection)
u.openConnection();
System.out.println(con.getResponseCode() + " : " +
con.getResponseMessage());
System.out.println(con.getResponseCode() ==
HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
System.out.println(false);
}
System.setProperty("java.net.useSystemProxies", "true");
Proxy proxy = (Proxy) ProxySelector.getDefault().
select(new URI("http://www.yahoo.com/")).iterator().
next();;
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress)
proxy.address();
if (addr == null) {
System.out.println("No Proxy");
}
else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}

Result: The above code sample will produce the following result.
200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80

[15]: How to create a socket at a specific port?

Solution: Following example shows how to sing Socket constructor of


Socket class.And also get Socket details using getLocalPort()
getLocalAddress , getInetAddress() & getPort() methods.
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Main {


public static void main(String[] args) {
try {
InetAddress addr =
InetAddress.getByName("74.125.67.100");
Socket theSocket = new Socket(addr, 80);

durgesh.tripathi2@gmail.com Page 135


JAVA PROGRAMS

System.out.println("Connected to "
+ theSocket.getInetAddress()
+ " on port " + theSocket.getPort() + " from port "
+ theSocket.getLocalPort() + " of "
+ theSocket.getLocalAddress());
}
catch (UnknownHostException e) {
System.err.println("I can't find " + e );
}
catch (SocketException e) {
System.err.println("Could not connect to " +e );
}
catch (IOException e) {
System.err.println(e);
}
}
}

Result: The above code sample will produce the following result.
Connected to /74.125.67.100 on port 80 from port
2857 of /192.168.1.4

[16]: TCS JAVA PROGRAMS ASSIGNMENT


[1]: Write a program to find the difference between sum of the
squares and the square of the sums of n numbers?

Solution:

import java.util.*;
class FindDifference
{
public static void main(String[] args)
{
int sum=0,sum1=0,sum2=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter value of n: ");
int n=input.nextInt();
for(int i=1;i<=n;i++){
int sq=i*i;
sum1+=sq;
}
//System.out.println(sum1);
for(int i=1;i<=n;i++){
sum+=i;
}
sum2=sum*sum;
//System.out.println(sum2);
int diff=0;
if(sum1>sum2){
diff=sum1-sum2;
}
else{
diff=sum2-sum1;
}
System.out.println(diff);

durgesh.tripathi2@gmail.com Page 136


JAVA PROGRAMS

}
}

[2]: Develop a program that accepts the area of a square and will
calculate its perimeter

Solution:

import java.util.*;
import java.text.*;
class PerimeterOfSquare{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("##.00");
Scanner input=new Scanner(System.in);
System.out.println("Enter Area of Square:");
double area=input.nextDouble();
double side=Math.sqrt(area);
System.out.println("Side of Square is: "+df.format(side));
double perimeter=4*side;
System.out.println("Perimeter of Square is: "+df.format(perimeter));

}
}
[3]: Develop the program calculateCylinderVolume., which accepts
radius of a cylinder's base disk and its height and computes the
volume of the cylinder.

Solution:

import java.util.*;
class CalculateCyliderVolume
{
public static void main(String[] args)
{
double PI=3.14;
Scanner input=new Scanner(System.in);
System.out.print("Enter Radius: ");
double r=input.nextDouble();

System.out.print("Enter Height: ");


double h=input.nextDouble();

double volume=PI*r*r*h;
System.out.println("Volume of Cylinder: "+volume);
}
}

[4]: Utopias tax accountants always use programs that compute


income taxes even though the tax rate is a solid, never-changing
15%. Define the program calculateTax which determines the tax
on the gross pay. Define calculateNetPay that determines the net
pay of an employee from the number of hours worked. Assume an
hourly rate of $12.

durgesh.tripathi2@gmail.com Page 137


JAVA PROGRAMS

Solution:

import java.util.*;
import java.text.*;
public class CalculateNetPay
{
public static void main(String[]args){
double taxRate=0.15;
double hourlyRate=12;
DecimalFormat df=new DecimalFormat("$##.00");
Scanner input=new Scanner(System.in);
System.out.print("Enter Number of Hours Worked: ");
double hrs=input.nextDouble();
double gp=hrs*hourlyRate;
double tax=gp*taxRate;
double netpay=gp-tax;
System.out.println("Net Pay is: "+df.format(netpay));
}
}

[5]: An old-style movie theater has a simple profit program. Each


customer pays $5 per ticket. Every performance costs the theater
$20, plus $.50 per attendee. Develop the program
calculateTotalProfit that consumes the number of attendees (of a
show) and calculates how much income the show earns.

Solution:

import java.util.*;
import java.text.*;
class CalculateTotalProfit{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("$##.00");
double theaterCost=20;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number of Customers: ");
double cus=input.nextDouble();
double earnFromTickets=5*cus;
double attendeesCost=cus*0.50;
double cost=attendeesCost+theaterCost;
double profit=earnFromTickets-cost;
System.out.println("Total Profit: "+df.format(profit));
}
}

[6]: Develop the program calculateHeight, which computes the


height that a rocket reaches in a given amount of time. If the
rocket accelerates at a constant rate g, it reaches a speed of g ·
t in t time units and a height of 1/2 * v * t where v is the speed at
t.

Solution:

durgesh.tripathi2@gmail.com Page 138


JAVA PROGRAMS

import java.util.*;
import java.text.*;
class CalculateHeight{
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("##.00");
Scanner input=new Scanner(System.in);
System.out.print("Enter constant rate:");
double g=input.nextDouble();
System.out.print("Enter time:");
double t=input.nextDouble();
double speed=g*t;
double h=speed*t;
double height=h/2;
System.out.println("Rocket reaches at the height of: "+df.format(height));
}
}

[7]: Develop the program calculatePipeArea. It computes the


surface area of a pipe , which isan open cylinder. The program
accpets three values: the pipes inner radius, its length, and the
thickness of its wall.
Solution:

import java.io.*;
class calculatePipeArea
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter inner radius");
int r=Integer.parseInt(br.readLine());
System.out.println("Enter thickness");
int t=Integer.parseInt(br.readLine());
System.out.println("Enter height");
int h=Integer.parseInt(br.readLine());
System.out.println("Volume: "+(2*Math.PI*(r+t)*h));
}
}

[8]: Develop a program that computes the distance a boat travels


across a river, given the width of the river, the boat's speed
perpendicular to the river, and the river's speed. Speed is
distance/time, and the Pythagorean Theorem is c2 = a2 + b2.
Solution:

import java.io.*;
class distance
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter boats speed");
double bs=Double.parseDouble(br.readLine());
System.out.println("Enter river speed");
double rs=Double.parseDouble(br.readLine());
System.out.println("Enter width of river");
double w=Double.parseDouble(br.readLine());
double x=rs/bs;

durgesh.tripathi2@gmail.com Page 139


JAVA PROGRAMS

x=1+x*x;
x=1/x;
x=Math.sqrt(x);
System.out.println("Distance: "+(w/x));
}
}

[9]: Develop a program that accepts an initial amount of money


(called the principal), a simple annual interest rate, and a number
of months will compute the balance at the end of that time.
Assume that no additional deposits or withdrawals are made and
that a month is 1/12 of a year. Total interest is the product of the
principal, the annual interest rate expressed as a decimal, and the
number of years.
Solution:

import java.io.*;
class SimpleInterest
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Principal");
int p=Integer.parseInt(br.readLine());
System.out.println("Enter Rate");
double r=Double.parseDouble(br.readLine());
System.out.println("Enter months");
Double t=Double.parseDouble(br.readLine());
t=t/12;
System.out.println("Interest: "+(0.01*(p*r*t)));
}
}

[10]: Create a Bank class with methods deposit & withdraw. The
deposit method would accept attributes amount & balance &
returns the new balance which is the sum of amount & balance.
Similarly, the withdraw method would accept the attributes
amount & balance & returns the new balance? balance ? Amount?
if balance > = amount or return 0 otherwise.
Solution:

static int output; // variables are defined at class level

public static void deposit(int amount, int balance) // performs deposit calculation
{
output = amount + balance;
}
public static void withdraw(int amount, int balance) // performs withdraw
calculation
{
output = balance - amount;
if (balance >= amount) {
System.out.println(":::Inside the WithDraw method :::");
} else {
System.out.println(":::Inside the WithDraw method :::");
output = 0;
}
}

durgesh.tripathi2@gmail.com Page 140


JAVA PROGRAMS

public static void main(String[] args) {


int amount, balance; // local variables
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("\t\t BANK ::::::::");
System.out.println("Enter the Amount value: ");
amount = Integer.parseInt(in.readLine()); // Input value from
keyboard for amount value
System.out.println("Enter the Balance value: ");
balance = Integer.parseInt(in.readLine()); // Input value from
keyboard for balance value
deposit(amount, balance); // deposit method called for
computation
System.out.println(":::Inside the Deposit method :::");
System.out.println("New Balance:::" + output);
withdraw(amount, balance); // withdraw method called for
compu
System.out.println("New Balance:::" + output);
} catch (Exception e) {
System.out.println("Error:::" + e);
}

[11]: Create an Employee class which has methods netSalary


which would accept salary & tax as arguments & returns the
netSalary which is tax deducted from the salary. Also it has a
method grade which would accept the grade of the employee &
return grade.
Solution:

import java.util.*;
class Employee
{
public double netSalary(double salary, double taxrate){
double tax=salary*taxrate;
double netpay=salary=tax;
return netpay;
}
public static void main(String[] args)
{
Employee emp=new Employee();
Scanner input=new Scanner(System.in);
System.out.print("Enter Salary: ");
double sal=input.nextDouble();
System.out.print("Enter Tax in %: ");
double taxrate=input.nextDouble()/100;
double net=emp.netSalary(sal,taxrate);
System.out.println("Net Salary is: "+net);
}
}

[12]: Create Product having following attributes: Product ID,


Name, Category ID and UnitPrice. Create ElectricalProduct having
the following additional attributes: VoltageRange and Wattage.
Add a behavior to change the Wattage and price of the electrical
product. Display the updated ElectricalProduct details
Solution:

durgesh.tripathi2@gmail.com Page 141


JAVA PROGRAMS

import java.util.*;
class Product{
int productID;
String name;
int categoryID;
double price;
Product(int productID,String name,int categoryID,double price){
this.productID=productID;
this.name=name;
this.categoryID=categoryID;
this.price=price;
}
}
public class ElectricalProduct extends Product{
int voltageRange;
int wattage;
ElectricalProduct(int productID,String name,int categoryID,double price,int
voltageRange, int wattage){
super(productID,name,categoryID,price);
this.voltageRange=voltageRange;
this.wattage=wattage;
}
public void display(){
System.out.println("Product ID: "+productID);
System.out.println("Name: "+name);
System.out.println("Category ID: "+categoryID);
System.out.println("Price: "+price);
System.out.println("Voltage Range: "+voltageRange);
System.out.println("Wattage: "+wattage);
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Product ID: ");
int pid=input.nextInt();
System.out.println("Enter Name: ");
String name=input.next();
System.out.println("Enter Catagory ID: ");
int cid=input.nextInt();
System.out.println("Enter Price: ");
double price=input.nextDouble();
System.out.println("Enter Voltage Range: ");
int vrange=input.nextInt();
System.out.println("Enter Wattage: ");
int wattage=input.nextInt();
System.out.println("****Details of Electrical Product****");
System.out.println();
ElectricalProduct p=new
ElectricalProduct(pid,name,cid,price,vrange,wattage);
p.display();
}
}

[13]: Create Book having following attributes: Book ID, Title,


Author and Price. Create Periodical which has the following
additional attributes: Period (weekly, monthly etc...) .Add a
behavior to modify the Price and the Period of the periodical.
Display the updated periodical details.
Solution:

durgesh.tripathi2@gmail.com Page 142


JAVA PROGRAMS

import java.util.*;

class Book{
int id;
String title;
String author;
double price;

public void setId(int id){


this.id=id;
}
public int getId(){
return id;
}
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
public void setAuthor(String author){
this.author=author;
}
public String getAuthor(){
return author;
}
public void setPrice(double price){
this.price=price;
}
public double getPrice(){
return price;
}
}
class Periodical
{
String timeperiod;
public void setTimeperiod(String timeperiod){
this.timeperiod=timeperiod;
}

public String getTimeperiod(){


return timeperiod;
}
}
public class BookInformation{
public static void main(String[]args){
Book b=new Book();
Periodical p=new Periodical();
Scanner input=new Scanner(System.in);
System.out.print("Book ID: ");
int id=input.nextInt();
b.setId(id);
System.out.print("Title: ");
String title=input.next();
b.setTitle(title);
System.out.print("Author: ");
String author=input.next();
b.setAuthor(author);
System.out.print("Price: ");
double price=input.nextDouble();
b.setPrice(price);

System.out.print("Period: ");

durgesh.tripathi2@gmail.com Page 143


JAVA PROGRAMS

String pp=input.next();
p.setTimeperiod(pp);
System.out.println();
System.out.println("----Book Information----");
System.out.println();
System.out.println("Book ID: "+b.getId());
System.out.println("Title: "+b.getTitle());
System.out.println("Author: "+b.getAuthor());
System.out.println("Price: "+b.getPrice());
System.out.println("Period: "+p.getTimeperiod());
}
}

[14]: Create Vehicle having following attributes: Vehicle No.,


Model, Manufacturer and Color. Create truck which has the
following additional attributes: loading capacity (100 tons?).Add a
behavior to change the color and loading capacity. Display the
updated truck details.
Solution:

import java.util.*;
class Vehicle
{
int no;
String model;
String manufacturer;
String color;

Vehicle(int no,String model,String manufacturer,String color){


this.no=no;
this.model=model;
this.manufacturer=manufacturer;
this.color=color;
}
}
public class Truck extends Vehicle{
int capacity;
Truck(int no,String model,String manufacturer,String color,int capacity){
super( no, model, manufacturer, color);
this.capacity=capacity;
}
void show(){
System.out.println("No = " + no);
System.out.println("Model = " + model);
System.out.println("manufacturer = " + manufacturer);
System.out.println("Color = " + color);
System.out.println("Capacity = " + capacity);
}

public static void main(String[] args)


{
Scanner input=new Scanner(System.in);
System.out.println("Truck No: ");
int no=input.nextInt();

System.out.println("Model: ");
String model=input.next();

System.out.println("Manufacturer: ");
String manufacturer=input.next();

durgesh.tripathi2@gmail.com Page 144


JAVA PROGRAMS

System.out.println("Color: ");
String color=input.next();

System.out.println("Loading Capacity: ");


int cap=input.nextInt();

Truck t=new Truck(no,model,manufacturer,color,cap);


System.out.println("****Truck Details****");
System.out.println();
t.show();
}
}

[15]: Write a program which performs to raise a number to a


power and returns the value. Provide a behavior to the program
so as to accept any type of numeric values and returns the results.
Solution:

import java.util.*;
import java.text.*;
class NumberProgram
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("##.##");
Scanner input=new Scanner(System.in);
System.out.print("Enter Number: ");
double num=input.nextDouble();
System.out.print("Raise Number's power: ");
double pow=input.nextDouble();
double value=Math.pow(num,pow);
System.out.println("Result is: "+df.format(value));
}
}

[16]: Write a function Model-of-Category for a Tata motor dealers,


which accepts category of car customer is looking for and returns
the car Model available in that category. the function should
accept the following categories "SUV", "SEDAN", "ECONOMY", and
"MINI" which in turn returns "TATA SAFARI" , "TATA INDIGO" ,
"TATA INDICA" and "TATA NANO" respectively.
Solution:

import java.util.*;

class TataMotors{
String category;
String model;
TataMotors(String category,String model){
this.category=category;
this.model=model;
}
public String getCategory(){
return category;
}
public String getModel(){
return model;
}

durgesh.tripathi2@gmail.com Page 145


JAVA PROGRAMS

public static void ModelOfCategory(ArrayList<TataMotors> list){


Scanner input=new Scanner(System.in);
System.out.print("Enter Category: ");
String category=input.nextLine();
System.out.println();
System.out.print("Model is: ");
for (TataMotors tm : list){
if(tm.getCategory().equals(category)){
System.out.print(tm.getModel());
}
}
}

public static void main(String[] args)


{
ArrayList<TataMotors> list=new ArrayList<TataMotors>();
list.add(new TataMotors("SUV","TATA SAFARI"));
list.add(new TataMotors("SEDAN","TATA INDIGO"));
list.add(new TataMotors("ECONOMY","TATA INDICA"));
list.add(new TataMotors("MINI","TATA NANO"));

ModelOfCategory(list);
}
}

[17]: Create a washing machine class with methods as switchOn,


acceptClothes, acceptDetergent, switchOff. acceptClothes accepts
the noofClothes as argument & returns the noofClothes
Solution:

public class WashingMachine{


public void switchOn(){
}
public int acceptClothes(int noofClothes){
return noofClothes;
}
public void acceptDetergent(){
}
public void switchOff(){
}
public static void main(String[] args){
WashingMachine wm = new WashingMachine();
wm.switchOn();
int clothesAccepted = wm.acceptClothes(10);
wm.acceptDtergent();
wm.switchOff();
}
}

[18]: Create a class called Student which has the following


methods:

I. Average: which would accept marks of 3 examinations & return


whether the student has passed or failed depending on whether
he has scored an average above 50 or not.

ii. Inputname: which would accept the name of the student &
returns the name.

durgesh.tripathi2@gmail.com Page 146


JAVA PROGRAMS

Solution:

import java.util.*;

public class Student{

Scanner input=new Scanner(System.in);

public String average(){


System.out.print("Enter Marks1: ");
double m1=input.nextDouble();
System.out.print("Enter Marks2: ");
double m2=input.nextDouble();
System.out.print("Enter Marks3: ");
double m3=input.nextDouble();
double tm=m1+m2+m3;
double avg=tm/3;
if(avg<50){
return "Failed";
}
if(avg>50){
return "Passed";
}
return " ";
}
public String getName(){
System.out.println("Enter Name:");
String name=input.nextLine();
String result=average();
return name+" get "+result;
}
public static void main(String[]args){
Student data=new Student();
String nameAndResut=data.getName();
System.out.println(nameAndResut);
}
}

[19]: Create a calculator class which will have methods add,


multiply, divide & subtract.
Solution:

class Calculation{
public int add(int a,int b){
return a+b;
}
public int subtract(int a,int b){
if(a>b){
return a-b;
}
else{
return b-a;
}
}
public int multiply(int a,int b){
return a*b;
}
public int divide(int a,int b){
if(a>b){
return a/b;
}
else{

durgesh.tripathi2@gmail.com Page 147


JAVA PROGRAMS

return b/a;
}
}
}
public class Calculator{
public static void main(String []args){
Calculation cal=new Calculation();
int add=cal.add(5,10);
int sub=cal.subtract(5,10);
int mul=cal.multiply(5,10);
int div=cal.divide(5,10);
System.out.println(add);
System.out.println(sub);
System.out.println(mul);
System.out.println(div);
}
}

[17]: SOME MORE IMPORTANT PROGRAMS


[1]: Write a program for the following output:
1 2 3 4 5

3 5 7 9

8 12 16

20 28

48

Solution:

class PrintDemo{

public static void main(String args[]) {

int i=0,j=0,n=5;

int a[]=new int[50];

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

a[i]=i+1;

System.out.print("" + a[i]);

for(i=4;i>0;i--) {

System.out.println();

for(j=0;j<1;j++) {

a[j]=a[j]+a[j+1];

System.out.print(" " + a[j]);

durgesh.tripathi2@gmail.com Page 148


JAVA PROGRAMS

[2]: Write a program to print Following Output:

*
**
***
****
*****

Solution:
public class Stars {

public static void main(String args[])

{ int c=1;

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

for(int j=i;j<5;j++)

{ System.out.print(" ");

for(int k=1;k<=c;k++)

if(k%2==0)

System.out.print(" ");

else

System.out.print("*");

System.out.println();

c+=2;

durgesh.tripathi2@gmail.com Page 149


JAVA PROGRAMS

[3]: Write a program to Print a character pattern like this. The


dots all stand for spaces. The spaces are mandatory. The pattern
is:-
abcde

.bcde

..cde

...de

....e

....ed

....edc

....edcb

....edcba

Solution:

class patsp
{
public static void main()
{
int ch,i,k,l='d',m=1,n='a';
for (i=5;i>=1;i--)
{
for(k=3;k>=i-1;k--)
System.out.print(" ");
for(ch=n;ch<='e';ch++)
{
System.out.print((char)ch);
}
System.out.println();
n=n+1;
}
for (i=4;i>=1;i--)
{
for(k=m;k<=i;k++)
System.out.print(" ");
for(ch='e';ch>=l;ch--)
{
System.out.print((char)ch);
}
System.out.println();
l=l-1;
m=m-1;
}
}
}

[4]: Clueless about this String Pattern Program.


SAIFEE

durgesh.tripathi2@gmail.com Page 150


JAVA PROGRAMS

SAIFE

SAIF

SAI

SA

Solution:
class Name
{
public static void main(String args[])
{
String s="SAIFEE";
int num=s.length();
while(num>0)
{
for(int j=0;j<num;j++)
{
System.out.print(" "+s.charAt(j)+" ");
}
System.out.println();
num--;
}
}
}

[5]: Write a Java Program to print pattern like this?


-----1
----121
---12321
--1234321
---12321
----121
-----1
Solution:

class test
{
public static void main(String[] s)
{ int a=0,b=0,c=0,d=0,i=0,e=1;
String r[]={"","","",""}; //requires initialization

/*array of string so that we can print the last 3 lines without


implementing any logic*/

String str=""; //for spacing


for(i=1;i<=4;i++)
{ a=i;
b=b*10+a;
c=b*e+d;

durgesh.tripathi2@gmail.com Page 151


JAVA PROGRAMS

d=rev(b); //reverses b
e=e*10;
System.out.println();
str="";
for(int p=i;p<6;p++)
str=str+" ";
System.out.print(str+c);
//prints the first four lines
r[i-1]=(str+c);
}
System.out.println();
for(i=2;i>=0;i--) //prints the last 3 lines
System.out.println(r[i]);
}

/*defined static so that can be called within the main without putting it in
seperate class and calling by class name*/

static int rev(int z)


{
int y=0;
while(z!=0)
{ y=y*10+z%10;
z=z/10;
}
return y;
}
}

[6]: Java program to print 1 8 27 64.?


Solution:
public class PrintCubes
{ public static void main(String args[])
{ for (int i = 0; i <= 10; i++)
{ int cube = i * i * i;
System.out.print(cube + " ");
}
}
}

[7]: Java code to print prime numbers from 1 to 100?


Solution:

import java.io.*;
class prmNo
{ public static void main(String[] args)
{ Console con = System.console();
System.out.println("Enter length of list :");
int n = con.readLine();
boolean flag;
System.out.print("1 ");
for (int i=2;i<=n;i++)
{ for (int j=2;j<i;j++)
{ if (i%j==0)

durgesh.tripathi2@gmail.com Page 152


JAVA PROGRAMS

flag=true;
}
if(!flag)
System.out.print(i+ " ");
flag=false;
}
}
}

[8]: How do you write a Program in java to print a diamond?


Solution:
import java.io.*;
class DiamondStar
{ public static void main(String args[])throws IOException
{ BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the limit");
int a=Integer.parseInt(in.readLine()),b,c,d,e,f,g,h=--a;
for(b=0;b<=a;b++)
{ System.out.println();
for(c=a;c>b;c--)
{ System.out.print(" ");
}
for(d=0;d<=b;d++)
{ System.out.print("* ");
}
}
for(e=0;e<h;e++)
{ System.out.println();
for(f=0;f<=e;f++)
{ System.out.print(" ");
}

for(g=f;g<=h;g++)
{ System.out.print("* ");
}
}
}
}

[9]: Write a program in java to print letters of a String in steps?

/* INPUT: Holy Home


* OUTPUT:H
* ------------ o
* --------------l
* ---------------y
* ---------------- _______________//The '-' are spaces
* ------------------H
* --------------------o
* ---------------------m
* -----------------------e
*
*/
Solution:
import java.io.*;
class StyleString

durgesh.tripathi2@gmail.com Page 153


JAVA PROGRAMS

{ public static void main()throws IOException


{ BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the String: ");
String s=in.readLine();
for(byte i=0;i<s.length();i++)
{ System.out.println();
for(byte j=0;j<i;j++)
System.out.print(' ');
System.out.print(s.charAt(i));
}
}
}

[10]: Write a program to print a to z letters?

Solution:
char letters[] = "abcdefghijklmnopqrstuvwxyz";
int i;
for (i = 0; i < 26; i++) printf ("%c\n", letters[i]);

[11]: Program to print the following pattern given the input as


number of rows(DIAMOND SHAPE). For e.g. Input = 7, the output
is as follows

*
* * *
* * ***
* * *****
* * ***
* * *
*

import java.io.*;

public class Diamond_Shape

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

{ BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Enter a no : ");

int i=Integer.parseInt(br.readLine());

int j,k,l;

j=k=l=0;

int n=i/2;

durgesh.tripathi2@gmail.com Page 154


JAVA PROGRAMS

for(j=0;j<n+1;j++)

{ for(k=0;k<n-j;k++)

{ System.out.print(" ");

for(l=0;l<j+1;l++)

{ System.out.print("*");

for(l=0;l<j;l++)

{ System.out.print("*");

System.out.println();

for(j=n;j>0;j--)

{ for(k=n-j+1;k>0;k--)

{ System.out.print(" ");

for(l=j-1;l>0;l--)

{ System.out.print("*");

for(l=j;l>0;l--)

{ System.out.print("*");

System.out.println();

}}

[12]: Write a java program to swap to no’s with and without using
a third variable

Solution:

1. public class SwapElementsWithoutThirdVariableExample {


2.
3. public static void main(String[] args) {
4.

durgesh.tripathi2@gmail.com Page 155


JAVA PROGRAMS

5. int num1 = 10;


6. int num2 = 20;
7.
8. System.out.println("Before Swapping");
9. System.out.println("Value of num1 is :" + num1);
10. System.out.println("Value of num2 is :" +num2);
11.
12. //add both the numbers and assign it to first
13. num1 = num1 + num2;
14. num2 = num1 - num2;
15. num1 = num1 - num2;
16.
17. System.out.println("Before Swapping");
18. System.out.println("Value of num1 is :" + num1);
19. System.out.println("Value of num2 is :" +num2);
20. }
21.
22.
23. }
24.
25. /*
26. Output of Swap Numbers Without Using Third Variable example would be
27. Before Swapping
28. Value of num1 is :10
29. Value of num2 is :20
30. Before Swapping
31. Value of num1 is :20
32. Value of num2 is :10
33. */

[13]: Write a java program that produces its source code as


output.

Solution:

import java.io.*;
class Source
{
public static void main(String args[])throws IOException
{
FileReader fr=new FileReader("Source.java");
int c;
while((c=fr.read())!=-1)
{
System.out.print((char)c);
}
}
}

[14]: Wright a program that Count letters in a String

Solution:

public class Main {

public void countLetters(String str) {


if (str == null)

durgesh.tripathi2@gmail.com Page 156


JAVA PROGRAMS

return;
int counter = 0;

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

if (Character.isLetter(str.charAt(i)))
counter++;
}

System.out.println("The input parameter contained " + counter + "


letters.");
}

public static void main(String[] args) {


new Main().countLetters("abcde123");
}
}

durgesh.tripathi2@gmail.com Page 157

You might also like