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
[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.
-320 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 13Solution: 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 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
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();
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)
} }
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"); }
}
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);
} } }
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;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
[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.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);
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 };
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 {
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]
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
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.
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); }
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 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) {
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);
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
[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
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 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
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))
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
[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)
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);
} }
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;
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.
[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 1 2 3 4
Display an array using for each loop 1 2 3 4
[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); }
}
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
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!