Professional Documents
Culture Documents
Many Java Programs PDF
Many Java Programs PDF
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
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
Result: The above code sample will produce the following result.
String before reverse:abcdef
durgesh.tripathi2@gmail.com Page 3
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Found Hello at index 0
Result: The above code sample will produce the following result.
Jan
feb
durgesh.tripathi2@gmail.com Page 4
JAVA PROGRAMS
march
jan
jan
jan
feb.march
feb.march
feb.march
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
for(int i=0;i<50000;i++){
String s1 = "hello";
String s2 = "hello";
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken for creation" + " of String literals : "+
(endTime - startTime)
+ " milli seconds" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s3 = new String("hello");
String s4 = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Time taken for creation" + " of String objects : " +
(endTime1 - startTime1)
+ " milli seconds");
}
}
Result: The above code sample will produce the following result.The result
may vary.
Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects : 16 milli seconds
durgesh.tripathi2@gmail.com Page 6
JAVA PROGRAMS
}
}
Result: The above code sample will produce the following result.The result
may vary.
Creation time of String literals : 0 ms
Creation time of String objects with 'new' key word : 31 ms
Creation time of String objects with intern(): 16 ms
Result: The above code sample will produce the following result.
2.718282
2,7183
durgesh.tripathi2@gmail.com Page 7
JAVA PROGRAMS
Result: The above code sample will produce the following result.The result
may vary.
Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 16 ms
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
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 8
JAVA PROGRAMS
2 4 6 8 10 12 14 16 18 20 22
24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82
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
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 .
durgesh.tripathi2@gmail.com Page 11
JAVA PROGRAMS
import java.util.Collections;
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.*;
durgesh.tripathi2@gmail.com Page 12
JAVA PROGRAMS
Result: The above code sample will produce the following result.
100
100
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
durgesh.tripathi2@gmail.com Page 13
JAVA PROGRAMS
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 @ " + index);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if(i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
}
Result: The above code sample will produce the following result.
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
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]
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]
durgesh.tripathi2@gmail.com Page 15
JAVA PROGRAMS
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
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
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
Result: The above code sample will produce the following result.The result
will change depending upon the current system time
06:40:32 AM
durgesh.tripathi2@gmail.com Page 17
JAVA PROGRAMS
import java.util.Calendar;
import java.util.Formatter;
Result: The above code sample will produce the following result.
October Oct 10
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;
durgesh.tripathi2@gmail.com Page 18
JAVA PROGRAMS
Result: The above code sample will produce the following result.The result
will change depending upon the current system date and time
Wed Oct 15 20:37:30 GMT+05:30 2008
Solution: This example formats the time into 24 hour format (00:00-
24:00) by using sdf.format(date) method of SimpleDateFormat class.
import java.text.SimpleDateFormat;
import java.util.Date;
Result: 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
durgesh.tripathi2@gmail.com Page 19
JAVA PROGRAMS
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.
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;
durgesh.tripathi2@gmail.com Page 20
JAVA PROGRAMS
Result: The above code sample will produce the following result.
weekday = Monday
weekday = Tuesday
weekday = Wednesday
weekday = Thursday
weekday = Friday
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
durgesh.tripathi2@gmail.com Page 21
JAVA PROGRAMS
df.format(d1));
}
}
Result: The above code sample will produce the following result.
today is Mon Jun 22 02:37:06 IST 2009
today is in Italian Language in Switzerlandluned�,
22. giugno 2009
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
Result: The above code sample will produce the following result.
today is Mon Jun 22 02:44:36 IST 2009
date after a month will be Thu Oct 22 02:44:36 IST 2009
date after 7 hrs will be Thu Oct 22 00:44:36 IST 2009
durgesh.tripathi2@gmail.com Page 22
JAVA PROGRAMS
Solution: The following example displays week no of the year & month.
import java.util.*;
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
durgesh.tripathi2@gmail.com Page 23
JAVA PROGRAMS
September 9, 2001
9/9/01
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
Solution: This example displays the way of using overloaded method for
printing types of array (integer, double and character).
public class MainClass {
public static void printArray(Integer[] inputArray) {
for (Integer element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Double[] inputArray) {
for (Double element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Character[] inputArray) {
for (Character element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void main(String args[]) {
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4,
5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(integerArray);
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray);
System.out.println("\nArray characterArray contains:");
printArray(characterArray);
}
}
Result: The above code sample will produce the following result.
Array integerArray contains:
1
2
3
durgesh.tripathi2@gmail.com Page 25
JAVA PROGRAMS
4
5
6
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))
durgesh.tripathi2@gmail.com Page 26
JAVA PROGRAMS
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
}
}
Result: The above code sample will produce the following result.
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55
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
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
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
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.
Result: The above code sample will produce the following result.
Found the substring .
durgesh.tripathi2@gmail.com Page 30
JAVA PROGRAMS
switch(c) {
case lamborghini:
System.out.println("You choose lamborghini!");
break;
case tata:
System.out.println("You choose tata!");
break;
case audi:
System.out.println("You choose audi!");
break;
case fiat:
System.out.println("You choose fiat!");
break;
case honda:
System.out.println("You choose honda!");
break;
default:
System.out.println("I don't know your car.");
break;
}
}
}
Result: The above code sample will produce the following result.
You choose tata!
Result: The above code sample will produce the following result.
All car prices:
lamborghini costs 900 thousand dollars.
tata costs 2 thousand dollars.
audi costs 50 thousand dollars.
fiat costs 15 thousand dollars.
honda costs 12 thousand dollars.
durgesh.tripathi2@gmail.com Page 31
JAVA PROGRAMS
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
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 32
JAVA PROGRAMS
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
durgesh.tripathi2@gmail.com Page 33
JAVA PROGRAMS
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
Result: The above code sample will produce the following result.
C:\JavaTemp37056.javatemp
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;
}
durgesh.tripathi2@gmail.com Page 36
JAVA PROGRAMS
return file.length();
}
public static void main(String[] args) {
long size = getFileSize("c:/java.txt");
System.out.println("Filesize in bytes: " + size);
}
}
Result: The above code sample will produce the following result.To test
this example, first create a text file 'java.txt' in 'C' drive.The size may vary
depending upon the size of the file.
File size in bytes: 480
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
durgesh.tripathi2@gmail.com Page 37
JAVA PROGRAMS
out.close();
}
}
Result: The above code sample will produce the following result.
temporary file created:
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.
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
Result: The above code sample will produce the following result.
Status = true
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
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
Result: The above code sample will produce the following result.
last modifed:10:20:54
Result: The above code sample will produce the following result.
Parent directory is : File
durgesh.tripathi2@gmail.com Page 43
JAVA PROGRAMS
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
durgesh.tripathi2@gmail.com Page 44
JAVA PROGRAMS
visitAllDirsAndFiles(C://Java);
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}
Result: The above code sample will produce the following result.
The Directory is traversed.
Result: The above code sample will produce the following result.
class Main{
public static void main(String[] args){
File[] roots = File.listRoots();
System.out.println("Root directories in your system are:");
for (int i=0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}
}
}
Result: The above code sample will produce the following result. The
result may vary depending on the system & operating system. If you are
using Unix system you will get a single root '/'.
Root directories in your system are:
durgesh.tripathi2@gmail.com Page 45
JAVA PROGRAMS
C:\
D:\
E:\
F:\
G:\
H:\
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
class Main {
public static void main(String[] args) {
File dir = new File("F:");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("Either dir does not exist or is not a directory");
}
else {
for (int i=0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
Result: The above code sample will produce the following result.
14
F:\C Drive Data Old HDD
F:\Desktop1
F:\harsh
F:\hharsh final
F:\hhhh
F:\mov
F:\msdownld.tmp
F:\New Folder
F:\ravi
F:\ravi3
durgesh.tripathi2@gmail.com Page 47
JAVA PROGRAMS
F:\RECYCLER
F:\System Volume Information
F:\temp
F:\work
Solution: This example shows how to use finally block to catch runtime
exceptions (Illegal Argument Exception) by the use of e.getMessage().
public class ExceptionDemo2 {
public static void main(String[] argv) {
new ExceptionDemo2().doTheWork();
}
public void doTheWork() {
Object o = null;
for (int i=0; i<5; i++) {
try {
o = makeObj(i);
}
catch (IllegalArgumentException e) {
System.err.println("Error: ("+ e.getMessage()+").");
return;
}
finally {
System.err.println("All done");
if (o==null)
System.exit(0);
}
System.out.println(o);
}
}
public Object makeObj(int type)
throws IllegalArgumentException {
if (type == 1)
throw new IllegalArgumentException
("Don't like type " + type);
return new Object();
}
}
Result: The above code sample will produce the following result.
All done
java.lang.Object@1b90b39
Error: (Don't like type 1).
All done
durgesh.tripathi2@gmail.com Page 48
JAVA PROGRAMS
Result: The above code sample will produce the following result.
It is mammal
Result: The above code sample will produce the following result.
Caught Exception
getMassage(): My Exception
gatLocalisedMessage(): My Exception
toString():java.lang.Exception: My Exception
print StackTrace():
java.lang.Exception: My Exception
at ExceptionMethods.main(ExceptionMeyhods.java:12)
durgesh.tripathi2@gmail.com Page 49
JAVA PROGRAMS
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;
Result: The above code sample will produce the following result.
Testing for empty stack
16 milliseconds
Catching EmptyStackException
3234 milliseconds
durgesh.tripathi2@gmail.com Page 50
JAVA PROGRAMS
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
Result: The above code sample will produce the following result.
Arithmetic exception occoured :
java.lang.ArithmeticException: / by zero
Chained exception thrown manually :
java.lang.NumberFormatException
durgesh.tripathi2@gmail.com Page 51
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
Result: The above code sample will produce the following result.
throwing an exception
durgesh.tripathi2@gmail.com Page 52
JAVA PROGRAMS
Result: The above code sample will produce the following result.
throwing an exception
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
Result: The above code sample will produce the following result.
The result is1
Array is out of Boundsjava.lang.ArrayIndexOutOfBoundsException : 5
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);
}
catch (Exception x){
System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}
durgesh.tripathi2@gmail.com Page 55
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Wrong input
durgesh.tripathi2@gmail.com Page 56
JAVA PROGRAMS
stackAddition();
System.out.println("Sum=" + ans);
}
public static void stackAddition() {
theStack = new Stack(10000);
ans = 0;
while (num > 0) {
theStack.push(num);
--num;
}
while (!theStack.isEmpty()) {
int newN = theStack.pop();
ans += newN;
}
}
}
class Stack {
private int maxSize;
private int[] data;
private int top;
public Stack(int s) {
maxSize = s;
data = new int[maxSize];
top = -1;
}
public void push(int p) {
data[++top] = p;
}
public int pop() {
return data[top--];
}
public int peek() {
return data[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
Result: The above code sample will produce the following result.
Sum=1225
[2]: How to get the first and the last element of a linked list?
Solution: Following example shows how to get the first and last element
of a linked list with the help of linkedlistname.getFirst() and
linkedlistname.getLast() of LinkedList class.
import java.util.LinkedList;
durgesh.tripathi2@gmail.com Page 57
JAVA PROGRAMS
" + lList.getFirst());
System.out.println("Last element of LinkedList is :
" + lList.getLast());
}
}
Result: The above code sample will produce the following result.
First element of LinkedList is :100
Last element of LinkedList is :500
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
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();
}
public int size() {
return list.size();
}
public void addItems(GenQueue q) {
while (q.hasItems())
list.addLast(q.dequeue());
}
}
durgesh.tripathi2@gmail.com Page 60
JAVA PROGRAMS
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
durgesh.tripathi2@gmail.com Page 61
JAVA PROGRAMS
Result: The above code sample will produce the following result.
JavaStringReversal
Reversed:lasreveRgnirtSavaJ
durgesh.tripathi2@gmail.com Page 62
JAVA PROGRAMS
Result: The above code sample will produce the following result.
First index of 2 is: 1
Last index of 2 is: 5
durgesh.tripathi2@gmail.com Page 63
JAVA PROGRAMS
System.out.print(" ");
}
System.out.println("");
}
}
Result: The above code sample will produce the following result.
50 40 30 20 10
Result: The above code sample will produce the following result.
12345
After swapping
52341
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 64
JAVA PROGRAMS
BBTHP
BBMHP
Result: The above code sample will produce the following result.
The max element is: 3.4324
Result: The above code sample will produce the following result.
[A, D, M, O, X]
Element found at : 1
durgesh.tripathi2@gmail.com Page 65
JAVA PROGRAMS
Result: The above code sample will produce the following result.
39
39
38
37
Result: The above code sample will produce the following result.
[one, two, three, four, five]
[one, two, three, Replaced, five]
durgesh.tripathi2@gmail.com Page 66
JAVA PROGRAMS
durgesh.tripathi2@gmail.com Page 67
JAVA PROGRAMS
}
}
Result: The above code sample will produce the following result.
How many elements you want to add to the array:
red white green
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
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.
durgesh.tripathi2@gmail.com Page 70
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Collection Example!
Collection size: 3
class UtilDemo3 {
public static void main(String[] args) {
String[] coins = { "A", "B", "C", "D", "E" };
List l = new ArrayList();
for (int i = 0; i < coins.length; i++)
l.add(coins[i]);
ListIterator liter = l.listIterator();
durgesh.tripathi2@gmail.com Page 71
JAVA PROGRAMS
System.out.println("Before reversal");
while (liter.hasNext())
System.out.println(liter.next());
Collections.reverse(l);
liter = l.listIterator();
System.out.println("After reversal");
while (liter.hasNext())
System.out.println(liter.next());
}
}
Result: The above code sample will produce the following result.
Before reversal
A
B
C
D
E
After reversal
E
D
C
B
A
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
import java.util.*;
Result: The above code sample will produce the following result.
Collection Example!
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 73
JAVA PROGRAMS
3rd
2nd
1st
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
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
}
}
}
Result: The above code sample will produce the following result.
Three
Two
One
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.*;
Result: The above code sample will produce the following result.
[one, Two, three, Four, five, six, one, three, Four]
max: three
min: Four
durgesh.tripathi2@gmail.com Page 76
JAVA PROGRAMS
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
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]
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]
rotate: [Four, five, six, one, Two, three]
durgesh.tripathi2@gmail.com Page 78
JAVA PROGRAMS
tt.setName("Thread");
System.out.println("before start(),
tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(),
tt.isAlive()=" + tt.isAlive());
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
System.out.println("The end of main(),
tt.isAlive()=" + tt.isAlive());
}
}
Result: The above code sample will produce the following result.
before start(),tt.isAlive()=false
just after start(), tt.isAlive()=true
name=main
name=main
name=main
name=main
name=main
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=Thread
name=main
name=main
The end of main().tt.isAlive()=false
durgesh.tripathi2@gmail.com Page 79
JAVA PROGRAMS
System.out.println("Finished");
}
thread.join();
}
}
Result: The above code sample will produce the following result.
Thread has not finished
Finished
Result: The above code sample will produce the following result.
Thread[Thread-0,10,main]: 5
Thread[Thread-0,10,main]: 4
Thread[Thread-0,10,main]: 3
Thread[Thread-0,10,main]: 2
Thread[Thread-0,10,main]: 1
Thread[Thread-1,1,main]: 5
Thread[Thread-1,1,main]: 4
durgesh.tripathi2@gmail.com Page 80
JAVA PROGRAMS
Thread[Thread-1,1,main]: 3
Thread[Thread-1,1,main]: 2
Thread[Thread-1,1,main]: 1
Thread[Thread-2,1,main]: 5
Thread[Thread-2,1,main]: 4
Thread[Thread-2,1,main]: 3
Thread[Thread-2,1,main]: 2
Thread[Thread-2,1,main]: 1
.
.
.
durgesh.tripathi2@gmail.com Page 81
JAVA PROGRAMS
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+"
Alive:="+thrd.isAlive()+"
State:=" + thrd.getState() );
}
}
Result: The above code sample will produce the following result.
main Alive=true State:=running
Result: The above code sample will produce the following result.
name=main
name=main
name=main
name=main
name=main
name=thread
name=thread
name=thread
name=thread
durgesh.tripathi2@gmail.com Page 82
JAVA PROGRAMS
durgesh.tripathi2@gmail.com Page 83
JAVA PROGRAMS
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));
Thread thread2 = new Thread(new TestThread(2));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("The priority has been set.");
}
}
Result: The above code sample will produce the following result.
durgesh.tripathi2@gmail.com Page 84
JAVA PROGRAMS
Result: The above code sample will produce the following result.
Detected stop
durgesh.tripathi2@gmail.com Page 85
JAVA PROGRAMS
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
throws InterruptedException {
for (int i = 0; i < 5; i++)
new SleepingThread().join();
System.out.println("The thread has been suspened.");
}
}
Result: The above code sample will produce the following result.
The thread has been suspened.
public Main(ThreadID v) {
this.var = v;
}
try {
Thread threadA = new Thread(shared, "threadA");
threadA.start();
Thread.sleep(500);
durgesh.tripathi2@gmail.com Page 86
JAVA PROGRAMS
threadB.start();
Thread.sleep(500);
public ThreadID() {
nextID = 10001;
}
Result: The above code sample will produce the following result.
threadA: in initialValue()
threadA: var getThreadID =10001
threadB: in initialValue()
threadB: var getThreadID =10002
threadC: in initialValue()
threadC: var getThreadID =10003
threadA: var getThreadID =10001
threadB: var getThreadID =10002
threadC: var getThreadID =10003
durgesh.tripathi2@gmail.com Page 87
JAVA PROGRAMS
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
durgesh.tripathi2@gmail.com Page 88
JAVA PROGRAMS
+ lstThreads[i].getName());
}
}
Result: The above code sample will produce the following result.
Thread No:0 = main
Thread No:1 = thread1
durgesh.tripathi2@gmail.com Page 89
JAVA PROGRAMS
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName()+" Alive:"
+thrd.isAlive()+" State:" + thrd.getState() );
}
}
Result: The above code sample will produce the following result.
MyThread #1 Alive:false State:NEW
MyThread #1 starting.
waiting:true
waiting:true
alive
alive
MyThread #1 terminating.
alive
MyThread #1 Alive:false State:TERMINATED
durgesh.tripathi2@gmail.com Page 90
JAVA PROGRAMS
while (true) {
for (int i = 0; i < 100000; i++) {
int j = i * 2;
}
System.out.println("A isInterrupted()="
+ Thread.currentThread().isInterrupted());
if (Thread.interrupted()) {
System.out.println("B isInterrupted()="
+ Thread.currentThread().isInterrupted());
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
GeneralInterrupt si = new GeneralInterrupt();
Thread t = new Thread(si);
t.start();
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
System.out.println("in main() -
interrupting other thread");
t.interrupt();
System.out.println("in main() - leaving");
}
}
Result: The above code sample will produce the following result.
in run() - about to work2()
in main() - interrupting other thread
in main() - leaving
C isInterrupted()=true
in run() - interrupted in work2()
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.
durgesh.tripathi2@gmail.com Page 92
JAVA PROGRAMS
g.drawString(str, 1, 150);
}
}
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
import java.applet.*;
import java.awt.*;
import java.util.*;
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
durgesh.tripathi2@gmail.com Page 93
JAVA PROGRAMS
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.
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.
durgesh.tripathi2@gmail.com Page 95
JAVA PROGRAMS
}
}
}
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
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
AppletContext a = getAppletContext();
URL url = new URL(link);
a.showDocument(url,"_blank");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
durgesh.tripathi2@gmail.com Page 97
JAVA PROGRAMS
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class readFileApplet extends Applet{
String fileToRead = "test1.txt";
StringBuffer strBuff;
TextArea txtArea;
Graphics g;
public void init(){
txtArea = new TextArea(100, 100);
txtArea.setEditable(false);
add(txtArea, "center");
String prHtml = this.getParameter("fileToRead");
if (prHtml != null) fileToRead = new String(prHtml);
readFile();
}
public void readFile(){
String line;
URL url = null;
try{
url = new URL(getCodeBase(), fileToRead);
}
catch(MalformedURLException e){}
try{
InputStream in = url.openStream();
BufferedReader bf = new BufferedReader
(new InputStreamReader(in));
strBuff = new StringBuffer();
while((line = bf.readLine()) != null){
strBuff.append(line + "\n");
}
txtArea.append("File Name : " + fileToRead + "\n");
txtArea.append(strBuff.toString());
}
catch(IOException e){
e.printStackTrace();
}
}
}
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
durgesh.tripathi2@gmail.com Page 98
JAVA PROGRAMS
durgesh.tripathi2@gmail.com Page 99
JAVA PROGRAMS
x.printStackTrace();
}
}
}
}
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
Result: The above code sample will produce the following result in a java
enabled web browser.
View in Browser.
Result: The above code sample will produce the following result.
Different font names are displayed in a frame.
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.
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.
Result: The above code sample will produce the following result.
Different shapes are created.
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
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.
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 java.awt.RenderingHints;
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
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
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
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?
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
Result: The above code sample will produce the following result.The result
may vary.
rows before rollback statement = 4
rows after rollback statement = 3
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
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
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
Result: The above code sample will produce the following result.
fix
rug
bag
fix
rig
rag
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Result: The above code sample will produce the following result.
The string has matched with the 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
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
Result: The above code sample will produce the following result.
ThisisaJavaprogram.ThisisanotherJavaprogram.
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}
Result: The above code sample will produce the following result.
numberOfGroups =3
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.
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
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.
m.appendReplacement(stringbf,
m.group(1).toUpperCase() + m.group(2).toLowerCase());
}
System.out.println(m.appendTail(stringbf).toString());
}
}
Result: The above code sample will produce the following result.
this is a java test
This Is A Java Test
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
Result: The above code sample will produce the following result.
Connected to http://www,javatutorial.com/102.32.56.14
}
}
Result: The above code sample will produce the following result.
The last modification time of java.bmp is :24 May 2009 12:14:50
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;
size = conn.getContentLength();
if (size < 0)
System.out.println("Could not determine file size.");
else
System.out.println("The size of the file is = " +size + "bytes");
conn.getInputStream().close();
}
}
Result: The above code sample will produce the following result.
The size of The file is = 16384 bytes
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
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
Result: The above code sample will produce the following result.
Date:05.26.2009
InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter(new FileWriter("data.html"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}
Result: The above code sample will produce the following result.
Welcome to Java Tutorial
Here we have plenty of examples for you!
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
Result: The above code sample will produce the following result.
Local HostAddress: 192.168.1.4
Local host name: harsh
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;
throws Exception{
try {
Properties systemSettings = System.getProperties();
systemSettings.put("proxySet", "true");
systemSettings.put("http.proxyHost", "proxy.mycompany1.local");
systemSettings.put("http.proxyPort", "80");
URL u = new URL("http://www.google.com");
HttpURLConnection con = (HttpURLConnection)
u.openConnection();
System.out.println(con.getResponseCode() + " : " +
con.getResponseMessage());
System.out.println(con.getResponseCode() ==
HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
System.out.println(false);
}
System.setProperty("java.net.useSystemProxies", "true");
Proxy proxy = (Proxy) ProxySelector.getDefault().
select(new URI("http://www.yahoo.com/")).iterator().
next();;
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress)
proxy.address();
if (addr == null) {
System.out.println("No Proxy");
}
else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
Result: The above code sample will produce the following result.
200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.mycompany1.local
proxy port : 80
System.out.println("Connected to "
+ theSocket.getInetAddress()
+ " on port " + theSocket.getPort() + " from port "
+ theSocket.getLocalPort() + " of "
+ theSocket.getLocalAddress());
}
catch (UnknownHostException e) {
System.err.println("I can't find " + e );
}
catch (SocketException e) {
System.err.println("Could not connect to " +e );
}
catch (IOException e) {
System.err.println(e);
}
}
}
Result: The above code sample will produce the following result.
Connected to /74.125.67.100 on port 80 from port
2857 of /192.168.1.4
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);
}
}
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));
}
}
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));
}
}
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));
}
}
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));
}
}
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));
}
}
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;
}
}
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);
}
}
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();
}
}
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());
}
}
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();
import java.util.*;
import java.text.*;
class NumberProgram
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("##.##");
Scanner input=new Scanner(System.in);
System.out.print("Enter Number: ");
double num=input.nextDouble();
System.out.print("Raise Number's power: ");
double pow=input.nextDouble();
double value=Math.pow(num,pow);
System.out.println("Result is: "+df.format(value));
}
}
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;
}
ModelOfCategory(list);
}
}
ii. Inputname: which would accept the name of the student &
returns the name.
Solution:
import java.util.*;
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);
}
}
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;
.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
d=rev(b); //reverses b
e=e*10;
System.out.println();
str="";
for(int p=i;p<6;p++)
str=str+" ";
System.out.print(str+c);
//prints the first four lines
r[i-1]=(str+c);
}
System.out.println();
for(i=2;i>=0;i--) //prints the last 3 lines
System.out.println(r[i]);
}
/*defined static so that can be called within the main without putting it in
seperate class and calling by class name*/
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(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]);
*
* * *
* * ***
* * *****
* * ***
* * *
*
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:
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:
return;
int counter = 0;
if (Character.isLetter(str.charAt(i)))
counter++;
}