Java Programming Examples 140117111234 Phpapp02
Java Programming Examples 140117111234 Phpapp02
Find the best practical and ready to use Java Programming Examples.
Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
These examples would be very useful for your projects and learning.
Example - Home
Example - Environment
Example - Strings
Example - Arrays
Example - Date & Time
Example - Methods
Example - Files
Example - Directories
Example - Exceptions
Example - Data Structure
Example - Collections
Example - Networking
Example - Threading
Example - Applets
Example - Simple GUI
Example - JDBC
Example - Regular Exp
Solution:
Following example demonstrates how to compile a java file using javac command.
Result:
Problem Description:
Solution:
Following example demonstrates how to set multiple classpath. Multiple class paths are separated by a
semicolon.
Result:
Problem Description:
Solution:
Following example demonstrates how to debug a java file using =g option with javac command.
Result:
Problem Description:
Solution:
Result:
Problem Description:
Solution:
Following example demonstrates how to view current classpath using echo command.
Result:
.;C:\Program Files\Java\jre1.6.0_03\lib\ext\QTJava.zip
Problem Description:
Solution:
Following example demonstrates how to set destination of the class file that will be created after compiling a
java file using -d option with javac command.
Result:
Problem Description:
Solution:
Following example demonstrates how to run a class file from command prompt using java command.
c:\jdk\demoapp>java First
Result:
Problem Description:
Solution:
Following example demonstrates how to check version of java installed on your system using version argument
with java command.
java -version
Result:
Problem Description:
Solution:
Following example demonstrates how to set class path when classes are stored in a .jar or .zip file.
Problem Description:
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 .
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
Result:
Problem Description:
Solution:
This example shows how to determine the last position of a substring inside a string with the help of
strOrig.lastIndexOf(Stringname) method.
Result:
Problem Description:
Solution:
Following example shows hoe to remove a character from a particular position from a string with the help of
removeCharAt(string,position) method.
Result:
Problem Description:
Solution:
This example describes how replace method of java String class can be used to replace character or substring
by new one.
Result:
Wello World
Wallo World
Hallo World
Problem Description:
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.
Result:
Problem Description:
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.
Result:
Problem Description:
Solution:
Following example splits a string into a number of substrings with the help of str split(string) method and then
prints the substrings.
Result:
jan
feb
march
jan
jan
jan
feb.march
feb.march
feb.march
Problem Description:
Solution:
Following example changes the case of a string to upper case by using String toUpperCase() method.
Result:
Solution:
Following example determines region matchs in two strings by using regionMatches() method.
Result:
Problem Description:
Solution:
Following example compares the performance of two strings created in two different ways.
The above code sample will produce the following result.The result may vary.
Problem Description:
Solution:
Result:
The above code sample will produce the following result.The result may vary.
Problem Description:
Solution:
Following example returns a formatted string value by using a specific locale, format and arguments in format()
method
import java.util.*;
Result:
2.718282
2,7183
Problem Description:
Solution:
Following example shows performance of concatenation by using "+" operator and StringBuffer.append()
method.
Result:
The above code sample will produce the following result.The result may vary.
Problem Description:
Solution:
This example shows you how to use codePointBefore() method to return the character (Unicode code point)
before the specified index.
Result:
Problem Description:
Solution:
Result:
2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82
Problem Description:
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;
Result:
Problem Description:
Solution:
Following example shows how to use sort () method and user defined method insertElement ()to accomplish
the task.
import java.util.Arrays;
Result:
Problem Description:
Solution:
Following example helps to determine the upper bound of a two dimentional array with the use of
arrayname.length.
Result:
Problem Description:
Solution:
import java.util.ArrayList;
import java.util.Collections;
Result:
Problem Description:
Solution:
Following example demonstrates writing elements of an array to the output console through looping.
Problem Description:
Solution:
This example shows how to search the minimum and maximum element in an array by using Collection.max()
and Collection.min() methods of Collection class .
import java.util.Arrays;
import java.util.Collections;
Result:
Min number: 1
Max number: 9
Problem Description:
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;
Result:
[A, E, I, O, U]
Problem Description:
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.*;
Result:
100
100
100
100
100
100
100
100
100
50
Problem Description:
Solution:
Following example shows how to extend an array after initialization by creating an new array.
Result:
A
B
C
D
E
Problem Description:
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;
Result:
Problem Description:
Solution:
import java.util.ArrayList;
Result:
Solution:
Following example uses Removeall method to remove one array from another.
import java.util.ArrayList;
Result:
Problem Description:
Solution:
Following example shows how to find common elements from two arrays and store them in an array.
import java.util.ArrayList;
Result:
Problem Description:
Solution:
import java.util.ArrayList;
Result:
Problem Description:
Solution:
Following example shows how to use equals () method of Arrays to check if two arrays are equal or not.
import java.util.Arrays;
Result:
Problem Description:
Solution:
Following example uses equals method to check whether two arrays are or not.
import java.util.Arrays;
Problem Description:
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;
Result:
The above code sample will produce the following result.The result will change depending upon the current
system time
Problem Description:
Solution:
This example shows how to display the current month in the (MMM) format with the help of
Calender.getInstance() method of Calender class and fmt.format() method of Formatter class.
import java.util.Calendar;
import java.util.Formatter;
Result:
October Oct 10
Problem Description:
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;
The above code sample will produce the following result.The result will chenge depending upon the current
system time.
03:20
Problem Description:
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;
Result:
The above code sample will produce the following result.The result will change depending upon the current
system date and time
Problem Description:
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;
Result:
hour in h format : 8
Problem Description:
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;
Result:
The above code sample will produce the following result.The result will change depending upon the current
system date
Problem Description:
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;
Result:
The above code sample will produce the following result.The result will change depending upon the current
system time.
seconds in ss format : 14
Problem Description:
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;
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
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;
Result:
weekday = Monday
weekday = Tuesday
weekday = Wednesday
weekday = Thursday
weekday = Friday
Problem Description:
Solution:
The following examples shows us how to add time to a date using add() method of Calender.
import java.util.*;
Result:
Problem Description:
Solution:
Following example uses Locale class & DateFormat class to disply date in different Country's format.
import java.text.DateFormat;
import java.util.*;
Result:
Problem Description:
Solution:
Result:
Problem Description:
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.*;
Result:
Solution:
import java.util.*;
Result:
Problem Description:
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);
Result:
9/9/01 7:16 AM
Sep 9, 2001
Sep 9, 2001
Sunday, September 9, 2001
September 9, 2001
9/9/01
Problem Description:
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;
Result:
Problem Description:
Solution:
This example displays the way of using overloaded method for printing types of array (integer, double and
character).
Result:
Problem Description:
Solution:
This example displays the way of using method for solving Tower of Hanoi problem( for 3 disks).
Result:
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
Problem Description:
Solution:
This example shows the way of using method for calculating Fibonacci Series upto n numbers.
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
Problem Description:
Solution:
This example shows the way of using method for calculating Factorial of 9(nine) numbers.
Result:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
Problem Description:
Solution:
This example demonstrates the way of method overriding by subclasses with different number and type of
parameters.
Result:
Problem Description:
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;
Result:
Problem Description:
Solution:
Result:
Problem Description:
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;
Result:
Problem Description:
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;
Result:
The above code sample will produce the following result (if "myfile.txt does not exist before)
Success!
Problem Description:
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;
Result:
Problem Description:
Solution:
This example demonstrates how to create a file in a specified directory using File.createTempFile() method of
File class.
import java.io.File;
Result:
C:\JavaTemp37056.javatemp
Problem Description:
Solution:
This example shows how to check a file�s existence by using file.exists() method of File class.
import java.io.File;
Result:
The above code sample will produce the following result (if the file "java.txt" exists in 'C' drive).
true
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;
Result:
The above code sample will produce the following result.To test the example,first create a file 'java.txt' in 'C'
drive.
true
false
Problem Description:
Solution:
This example demonstrates how to renaming a file using oldName.renameTo(newName) method of File class.
import java.io.File;
Result:
The above code sample will produce the following result.To test this example, first create a file 'program.txt' in
'C' drive.
Problem Description:
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;
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.
Problem Description:
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;
Result:
The above code sample will produce the following result.The result may vary depending upon the system time.
Problem Description:
Solution:
This example shows how to create a temporary file using createTempFile() method of File class.
import java.io.*;
Result:
Problem Description:
This example shows how to append a string in an existing file using filewriter method.
import java.io.*;
Result:
aString1
aString2
Problem Description:
Solution:
This example shows how to copy contents of one file into another file using read & write methods of
BufferedWriter class.
import java.io.*;
Result:
string to be copied
Problem Description:
Solution:
This example shows how to delete a file using delete() method of File class.
import java.io.*;
Result:
Problem Description:
Solution:
This example shows how to read a file using readLine method of BufferedReader class.
import java.io.*;
Result:
aString
Problem Description:
This example shows how to write to a file using write method of BufferedWriter.
import java.io.*;
Result:
Problem Description:
Following example shows how to create directories recursively with the help of file.mkdirs() methods of File
class.
import java.io.File;
Result:
Status = true
Problem Description:
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;
Result:
Problem Description:
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;
Result:
Problem Description:
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;
Problem Description:
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;
Result:
-Java
-----codes
---------string.txt
---------array.txt
-----tutorial
Problem Description:
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;
last modifed:10:20:54
The above code sample will produce the following result (as Demo.txt is hidden).
True
Problem Description:
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;
Result:
Problem Description:
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;
Result:
sdk
---vehicles
------body.txt
------color.txt
------engine.txt
---ships
------shipengine.txt
Problem Description:
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;
Result:
Problem Description:
Solution:
This example shows how to use finally block to catch runtime exceptions (Illegal Argument Exception) by the
use of e.getMessage().
Result:
All done
java.lang.Object@1b90b39
Error: (Don't like type 1).
All done
Problem Description:
Solution:
This example shows how to handle the exception hierarchies by extending Exception class ?
Result:
It is mammel
Problem Description:
This example shows how to handle the exception methods by using System.err.println() method of System
class .
Result:
Caught Exception
getMassage(): My Exception
gatLocalisedMessage(): My Exception
toString():java.lang.Exception: My Exception
print StackTrace():
java.lang.Exception: My Exception
at ExceptionMethods.main(ExceptionMeyhods.java:12)
Problem Description:
Solution:
This example shows how to handle the runtime exception in a java programs.
Result:
Problem Description:
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;
Result:
Problem Description:
Solution:
Result:
Problem Description:
Solution:
This example shows how to handle chained exception using multiple catch blocks.
Result:
Problem Description:
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.
Result:
30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException: / by zero
Problem Description:
Solution:
Following example demonstrates how to add first n natural numbers by using the concept of stack .
import java.io.IOException;
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;
}
Result:
Sum=1225
Problem Description:
How to get the first and the last element of a linked list ?
Solution:
Following example shows how to get the first and last element of a linked list with the help of
linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class.
import java.util.LinkedList;
Result:
Problem Description:
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;
Result:
1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6
Problem Description:
Solution:
Following example demonstrates how to convert an infix to postfix expression by using the concept of stack.
import java.io.IOException;
Result:
124*5/+7-36/+
Postfix is 124*5/+7-36/+
Problem Description:
Solution:
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());
}
}
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;
}
}
Result:
Problem Description:
Solution:
Following example shows how to reverse a string using stack with the help of user defined method
StringReverserThroughStack().
import java.io.IOException;
Result:
JavaStringReversal
Reversed:lasreveRgnirtSavaJ
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;
Result:
Problem Description:
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.
Result:
50 40 30 20 10
Problem Description:
Solution:
Following example .
import java.util.Collections;
import java.util.Vector;
Result:
1 2 3 4 5
After swapping
5 2 3 4 1
Problem Description:
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;
Result:
BBTHP
BBMHP
Problem Description:
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;
Result:
Problem Description:
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;
Result:
[A, D, M, O, X]
Element found at : 1
Solution:
Following example demonstrates how to get elements of LinkedList using top() & pop() methods.
import java.util.*;
Result:
39
39
38
37
Problem Description:
Solution:
Following example demonstrates how to delete many elements of linkedList using Clear() method.
import java.util.*;
Result:
Problem Description:
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.*;
Result:
Problem Description:
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:
Penny
dime
----------
nickle
Quarter
Problem Description:
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.*;
Result:
Problem Description:
Solution:
Result:
C:\collection>javac TreeExample.java
C:\collection>java TreeExample
Tree Map Example!
C:\collection>
Problem Description:
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;
Result:
Problem Description:
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.*;
Result:
Collection Example!
Collection size: 3
Problem Description:
Following example demonstratres how to reverse a collection with the help of listIterator() and
Collection.reverse() methods of Collection and Listiterator class .
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
class UtilDemo3 {
public static void main(String[] args) {
String[] coins = { "A", "B", "C", "D", "E" };
List l = new ArrayList();
for (int i = 0; i < coins.length; i++)
l.add(coins[i]);
ListIterator liter = l.listIterator();
System.out.println("Before reversal");
while (liter.hasNext())
System.out.println(liter.next());
Collections.reverse(l);
liter = l.listIterator();
System.out.println("After reversal");
while (liter.hasNext())
System.out.println(liter.next());
}
}
Result:
Before reversal
A
B
C
D
E
After reversal
E
D
C
B
A
Problem Description:
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;
Result:
I
O
A
U
E
Problem Description:
Solution:
Following example shows how to get the size of a collection by the use of collection.add() to add new data and
collection.size() to get the size of the collection of Collections class.
import java.util.*;
Result:
Collection Example!
Problem Description:
Solution:
Following example uses iterator Method of Collection class to iterate through the HashMap.
import java.util.*;
Result:
3rd
2nd
1st
Problem Description:
Solution:
Following example uses different types of collection classes and adds an element in those collections.
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;
Result:
Problem Description:
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;
Three
Two
One
Problem Description:
Solution:
Following example uses keys() method to get Enumeration of Keys of the Hashtable.
import java.util.Enumeration;
import java.util.Hashtable;
Result:
3
2
1
Problem Description:
Solution:
Following example uses min & max Methods to find minimum & maximum of the List.
import java.util.*;
Result:
Problem Description:
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.*;
Result:
List :[one, Two, three, Four, five, six, one, three, Four]
SubList :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7
Problem Description:
Following example uses replaceAll() method to replace all the occurance of an element with a different element
in a list.
import java.util.*;
Result:
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six,
hundread, three, Four]
Problem Description:
Solution:
Following example uses rotate() method to rotate elements of the list depending on the 2nd argument of the
method.
import java.util.*;
Result:
Problem Description:
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;
Result:
Problem Description:
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;
Result:
Connected to http://www.sbdsisaikat.com/102.32.56.14
Problem Description:
Solution:
import java.net.URL;
import java.net.URLConnection;
}
}
Result:
Problem Description:
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;
Listening
Connected
Problem Description:
Solution:
Following example demonstrates How to get the file size from the server.
import java.net.URL;
import java.net.URLConnection;
Result:
Problem Description:
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;
Result:
Listening
10 from Java Source and Support
9 from Java Source and Support
8 from Java Source and Support
7 from Java Source and Support
6 from Java Source and Support
5 from Java Source and Support
4 from Java Source and Support
3 from Java Source and Support
2 from Java Source and Support
1 from Java Source and Support
0 from Java Source and Support
Problem Description:
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;
Result:
Listening
Terminate batch job (Y/N)? n
Connection made to 112.63.21.45
Problem Description:
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;
Result:
Problem Description:
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;
Result:
Date:05.26.2009
Problem Description:
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;
Result:
Problem Description:
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;
Result:
http://www.sbdsisaikat.com = 123.14.2.35
Solution:
Following example shows how to find local IP Address & Hostname of the system using getLocalAddress()
method of InetAddress class.
import java.net.InetAddress;
Result:
Problem Description:
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.*;
Result:
Looking for 0
Looking for 1
Looking for 2
Looking for 3
Looking for 4. . .
Problem Description:
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;
Result:
200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80
Problem Description:
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;
Result:
Problem Description:
Solution:
Following example demonstrates how to check a thread is alive or not by extending Threda class and using
currentThread() method.
Result:
before start(),tt.isAlive()=false
just after start(), tt.isAlive()=true
name=main
name=main
name=main
name=main
name=main
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=main
name=main
The end of main().tt.isAlive()=false
Problem Description:
Solution:
Following example demonstrates how to check a thread has stop or not by checking with isAlive() method.
Result:
Problem Description:
Solution:
Following example demonstrates how to solve deadlock using the concept of thread.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public DeadlockDetectingLock() {
this(false, false);
}
locks.
public class DeadlockDetectingCondition implements Condition {
Condition embedded;
protected DeadlockDetectingCondition(ReentrantLock lock,
Condition embedded) {
this.embedded = embedded;
}
Problem Description:
Solution:
Following example prints the priority of the running threads by using setPriority() method .
Result:
Thread[Thread-0,10,main]: 5
Problem Description:
Solution:
Following example demonstrates how to monitor a thread's status by extending Thread class and using
currentThread.getName() method.
Result:
Problem Description:
Solution:
name=main
name=main
name=main
name=main
name=main
name=thread
name=thread
name=thread
name=thread
Problem Description:
Solution:
Following example demonstrates how to solve the producer consumer problem using thread.
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
Problem Description:
Solution:
Following example how to set the priority of a thread with the help of.
Result:
Problem Description:
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;
Result:
Detected stop
Problem Description:
Solution:
Following example shows how to suspend a thread for a while by creating sleepingThread() method.
Problem Description:
Solution:
Following example demonstrates how to get the Id of a running thread using getThreadId() method.
public Main(ThreadID v) {
this.var = v;
}
try {
Thread threadA = new Thread(shared, "threadA");
threadA.start();
Thread.sleep(500);
Thread.sleep(500);
Result:
threadA: in initialValue()
threadA: var getThreadID =10001
threadB: in initialValue()
threadB: var getThreadID =10002
threadC: in initialValue()
threadC: var getThreadID =10003
threadA: var getThreadID =10001
threadB: var getThreadID =10002
threadC: var getThreadID =10003
Problem Description:
Solution:
Following example demonstrates how to check priority level of a thread using getPriority() method of a Thread.
Result:
in main() - Thread.currentThread().getPriority()=5
in main() - Thread.currentThread().getName()=main
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in main() - threadA.getPriority()=5
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
Problem Description:
Solution:
Following example demonstrates how to display names of all the running threads using getName() method.
Result:
Problem Description:
Solution:
Following example demonstrates how to display different status of thread using isAlive() & getStatus()
methods of Thread.
Result:
Problem Description:
Solution:
Following example demonstrates how to interrupt a running thread interrupt() method of thread and check if a
thread is interrupted using isInterrupted() method.
Result:
Problem Description:
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.*;
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.
Problem Description:
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.*;
Result:
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
Problem Description:
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.applet.*;
import java.awt.*;
import java.util.*;
Result:
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
Problem Description:
Solution:
Following example demonstrates how to create an applet which will have a line, an Oval & a Rectangle using
drawLine(), drawOval(, drawRect() methods of Graphics clas.
import java.applet.*;
import java.awt.*;
The above code sample will produce the following result in a java enabled web browser.
Problem Description:
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.*;
Result:
The above code sample will produce the following result in a java enabled web browser.
Problem Description:
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.*;
Result:
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
Problem Description:
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.*;
Result:
The above code sample will produce the following result in a java enabled web browser.
View in Browser.
Problem Description:
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.*
Result:
Problem Description:
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;
Result:
Problem Description:
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;
Result:
Problem Description:
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.*;
Result:
Problem Description:
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.*
Result:
Problem Description:
Solution:
Following example demonstrates how to display different shapes using Arc2D, Ellipse2D, Rectangle2D,
RoundRectangle2D classes.
import java.awt.Shape;
Result:
Problem Description:
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;
Result:
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;
Result:
Problem Description:
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;
Result:
False
False
False
Problem Description:
Solution:
Following example displays how to a display all the colors in a frame using setRGB method of image class.
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
Result:
Problem Description:
Solution:
Following example displays how to a display a piechart by making Slices class & creating arc depending on the
slices.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = { new Slice(5, Color.black),
new Slice(33, Color.green),
new Slice(20, Color.yellow), new Slice(15, Color.red) };
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
Result:
Problem Description:
Solution:
Following example demonstrates how to draw text drawString(), setFont() methods of Graphics class.
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
Problem Description:
How to connect to a database using JDBC? Assume that database name is testDb and it has table named
employee which has 2 records.
Solution:
Following example uses getConnection, createStatement & executeQuery methods to connect to a database &
execute queries.
import java.sql.*;
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.
Problem Description:
Solution:
Following example uses create, alter & drop SQL commands to create, edit or delete table
import java.sql.*;
The above code sample will produce the following result.The result may vary.
Problem Description:
Solution:
Following example uses getString,getInt & executeQuery methods to fetch & display the contents of the table.
import java.sql.*;
Result:
The above code sample will produce the following result.The result may vary.
id name job
1 alok trainee
2 ravi trainee
Solution:
Following method uses update, delete & insert SQL commands to edit or delete row contents.
import java.sql.*;
Result:
The above code sample will produce the following result.The result may vary.
id name job
2 ravi trainee
1 ronak manager
Problem Description:
Following method uses where & like sql Commands to search through the database.
import java.sql.*;
Result:
The above code sample will produce the following result.The result may vary.
Problem Description:
Solution:
import java.sql.*;
Result:
The above code sample will produce the following result.The result may vary.
Problem Description:
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.*;
Result:
The above code sample will produce the following result.The result may vary.
Problem Description:
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;
Result:
fix
rug
bag
fix
rig
rag
Problem Description:
Solution:
Following example shows how to search duplicate words in a regular expression by using p.matcher() method
and m.group() method of regex.Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Result:
Problem Description:
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;
Result:
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;
Result:
Problem Description:
How to print all the strings that match a given pattern from a file?
Solution:
Following example shows how to print all the strings that match a given pattern from a file with the help of
Patternname.matcher() method of Util.regex class.
import java.util.regex.*;
import java.io.*;
Result:
Ian
Darwin
http
www
darwinsys
com
All
rights
reserved
Software
written
by
Ian
Darwin
and
others
Problem Description:
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;
ThisisaJavaprogram.ThisisanotherJavaprogram.
Problem Description:
Solution:
Following example shows how to match phone numbers in a list to a perticlar pattern by using
phone.matches(phoneNumberPattern) method .
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
Problem Description:
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;
Result:
numberOfGroups =3
Problem Description:
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;
Result:
Problem Description:
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;
Result:
this
is
the
Java
example
Problem Description:
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;
Result:
Problem Description:
Solution:
Following example demonstrates how to check whether the date is in a proper format or not using matches
method of String class.
Result:
Solution:
Following example demonstrates how to validate e-mail address using matches() method of String class.
Result:
Problem Description:
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;
Problem Description:
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;
Result: