Java Programs
Java Programs
JAVA PROGRAMS
[1]: JAVA STRING - Programming Examples
durgesh.tripathi2@gmail.com Page 1
JAVA PROGRAMS
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
Result: The above code sample will produce the following result.
-32
0
0
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: The above code sample will produce the following result.
Last occurrence of Hello is at index 13
durgesh.tripathi2@gmail.com Page 2
JAVA PROGRAMS
Result: The above code sample will produce the following result.
thi is Java
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
Solution: Following example shows how to reverse a String after taking it from
command line argument .The program buffers the input String using
StringBuffer(String string) method, reverse the buffer and then converts the
buffer into a String with the help of toString() method.
public class StringReverseExample{
public static void main(String[] args){
String string="abcdef";
String reverse = new StringBuffer(string).
reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
Result: The above code sample will produce the following result.
String before reverse:abcdef
String after reverse:fedcba
durgesh.tripathi2@gmail.com Page 3
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Found Hello at index 0
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
durgesh.tripathi2@gmail.com Page 4
JAVA PROGRAMS
jan
jan
jan
feb.march
feb.march
feb.march
Result: The above code sample will produce the following result.
Original String: string abc touppercase
String changed to upper case: STRING ABC TOUPPERCASE
Result: The above code sample will produce the following result.
first_str[11 -19] == second_str[12 - 21]:-true
durgesh.tripathi2@gmail.com Page 5
JAVA PROGRAMS
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
Result: The above code sample will produce the following result.The result may vary.
durgesh.tripathi2@gmail.com Page 6
JAVA PROGRAMS
Result: The above code sample will produce the following result.
2.718282
2,7183
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
durgesh.tripathi2@gmail.com Page 7
JAVA PROGRAMS
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
Solution: Following example buffers strings and flushes it by using emit() method.
public class StringBuffer{
public static void main(String[] args) {
countTo_N_Improved();
}
private final static int MAX_LENGTH=30;
private static String buffer = "";
private static void emit(String nextChunk) {
if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
System.out.println(buffer);
buffer = "";
}
buffer += nextChunk;
}
private static final int N=100;
private static void countTo_N_Improved() {
for (int count=2; count<=N; count=count+2) {
emit(" " + count);
}
}
}
Result: The above code sample will produce the following result.
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
durgesh.tripathi2@gmail.com Page 8
JAVA PROGRAMS
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: 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
durgesh.tripathi2@gmail.com Page 9
JAVA PROGRAMS
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
Solution: Following example helps to determine the upper bound of a two dimentional
array with the use of arrayname.length.
public class Main {
public static void main(String args[]) {
String[][] data = new String[2][5];
System.out.println("Dimension 1: " + data.length);
System.out.println("Dimension 2: " + data[0].length);
}
}
Result: The above code sample will produce the following result.
Dimension 1: 2
Dimension 2: 5
durgesh.tripathi2@gmail.com Page 10
JAVA PROGRAMS
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]
Result: The above code sample will produce the following result.
This is the greeting
For all the readers From
Java source .
[6]: How to search the minimum and the maximum element in an array?
Solution: This example shows how to search the minimum and maximum element in an
array by using Collection.max() and Collection.min() methods of Collection class .
import java.util.Arrays;
import java.util.Collections;
durgesh.tripathi2@gmail.com Page 11
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Min number: 1
Max number: 9
Result: The above code sample will produce the following result.
[A, E, I, O, U]
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: The above code sample will produce the following result.
100
100
durgesh.tripathi2@gmail.com Page 12
JAVA PROGRAMS
100
100
100
100
100
100
100
50
50
50
Result: The above code sample will produce the following result.
A
B
C
D
E
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;
durgesh.tripathi2@gmail.com Page 13
JAVA PROGRAMS
}
System.out.print(array[i]);
}
System.out.println();
}
}
Result: The above code sample will produce the following result.
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]
durgesh.tripathi2@gmail.com Page 14
JAVA PROGRAMS
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]
Solution: Following example shows how to find common elements from two arrays and
store them in an array.
import java.util.ArrayList;
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");
durgesh.tripathi2@gmail.com Page 15
JAVA PROGRAMS
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
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: 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
Solution: Following example uses equals method to check whether two arrays are or not.
import java.util.Arrays;
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
durgesh.tripathi2@gmail.com Page 16
JAVA PROGRAMS
Result: The above code sample will produce the following result.The result will change
depending upon the current system time
06:40:32 AM
Result: The above code sample will produce the following result.
October Oct 10
durgesh.tripathi2@gmail.com Page 17
JAVA PROGRAMS
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;
Result: The above code sample will produce the following result.The result will chenge
depending upon the current system time.
03:20
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
Wed Oct 15 20:37:30 GMT+05:30 2008
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;
durgesh.tripathi2@gmail.com Page 18
JAVA PROGRAMS
Result: The above code sample will produce the following result.
hour in h format : 8
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
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
Solution: This example displays the names of the months in short form with the help of
DateFormatSymbols().getShortMonths() method of DateFormatSymbols class.
durgesh.tripathi2@gmail.com Page 19
JAVA PROGRAMS
import java.text.SimpleDateFormat;
import java.text.DateFormatSymbols;
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
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: The above code sample will produce the following result.
weekday = Monday
weekday = Tuesday
weekday = Wednesday
weekday = Thursday
weekday = Friday
durgesh.tripathi2@gmail.com Page 20
JAVA PROGRAMS
Solution: The following examples shows us how to add time to a date using add() method
of Calender.
import java.util.*;
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
Solution: Following example uses Locale class & DateFormat class to disply date in different
Country's format.
import java.text.DateFormat;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Date d1 = new Date();
System.out.println("today is "+ d1.toString());
Locale locItalian = new Locale("it","ch");
DateFormat df = DateFormat.getDateInstance
(DateFormat.FULL, locItalian);
System.out.println("today is in Italian Language in Switzerland Format : "+ df.format(d1));
}
}
Result: The above code sample will produce the following result.
today is Mon Jun 22 02:37:06 IST 2009
today is in Italian Language in Switzerlandluned�,
22. giugno 2009
durgesh.tripathi2@gmail.com Page 21
JAVA PROGRAMS
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
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: 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
Solution: The following example displays week no of the year & month.
import java.util.*;
durgesh.tripathi2@gmail.com Page 22
JAVA PROGRAMS
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
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: The above code sample will produce the following result.
9/9/01 7:16 AM
Sep 9, 2001
Sep 9, 2001
Sunday, September 9, 2001
September 9, 2001
9/9/01
durgesh.tripathi2@gmail.com Page 23
JAVA PROGRAMS
Solution: This example displays the way of overloading a method depending on type and
number of parameters.
class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is " + i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height + " feet tall");
}
void info(String s) {
System.out.println(s + ": House is " + height + " feet tall");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");
//Overloaded constructor:
new MyClass();
durgesh.tripathi2@gmail.com Page 24
JAVA PROGRAMS
}
}
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
durgesh.tripathi2@gmail.com Page 25
JAVA PROGRAMS
2.2
3.3
4.4
5.5
6.6
7.7
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
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);
}
durgesh.tripathi2@gmail.com Page 26
JAVA PROGRAMS
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
Solution: This example shows the way of using method for calculating Factorial of 9(nine)
numbers.
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter, factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
Result: The above code sample will produce the following result.
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
durgesh.tripathi2@gmail.com Page 27
JAVA PROGRAMS
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
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;
durgesh.tripathi2@gmail.com Page 28
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Object was an instance of the class java.util.ArrayList
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
Solution: This example uses continue statement to jump out of a loop in a method.
public class Main {
public static void main(String[] args) {
StringBuffer searchstr = new StringBuffer( "hello how are you. ");
int length = searchstr.length();
int count = 0;
for (int i = 0; i < length; i++) {
if (searchstr.charAt(i) != 'h')
continue;
count++;
searchstr.setCharAt(i, 'h');
}
System.out.println("Found " + count + " h's in the string.");
System.out.println(searchstr);
}
durgesh.tripathi2@gmail.com Page 29
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Found 2 h's in the string.
hello how are you.
[10]: How to use method overloading for printing different types of array?
Solution: This example shows how to jump to a particular label when break or continue
statements occour in a loop.
public class Main {
public static void main(String[] args) {
String strSearch = "This is the string in which you have to search for a substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() - substring.length();
testlbl:
for (int i = 0; i < = max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) != substring.charAt(k++){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("Found the substring .");
}
else {
System.out.println("did not find the substing in the string.");
}
}
}
Result: The above code sample will produce the following result.
Found the substring .
Solution: This example displays how to check which enum member is selected using Switch
statements.
enum Car {
lamborghini,tata,audi,fiat,honda
}
public class Main {
public static void main(String args[]){
Car c;
c = Car.tata;
switch(c) {
case lamborghini:
durgesh.tripathi2@gmail.com Page 30
JAVA PROGRAMS
Result: The above code sample will produce the following result.
You choose tata!
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.
durgesh.tripathi2@gmail.com Page 31
JAVA PROGRAMS
Solution: This example displays an integer array using for loop & foreach loops.
public class Main {
public static void main(String[] args) {
int[] intary = { 1,2,3,4};
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a){
System.out.println("Display an array using for loop");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachDisplay(int[] data){
System.out.println("Display an array using for each loop");
for (int a : data) {
System.out.print(a+ " ");
}
}
}
Result: The above code sample will produce the following result.
Display an array using for loop
1234
Display an array using for each loop
1234
Solution: This example creates sumvarargs() method which takes variable no of int
numbers as an argument and returns the sum of these arguments as an output.
public class Main {
static int sumvarargs(int... intArrays){
int sum, i;
sum=0;
for(i=0; i< intArrays.length; i++) {
sum += intArrays[i];
}
return(sum);
}
public static void main(String args[]){
int sum=0;
sum = sumvarargs(new int[]{10,12,33});
System.out.println("The sum of the numbers is: " + sum);
}
}
Result: The above code sample will produce the following result.
The sum of the numbers is: 55
[15]: How to use variable arguments as an input when dealing with method
overloading?
durgesh.tripathi2@gmail.com Page 32
JAVA PROGRAMS
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
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;
durgesh.tripathi2@gmail.com Page 33
JAVA PROGRAMS
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!
Result: The above code sample will produce the following result (if "myfile.txt does not
exist before)
Success!
Solution: This example shows how to get the last modification date of a file using
file.lastModified() method of File class.
import java.io.File;
import java.util.Date;
durgesh.tripathi2@gmail.com Page 34
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Tue 12 May 10:18:50 PDF 2009
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: The above code sample will produce the following result.
C:\JavaTemp37056.javatemp
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
durgesh.tripathi2@gmail.com Page 35
JAVA PROGRAMS
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
Result: The above code sample will produce the following result.To test this example, first
create a file 'program.txt' in 'C' drive.
Renamed
Solution: This example shows how to get a file's size in bytes by using file.exists() and
file.length() method of File class.
import java.io.File;
public class Main {
public static long getFileSize(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\'t exist");
return -1;
}
return file.length();
}
public static void main(String[] args) {
long size = getFileSize("c:/java.txt");
System.out.println("Filesize in bytes: " + size);
}
durgesh.tripathi2@gmail.com Page 36
JAVA PROGRAMS
Result: The above code sample will produce the following result.To test this example, first
create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file.
File size in bytes: 480
Solution: This example shows how to change the last modification time of a file with the
help of fileToChange.lastModified() and fileToChange setLastModified() methods of File class
.
import java.io.File;
import java.util.Date;
public class Main {
public static void main(String[] args)
throws Exception {
File fileToChange = new File("C:/myjavafile.txt");
fileToChange.createNewFile();
Date filetime = new Date
(fileToChange.lastModified());
System.out.println(filetime.toString());
System.out.println(fileToChange.setLastModified(System.currentTimeMillis()));
filetime = new Date(fileToChange.lastModified());
System.out.println(filetime.toString());
}
}
Result: The above code sample will produce the following result.The result may vary
depending upon the system time.
Sat Oct 18 19:58:20 GMT+05:30 2008
true
Sat Oct 18 19:58:20 GMT+05:30 2008
Solution: This example shows how to create a temporary file using createTempFile()
method of File class.
import java.io.*;
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 37
JAVA PROGRAMS
Solution: This example shows how to append a string in an existing file using filewriter
method.
import java.io.*;
Result: The above code sample will produce the following result.
aString1
aString2
Solution: This example shows how to copy contents of one file into another file using read
& write methods of BufferedWriter class.
import java.io.*;
durgesh.tripathi2@gmail.com Page 38
JAVA PROGRAMS
Result: The above code sample will produce the following result.
string to be copied
Solution: This example shows how to delete a file using delete() method of File class.
import java.io.*;
Result: The above code sample will produce the following result.
The file has been successfully deleted
exception occouredjava.io.FileNotFoundException:
filename (The system cannot find the file specified)
File does not exist or you are trying to read a
file that has been deleted
Solution: This example shows how to read a file using readLine method of BufferedReader
class.
durgesh.tripathi2@gmail.com Page 39
JAVA PROGRAMS
import java.io.*;
Result: The above code sample will produce the following result.
aString
Solution: This example shows how to write to a file using write method of BufferedWriter.
import java.io.*;
Result: The above code sample will produce the following result.
File created successfully.
durgesh.tripathi2@gmail.com Page 40
JAVA PROGRAMS
Solution: Following example shows how to create directories recursively with the help of
file.mkdirs() methods of File class.
import java.io.File;
Result: The above code sample will produce the following result.
Status = true
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: The above code sample will produce the following result.
The directory is deleted.
durgesh.tripathi2@gmail.com Page 41
JAVA PROGRAMS
Result: The above code sample will produce the following result.
The D://Java/file.txt is not empty!
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;
Result: The above code sample will produce the following result (as Demo.txt is hidden).
True
Solution: Following example shows how to print the hierarchy of a specified directory using
file.getName() and file.listFiles() method of File class.
import java.io.File;
import java.io.IOException;
durgesh.tripathi2@gmail.com Page 42
JAVA PROGRAMS
Result: The above code sample will produce the following result.
-Java
-----codes
---------string.txt
---------array.txt
-----tutorial
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;
Result: The above code sample will produce the following result.
last modifed:10:20:54
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: The above code sample will produce the following result.
Parent directory is : File
Solution: Following example demonstrares how to search and get a list of all files under a
specified directory by using dir.list() method of File class.
import java.io.File;
durgesh.tripathi2@gmail.com Page 43
JAVA PROGRAMS
throws Exception {
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist or is not a directory");
}
else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Result: The above code sample will produce the following result.
Sdk
---vehicles
------body.txt
------color.txt
------engine.txt
---ships
------shipengine.txt
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: The above code sample will produce the following result.
Size: 2048 bytes
Solution: Following example demonstratres how to traverse a directory with the help of
dir.isDirectory() and dir.list() methods of File class.
import java.io.File;
durgesh.tripathi2@gmail.com Page 44
JAVA PROGRAMS
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}
Result: The above code sample will produce the following result.
The Directory is traversed.
Solution: Following example shows how to get current directory using getProperty()
method.
class Main {
public static void main(String[] args) {
String curDir = System.getProperty("user.dir");
System.out.println("You currently working in :" + curDir+ ": Directory");
}
}
Result: The above code sample will produce the following result.
Solution: Following example shows how to find root directories in your system using
listRoots() method of File class.
import java.io.*;
class Main{
public static void main(String[] args){
File[] roots = File.listRoots();
System.out.println("Root directories in your system are:");
for (int i=0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}
}
}
Result: The above code sample will produce the following result. The result may vary
depending on the system & operating system. If you are using Unix system you will get a
single root '/'.
durgesh.tripathi2@gmail.com Page 45
JAVA PROGRAMS
Solution: Following example shows how to search for a particular file in a directory by
making a Filefiter. Following example displays all the files having file names starting with 'b'.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("b");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}
else {
for (int i=0; i< children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Result: The above code sample will produce the following result.
Build
build.xml
Solution: Following example shows how to display all the filess contained in a directory
using list method of File class.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:");
String[] children = dir.list();
if (children == null) {
System.out.println( "Either dir does not exist or is not a directory");
}else {
for (int i=0; i< children.length; i++) {
String filename = children[i];
System.out.println(filename);
durgesh.tripathi2@gmail.com Page 46
JAVA PROGRAMS
}
}
}
}
Result: The above code sample will produce the following result.
build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test
Solution: Following example shows how to display all the directories contained in a
directory making a filter which list method of File class.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("F:");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("Either dir does not exist or is not a directory");
}
else {
for (int i=0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
Result: The above code sample will produce the following result.
14
F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh final
F:\hhhh
F:\mov
F:\msdownld.tmp
F:\New Folder
durgesh.tripathi2@gmail.com Page 47
JAVA PROGRAMS
F:\ravi
F:\ravi3
F:\RECYCLER
F:\System Volume Information
F:\temp
F:\work
Solution: This example shows how to use finally block to catch runtime exceptions (Illegal
Argument Exception) by the use of e.getMessage().
public class ExceptionDemo2 {
public static void main(String[] argv) {
new ExceptionDemo2().doTheWork();
}
public void doTheWork() {
Object o = null;
for (int i=0; i<5; i++) {
try {
o = makeObj(i);
}
catch (IllegalArgumentException e) {
System.err.println("Error: ("+ e.getMessage()+").");
return;
}
finally {
System.err.println("All done");
if (o==null)
System.exit(0);
}
System.out.println(o);
}
}
public Object makeObj(int type)
throws IllegalArgumentException {
if (type == 1)
throw new IllegalArgumentException
("Don't like type " + type);
return new Object();
}
}
Result: The above code sample will produce the following result.
All done
java.lang.Object@1b90b39
Error: (Don't like type 1).
durgesh.tripathi2@gmail.com Page 48
JAVA PROGRAMS
All done
Solution: This example shows how to handle the exception hierarchies by extending
Exception class?
class Animal extends Exception {
}
class Mammel extends Animal {
}
public class Human {
public static void main(String[] args) {
try {
throw new Mammel();
}
catch (Mammel m) {
System.err.println("It is mammel");
}
catch (Annoyance a) {
System.err.println("It is animal");
}
}
}
Result: The above code sample will produce the following result.
It is mammal
Solution: This example shows how to handle the exception methods by using
System.err.println() method of System class .
public static void main(String[] args) {
try {
throw new Exception("My Exception");
} catch (Exception e) {
System.err.println("Caught Exception");
System.err.println("getMessage():" + e.getMessage());
System.err.println("getLocalizedMessage():"+ e.getLocalizedMessage());
System.err.println("toString():" + e);
System.err.println("printStackTrace():");
e.printStackTrace();
}
}
Result: The above code sample will produce the following result.
Caught Exception
getMassage(): My Exception
gatLocalisedMessage(): My Exception
toString():java.lang.Exception: My Exception
print StackTrace():
durgesh.tripathi2@gmail.com Page 49
JAVA PROGRAMS
java.lang.Exception: My Exception
at ExceptionMethods.main(ExceptionMeyhods.java:12)
Solution: This example shows how to handle the runtime exception in a java programs.
public class NeverCaught {
static void f() {
throw new RuntimeException("From f()");
}
static void g() {
f();
}
public static void main(String[] args) {
g();
}
}
Result: The above code sample will produce the following result.
From f()
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;
durgesh.tripathi2@gmail.com Page 50
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Testing for empty stack
16 milliseconds
Catching EmptyStackException
3234 milliseconds
Solution: This example shows how to use catch to handle the exception.
public class Main{
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try{
result = num1/num2;
System.out.println("The result is" +result);
for(int i =5;i >=0; i--) {
System.out.println("The value of array is" +array[i]);
}
}
catch (Exception e) {
System.out.println("Exception occoured : "+e);
}
}
}
Result: The above code sample will produce the following result.
The result is1
Exception occoured : java.lang.ArrayIndexOutOfBoundsException: 5
Solution: This example shows how to handle chained exception using multiple catch blocks.
public class Main{
public static void main (String args[])throws Exception {
int n=20,result=0;
try{
result=n/0;
System.out.println("The result is"+result);
}
catch(ArithmeticException ex){
System.out.println("Arithmetic exception occoured: "+ex);
try {
throw new NumberFormatException();
}
catch(NumberFormatException ex1) {
System.out.println("Chained exception thrown manually : "+ex1);
}
}
}
}
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 51
JAVA PROGRAMS
Solution: This example shows how to handle the exception with overloaded methods. You
need to have a try catch block in each method or where the are used.
public class Main {
double method(int i) throws Exception{
return i/0;
}
boolean method(boolean b) {
return !b;
}
static double method(int x, double y) throws Exception {
return x + y ;
}
static double method(double x, double y) {
return x + y - 3;
}
public static void main(String[] args) {
Main mn = new Main();
try{
System.out.println(method(10, 20.0));
System.out.println(method(10.0, 20));
System.out.println(method(10.0, 20.0));
System.out.println(mn.method(10));
}
catch (Exception ex){
System.out.println("exception occoure: "+ ex);
}
}
}
Result: The above code sample will produce the following result.
30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException: / by zero
Solution: This example shows how to handle checked exception using catch block.
public class Main {
public static void main (String args[]) {
try{
throw new Exception("throwing an exception");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
durgesh.tripathi2@gmail.com Page 52
JAVA PROGRAMS
Result: The above code sample will produce the following result.
throwing an exception
Solution: This example shows how to pass arguments while throwing an exception & how
to use these arguments while catching an exception using getMessage() method of
Exception class.
public class Main{
public static void main (String args[]) {
try {
throw new Exception("throwing an exception");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Result: The above code sample will produce the following result.
throwing an exception
Solution: This example shows how to handle multiple exceptions while deviding by zero?
public class Main {
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=0;
int result=0;
try {
result = num1/num2;
System.out.println("The result is" +result);
for(int i =2;i >=0; i--){
System.out.println("The value of array is" +array[i]);
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error�. Array is out of Bounds"+e);
}
catch (ArithmeticException e) {
System.out.println("Can't be divided by Zero"+e);
}
}
}
Result: The above code sample will produce the following result.
Can't be divided by Zerojava.lang.ArithmeticException: / by zero
durgesh.tripathi2@gmail.com Page 53
JAVA PROGRAMS
Solution: This example shows how to handle multiple exception methods by using
System.err.println() method of System class .
public class Main {
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try {
result = num1/num2;
System.out.println("The result is" +result);
for(int i =5;i >=0; i--) {
System.out.println("The value of array is" +array[i]);
}
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array is out of Bounds"+e);
}
catch (ArithmeticException e) {
System.out.println ("Can't divide by Zero"+e);
}
}
}
Result: The above code sample will produce the following result.
The result is1
Array is out of Boundsjava.lang.ArrayIndexOutOfBoundsException : 5
Solution: This example shows how to handle the exception with overloaded methods.
You need to have a try catch block in each method or where they are used.
public class Main {
double method(int i) throws Exception{
return i/0;
}
boolean method(boolean b) {
return !b;
}
static double method(int x, double y) throws Exception {
return x + y ;
}
static double method(double x, double y) {
return x + y - 3;
}
public static void main(String[] args) {
Main mn = new Main();
try{
System.out.println(method(10, 20.0));
System.out.println(method(10.0, 20));
System.out.println(method(10.0, 20.0));
System.out.println(mn.method(10));
}
catch (Exception ex){
durgesh.tripathi2@gmail.com Page 54
JAVA PROGRAMS
Result: The above code sample will produce the following result.
30.0
27.0
27.0
exception occoure: java.lang.ArithmeticException: / by zero
Solution: This example shows how to print stack of the exception using printStack() method
of the exception class.
public class Main{
public static void main (String args[]){
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try{
result = num1/num2;
System.out.println("The result is" +result);
for(int i =5;i >=0; i--) {
System.out.println("The value of array is" +array[i]);
}
}
catch (Exception e) {
e.printStackTrace();
}
}}
Result: The above code sample will produce the following result.
The result is1
java.lang.ArrayIndexOutOfBoundsException: 5
at testapp.Main.main(Main.java:28)
Solution: This example shows how to handle the exception while dealing with threads.
class MyThread extends Thread{
public void run(){
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
class Main {
public static void main(String[] args){
MyThread t = new MyThread();
t.start();
try{
Thread.sleep(1000);
}
durgesh.tripathi2@gmail.com Page 55
JAVA PROGRAMS
Solution: This example shows how to create user defined exception by extending Exception
Class.
class WrongInputException extends Exception {
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong input");
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
Result: The above code sample will produce the following result.
Wrong input
Solution: Following example demonstrates how to add first n natural numbers by using the
concept of stack .
import java.io.IOException;
durgesh.tripathi2@gmail.com Page 56
JAVA PROGRAMS
class Stack {
private int maxSize;
private int[] data;
private int top;
public Stack(int s) {
maxSize = s;
data = new int[maxSize];
top = -1;
}
public void push(int p) {
data[++top] = p;
}
public int pop() {
return data[top--];
}
public int peek() {
return data[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
Result: The above code sample will produce the following result.
Sum=1225
[2]: How to get the first and the last element of a linked list?
Solution: Following example shows how to get the first and last element of a linked list with
the help of linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class.
import java.util.LinkedList;
durgesh.tripathi2@gmail.com Page 57
JAVA PROGRAMS
Result: The above code sample will produce the following result.
First element of LinkedList is :100
Last element of LinkedList is :500
[3]: How to add an element at first and last position of a linked list?
Solution: Following example shows how to add an element at the first and last position of a
linked list by using addFirst() and addLast() method of Linked List class.
import java.util.LinkedList;
Result: The above code sample will produce the following result.
1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6
durgesh.tripathi2@gmail.com Page 58
JAVA PROGRAMS
durgesh.tripathi2@gmail.com Page 59
JAVA PROGRAMS
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "1+2*4/5-7+3/6";
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
Result: The above code sample will produce the following result.
124*5/+7-36/+
Postfix is 124*5/+7-36/+
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();
}
durgesh.tripathi2@gmail.com Page 60
JAVA PROGRAMS
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: The above code sample will produce the following result.
The employees' name are:
TD
GB
FS
Solution: Following example shows how to reverse a string using stack with the help of user
defined method StringReverserThroughStack().
durgesh.tripathi2@gmail.com Page 61
JAVA PROGRAMS
import java.io.IOException;
Result: The above code sample will produce the following result.
JavaStringReversal
Reversed:lasreveRgnirtSavaJ
durgesh.tripathi2@gmail.com Page 62
JAVA PROGRAMS
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: The above code sample will produce the following result.
First index of 2 is: 1
Last index of 2 is: 5
Solution: Following example shows how to implement stack by creating user defined push()
method for entering elements and pop() method for retriving elements from the stack.
public class MyStack {
private int maxSize;
private long[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;
}
public long pop() {
return stackArray[top--];
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
MyStack theStack = new MyStack(10);
durgesh.tripathi2@gmail.com Page 63
JAVA PROGRAMS
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
theStack.push(50);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
Result: The above code sample will produce the following result.
50 40 30 20 10
Result: The above code sample will produce the following result.
12345
After swapping
52341
durgesh.tripathi2@gmail.com Page 64
JAVA PROGRAMS
officers.add("T");
officers.add("H");
officers.add("P");
System.out.println(officers);
officers.set(2, "M");
System.out.println(officers);
}
}
Result: The above code sample will produce the following result.
BBTHP
BBMHP
Solution: Following example demonstrates how to get the maximum element of a vector by
using v.add() method of Vector class and Collections.max() method of Collection class.
import java.util.Collections;
import java.util.Vector;
Result: The above code sample will produce the following result.
The max element is: 3.4324
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;
durgesh.tripathi2@gmail.com Page 65
JAVA PROGRAMS
Result: The above code sample will produce the following 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.*;
public class Main {
private LinkedList list = new LinkedList();
public void push(Object v) {
list.addFirst(v);
}
public Object top() {
return list.getFirst();
}
public Object pop() {
return list.removeFirst();
}
public static void main(String[] args) {
Main stack = new Main();
for (int i = 30; i < 40; i++)
stack.push(new Integer(i));
System.out.println(stack.top());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
Result: The above code sample will produce the following result.
39
39
38
37
Solution: Following example demonstrates how to delete many elements of linkedList using
Clear() method.
import java.util.*;
durgesh.tripathi2@gmail.com Page 66
JAVA PROGRAMS
lList.add("5");
System.out.println(lList);
lList.subList(2, 4).clear();
System.out.println(lList);
}
}
Result: The above code sample will produce the following result.
[one, two, three, four, five]
[one, two, three, Replaced, five]
durgesh.tripathi2@gmail.com Page 67
JAVA PROGRAMS
int n = Integer.parseInt(in.readLine());
String[] name = new String[n];
for(int i = 0; i < n; i++){
name[i] = in.readLine();
}
List list = Arrays.asList(name);
System.out.println();
for(String li: list){
String str = li;
System.out.print(str + " ");
}
}
}
Result: The above code sample will produce the following result.
How many elements you want to add to the array:
red white green
class MainClass {
public static void main(String[] args) {
String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };
Set set = new TreeSet();
for (int i = 0; i < coins.length; i++)
set.add(coins[i]);
System.out.println(Collections.min(set));
System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
for(int i=0;i< =10;i++)
System.out.print(-);
System.out.println(Collections.max(set));
System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER));
}
}
Result: The above code sample will produce the following result.
Penny
dime
----------
nickle
Quarter
durgesh.tripathi2@gmail.com Page 68
JAVA PROGRAMS
import java.util.*;
Result: The above code sample will produce the following result.
This is a good program.
Result: The above code sample will produce the following result.
C:\collection>javac TreeExample.java
C:\collection>java TreeExample
Tree Map Example!
durgesh.tripathi2@gmail.com Page 69
JAVA PROGRAMS
C:\collection>
Result: The above code sample will produce the following result.
Collection is read-only now.
Result: The above code sample will produce the following result.
Collection Example!
Collection size: 3
Solution: Following example demonstratres how to reverse a collection with the help of
listIterator() and Collection.reverse() methods of Collection and Listiterator class .
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
class UtilDemo3 {
durgesh.tripathi2@gmail.com Page 71
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Before reversal
A
B
C
D
E
After reversal
E
D
C
B
A
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: The above code sample will produce the following result.
I
O
A
U
E
durgesh.tripathi2@gmail.com Page 72
JAVA PROGRAMS
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: The above code sample will produce the following result.
Collection Example!
Solution: Following example uses iterator Method of Collection class to iterate through the
HashMap.
import java.util.*;
durgesh.tripathi2@gmail.com Page 73
JAVA PROGRAMS
Result: The above code sample will produce the following result.
3rd
2nd
1st
Solution: Following example uses different types of collection classes and adds an element
in those collections.
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
durgesh.tripathi2@gmail.com Page 74
JAVA PROGRAMS
treeSet.add("4");
displayAll(treeSet);
LinkedHashSet lnkHashset = new LinkedHashSet();
lnkHashset.add("one");
lnkHashset.add("two");
lnkHashset.add("three");
lnkHashset.add("four");
displayAll(lnkHashset);
Map ma p1 = new HashMap();
map1.put("key1", "J");
map1.put("key2", "K");
map1.put("key3", "L");
map1.put("key4", "M");
displayAll(map1.keySet());
displayAll(map1.values());
SortedMap map2 = new TreeMap();
map2.put("key1", "JJ");
map2.put("key2", "KK");
map2.put("key3", "LL");
map2.put("key4", "MM");
displayAll(map2.keySet());
displayAll(map2.values());
LinkedHashMap map3 = new LinkedHashMap();
map3.put("key1", "JJJ");
map3.put("key2", "KKK");
map3.put("key3", "LLL");
map3.put("key4", "MMM");
displayAll(map3.keySet());
displayAll(map3.values());
}
static void displayAll(Collection col) {
Iterator itr = col.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.print(str + " ");
}
System.out.println();
}
}
Result: The above code sample will produce the following result.
element1 element2 element3 element4
xyzw
set1 set2 set3 set4
1234
one two three four
key4 key3 key2 key1
MLKJ
key1 key2 key3 key4
JJ KK LL MM
key1 key2 key3 key4
JJJ KKK LLL MMM
durgesh.tripathi2@gmail.com Page 75
JAVA PROGRAMS
import java.util.Enumeration;
import java.util.Hashtable;
Result: The above code sample will produce the following result.
Three
Two
One
Solution: Following example uses keys() method to get Enumeration of Keys of the
Hashtable.
import java.util.Enumeration;
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Result: The above code sample will produce the following result.
3
2
1
Solution: Following example uses min & max Methods to find minimum & maximum of the
List.
import java.util.*;
durgesh.tripathi2@gmail.com Page 76
JAVA PROGRAMS
System.out.println(list);
System.out.println("max: " + Collections.max(list));
System.out.println("min: " + Collections.min(list));
}
}
Result: The above code sample will produce the following result.
[one, Two, three, Four, five, six, one, three, Four]
max: three
min: Four
Result: The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
SubList :[three, Four]
indexOfSubList: 2
lastIndexOfSubList: 7
Solution: Following example uses replaceAll() method to replace all the occurance of an
element with a different element in a list.
import java.util.*;
durgesh.tripathi2@gmail.com Page 77
JAVA PROGRAMS
Result: The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six,
hundread, three, Four]
Solution: Following example uses rotate() method to rotate elements of the list depending
on the 2nd argument of the method.
import java.util.*;
Result: The above code sample will produce the following result.
List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]
durgesh.tripathi2@gmail.com Page 78
JAVA PROGRAMS
Result: The above code sample will produce the following result.
before start(),tt.isAlive()=false
just after start(), tt.isAlive()=true
name=main
name=main
name=main
name=main
name=main
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=main
name=main
The end of main().tt.isAlive()=false
Solution: Following example demonstrates how to check a thread has stop or not by
checking with isAlive() method.
public class Main {
public static void main(String[] argv)
throws Exception {
Thread thread = new MyThread();
thread.start();
if (thread.isAlive()) {
System.out.println("Thread has not finished");
durgesh.tripathi2@gmail.com Page 79
JAVA PROGRAMS
}
else {
System.out.println("Finished");
}
long delayMillis = 5000;
thread.join(delayMillis);
if (thread.isAlive()) {
System.out.println("thread has not finished");
}
else {
System.out.println("Finished");
}
thread.join();
}
}
Result: The above code sample will produce the following result.
Thread has not finished
Finished
Solution: Following example prints the priority of the running threads by using setPriority()
method .
public class SimplePriorities extends Thread {
private int countDown = 5;
private volatile double d = 0;
public SimplePriorities(int priority) {
setPriority(priority);
start();
}
public String toString() {
return super.toString() + ": " + countDown;
}
public void run() {
while(true) {
for(int i = 1; i < 100000; i++)
d = d + (Math.PI + Math.E) / (double)i;
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
new SimplePriorities(Thread.MAX_PRIORITY);
for(int i = 0; i < 5; i++)
new SimplePriorities(Thread.MIN_PRIORITY);
}
durgesh.tripathi2@gmail.com Page 80
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Thread[Thread-0,10,main]: 5
Thread[Thread-0,10,main]: 4
Thread[Thread-0,10,main]: 3
Thread[Thread-0,10,main]: 2
Thread[Thread-0,10,main]: 1
Thread[Thread-1,1,main]: 5
Thread[Thread-1,1,main]: 4
Thread[Thread-1,1,main]: 3
Thread[Thread-1,1,main]: 2
Thread[Thread-1,1,main]: 1
Thread[Thread-2,1,main]: 5
Thread[Thread-2,1,main]: 4
Thread[Thread-2,1,main]: 3
Thread[Thread-2,1,main]: 2
Thread[Thread-2,1,main]: 1
.
.
.
durgesh.tripathi2@gmail.com Page 81
JAVA PROGRAMS
}
public class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+"
Alive:="+thrd.isAlive()+"
State:=" + thrd.getState() );
}
}
Result: The above code sample will produce the following result.
main Alive=true State:=running
Solution: Following example shows How to get the name of a running thread .
public class TwoThreadGetName extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args) {
TwoThreadGetName tt = new TwoThreadGetName();
tt.start();
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
}
}
Result: The above code sample will produce the following result.
name=main
name=main
name=main
durgesh.tripathi2@gmail.com Page 82
JAVA PROGRAMS
name=main
name=main
name=thread
name=thread
name=thread
name=thread
Solution: Following example demonstrates how to solve the producer consumer problem
using thread.
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
durgesh.tripathi2@gmail.com Page 83
JAVA PROGRAMS
value = cubbyhole.get();
System.out.println("Consumer #"
+ this.number
+ " got: " + value);
}
}
}
Result: The above code sample will produce the following result.
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Solution: Following example how to set the priority of a thread with the help of.
public class Main {
public static void main(String[] args)
throws Exception {
Thread thread1 = new Thread(new TestThread(1));
durgesh.tripathi2@gmail.com Page 84
JAVA PROGRAMS
Result: The above code sample will produce the following result.
The priority has been set.
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: The above code sample will produce the following result.
Detected stop
durgesh.tripathi2@gmail.com Page 85
JAVA PROGRAMS
Solution: Following example shows how to suspend a thread for a while by creating
sleepingThread() method.
public class SleepingThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread() {
super("" + ++threadCount);
start();
}
public String toString() {
return "#" + getName() + ": " + countDown;
}
public void run() {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
throws InterruptedException {
for (int i = 0; i < 5; i++)
new SleepingThread().join();
System.out.println("The thread has been suspened.");
}
}
Result: The above code sample will produce the following result.
The thread has been suspened.
Solution: Following example demonstrates how to get the Id of a running thread using
getThreadId() method.
public class Main extends Object implements Runnable {
private ThreadID var;
public Main(ThreadID v) {
this.var = v;
}
durgesh.tripathi2@gmail.com Page 86
JAVA PROGRAMS
try {
Thread threadA = new Thread(shared, "threadA");
threadA.start();
Thread.sleep(500);
Thread.sleep(500);
public ThreadID() {
nextID = 10001;
}
Result: The above code sample will produce the following result.
threadA: in initialValue()
threadA: var getThreadID =10001
durgesh.tripathi2@gmail.com Page 87
JAVA PROGRAMS
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
Solution: Following example demonstrates how to check priority level of a thread using
getPriority() method of a Thread.
public class Main extends Object {
private static Runnable makeRunnable() {
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
Thread t = Thread.currentThread();
System.out.println("in run() - priority="
+ t.getPriority()+ ", name=" + t.getName());
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
}
}
};
return r;
}
public static void main(String[] args) {
System.out.println("in main() - Thread.currentThread().
getPriority()=" + Thread.currentThread().getPriority());
System.out.println("in main() - Thread.currentThread()
.getName()="+ Thread.currentThread().getName());
Thread threadA = new Thread(makeRunnable(), "threadA");
threadA.start();
try {
Thread.sleep(3000);
}
catch (InterruptedException x) {
}
System.out.println("in main() - threadA.getPriority()="
+ threadA.getPriority());
}
}
Result: The above code sample will produce the following result.
in main() - Thread.currentThread().getPriority()=5
in main() - Thread.currentThread().getName()=main
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in main() - threadA.getPriority()=5
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
in run() - priority=5, name=threadA
Solution: Following example demonstrates how to display names of all the running threads
using getName() method.
public class Main extends Thread {
public static void main(String[] args) {
Main t1 = new Main();
t1.setName("thread1");
t1.start();
ThreadGroup currentGroup =
Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++)
System.out.println("Thread No:" + i + " = "
+ lstThreads[i].getName());
}
}
Result: The above code sample will produce the following result.
Thread No:0 = main
Thread No:1 = thread1
Solution: Following example demonstrates how to display different status of thread using
isAlive() & getStatus() methods of Thread.
class MyThread extends Thread{
boolean waiting= true;
boolean ready= false;
MyThread() {
}
public void run() {
String thrdName = Thread.currentThread().getName();
System.out.println(thrdName + " starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
}
catch(Exception exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
}
catch(InterruptedException exc) {
System.out.println("wait() interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
durgesh.tripathi2@gmail.com Page 89
JAVA PROGRAMS
}
}
public class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+" Alive:"
+thrd.isAlive()+" State:" + thrd.getState() );
}
}
Result: The above code sample will produce the following result.
MyThread #1 Alive:false State:NEW
MyThread #1 starting.
waiting:true
waiting:true
alive
alive
MyThread #1 terminating.
alive
MyThread #1 Alive:false State:TERMINATED
durgesh.tripathi2@gmail.com Page 90
JAVA PROGRAMS
Result: The above code sample will produce the following result.
in run() - about to work2()
in main() - interrupting other thread
in main() - leaving
C isInterrupted()=true
in run() - interrupted in work2()
durgesh.tripathi2@gmail.com Page 91
JAVA PROGRAMS
Now compile the above code and call the generated class in your HTML code as follows:
<HTML>
<HEAD>
</HEAD>
<BODY>
<div >
<APPLET CODE="Main.class" WIDTH="800" HEIGHT="500">
</APPLET>
</div>
</BODY>
</HTML>
Result: The above code sample will produce the following result in a java enabled web
browser.
Welcome in Java Applet.
Solution: Following example demonstrates how to play a sound using an applet image using
Thread class. It also uses drawRect(), fillRect() , drawString() methods of Graphics class.
import java.awt.*;
import java.applet.*;
durgesh.tripathi2@gmail.com Page 92
JAVA PROGRAMS
ch = str.charAt(0);
str = str.substring(1, str.length());
str = str + ch;
}
catch(InterruptedException e) {}
}
}
public void paint(Graphics g) {
g.drawRect(1,1,300,150);
g.setColor(Color.yellow);
g.fillRect(1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}
}
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
Solution: Following example demonstrates how to display a clock using valueOf() mehtods
of String Class. & using Calender class to get the second, minutes & hours.
import java.awt.*;
import java.applet.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
Result: The above code sample will produce the following result in a java enabled web
browser.
durgesh.tripathi2@gmail.com Page 93
JAVA PROGRAMS
View in Browser.
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.*;
Result: The above code sample will produce the following result in a java enabled web
browser.
A line , Oval & a Rectangle will be drawn in the browser.
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.
A Rectangle with yellow color filled in it willl be drawn in the browser.
durgesh.tripathi2@gmail.com Page 94
JAVA PROGRAMS
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
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.*;
durgesh.tripathi2@gmail.com Page 95
JAVA PROGRAMS
}
if(i >j){
Sub = i - j;
}
else{
Sub = j - i;
}
if(source.getLabel() == "Subtract"){
txtArea.append("Sub : " + Sub + "\n");
}
}
}
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
Solution: Following example demonstrates how to display image using getImage() method.
It also uses addImage() method of MediaTracker class.
import java.applet.*;
import java.awt.*;
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
durgesh.tripathi2@gmail.com Page 96
JAVA PROGRAMS
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
Solution: Following example demonstrates how to play a sound using an applet image using
getAudioClip(), play() & stop() methods of AudioClip() class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Result: The above code sample will produce the following result in a java enabled web
browser.
durgesh.tripathi2@gmail.com Page 97
JAVA PROGRAMS
View in Browser.
Solution: Following example demonstrates how to read a file using an Applet using
openStream() method of URL.
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class readFileApplet extends Applet{
String fileToRead = "test1.txt";
StringBuffer strBuff;
TextArea txtArea;
Graphics g;
public void init(){
txtArea = new TextArea(100, 100);
txtArea.setEditable(false);
add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");
if (prHtml != null) fileToRead = new String(prHtml);
readFile();
}
public void readFile(){
String line;
URL url = null;
try{
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e){}
try{
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader
(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null){
strBuff.append(line + "\n");
}
txtArea.append("File Name : " + fileToRead + "\n");
txtArea.append(strBuff.toString());
}
catch(IOException e){
e.printStackTrace();
}
}
}
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
Solution: Following example demonstrates how to write to a a file by making textarea for
writing in a browser using TextArea() making Labels & then creating file using File()
constructor.
durgesh.tripathi2@gmail.com Page 98
JAVA PROGRAMS
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import java.net.*;
durgesh.tripathi2@gmail.com Page 99
JAVA PROGRAMS
}
else{
JOptionPane.showMessageDialog
(null,"File not found!");
text.setText("");
text.requestFocus();
}
}
}
catch(Exception x){
x.printStackTrace();
}
}
}
}
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the second Text Box : " + output.getText());
}
catch(NumberFormatException e){
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}
}
Result: The above code sample will produce the following result in a java enabled web
browser.
View in Browser.
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.*
System.exit(0);
}
}
);
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}
Result: The above code sample will produce the following result.
Different font names are displayed in a frame.
Solution: Following example demonstrates how to draw a line using draw() method of
Graphics2D class with Line2D object as an argument.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Main extends JApplet {
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
int x = 5;
int y = 7;
g2.draw(new Line2D.Double(x, y, 200, 200));
g2.drawString("Line", x, 250);
}
public static void main(String s[]) {
JFrame f = new JFrame("Line");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JApplet applet = new Main();
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(300, 300));
f.setVisible(true);
}
}
Result: The above code sample will produce the following result.
Line is displayed in a frame.
Result: The above code sample will produce the following result.
JAVA and J2EE displayed in a new Frame.
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Polygon");
frame.setSize(350, 250);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
}
Result: The above code sample will produce the following result.
Polygon is displayed in a frame.
Result: The above code sample will produce the following result.
Each character is displayed in a rectangle.
Solution: Following example demonstrates how to display different shapes using Arc2D,
Ellipse2D, Rectangle2D, RoundRectangle2D classes.
import java.awt.Shape;
import java.awt.geom.*;
Result: The above code sample will produce the following result.
Different shapes are created.
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: The above code sample will produce the following result.
Solid rectangle is created.
Result: The above code sample will produce the following result.
Transparent Cursor created.
Result: The above code sample will produce the following result.
False
False
False
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: The above code sample will produce the following result.
Displays all the colours in a frame.
Solution: Following example displays how to a display a piechart by making Slices class
& creating arc depending on the slices.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class MyComponent extends JComponent {
Slice[] slices = { new Slice(5, Color.black),
new Slice(33, Color.green),
new Slice(20, Color.yellow), new Slice(15, Color.red) };
MyComponent() {}
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), slices);
}
void drawPie(Graphics2D g, Rectangle area, Slice[] slices) {
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 0.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height,
startAngle, arcAngle);
curValue += slices[i].value;
}
}
}
public class Main {
public static void main(String[] argv) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Result: The above code sample will produce the following result.
Displays a piechart in a frame.
import javax.swing.JFrame;
import javax.swing.JPanel;
Result: The above code sample will produce the following result.
Text is displayed in a frame.
Result: The above code sample will produce the following result.The result may vary. You
will get ClassNotfound exception if your JDBC driver is not installed properly.
JDBC Class found
There are 2 record in the table
[2]: How to edit(Add or update) columns of a Table and how to delete a table?
Solution: Following example uses create, alter & drop SQL commands to create, edit or
delete table
import java.sql.*;
Result: The above code sample will produce the following result.The result may vary.
Employee table created
Address column added to the table & last_name
column removed from the table
Employees table removed from the database
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
Solution: 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.
Names for query SELECT * FROM emp where id=1 are
ravi
Names for query select name from emp where name like 'ravi_' are
ravi2 ravi3
Names for query select name from emp where name like 'ravi%' are
ravi ravi2 ravi3 ravi123 ravi222
Solution: Following example uses Order by SQL command to sort the table.
import java.sql.*;
Result: The above code sample will produce the following result.The result may vary.
Table contents after sorting by Name
Id Name Job
1 ravi trainee
5 ravi MD
4 ravi CEO
2 ravindra CEO
2 ravish trainee
Table contents after sorting by Name & job
Id Name Job
4 ravi CEO
5 ravi MD
1 ravi trainee
2 ravindra CEO
2 ravish trainee
[7]: How to join contents of more than one table & display?
Solution: Following example uses inner join sql command to combine data from two tables.
To display the contents of the table getString() method of resultset is used.
import java.sql.*;
Result: The above code sample will produce the following result.The result may vary.
Fname Lname ISBN
john grisham 123
jeffry archer 113
jeffry archer 112
jeffry archer 122
Result: The above code sample will produce the following result.The result may vary.
No. of rows before commit statement = 1
No. of rows after commit statement = 3
Result: The above code sample will produce the following result.The result may vary.
Id Name Job
23 Roshan CEO
no_of_rows = 0;
rs = stmt.executeQuery(query2);
while (rs.next()) {
no_of_rows++;
}
System.out.println("rows after rollback statement = " + no_of_rows);
}
}
Result: The above code sample will produce the following result.The result may vary.
rows before rollback statement = 4
rows after rollback statement = 3
Solution: Following example uses addBatch & executeBatch commands to execute multiple
SQL commands simultaneously.
import java.sql.*;
Result: The above code sample will produce the following result.The result may vary.
rows before batch execution= 6
Batch executed
rows after batch execution= = 9
[13]: How to use different row methods to get no of rows in a table, update table
etc?
Result: The above code sample will produce the following result.For this code to compile
your database has to be updatable. The result may vary.
No of rows in table=5
Row added
first row deleted
[14]: How to use different methods of column to Count no of columns, get column
name, get column type etc?
Result: The above code sample will produce the following result.The result may vary.
no of columns in the table= 3
Name of the first columnID
Type of the second columnVARCHAR
No of characters in 3rd column20
Solution: Following example demonstrates how to reset the pattern of a regular expression
by using Pattern.compile() of Pattern class and m.find() method of Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Result: The above code sample will produce the following result.
fix
rug
bag
fix
rig
rag
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;
Pattern p = Pattern.compile(duplicatePattern);
int matches = 0;
String phrase = " this is a test ";
Matcher m = p.matcher(phrase);
String val = null;
while (m.find()) {
val = ":" + m.group() + ":";
matches++;
}
if(val>0)
System.out.println("The string has matched with the pattern.");
else
System.out.println("The string has not matched with the pattern.");
}
}
Result: The above code sample will produce the following result.
The string has matched with the pattern.
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: The above code sample will produce the following result.
INPUT: this is a test ,A TEST.
REGEX: \\ba\\w*\\b
MATCH: a test
MATCH: A TEST
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: The above code sample will produce the following result.
The last index of Java is: 42
[5]: How to print all the strings that match a given pattern from a file?
Solution: Following example shows how to print all the strings that match a given pattern
from a file with the help of Patternname.matcher() method of Util.regex class.
import java.util.regex.*;
import java.io.*;
Result: The above code sample will produce the following result.
Ian
Darwin
http
www
darwinsys
com
All
rights
reserved
Software
written
by
Ian
Darwin
and
others
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;
Result: The above code sample will produce the following result.
ThisisaJavaprogram.ThisisanotherJavaprogram.
Solution: Following example shows how to match phone numbers in a list to a perticlar
pattern by using phone.matches(phoneNumberPattern) method .
public class MatchPhoneNumber {
public static void main(String args[]) {
isPhoneValid("1-999-585-4009");
isPhoneValid("999-585-4009");
isPhoneValid("1-585-4009");
isPhoneValid("585-4009");
isPhoneValid("1.999-585-4009");
isPhoneValid("999 585-4009");
isPhoneValid("1 585 4009");
isPhoneValid("111-Java2s");
}
public static boolean isPhoneValid(String phone) {
boolean retval = false;
String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";
retval = phone.matches(phoneNumberPattern);
String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern;
if (retval) {
msg = " MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern;
}
System.out.println(msg + "\r\n");
return retval;
}
}
Result: The above code sample will produce the following result.
MATCH: pattern:1-999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
MATCH: pattern:999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
MATCH: pattern:1-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:1.999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:999 585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:1 585 4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:111-Java2s
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
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: The above code sample will produce the following result.
numberOfGroups =3
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: The above code sample will produce the following result.
This is a java program. This is another java program.
The index for java is: 11
Result: The above code sample will produce the following result.
this
is
the
Java
Example
Result: The above code sample will produce the following result.
initial String: hello hello hello.
String after replacing 1st Match: Java hello hello.
Solution: Following example demonstrates how to check whether the date is in a proper
format or not using matches method of String class.
public class Main {
public static void main(String[] argv) {
boolean isDate = false;
String date1 = "8-05-1988";
String date2 = "08/04/1987" ;
String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
isDate = date1.matches(datePattern);
System.out.println("Date :"+ date1+": matches with
the this date Pattern:"+datePattern+"Ans:"+isDate);
isDate = date2.matches(datePattern);
System.out.println("Date :"+ date2+": matches with
the this date Pattern:"+datePattern+"Ans:"+isDate);
}
}
Result: The above code sample will produce the following result.
Date :8-05-1988: matches with the this date Pattern:
\d{1,2}-\d{1,2}-\d{4}Ans:true
Date :08/04/1987: matches with the this date Pattern:
\d{1,2}-\d{1,2}-\d{4}Ans:false
Solution: Following example demonstrates how to validate e-mail address using matches()
method of String class.
public class Main {
public static void main(String[] args) {
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\
@([\\w]+\\.)+[\\w]+[\\w]$";
String email1 = "user@domain.com";
Boolean b = email1.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email1+" :Valid = " + b);
String email2 = "user^domain.co.in";
b = email2.matches(EMAIL_REGEX);
System.out.println("is e-mail: "+email2 +" :Valid = " + b);
}
}
Result: The above code sample will produce the following result.
is e-mail: user@domain.com :Valid = true
is e-mail: user^domain.co.in :Valid = false
Result: The above code sample will produce the following result.
initial String: hello hello hello.
String after replacing 1st Match: Java Java Java.
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: The above code sample will produce the following result.
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: The above code sample will produce the following result.
http://www.javatutorial.com = 123.14.2.35
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: The above code sample will produce the following result.
Connected to http://www,javatutorial.com/102.32.56.14
Solution: Following example shows How to check a file is modified at a server or not.
import java.net.URL;
import java.net.URLConnection;
}
}
Result: The above code sample will produce the following result.
The last modification time of java.bmp is :24 May 2009 12:14:50
this.csocket = csocket;
}
Result: The above code sample will produce the following result.
Listening
Connected
Solution: Following example demonstrates How to get the file size from the server.
import java.net.URL;
import java.net.URLConnection;
Result: The above code sample will produce the following result.
The size of The file is = 16384 bytes
Result: The above code sample will produce the following result.
Listening
10 from Java Source and Support
9 from Java Source and Support
8 from Java Source and Support
7 from Java Source and Support
6 from Java Source and Support
5 from Java Source and Support
4 from Java Source and Support
3 from Java Source and Support
2 from Java Source and Support
1 from Java Source and Support
0 from Java Source and Support
[7]: How to make a srever to allow the connection to the socket 6123?
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: The above code sample will produce the following result.
Listening
Terminate batch job (Y/N)? n
Connection made to 112.63.21.45
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: The above code sample will produce the following result.
URL is http://www.server.com
protocol is TCP/IP
file name is java_program.txt
host is 122.45.2.36
path is
port is 2
default port is 1
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: The above code sample will produce the following result.
Date:05.26.2009
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: The above code sample will produce the following result.
Welcome to Java Tutorial
Here we have plenty of examples for you!
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: The above code sample will produce the following result.
http://www.javatutorial.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: The above code sample will produce the following result.
Local HostAddress: 192.168.1.4
Local host name: harsh
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.*;
if (args.length > 0) {
host = args[0];
}
for (int i = 0; i < 1024; i++) {
try {
System.out.println("Looking for "+ i);
Skt = new Socket(host, i);
System.out.println("There is a server on port " + i + " of " + host);
}
catch (UnknownHostException e) {
System.out.println("Exception occured"+ e);
break;
}
catch (IOException e) {
}
}
}
}
Result: The above code sample will produce the following result.
Looking for 0
Looking for 1
Looking for 2
Looking for 3
Looking for 4. . .
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: The above code sample will produce the following result.
200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80
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: The above code sample will produce the following result.
Connected to /74.125.67.100 on port 80 from port
2857 of /192.168.1.4
Solution:
import java.util.*;
class FindDifference
{
public static void main(String[] args)
{
int sum=0,sum1=0,sum2=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter value of n: ");
int n=input.nextInt();
for(int i=1;i<=n;i++){
int sq=i*i;
sum1+=sq;
}
//System.out.println(sum1);
for(int i=1;i<=n;i++){
sum+=i;
}
sum2=sum*sum;
//System.out.println(sum2);
int diff=0;
if(sum1>sum2){
diff=sum1-sum2;
}
else{
diff=sum2-sum1;
}
System.out.println(diff);
}
}
[2]: Develop a program that accepts the area of a square and will calculate its
perimeter
Solution:
import java.util.*;
import java.text.*;
class PerimeterOfSquare{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat("##.00");
Scanner input=new Scanner(System.in);
System.out.println("Enter Area of Square:");
double area=input.nextDouble();
double side=Math.sqrt(area);
System.out.println("Side of Square is: "+df.format(side));
double perimeter=4*side;
System.out.println("Perimeter of Square is: "+df.format(perimeter));
}
}
[3]: Develop the program calculateCylinderVolume., which accepts radius of a
cylinder's base disk and its height and computes the volume of the cylinder.
Solution:
import java.util.*;
class CalculateCyliderVolume
{
public static void main(String[] args)
{
double PI=3.14;
Scanner input=new Scanner(System.in);
System.out.print("Enter Radius: ");
double r=input.nextDouble();
double volume=PI*r*r*h;
System.out.println("Volume of Cylinder: "+volume);
}
}
[4]: Utopias tax accountants always use programs that compute income taxes even
though the tax rate is a solid, never-changing 15%. Define the program
calculateTax which determines the tax on the gross pay. Define calculateNetPay
that determines the net pay of an employee from the number of hours worked.
Assume an hourly rate of $12.
Solution:
import java.util.*;
import java.text.*;
public class CalculateNetPay
{
public static void main(String[]args){
double taxRate=0.15;
double hourlyRate=12;
DecimalFormat df=new DecimalFormat("$##.00");
Scanner input=new Scanner(System.in);
System.out.print("Enter Number of Hours Worked: ");
double hrs=input.nextDouble();
double gp=hrs*hourlyRate;
double tax=gp*taxRate;
double netpay=gp-tax;
System.out.println("Net Pay is: "+df.format(netpay));
}
}
[5]: An old-style movie theater has a simple profit program. Each customer pays
$5 per ticket. Every performance costs the theater $20, plus $.50 per attendee.
Develop the program calculateTotalProfit that consumes the number of attendees
(of a show) and calculates how much income the show earns.
Solution:
import java.util.*;
import java.text.*;
class CalculateTotalProfit{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("$##.00");
double theaterCost=20;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number of Customers: ");
double cus=input.nextDouble();
double earnFromTickets=5*cus;
double attendeesCost=cus*0.50;
double cost=attendeesCost+theaterCost;
double profit=earnFromTickets-cost;
System.out.println("Total Profit: "+df.format(profit));
}
}
[6]: Develop the program calculateHeight, which computes the height that a
rocket reaches in a given amount of time. If the rocket accelerates at a constant
rate g, it reaches a speed of g · t in t time units and a height of 1/2 * v * t where v
is the speed at t.
Solution:
import java.util.*;
import java.text.*;
class CalculateHeight{
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("##.00");
Scanner input=new Scanner(System.in);
System.out.print("Enter constant rate:");
double g=input.nextDouble();
System.out.print("Enter time:");
double t=input.nextDouble();
double speed=g*t;
double h=speed*t;
double height=h/2;
System.out.println("Rocket reaches at the height of: "+df.format(height));
}
}
[7]: Develop the program calculatePipeArea. It computes the surface area of a pipe
, which isan open cylinder. The program accpets three values: the pipes inner
radius, its length, and the thickness of its wall.
Solution:
import java.io.*;
class calculatePipeArea
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter inner radius");
int r=Integer.parseInt(br.readLine());
System.out.println("Enter thickness");
int t=Integer.parseInt(br.readLine());
System.out.println("Enter height");
int h=Integer.parseInt(br.readLine());
System.out.println("Volume: "+(2*Math.PI*(r+t)*h));
}
}
[8]: Develop a program that computes the distance a boat travels across a river,
given the width of the river, the boat's speed perpendicular to the river, and the
river's speed. Speed is distance/time, and the Pythagorean Theorem is c2 = a2 +
b2.
Solution:
import java.io.*;
class distance
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter boats speed");
double bs=Double.parseDouble(br.readLine());
System.out.println("Enter river speed");
double rs=Double.parseDouble(br.readLine());
System.out.println("Enter width of river");
double w=Double.parseDouble(br.readLine());
double x=rs/bs;
x=1+x*x;
x=1/x;
x=Math.sqrt(x);
System.out.println("Distance: "+(w/x));
}
}
[9]: Develop a program that accepts an initial amount of money (called the
principal), a simple annual interest rate, and a number of months will compute
the balance at the end of that time. Assume that no additional deposits or
withdrawals are made and that a month is 1/12 of a year. Total interest is the
product of the principal, the annual interest rate expressed as a decimal, and the
number of years.
Solution:
import java.io.*;
class SimpleInterest
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Principal");
int p=Integer.parseInt(br.readLine());
System.out.println("Enter Rate");
double r=Double.parseDouble(br.readLine());
System.out.println("Enter months");
Double t=Double.parseDouble(br.readLine());
t=t/12;
System.out.println("Interest: "+(0.01*(p*r*t)));
}
}
[10]: Create a Bank class with methods deposit & withdraw. The deposit method
would accept attributes amount & balance & returns the new balance which is the
sum of amount & balance. Similarly, the withdraw method would accept the
attributes amount & balance & returns the new balance? balance ? Amount? if
balance > = amount or return 0 otherwise.
Solution:
public static void deposit(int amount, int balance) // performs deposit calculation
{
output = amount + balance;
}
public static void withdraw(int amount, int balance) // performs withdraw calculation
{
output = balance - amount;
if (balance >= amount) {
System.out.println(":::Inside the WithDraw method :::");
} else {
System.out.println(":::Inside the WithDraw method :::");
output = 0;
}
}
[11]: Create an Employee class which has methods netSalary which would accept
salary & tax as arguments & returns the netSalary which is tax deducted from the
salary. Also it has a method grade which would accept the grade of the employee &
return grade.
Solution:
import java.util.*;
class Employee
{
public double netSalary(double salary, double taxrate){
double tax=salary*taxrate;
double netpay=salary=tax;
return netpay;
}
public static void main(String[] args)
{
Employee emp=new Employee();
Scanner input=new Scanner(System.in);
System.out.print("Enter Salary: ");
double sal=input.nextDouble();
System.out.print("Enter Tax in %: ");
double taxrate=input.nextDouble()/100;
double net=emp.netSalary(sal,taxrate);
System.out.println("Net Salary is: "+net);
}
}
[12]: Create Product having following attributes: Product ID, Name, Category ID
and UnitPrice. Create ElectricalProduct having the following additional attributes:
VoltageRange and Wattage. Add a behavior to change the Wattage and price of the
electrical product. Display the updated ElectricalProduct details
Solution:
import java.util.*;
class Product{
int productID;
String name;
int categoryID;
double price;
Product(int productID,String name,int categoryID,double price){
this.productID=productID;
this.name=name;
this.categoryID=categoryID;
this.price=price;
}
}
public class ElectricalProduct extends Product{
int voltageRange;
int wattage;
ElectricalProduct(int productID,String name,int categoryID,double price,int
voltageRange, int wattage){
super(productID,name,categoryID,price);
this.voltageRange=voltageRange;
this.wattage=wattage;
}
public void display(){
System.out.println("Product ID: "+productID);
System.out.println("Name: "+name);
System.out.println("Category ID: "+categoryID);
System.out.println("Price: "+price);
System.out.println("Voltage Range: "+voltageRange);
System.out.println("Wattage: "+wattage);
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Product ID: ");
int pid=input.nextInt();
System.out.println("Enter Name: ");
String name=input.next();
System.out.println("Enter Catagory ID: ");
int cid=input.nextInt();
System.out.println("Enter Price: ");
double price=input.nextDouble();
System.out.println("Enter Voltage Range: ");
int vrange=input.nextInt();
System.out.println("Enter Wattage: ");
int wattage=input.nextInt();
System.out.println("****Details of Electrical Product****");
System.out.println();
ElectricalProduct p=new ElectricalProduct(pid,name,cid,price,vrange,wattage);
p.display();
}
}
[13]: Create Book having following attributes: Book ID, Title, Author and Price.
Create Periodical which has the following additional attributes: Period (weekly,
monthly etc...) .Add a behavior to modify the Price and the Period of the
periodical. Display the updated periodical details.
Solution:
import java.util.*;
class Book{
int id;
String title;
String author;
double price;
System.out.print("Period: ");
String pp=input.next();
p.setTimeperiod(pp);
System.out.println();
System.out.println("----Book Information----");
System.out.println();
System.out.println("Book ID: "+b.getId());
System.out.println("Title: "+b.getTitle());
System.out.println("Author: "+b.getAuthor());
System.out.println("Price: "+b.getPrice());
System.out.println("Period: "+p.getTimeperiod());
}
}
[14]: Create Vehicle having following attributes: Vehicle No., Model, Manufacturer
and Color. Create truck which has the following additional attributes: loading
capacity (100 tons?).Add a behavior to change the color and loading capacity.
Display the updated truck details.
Solution:
import java.util.*;
class Vehicle
{
int no;
String model;
String manufacturer;
String color;
System.out.println("Model: ");
String model=input.next();
System.out.println("Manufacturer: ");
String manufacturer=input.next();
System.out.println("Color: ");
String color=input.next();
[15]: Write a program which performs to raise a number to a power and returns
the value. Provide a behavior to the program so as to accept any type of numeric
values and returns the results.
Solution:
import java.util.*;
import java.text.*;
class NumberProgram
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("##.##");
[16]: Write a function Model-of-Category for a Tata motor dealers, which accepts
category of car customer is looking for and returns the car Model available in that
category. the function should accept the following categories "SUV", "SEDAN",
"ECONOMY", and "MINI" which in turn returns "TATA SAFARI" , "TATA INDIGO" ,
"TATA INDICA" and "TATA NANO" respectively.
Solution:
import java.util.*;
class TataMotors{
String category;
String model;
TataMotors(String category,String model){
this.category=category;
this.model=model;
}
public String getCategory(){
return category;
}
public String getModel(){
return model;
}
public static void ModelOfCategory(ArrayList<TataMotors> list){
Scanner input=new Scanner(System.in);
System.out.print("Enter Category: ");
String category=input.nextLine();
System.out.println();
System.out.print("Model is: ");
for (TataMotors tm : list){
if(tm.getCategory().equals(category)){
System.out.print(tm.getModel());
}
}
}
ModelOfCategory(list);
}
}
[18]: Create a class called Student which has the following methods:
I. Average: which would accept marks of 3 examinations & return whether the
student has passed or failed depending on whether he has scored an average
above 50 or not.
ii. Inputname: which would accept the name of the student & returns the name.
Solution:
import java.util.*;
System.out.println("Enter Name:");
String name=input.nextLine();
String result=average();
return name+" get "+result;
}
public static void main(String[]args){
Student data=new Student();
String nameAndResut=data.getName();
System.out.println(nameAndResut);
}
}
[19]: Create a calculator class which will have methods add, multiply, divide &
subtract.
Solution:
class Calculation{
public int add(int a,int b){
return a+b;
}
public int subtract(int a,int b){
if(a>b){
return a-b;
}
else{
return b-a;
}
}
public int multiply(int a,int b){
return a*b;
}
public int divide(int a,int b){
if(a>b){
return a/b;
}
else{
return b/a;
}
}
}
public class Calculator{
public static void main(String []args){
Calculation cal=new Calculation();
int add=cal.add(5,10);
int sub=cal.subtract(5,10);
int mul=cal.multiply(5,10);
int div=cal.divide(5,10);
System.out.println(add);
System.out.println(sub);
System.out.println(mul);
System.out.println(div);
}
}
1 2 3 4 5
3 5 7 9
8 12 16
20 28
48
Solution:
class PrintDemo{
int i=0,j=0,n=5;
for(i=0;i<n;i++) {
a[i]=i+1;
System.out.print("" + a[i]);
for(i=4;i>0;i--) {
System.out.println();
for(j=0;j<1;j++) {
a[j]=a[j]+a[j+1];
*
* *
* * *
* * * *
*****
Solution:
public class Stars {
{ int c=1;
for(int i=1;i<=5;i++) {
for(int j=i;j<5;j++)
{ System.out.print(" ");
for(int k=1;k<=c;k++)
if(k%2==0)
System.out.print(" ");
else
System.out.print("*");
System.out.println();
c+=2;
[3]: Write a program to Print a character pattern like this. The dots all stand for
spaces. The spaces are mandatory. The pattern is:-
abcde
.bcde
..cde
...de
....e
....ed
....edc
....edcb
....edcba
Solution:
class patsp
{
public static void main()
{
int ch,i,k,l='d',m=1,n='a';
for (i=5;i>=1;i--)
{
for(k=3;k>=i-1;k--)
System.out.print(" ");
for(ch=n;ch<='e';ch++)
{
System.out.print((char)ch);
}
System.out.println();
n=n+1;
}
for (i=4;i>=1;i--)
{
for(k=m;k<=i;k++)
System.out.print(" ");
for(ch='e';ch>=l;ch--)
{
System.out.print((char)ch);
}
System.out.println();
l=l-1;
m=m-1;
}
}
}
SAIFE
SAIF
SAI
SA
Solution:
class Name
{
public static void main(String args[])
{
String s="SAIFEE";
int num=s.length();
while(num>0)
{
for(int j=0;j<num;j++)
{
System.out.print(" "+s.charAt(j)+" ");
}
System.out.println();
num--;
}
}
}
class test
{
public static void main(String[] s)
{ int a=0,b=0,c=0,d=0,i=0,e=1;
String r[]={"","","",""}; //requires initialization
/*array of string so that we can print the last 3 lines without implementing any logic*/
/*defined static so that can be called within the main without putting it in seperate class and calling
by class name*/
}
}
import java.io.*;
class prmNo
{ public static void main(String[] args)
{ Console con = System.console();
System.out.println("Enter length of list :");
int n = con.readLine();
boolean flag;
System.out.print("1 ");
for (int i=2;i<=n;i++)
{ for (int j=2;j<i;j++)
{ if (i%j==0)
flag=true;
}
if(!flag)
System.out.print(i+ " ");
flag=false;
}
}
}
for(e=0;e<h;e++)
{ System.out.println();
for(f=0;f<=e;f++)
{ System.out.print(" ");
}
for(g=f;g<=h;g++)
{ System.out.print("* ");
}
}
}
}
Solution:
char letters[] = "abcdefghijklmnopqrstuvwxyz";
int i;
for (i = 0; i < 26; i++) printf ("%c\n", letters[i]);
[11]: Program to print the following pattern given the input as number of
rows(DIAMOND SHAPE). For e.g. Input = 7, the output is as follows
*
* * *
* * * * *
* * * * * * *
* * * * *
* * *
*
import java.io.*;
System.out.println("Enter a no : ");
int i=Integer.parseInt(br.readLine());
int j,k,l;
j=k=l=0;
int n=i/2;
for(j=0;j<n+1;j++)
{ for(k=0;k<n-j;k++)
{ System.out.print(" ");
for(l=0;l<j+1;l++)
{ System.out.print("*");
for(l=0;l<j;l++)
{ System.out.print("*");
System.out.println();
for(j=n;j>0;j--)
{ for(k=n-j+1;k>0;k--)
{ System.out.print(" ");
for(l=j-1;l>0;l--)
{ System.out.print("*");
for(l=j;l>0;l--)
{ System.out.print("*");
System.out.println();
}}
[12]: Write a java program to swap to no’s with and without using a third variable
Solution:
4.
7.
8. System.out.println("Before Swapping");
11.
16.
20. }
21.
22.
23. }
24.
25. /*
26. Output of Swap Numbers Without Using Third Variable example would be
33. */
[13]: Write a java program that produces its source code as output.
Solution:
import java.io.*;
class Source
{
public static void main(String args[])throws IOException
{
FileReader fr=new FileReader("Source.java");
int c;
while((c=fr.read())!=-1)
{
System.out.print((char)c);
}
}
}
Solution:
public class Main {
public void countLetters(String str) {
if (str == null)
return;
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
counter++;
}
System.out.println("The input parameter contained " + counter + " letters.");
}
public static void main(String[] args) {
new Main().countLetters("abcde123");
}
}