//In call by reference, the original value is changed if we made changes in the called method.
import java.util.*;
class AddTwoMatrix
int m, n;
int first[][] = new int[m][n];
int second[][] = new int[m][n];
AddTwoMatrix(int[][] first, int[][] second, int m, int n)
this.first = first;
this.second = second;
this.m = m;
this.n = n;
public static void main(String[] args)
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
int second[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println("Enter the elements of second matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
second[c][d] = in.nextInt();
System.out.println("\nElements of First matrix is : ");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
System.out.print(first[c][d] + "\t");
System.out.println();
}
System.out.println("\nElements of Second matrix is : ");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
System.out.print(second[c][d] + "\t");
System.out.println();
AddTwoMatrix a = new AddTwoMatrix(first, second, m, n);
//call by reference
a.addmatrix(a); //Passing Object
//Function for Adding two matrix and storing in third matrix
public void addmatrix(AddTwoMatrix a)
int c, d;
int sum[][] = new int[a.m][a.n];
for (c = 0; c < a.m; c++)
for (d = 0; d < a.n; d++)
sum[c][d] = a.first[c][d] + a.second[c][d];
System.out.println("\nSum of the two matrices is : ");
for (c = 0; c < a.m; c++)
for (d = 0; d < a.n; d++)
System.out.print(sum[c][d] + "\t");
System.out.println();
class ArrayCopyExample
public static void main(String[] args)
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a',
't', 'e', 'd'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
class ArrayCopyExample
public static void main(String[] args)
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a',
't', 'e', 'd'};
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
class ArrayCopyOfRangeExample {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a',
't', 'e', 'd' };
char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
System.out.println(new String(copyTo));
class ArrayExample
public static void main(String[] args)
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: " + anArray[0]);
System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
System.out.println("Element at index 5: " + anArray[5]);
System.out.println("Element at index 6: " + anArray[6]);
System.out.println("Element at index 7: " + anArray[7]);
System.out.println("Element at index 8: " + anArray[8]);
System.out.println("Element at index 9: " + anArray[9]);
class ArrayOfArraysAnimalDemo
public static void main(String[] args)
String[][] animals = {{"DanaDog", "WallyDog", "JessieDog", "AlexisDog", "LuckyDog"}, {"BibsCat",
"DoodleCat", "MillieCat", "SimonCat"}, {"ElyFish", "CloieFish", "GoldieFish", "OscarFish", "ZippyFish",
"TedFish"}, {"RascalMule", "GeorgeMule", "GracieMule", "MontyMule", "BuckMule", "RosieMule"}};
for (int i = 0; i < animals.length; i++)
{
System.out.print(animals[i][0] + ": ");
for (int j = 1; j < animals[i].length; j++)
System.out.print(animals[i][j] + " ");
System.out.println();
class ArrayOperations
public static void main(String[] args)
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++)
System.out.println(myList[i] + " ");
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++)
total += myList[i];
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++)
if (myList[i] > max)
max = myList[i];
System.out.println("Max is " + max);
import java.util.Arrays;
class ArraySort
// This program is the example of array sorting
public static void main(String[] args)
// TODO Auto-generated method stub
// initializing unsorted array
String iArr[] = {"Programming", "Hub", "Alice", "Wonder", "Land"};
// sorting array
Arrays.sort(iArr);
// let us print all the elements available in list
System.out.println("The sorted array is:");
for (int i = 0; i < iArr.length; i++)
System.out.println(iArr[i]);
}
}
import java.io.*;
class ArrayAverage
public static void main(String[] args)
//define an array
int[] numbers = new int[]{10, 20, 15, 25, 16, 60, 100};
int sum = 0;
for (int i = 0; i < numbers.length; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Sum of array elements is : " + sum);
System.out.println("Average value of array elements is : " + average);
import java.util.*;
class ArrayBasic
public static void main(String[] args)
int[] arr;
int size, i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
size = sc.nextInt();
arr = new int[size];
System.out.println("\nEnter array elements");
for (i = 0; i < size; i++)
arr[i] = sc.nextInt();
System.out.println("\nElements in the Array are : ");
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
import java.util.Scanner;
class Matrix_Create {
Scanner scan;
int matrix[][];
int row, column;
void create() {
scan = new Scanner(System.in);
System.out.println("Matrix Creation");
System.out.println("\nEnter number of rows :");
row = Integer.parseInt(scan.nextLine());
System.out.println("Enter number of columns :");
column = Integer.parseInt(scan.nextLine());
matrix = new int[row][column];
System.out.println("Enter the data :");
for(int i=0; i<row ; i++) {
for(int j=0; j
<column ; j++) {
matrix[i][j] =scan.nextInt();
void display() {
System.out.println("\nThe Matrix is :");
for(int i=0; i <row ; i++) {
for(int j=0; j <column ; j++) {
System.out.print("\t" + matrix[i][j]);
System.out.println();
class CreateAndDisplayMatrix {
public static void main(String
args[]) {
Matrix_Create obj=new Matrix_Create();
obj.create();
obj.display();
class DisplayArrayForEach
public static void main(String[] args)
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element : myList)
System.out.println(element);
}
import java.util.*;
import java.text.DecimalFormat;
class DoubleMatrix
public static void main(String[] args)
double[][] a;
double[] s;
int row, col, k = 0, i, j;
double sum = 0.0;
DecimalFormat f = new DecimalFormat("##.####");
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of row and column");
row = sc.nextInt();
col = sc.nextInt();
a = new double[row][col];
s = new double[col];
System.out.println("Enter elements of matrix");
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
a[i][j] = sc.nextDouble();
}
System.out.println("Double Matrix is : ");
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
System.out.print(" " + a[i][j]);
System.out.println();
//sum of the elements of double matrix
for (i = 0; i < col; i++)
for (j = 0; j < row; j++)
sum = sum + a[j][i];
s[k] = sum;
k++;
sum = 0;
for (i = 0; i < col; i++)
System.out.println("Sum of Column " + (i + 1) + " is : " + f.format(s[i]));
//Sum of Numbers in an Array
import java.util.*;
class PassingArraystoFunction
public static void main(String[] args)
int[] a;
int size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
size = sc.nextInt();
a = new int[size];
System.out.println("Enter elements in the array");
for(int i = 0 ;i < size; i++)
a[i] = sc.nextInt();
System.out.println("The Elements of the array are : ");
for(int i = 0 ;i < size; i++)
System.out.print(a[i] + " ");
//Passing array to the function
addElements(a, size);
}
public static void addElements(int[] a , int size)
int sum = 0;
for(int i = 0; i < size; i++)
sum += a[i];
System.out.println("\nSum of the elements of arrays is : "+sum);
import java.util.*;
class ClosestValue
public static void main(String[] args)
int a[];
int find;
int closest = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
int size = sc.nextInt();
a = new int[size];
System.out.println("Enter numbers in array");
for (int i = 0; i < size; i++)
{
a[i] = sc.nextInt();
System.out.println("Numbers are : ");
for (int i = 0; i < size; i++)
System.out.print(a[i] + " ");
System.out.println();
System.out.println("Enter Number to find closest value");
find = sc.nextInt();
int distance = Math.abs(closest - find);
for (int i : a)
int distanceI = Math.abs(i - find);
if (distance > distanceI)
closest = i;
distance = distanceI;
System.out.println("Closest Value is : " + closest);
import java.io.*;
class MagicMatrix
public static void main(String args[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the size of the matrix : ");
int n = Integer.parseInt(br.readLine());
if (n > 5)
System.out.println("Enter a number between 1 to 5 ");
else
int A[][] = new int[n][n]; // Creating the Magic Matrix
int i, j, k, t;
/*Initializing every cell of the matrix with 0 */
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
A[i][j] = 0;
/* When the size of the matrix is Odd */
if (n % 2 != 0)
i = 0;
j = n / 2;
k = 1;
while (k <= n * n)
A[i][j] = k++;
i--; // Making one step upward
j++; // Moving one step to the right
if (i < 0 && j > n - 1) // Condition for the top-right corner element
i = i + 2;
j--;
if (i < 0) // Wrapping around the row if it goes out of boundary
i = n - 1;
if (j > n - 1) // Wrapping around the column if it goes out of boundary
j = 0;
if (A[i][j] > 0) // Condition when the cell is already filled
i = i + 2;
j--;
/* When the size of the matrix is even */
else
k = 1;
/* Filling the matrix with natural numbers from 1 till n*n */
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
A[i][j] = k++;
j = n - 1;
for (i = 0; i < n / 2; i++)
/* swapping corner elements of primary diagonal */
t = A[i][i];
A[i][i] = A[j][j];
A[j][j] = t;
/* swapping corner elements of secondary diagonal */
t = A[i][j];
A[i][j] = A[j][i];
A[j][i] = t;
j--;
/* Printing the Magic matrix */
System.out.println("The Magic Matrix of size " + n + "x" + n + " is:");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
System.out.print(A[i][j] + "\t");
System.out.println();
import java.util.Scanner;
class MatrixAddition {
Scanner scan;
int matrix1[][], matrix2[][], sum[][];
int row, column;
void create() {
scan = new Scanner(System.in);
System.out.println("Matrix Addition");
// First Matrix Creation..
System.out.println("\nEnter number of rows & columns");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
matrix1 = new int[row][column];
matrix2 = new int[row][column];
sum = new int[row][column];
System.out.println("Enter the data for first matrix :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
matrix1[i][j] = scan.nextInt();
// Second Matrix Creation..
System.out.println("Enter the data for second matrix :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
matrix2[i][j] = scan.nextInt();
void display() {
System.out.println("\nThe First Matrix is :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
System.out.print("\t" + matrix1[i][j]);
}
System.out.println();
System.out.println("\n\nThe Second Matrix is :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
System.out.print("\t" + matrix2[i][j]);
System.out.println();
void add() {
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
System.out.println("\n\nThe Sum is :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
System.out.print("\t" + sum[i][j]);
System.out.println();
class MatrixAdditionExample {
public static void main(String args[]) {
MatrixAddition obj = new MatrixAddition();
obj.create();
obj.display();
obj.add();
import java.util.Scanner;
class MatrixMultiplication
public static void main(String args[])
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if (n != p)
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
second[c][d] = in.nextInt();
}
for (c = 0; c < m; c++)
for (d = 0; d < q; d++)
for (k = 0; k < p; k++)
sum = sum + first[c][k] * second[k][d];
multiply[c][d] = sum;
sum = 0;
System.out.println("Product of entered matrices:-");
for (c = 0; c < m; c++)
for (d = 0; d < q; d++)
System.out.print(multiply[c][d] + "\t");
System.out.print("\n");
}
import java.util.Scanner;
public class Matrices {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
int columns = scanner.nextInt();
System.out.println();
System.out.println("Enter first matrix");
int[][] a = readMatrix(rows, columns);
System.out.println();
System.out.println("Enter second matrix");
int[][] b = readMatrix(rows, columns);
int[][] sum = add(a, b);
int[][] difference1 = subtract(a, b);
int[][] difference2 = subtract(b, a);
System.out.println();
System.out.println("A + B =");
printMatrix(sum);
System.out.println();
System.out.println("A - B =");
printMatrix(difference1);
System.out.println();
System.out.println("B - A =");
printMatrix(difference2);
public static int[][] readMatrix(int rows, int columns) {
int[][] result = new int[rows][columns];
Scanner s = new Scanner(System.in);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = s.nextInt();
return result;
public static int[][] add(int[][] a, int[][] b) {
int rows = a.length;
int columns = a[0].length;
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
return result;
public static int[][] subtract(int[][] a, int[][] b) {
int rows = a.length;
int columns = a[0].length;
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] - b[i][j];
return result;
public static void printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
System.out.println();
import java.util.Scanner;
class Matrix_Subtraction {
Scanner scan;
int matrix1[][], matrix2[][], sub[][];
int row, column;
void create() {
scan = new Scanner(System.in);
System.out.println("Matrix Subtraction");
// First Matrix Creation..
System.out.println("\nEnter number of rows & columns");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
matrix1 = new int[row][column];
matrix2 = new int[row][column];
sub = new int[row][column];
System.out.println("Enter the data for first matrix :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
matrix1[i][j] = scan.nextInt();
// Second Matrix Creation..
System.out.println("Enter the data for second matrix :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
matrix2[i][j] = scan.nextInt();
void display() {
System.out.println("\nThe First Matrix is :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
System.out.print("\t" + matrix1[i][j]);
System.out.println();
System.out.println("\n\nThe Second Matrix is :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
System.out.print("\t" + matrix2[i][j]);
System.out.println();
void sub() {
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
sub[i][j] = matrix1[i][j] - matrix2[i][j];
System.out.println("\n\nThe Subtraction is :");
for(int i=0; i < row; i++) {
for(int j=0; j < column; j++) {
System.out.print("\t" + sub[i][j]);
System.out.println();
class MatrixSubtractionExample {
public static void main(String args[]) {
Matrix_Subtraction obj = new Matrix_Subtraction();
obj.create();
obj.display();
obj.sub();
class MergeArrayDemo
public static void main(String args[])
Integer a[]={1,2,3,4};
Integer b[]={5,6,7,0};
Integer[] both = concat(a, b);
System.out.print("\nFirst Array : ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
System.out.print("\nSecond Array : ");
for(int i=0;i<b.length;i++)
System.out.print(b[i]+"\t");
System.out.print("\nMerged Array : ");
for(int i=0;i<both.length;i++)
System.out.print(both[i]+"\t");
public static Integer[] concat(Integer[] a, Integer[] b)
int aLen = a.length;
int bLen = b.length;
Integer[] c= new Integer[aLen+bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
import java.util.*;
class MiddleValue
public static void main(String args[])
int[] a;
int i, j, n, sum = 0, swap, size;
double t;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
size = sc.nextInt();
a = new int[size];
System.out.println("Enter numbers ");
for (i = 0; i < size; i++)
a[i] = sc.nextInt();
System.out.println("Numbers are : ");
for (i = 0; i < size; i++)
System.out.print(a[i] + " ");
//Sorting
for (i = 0; i < (size - 1); i++)
for (j = 0; j < (size - i - 1); j++)
{
if (a[j] > a[j + 1])
swap = a[j];
a[j] = a[j + 1];
a[j + 1] = swap;
System.out.println("\nNumbers in sorted order : ");
for (i = 0; i < size; i++)
System.out.print(a[i] + " ");
//Finding the Middle Value
if (size % 2 == 0)
n = (size + 1) / 2;
t = (a[n] + a[n - 1]) / 2.0;
System.out.println("\nMiddle Value is : " + t);
else
System.out.println("\nMiddle Value is : " + a[size / 2]);
}
import java.util.*;
class MirrorMatrix
public static void main(String[] args)
int row, column;
Scanner in = new Scanner(System.in);
System.out.print("Enter number of rows for matrix :");
row = in.nextInt();
System.out.print("Enter number of rows for matrix :");
column = in.nextInt();
int matrix[][] = new int[row][column];
System.out.println("Enter matrix : ");
for (int i = 0; i < row; i++)
for (int j = 0; j < column; j++)
matrix[i][j] = in.nextInt();
System.out.println("Mirror matrix : ");
for (int i = 0; i < row; i++)
for (int j = column - 1; j >= 0; j--)
{
System.out.print(matrix[i][j] + "\t");
System.out.println("");
class MissingNumberArray
public static int count = 0;
public static int position = 0;
public static boolean flag = false;
public static void main(String[] args)
int a[] = {0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23};
findMissingNumbers(a, position);
private static void findMissingNumbers(int a[], int position)
if (position == a.length - 1)
return;
for (; position < a[a.length - 1]; position++)
if ((a[position] - count) != position)
System.out.println("Missing Number: " + (position + count));
flag = true;
count++;
break;
if (flag)
flag = false;
findMissingNumbers(a, position);
class MultiDimArrayExample
public static void main(String[] args)
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
import java.io.*;
class Employee
String name;
int emp_id;
int salary;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void get_data()
try
System.out.print("\nEnter name: ");
name = br.readLine();
System.out.print("\nEnter emp id: ");
emp_id = Integer.parseInt(br.readLine());
System.out.print("\nEnter salary: ");
salary = Integer.parseInt(br.readLine());
catch (Exception e)
System.out.print("\n" + e);
public void display()
System.out.print("\nName: " + name);
System.out.print("\nEmp id: " + emp_id);
System.out.print("\nSalary: " + salary);
class ObjectArray
public static void main(String args[]) throws Exception
{
int i;
Employee emp[] = new Employee[5];
for (i = 0; i < 5; i++)
emp[i] = new Employee();
for (i = 0; i < 5; i++)
System.out.print("\nEnter Employee Detail for employee " + (i + 1));
emp[i].get_data();
for (i = 0; i < 5; i++)
System.out.print("\nEmployee Details for employee " + (i + 1));
emp[i].display();
import java.io.*;
class SortArray
public static void main(String args[]) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the no. of rows: "); //enter number of rows
int m = Integer.parseInt(br.readLine());
System.out.print("\nEnter the no. of columns: "); //enter number of columns
int n = Integer.parseInt(br.readLine());
int A[][] = new int[m][n]; //creating a 2D array
//enter elements in 2D Array
System.out.println();
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
System.out.print("Enter the elements: ");
A[i][j] = Integer.parseInt(br.readLine());
//Printing the original 2D Array
System.out.println("\nThe original array: ");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
System.out.print(A[i][j] + "\t");
System.out.println();
//Sorting the 2D Array
int t = 0;
for (int x = 0; x < m; x++)
{
for (int y = 0; y < n; y++)
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (A[i][j] > A[x][y])
t = A[x][y];
A[x][y] = A[i][j];
A[i][j] = t;
//Printing the sorted 2D Array
System.out.println("\nThe Sorted Array:");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
System.out.print(A[i][j] + "\t");
System.out.println();
import java.util.*;
class ArraySortingDemo
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Enter no. of elements to sort : ");
int size = in.nextInt();
// initializing unsorted int array
int iArr[] = new int[size];
System.out.println("Enter " + size + " integer(s) :");
for (int i = 0; i < size; i++)
iArr[i] = in.nextInt();
// let us print all the elements available in list
for (int number : iArr)
System.out.println("Number = " + number);
// sorting array
Arrays.sort(iArr);
// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : iArr)
{
System.out.println("Number = " + number);
import java.io.*;
import java.util.*;
class SymmetricMatrix
public static void main(String args[]) throws IOException
int m, n, c, d;
int matrix[][], transpose[][];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
if (m == n)
matrix = new int[m][n];
System.out.println("Enter the elements of matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
matrix[c][d] = in.nextInt();
}
transpose = new int[n][m];
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
transpose[d][c] = matrix[c][d];
System.out.println("Transpose of entered matrix:-");
for (c = 0; c < n; c++)
for (d = 0; d < m; d++)
System.out.print(transpose[c][d] + "\t");
System.out.print("\n");
for (c = 0; c < n; c++)
for (d = 0; d < m; d++)
if (matrix[c][d] != transpose[c][d])
break;
if (d != m)
break;
}
if (c == n)
System.out.println("Symmetric matrix.");
else
System.out.println("Please enter Sqare matrix");
import java.util.*;
class TransposeMatrix
public static void main(String s[])
int i,j;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter number of rows : ");
int r = sc.nextInt();
System.out.print("\nEnter number of columns : ");
int c = sc.nextInt();
int a[][] = new int[r][c];
// take input from user
System.out.println("\nEnter matrix elements : ");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
a[i][j] = sc.nextInt();
// Logic for Transpose
for(i=0;i<r;i++)
for(j=0;j<c;j++)
if(i<j)
int temp = a[j][i];
a[j][i] = a[i][j];
a[i][j] = temp;
// print Transpose matrix
System.out.println("\nTranspose Matrix :");
for(i=0;i<r;i++)
System.out.print("\n");
for(j=0;j<c;j++)
System.out.print(a[i][j] + "\t");
}
}
import java.awt.*;
class FontTextLabel extends Frame
// Declare component Label
Label lbl1,lbl2;
public FontTextLabel()
setLayout(new FlowLayout());
// construct Label
lbl1 = new Label("Text Font Label");
lbl2 =new Label("Normal Text Label");
// "super" Frame adds Label
add(lbl1);
add(lbl2);
Font myFont = new Font("Serif",Font.BOLD,12);
lbl1.setFont(myFont);
setTitle("AWT Elements");
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args)
// allocating an instance
FontTextLabel fntlbl = new FontTextLabel();
import java.awt.*;
public class LabelExample extends Frame
// Declare component Label
Label lblCount;
public LabelExample()
setLayout(new FlowLayout());
// construct Label
lblCount = new Label("Label Example");
// "super" Frame adds Label
add(lblCount);
setTitle("AWT Elements");
setSize(200, 200);
setVisible(true);
public static void main(String[] args)
{
// allocating an instance
LabelExample app = new LabelExample();
import java.io.*;
class BufferedReaderExample
public static void main(String[] args) throws Exception
String str;
int i;
float f;
double d;
long l;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String");
str = br.readLine();
System.out.println("Enter Integer");
i = Integer.parseInt(br.readLine());
System.out.println("Enter float");
f = Float.parseFloat(br.readLine());
System.out.println("Enter double");
d = Double.parseDouble(br.readLine());
System.out.println("String : " + str);
System.out.println("Integer : " + i);
System.out.println("Float : " + f);
System.out.println("Double : " + d);
class CommandLineArgs
public static void main(String args[])
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = Integer.parseInt(args[2]);
if (a > b && a > c) {
System.out.println("Largest Number is : " + a);
} else if (b > c) {
System.out.println("Largest Number is : " + b);
} else {
System.out.println("Largest Number is : " + c);
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
class ArrayListBasics
public static void main(String[] args)
ArrayList<String> al = new ArrayList<String>();
// adding object in arraylist
al.add("Java");
al.add("C");
al.add("C++");
al.add("php");
al.add("python");
al.add("css");
// add
al.add("html");
// add at specific index
al.add(1, "Android");
System.out.print("ArrayList :" + al);
System.out.println();
// remove from arraylist
al.remove("php");
// Size of ArrayList
System.out.print("Size of ArrayList after removing php :" + al.size());
System.out.println();
System.out.println("Is java is in list :" + al.contains("Java"));
//get specific element
System.out.print("I want " + al.get(0));
System.out.println();
// list to array
Object[] a = al.toArray();
System.out.print("Array :");
for (Object object : a)
System.out.print(object + " ");
System.out.println();
// change element
al.set(6, "Javascript");
System.out.print("ArrayList after replace:" + al);
System.out.println();
// sort list using Collections Class
Collections.sort(al);
System.out.print("ArrayList after sort :" + al);
System.out.println();
//Index
System.out.println("Index of Android :" + al.indexOf("Android"));
//clear whole list
al.clear();
System.out.print(al + " " + "Is list empty after clear :" + al.isEmpty());
import java.util.HashMap;
public class HashMapBasics
public static void main(String[] args)
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "android");
hm.put(2, "java");
hm.put(3, "php");
hm.put(4, "c++");
hm.put(5, "javascript");
hm.put(6, "html");
System.out.println(hm + " ");
System.out.println();
System.out.println("Value at 1 is android :" + hm.containsKey(1));
System.out.println("Value at 1 :" + hm.get(1));
System.out.println("java is present :" + hm.containsValue("java"));
//remove
hm.remove(2);
hm.remove(6, "html");
System.out.println("Size after remove operation :" + hm.size());
//replace
hm.replace(5, "jquery");
hm.replace(4, "c++", "scala");
System.out.println("HashMap after replace " + hm);
hm.clear();
System.out.println(hm + " Is Map is empty " + hm.isEmpty());
import java.util.HashSet;
class HashSetBasic
public static void main(String[] args)
HashSet<String> hs = new HashSet<String>();
hs.add("Java");
hs.add("Android");
hs.add("Php");
hs.add("Ajax");
System.out.println(hs);
hs.add("Python");
System.out.println(hs);
// Can't add duplicate
System.out.println("Is Java added :" + hs.add("Java"));
// remove from HashSet
hs.remove("Php");
// Size of HashSet
System.out.print("Size of ArrayList after removing Php :" + hs.size());
System.out.println();
System.out.println("Is java is in list :" + hs.contains("Java"));
// HashSet to array
Object[] a = hs.toArray();
System.out.print("Array :");
for (Object object : a)
System.out.print(object + " ");
System.out.println();
//clear whole HashSet
hs.clear();
System.out.print(hs + " " + "Is HashSet empty after clear :" + hs.isEmpty());
import java.util.TreeSet;
public class TreeSetBasics
public static void main(String[] args)
{
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(12);
ts.add(11);
ts.add(14);
ts.add(15);
ts.add(10);
ts.add(16);
ts.add(17);
System.out.println(ts);
// getting the ceiling value for 13
System.out.println("ceiling value :" + ts.ceiling(13));
//getting the floor value for 13
System.out.println("floor value :" + ts.floor(13));
//first element
System.out.println("first element :" + ts.first());
//last element
System.out.println("last element :" + ts.last());
System.out.println("poll first element :" + ts.pollFirst());
System.out.println("poll last element :" + ts.pollLast());
System.out.println("TreeSet after polling :" + ts);
//the greatest element less than 12
System.out.println("lower element of 12 :" + ts.lower(12));
//the least element greater than 12
System.out.println("higher element of 12 :" + ts.higher(12));
System.out.println("Is 12 is present " + ts.contains(12));
//TreeSet to Array
Object[] a = ts.toArray();
System.out.print("Array :");
for (Object object : a)
System.out.print(object + " ");
System.out.println();
// descending Set
System.out.print("descending Set" + ts.descendingSet());
System.out.println();
//remove from TreeSet
ts.remove(11);
//Size of TreeSet
System.out.println("size of TreeSet after removal of 11 :" + ts.size());
//clear whole TreeSet
ts.clear();
System.out.println(ts + " " + "Is TreeSet is empty :" + ts.isEmpty());
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapTest
public static void main(String[] args)
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "android");
hm.put(2, "java");
hm.put(3, "php");
hm.put(4, "c++");
hm.put(5, "javascript");
System.out.println(hm + " ");
System.out.println();
//following are the ways to access the HashMap
Iterator iterator = hm.entrySet().iterator();
while (iterator.hasNext())
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is: " + mapEntry.getKey()
+ ",value is :" + mapEntry.getValue());
System.out.println();
for (Entry<Integer, String> entry : hm.entrySet())
{
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
System.out.println();
for (Object key : hm.keySet())
System.out.println("Key : " + key.toString() + " Value : "
+ hm.get(key));
import java.util.HashSet;
import java.util.Iterator;
class HashSetTest
public static void main(String[] args)
//Creating HashSet of type String
HashSet<String> al = new HashSet<String>();
al.add("Java");
al.add("Android");
al.add("Php");
al.add("Ajax");
System.out.println(al);
// Using Iterator
Iterator<String> itr = al.iterator();
while (itr.hasNext())
{
System.out.print(itr.next() + " ");
System.out.println();
// Using enhance for-loop
for (String string : al)
System.out.print(string + " ");
import java.util.Iterator;
import java.util.PriorityQueue;
public class PriorityQueueTest
public static void main(String[] args)
PriorityQueue<String> queue = new PriorityQueue<String>();
queue.add("java");
queue.add("android");
queue.add("php");
queue.add("c++");
queue.add("css");
queue.add("javascript");
queue.add("python");
queue.add("ajax");
queue.offer("jquery");
//using iterator
Iterator itr = queue.iterator();
while (itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();
//Retrieves, but does not remove, the head of this queue
//throws Exception if Queue is empty
System.out.println("head:" + queue.element());
//Retrieves, but does not remove, the head of this queue
System.out.println("head:" + queue.peek());
//Retrieves and removes the head of this queue
//throws Exception if Queue is empty
queue.remove();
//Retrieves and removes the head of this queue
queue.poll();
//remove specific value
queue.remove("css");
System.out.println("Queue After remove and poll operation:" + queue);
System.out.println("Is python is present :" + queue.contains("python"));
Object a[] = queue.toArray();
for (Object object : a)
{
System.out.print(object + " ");
System.out.println();
queue.clear();
System.out.println(queue + " queue size :" + queue.size());
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
class SortMap
public static void main(String a[])
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("VB.net", 20);
map.put("Java", 55);
map.put("Python", 7);
map.put("C++", 68);
map.put("Javascript", 26);
map.put("C", 86);
Set<Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
return (o2.getValue()).compareTo(o1.getValue());
});
System.out.println("In Descending Order:");
for (Map.Entry<String, Integer> entry : list)
System.out.println(entry.getValue() + ")\t" + entry.getKey());
import java.util.Map;
import java.util.TreeMap;
public class TreeMapTest
public static void main(String[] args)
//TreeMap is sorted
TreeMap<Integer, String> hm = new TreeMap<Integer, String>();
hm.put(100, "java");
hm.put(102, "android");
hm.put(101, "php");
hm.put(103, "c++");
hm.put(104, "html");
System.out.println(hm);
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest
public static void main(String[] args)
TreeSet<String> ts = new TreeSet<String>();
ts.add("java");
ts.add("php");
ts.add("android");
ts.add("css");
System.out.println(ts);
//using Iterator
Iterator<String> itr = ts.iterator();
while (itr.hasNext())
System.out.print(itr.next() + " ");
System.out.println();
//Using enhanced for-loop
for (String string : ts)
{
System.out.print(string + " ");
import java.util.Scanner;
class Node
protected int data;
protected Node next, prev;
public Node()
next = null;
prev = null;
data = 0;
public Node(int d, Node n, Node p)
data = d;
next = n;
prev = p;
// Function to set link to next node
public void setLinkNext(Node n)
{
next = n;
// Function to set link to previous node
public void setLinkPrev(Node p)
prev = p;
// Funtion to get link to next node
public Node getLinkNext()
return next;
// Function to get link to previous node
public Node getLinkPrev()
return prev;
// Function to set data to node
public void setData(int d)
data = d;
// Function to get data from node
public int getData()
return data;
}
class linkedList
protected Node start;
protected Node end ;
public int size;
public linkedList()
start = null;
end = null;
size = 0;
// Function to check if list is empty
public boolean isEmpty()
return start == null;
// Function to get size of list
public int getSize()
return size;
// Function to insert element at begining
public void insertAtStart(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
start = nptr;
end = start;
else
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
size++;
// Function to insert element at end
public void insertAtEnd(int val)
Node nptr = new Node(val, null, null);
if(start == null)
start = nptr;
end = start;
else
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
size++;
}
// Function to insert element at position
public void insertAtPos(int val , int pos)
Node nptr = new Node(val, null, null);
if (pos == 1)
insertAtStart(val);
return;
Node ptr = start;
for (int i = 2; i <= size; i++)
if (i == pos)
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
ptr = ptr.getLinkNext();
size++ ;
// Function to delete node at position
public void deleteAtPos(int pos)
if (pos == 1)
{
if (size == 1)
start = null;
end = null;
size = 0;
return;
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
if (pos == size)
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
if (i == pos)
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
// Function to display status of list
public void display()
System.out.print("\nDoubly Linked List = ");
if (size == 0)
System.out.print("empty\n");
return;
if (start.getLinkNext() == null)
System.out.println(start.getData() );
return;
Node ptr = start;
System.out.print(start.getData()+ " <-> ");
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
System.out.print(ptr.getData()+ " <-> ");
ptr = ptr.getLinkNext();
System.out.print(ptr.getData()+ "\n");
}
public class DoublyLinkedList
public static void main(String[] args)
Scanner scan = new Scanner(System.in);
// Creating object of linkedList
linkedList list = new linkedList();
System.out.println("Doubly Linked List Test\n");
char ch;
// Perform list operations
System.out.println("\nDoubly Linked List Operations\n");
System.out.println("1. Insert at begining");
System.out.println("2. Insert at end");
System.out.println("3. Insert at position");
System.out.println("4. Delete at position");
System.out.println("5. Check empty");
System.out.println("6. Get size");
do
System.out.print("Enter choice : ");
int choice = scan.nextInt();
switch (choice)
case 1 :
System.out.print("Enter integer element to insert : ");
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.print("Enter integer element to insert : ");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.print("Enter integer element to insert : ");
int num = scan.nextInt() ;
System.out.print("Enter position : ");
int pos = scan.nextInt() ;
if (pos < 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.print("Enter position : ");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.print("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.print("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.print("Size = "+ list.getSize() +" \n");
break;
default :
System.out.print("Wrong Entry \n ");
break;
}
// Display List
list.display();
System.out.print("\nDo you want to continue (Type y or n) : ");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
import java.io.*;
class Stack
private char[] a;
private int top, m;
public Stack(int max)
m = max;
a = new char[m];
top = -1;
public void push(char key)
a[++top] = key;
public char pop()
return (a[top--]);
}
public char peek()
return (a[top]);
public boolean isEmpty()
return (top == -1);
class Evaluation
private Stack s;
private String input;
private String output = "";
public Evaluation(String str)
input = str;
s = new Stack(str.length());
public String inToPre()
int i;
for (i = (input.length() - 1); i >= 0; i--)
char ch = input.charAt(i);
switch (ch)
case '+':
case '-':
gotOperator(ch, 1, ')');
break;
case '*':
case '/':
gotOperator(ch, 2, ')');
break;
case ')':
s.push(ch);
break;
case '(':
gotParenthesis(')');
break;
default:
output = ch + output;
while (!s.isEmpty())
output = s.pop() + output;
return output;
public String inToPost()
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
switch (ch)
case '+':
case '-':
gotOperator(ch, 1, '(');
break;
case '*':
case '/':
gotOperator(ch, 2, '(');
break;
case '(':
s.push(ch);
break;
case ')':
gotParenthesis('(');
break;
default:
output = output + ch;
while (!s.isEmpty())
output = output + s.pop();
return output;
public String preToPost()
{
Stack f = new Stack(input.length());
for (int i = 0; i < input.length(); i++)
char ch = input.charAt(i);
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
s.push(ch);
f.push('0');
else
output = output + ch;
while (f.peek() == '1')
output = output + s.pop();
f.pop();
if (f.isEmpty())
break;
if (!f.isEmpty())
f.pop();
f.push('1');
return output;
private void gotOperator(char opThis, int prec1, char x)
while (!s.isEmpty())
{
char opTop = s.pop();
if (opTop == x)
s.push(opTop);
break;
else
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1 && x == '(')
s.push(opTop);
break;
else if (prec2 <= prec1 && x == ')')
s.push(opTop);
break;
else
if (x == ')')
output = opTop + output;
else
output = output + opTop;
}
}
s.push(opThis);
private void gotParenthesis(char x)
while (!s.isEmpty())
char ch = s.pop();
if (ch == x)
break;
else
if (x == ')')
output = ch + output;
else
output = output + ch;
class BinaryTreeTraversal
public static void main(String args[]) throws IOException
String s, check = "y";
int n;
Evaluation ev;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (check.equals("y"))
System.out.println("MENU");
System.out.println("1. Infix to Prefix");
System.out.println("2. Infix to Postfix");
System.out.println("3. Prefix to Postfix");
System.out.println("Enter your choice");
n = Integer.parseInt(br.readLine());
switch (n)
case 1:
System.out.println("Enter the infix expression ");
s = br.readLine();
ev = new Evaluation(s);
System.out.println("Prefix expression : " + ev.inToPre());
break;
case 2:
System.out.println("Enter the infix expression ");
s = br.readLine();
ev = new Evaluation(s);
System.out.println("Postfix expression : " + ev.inToPost());
break;
case 3:
System.out.println("Enter the Prefix expression ");
s = br.readLine();
ev = new Evaluation(s);
System.out.println("Postfix expression : " + ev.preToPost());
break;
default:
System.out.println("Invalid input");
System.out.println("Press y to continue");
check = br.readLine();
import java.util.*;
class Node
protected int data;
protected Node link;
public Node()
link = null;
data = 0;
public Node(int d, Node n)
data = d;
link = n;
public void setLink(Node n)
{
link = n;
// Function to set data to current Node
public void setData(int d)
data = d;
// Function to get link to next node
public Node getLink()
return link;
// Function to get data from current Node
public int getData()
return data;
class linkedQueue
protected Node front, rear;
public int size;
public linkedQueue()
{
front = null;
rear = null;
size = 0;
// Function to check if queue is empty
public boolean isEmpty()
return front == null;
// Function to get the size of the queue
public int getSize()
return size;
// Function to insert an element to the queue
public void insert(int data)
Node nptr = new Node(data, null);
if (rear == null)
front = nptr;
rear = nptr;
else
rear.setLink(nptr);
rear = rear.getLink();
}
size++;
// Function to remove front element from the queue
public int remove()
if (isEmpty())
throw new NoSuchElementException("Underflow Exception");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size--;
return ptr.getData();
// Function to check the front element of the queue
public int peek()
if (isEmpty())
throw new NoSuchElementException("Underflow Exception");
return front.getData();
// Function to display the status of the queue
public void display()
System.out.print("\nQueue = ");
if (size == 0)
System.out.print("Empty\n");
return;
Node ptr = front;
while (ptr != rear.getLink())
System.out.print(ptr.getData() + " ");
ptr = ptr.getLink();
System.out.println();
class LinkedQueueImplement
public static void main(String[] args)
Scanner scan = new Scanner(System.in);
linkedQueue lq = new linkedQueue();
System.out.println("Linked Queue Test\n");
char ch;
System.out.println("\nQueue Operations");
System.out.println("1. Insert");
System.out.println("2. Remove");
System.out.println("3. Peek");
System.out.println("4. Check empty");
System.out.println("5. Size");
do
System.out.print("Enter choice : ");
int choice = scan.nextInt();
switch (choice)
case 1:
System.out.print("Enter integer element to insert : ");
lq.insert(scan.nextInt());
break;
case 2:
try
System.out.println("Removed Element = " + lq.remove());
catch (Exception e)
System.out.println("Error : " + e.getMessage());
break;
case 3:
try
System.out.println("Peek Element = " + lq.peek());
catch (Exception e)
System.out.println("Error : " + e.getMessage());
break;
case 4:
System.out.println("Empty status = " + lq.isEmpty());
break;
case 5:
System.out.println("Size = " + lq.getSize());
break;
default:
System.out.println("Wrong Entry \n ");
break;
// display queue
lq.display();
System.out.print("\nDo you want to continue (Type y or n) : ");
ch = scan.next().charAt(0);
while (ch == 'Y' || ch == 'y');
import java.util.Scanner;
class Node
protected int data;
protected Node link;
public Node()
link = null;
data = 0;
public Node(int d, Node n)
{
data = d;
link = n;
// Function to set link to next Node
public void setLink(Node n)
link = n;
// Function to set data to current Node
public void setData(int d)
data = d;
// Function to get link to next node
public Node getLink()
return link;
// Function to get data from current Node
public int getData()
return data;
// Class linkedList
class linkedList
protected Node start;
protected Node end;
public int size;
public linkedList()
start = null;
end = null;
size = 0;
// Function to check if list is empty
public boolean isEmpty()
return start == null;
// Function to get size of list
public int getSize()
return size;
// Function to insert an element at begining
public void insertAtStart(int val)
Node nptr = new Node(val, null);
size++;
if (start == null)
start = nptr;
end = start;
else
nptr.setLink(start);
start = nptr;
// Function to insert an element at end
public void insertAtEnd(int val)
Node nptr = new Node(val, null);
size++;
if (start == null)
start = nptr;
end = start;
else
end.setLink(nptr);
end = nptr;
// Function to insert an element at position
public void insertAtPos(int val, int pos)
Node nptr = new Node(val, null);
Node ptr = start;
pos = pos - 1;
for (int i = 1; i < size; i++)
if (i == pos)
Node tmp = ptr.getLink();
ptr.setLink(nptr);
nptr.setLink(tmp);
break;
ptr = ptr.getLink();
size++;
// Function to delete an element at position
public void deleteAtPos(int pos)
if (pos == 1)
start = start.getLink();
size--;
return;
if (pos == size)
Node s = start;
Node t = start;
while (s != end)
t = s;
s = s.getLink();
end = t;
end.setLink(null);
size--;
return;
Node ptr = start;
pos = pos - 1;
for (int i = 1; i < size - 1; i++)
if (i == pos)
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
ptr = ptr.getLink();
size--;
// Function to display elements
public void display()
System.out.print("\nSingly Linked List = ");
if (size == 0)
System.out.print("empty\n");
return;
if (start.getLink() == null)
System.out.println(start.getData());
return;
Node ptr = start;
System.out.print(start.getData() + "->");
ptr = start.getLink();
while (ptr.getLink() != null)
System.out.print(ptr.getData() + "->");
ptr = ptr.getLink();
System.out.print(ptr.getData() + "\n");
class SinglyLinkedList
public static void main(String[] args)
Scanner scan = new Scanner(System.in);
linkedList list = new linkedList();
char ch;
// Perform list operations
do
System.out.println("Singly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
case 1:
System.out.println("Enter integer element to insert");
list.insertAtStart(scan.nextInt());
break;
case 2:
System.out.println("Enter integer element to insert");
list.insertAtEnd(scan.nextInt());
break;
case 3:
System.out.println("Enter integer element to insert");
int num = scan.nextInt();
System.out.println("Enter position");
int pos = scan.nextInt();
if (pos <= 1 || pos > list.getSize())
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4:
System.out.println("Enter position");
int p = scan.nextInt();
if (p < 1 || p > list.getSize())
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5:
System.out.println("Empty status = " + list.isEmpty());
break;
case 6:
System.out.println("Size = " + list.getSize() + " \n");
break;
default:
System.out.println("Wrong Entry \n ");
break;
/* Display List */
list.display();
System.out.println("Do you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
while (ch == 'Y' || ch == 'y');
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Stack
private int top;
private int item[];
Stack(int size)
top = -1;
item = new int[size];
void pushItem(int data)
if (top == item.length - 1)
{
System.out.println("Stack is Full");
else
item[++top] = data;
System.out.println("Pushed Item :" + item[top]);
int popItem()
if (top < 0)
System.out.println("Stack Underflow");
return 0;
else
System.out.println("Pop Item : " + item[top]);
return item[top--];
void displayAll()
for (int i = 0; item[i] != 0; i++)
System.out.print(item[i] + "\t");
System.out.println("");
}
class StackDemo
public static void main(String[] args) throws IOException
Stack stk = new Stack(5);
boolean yes = true;
int choice;
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
System.out.print("1).Push\n2).Pop\n3).Display\n4).Exit\n");
do
System.out.print("\nEnter Choice : ");
choice = Integer.parseInt(is.readLine());
switch (choice)
case 1:
System.out.print("Enter Push Item :");
stk.pushItem(Integer.parseInt(is.readLine()));
break;
case 2:
stk.popItem();
break;
case 3:
stk.displayAll();
break;
case 4:
yes = false;
break;
default:
System.out.println("Invalid Choice");
while (yes == true);
class MyOwnException
public static void main(String[] a)
try
MyOwnException.myTest(null);
catch (MyAppException mae)
System.out.println("Inside catch block: " + mae.getMessage());
}
static void myTest(String str) throws MyAppException
if (str == null)
throw new MyAppException("String val is null");
class MyAppException extends Exception
private String message = null;
public MyAppException()
super();
public MyAppException(String message)
super(message);
this.message = message;
}
public MyAppException(Throwable cause)
super(cause);
@Override
public String toString()
return message;
@Override
public String getMessage()
return message;
import java.util.Scanner;
class DivisionByZero
{
public static void main(String[] args)
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
// try block
try
result = a / b;
System.out.println("Result = " + result);
// catch block
catch (ArithmeticException e)
System.out.println("Exception caught: Division by zero.");
}
import java.net.MalformedURLException;
import java.net.URL;
class MyMultipleCatchBlocks
public static void main(String a[])
MyMultipleCatchBlocks mmcb = new MyMultipleCatchBlocks();
mmcb.execute(1);
mmcb.execute(2);
public void execute(int i)
try
if (i == 1)
getIntValue("7u");
else
getUrlObj("www.junksite.com");
}
catch (NumberFormatException nfe)
System.out.println("Inside NumberFormatException... "
+ nfe.getMessage());
catch (MalformedURLException mue)
System.out.println("Inside MalformedURLException... "
+ mue.getMessage());
catch (Exception ex)
System.out.println("Inside Exception... " + ex.getMessage());
public int getIntValue(String num)
return Integer.parseInt(num);
}
public URL getUrlObj(String urlStr) throws MalformedURLException
return new URL(urlStr);
class MyExplicitThrow
public static void main(String a[])
try
MyExplicitThrow met = new MyExplicitThrow();
System.out
.println("length of JUNK is " + met.getStringSize("JUNK"));
System.out.println("length of WRONG is "
+ met.getStringSize("WRONG"));
System.out.println("length of null string is "
+ met.getStringSize(null));
catch (Exception ex)
{
System.out.println("Exception message: " + ex.getMessage());
public int getStringSize(String str) throws Exception
if (str == null)
throw new Exception("String input is null");
return str.length();
class UsingFinally
public static void main(String[] args)
try
int a = 3 / 0;
System.out.println(a);
}
catch (Exception e)
System.out.println(e);
finally
System.out.println("finally block will execute always.");
import java.net.MalformedURLException;
import java.net.URL;
class MyTryBlockOnly
public static void main(String a[]) throws MalformedURLException
try
URL url = new URL("http://www.google.com");
finally
{
System.out.println("In finally block");
import java.io.IOException;
class UsingThrows
void m() throws IOException
throw new IOException("device error");// checked exception
void n() throws IOException
m();
void p()
try
{
n();
catch (Exception e)
System.out.println("exception handled");
public static void main(String args[])
UsingThrows obj = new UsingThrows();
obj.p();
System.out.println("normal flow...");
import java.io.*;
class CopyFile
public static void main(String args[]) throws IOException
FileReader in = null;
FileWriter out = null;
try
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
out.write(c);
finally
if (in != null)
in.close();
if (out != null)
out.close();
import java.io.*;
class CreateDirectoryTest
public static void main(String args[])
{
if (new File("docs").mkdir())
System.out.println("Successfully created directory.");
else
System.out.println("Failed to create directory.");
import java.io.*;
class CreateFileTest
public static void main(String args[])
try
if (new File("output.txt").createNewFile())
System.out.println("Successfully created File.");
else
System.out.println("Failed to create file.");
catch (IOException e)
System.err.println(e.getMessage());
import java.io.File;
public class DirectoryDeleteTest
public static boolean deleteFile(String filename)
{
boolean exists = new File(filename).delete();
return exists;
public static void test(String type, String filename)
System.out.println("The following "+type+
" called "+filename+(deleteFile(filename)?
" was deleted." : " does not exist."));
public static void main(String args[])
test("directory", File.seperator + "docs" + File.seperator);
import java.io.File;
class FileDeleteTest
public static boolean deleteFile(String filename)
boolean exists = new File(filename).delete();
return exists;
public static void test(String type, String filename)
System.out.println("The following " + type + " called " + filename + (deleteFile(filename) ? " was
deleted." : " does not exist."));
}
public static void main(String args[])
test("file", "Main.java");
import java.io.*;
class ReadBinaryFile
public static void main(String[] args)
// The name of the file to open.
String fileName = "file.txt";
FileInputStream inputStream = null;
try
// Use this for reading the data.
byte[] buffer = new byte[1000];
inputStream = new FileInputStream(fileName);
// read fills buffer with data and returns
// the number of bytes read (which of course
// may be less than the buffer size, but
// it will never be more).
int total = 0;
int nRead = 0;
while ((nRead = inputStream.read(buffer)) != -1)
// Convert to String so we can display it.
// Of course you wouldn't want to do this with
// a 'real' binary file.
System.out.println(new String(buffer));
total += nRead;
System.out.println("Read " + total + " bytes");
catch (FileNotFoundException ex)
System.out.println("Unable to open file '" + fileName + "'");
catch (IOException ex)
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
finally
// Always close files.
try
if (inputStream != null)
inputStream.close();
}
}
catch (IOException e)
import java.io.*;
class ReadFile
public static void main(String[] args)
// The name of the file to open.
String fileName = "file.txt";
// This will reference one line at a time
String line = null;
BufferedReader bufferedReader = null;
try
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
catch (FileNotFoundException ex)
System.out.println("Unable to open file '" + fileName + "'");
catch (IOException ex)
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
finally
// Always close files.
try
if (bufferedReader != null)
bufferedReader.close();
catch (IOException e)
import java.io.*;
class Employee implements java.io.Serializable
public String name;
public String address;
// transient variable are not serialized
public transient int id;
public int number;
class SerializeDemo
public static void main(String[] args)
Employee e = new Employee();
e.name = "Andy Rubin";
e.address = "Chappaqua, New York, United States";
e.id = 007;
e.number = 5893254;
try
FileOutputStream fileOut = new FileOutputStream("employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /employee.ser");
catch (IOException i)
i.printStackTrace();
}
}
import java.io.*;
class WriteBinaryFile
public static void main(String[] args)
// The name of the file to open.
String fileName = "file.txt";
BufferedWriter bufferedWriter = null;
try
// Assume default encoding.
FileWriter fileWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
bufferedWriter = new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");
// Always close files.
bufferedWriter.close();
}
catch (IOException ex)
System.out.println("Error writing to file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
finally
// Always close files.
try
if (bufferedWriter != null)
bufferedWriter.close();
catch (IOException e)
import java.io.*;
class WriteFile
public static void main(String[] args)
{
// The name of the file to open.
String fileName = "file.txt";
BufferedWriter bufferedWriter = null;
try
// Assume default encoding.
FileWriter fileWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
bufferedWriter = new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");
catch (IOException ex)
System.out.println("Error writing to file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
finally
// Always close files.
try
{
if (bufferedWriter != null)
bufferedWriter.close();
catch (IOException e)
class CalculateCircleAreaExample
public static void main(String[] args)
int radius = 3;
System.out.println("The radius of the circle is " + radius);
/*
* Area of a circle is pi * r * r where r is a radius of a circle.
*/
// NOTE : use Math.PI constant to get value of pi
double area = Math.PI * radius * radius;
System.out.println("Area of a circle is " + area);
import java.util.Scanner;
class AreaOfRectangle
public static void main(String[] args)
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of Rectangle:");
double length = scanner.nextDouble();
System.out.println("Enter the width of Rectangle:");
double width = scanner.nextDouble();
//Area = length*width;
double area = length * width;
System.out.println("Area of Rectangle is:" + area);
import java.util.*;
class AreaOfSquare
public static void main(String args[])
int side, area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of the sides of square");
side = sc.nextInt();
area = side * side;
System.out.println("Area of Square : " + area);
import java.util.*;
class BinaryCalculator
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("First Binary: ");
String binOne = in.next();
System.out.print("Second Binary: ");
String binTwo = in.next();
int left = Integer.parseInt(binOne, 2);
int right = Integer.parseInt(binTwo, 2);
System.out.println("Sum of the binary numbers : " + Integer.toBinaryString(left + right));
System.out.println("Difference of the binary numbers : " + Integer.toBinaryString(left - right));
System.out.println("Product of the binary numbers : " + Integer.toBinaryString(left * right));
System.out.println("Quotient of the binary numbers : " + Integer.toBinaryString(left / right));
import java.io.*;
class BinaryToDecimal
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Binary no. to convert in Decimal : ");
String number = br.readLine();
/*
to convert Binary number to decimal number use,
int parseInt method of Integer wrapper class.
Pass 2 as redix second argument.
*/
int decimalNumber = Integer.parseInt(number, 2);
System.out.println("Binary number converted to decimal number");
System.out.println("Decimal number is : " + decimalNumber);
import java.io.*;
class BinaryToOctal
public static void main(String[] args) throws Exception
{
String num = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter binary number : ");
num = br.readLine();
int dec = Integer.parseInt(num, 2);
String oct = Integer.toOctalString(dec);
System.out.println("Binary " + num + " in Octal is " + oct);
import java.util.Scanner;
class CalculateMean
public static void main(String[] args)
int sum = 0, inputNum;
int counter;
float mean;
Scanner NumScanner = new Scanner(System.in);
System.out.println("Enter the total number of terms whose mean you want to calculate");
counter = NumScanner.nextInt();
System.out.println("Please enter " + counter + " numbers:");
for (int x = 1; x <= counter; x++)
inputNum = NumScanner.nextInt();
sum = sum + inputNum;
System.out.println();
mean = sum / counter;
System.out.println("The mean of the " + counter + " numbers you entered is " + mean);
import java.lang.*;
import java.util.Scanner;
class CalculateInterest
public static void main(String[] args)
double p, n, r, si, ci;
Scanner s = new Scanner(System.in);
System.out.print("Enter the amount : ");
p = s.nextDouble();
System.out.print("Enter the No.of years : ");
n = s.nextDouble();
System.out.print("Enter the Rate of interest : ");
r = s.nextDouble();
si = (p * n * r) / 100;
ci = p * Math.pow(1.0 + r / 100.0, n) - p;
System.out.println("\nAmount : " + p);
System.out.println("No. of years : " + n);
System.out.println("Rate of interest : " + r);
System.out.println("Simple Interest : " + si);
System.out.println("Compound Interest : " + ci);
import java.util.Scanner;
import java.io.*;
class Calculator
public static void main(String[] args)
int choice;
int x = 0;
int y = 0;
int sum;
PrintStream out;
Scanner input;
Calculator calc = new Calculator();
try
out = new PrintStream("calclog.txt");
do
System.out.println("Calculator Program");
System.out.println("--------------------\n");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Mod");
System.out.println("6. Power");
System.out.println("99. End Program\n");
System.out.println("Enter Choice: ");
input = new Scanner(System.in);
choice = input.nextInt();
while ((choice < 1 || choice > 6) && choice != 99)
System.out.println("Please enter 1, 2, 3, 4, 5, or 6: ");
choice = input.nextInt();
if (choice != 99)
{
System.out.println("Please enter 2 numbers only: ");
x = input.nextInt();
y = input.nextInt();
switch (choice)
case 1:
sum = calc.add(x, y);
System.out.printf("The sum is %d\n\n", sum);
out.println(x + "+" + y + "=" + sum);
break;
case 2:
sum = calc.sub(x, y);
System.out.printf("The answer is %d\n\n", sum);
out.println(x + "-" + y + "=" + sum);
break;
case 3:
sum = calc.multi(x, y);
System.out.printf("The answer is %d\n\n", sum);
out.println(x + "*" + y + "=" + sum);
break;
case 4:
try
sum = calc.div(x, y);
System.out.printf("The answer is %d\n\n", sum);
out.println(x + "/" + y + "=" + sum);
catch (Exception e)
System.out
.println("\nError: Cannot Divide by zero\n\n");
break;
case 5:
sum = calc.mod(x, y);
System.out.printf("The mod is %d\n\n", sum);
out.println(x + "%" + y + "=" + sum);
break;
case 6:
sum = calc.pow(x, y);
System.out.printf("The answer is %d\n\n", sum);
out.println(x + "^" + y + "=" + sum);
break;
while (choice != 99);
input.close();
System.out.println("Ending program...");
catch (Exception e)
System.out.println("ERROR: Some error occured");
e.printStackTrace();
public int add(int num1, int num2)
int sum;
sum = num1 + num2;
return sum;
public int sub(int num1, int num2)
int sum;
sum = num1 - num2;
return sum;
public int multi(int num1, int num2)
int sum;
sum = num1 * num2;
return sum;
public int div(int num1, int num2)
int sum;
sum = num1 / num2;
return sum;
}
public int mod(int num1, int num2)
int sum;
sum = num1 % num2;
return sum;
public int pow(int base, int exp)
int sum = 1;
if (exp == 0)
sum = 1;
while (exp > 0)
sum = sum * base;
exp--;
return sum;
}
import java.util.*;
class CelsiustoFahrenheit
public static void main(String[] args)
double temperature;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature in Celsius");
temperature = in.nextInt();
temperature = (temperature * 9 / 5.0) + 32;
System.out.println("Temperature in Fahrenheit = " + temperature);
import java.util.Scanner;
class DecimalToBinary
public String toBinary(int n)
if (n == 0)
return "0";
String binary = "";
while (n > 0)
{
int rem = n % 2;
binary = rem + binary;
n = n / 2;
return binary;
public static void main(String[] args)
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int decimal = scanner.nextInt();
DecimalToBinary decimalToBinary = new DecimalToBinary();
String binary = decimalToBinary.toBinary(decimal);
System.out.println("The binary representation is " + binary);
import java.util.*;
class FahrenheitToCelsius
public static void main(String[] args)
float temperature;
Scanner in = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit : ");
temperature = in.nextInt();
temperature = (temperature - 32) * 5 / 9;
System.out.println("Temperature in Celsius = " + temperature);
import java.util.*;
class FractionAdding
public static void main(String args[])
float a, b, c, d;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a : ");
a = scanner.nextFloat();
System.out.print("Enter b : ");
b = scanner.nextFloat();
System.out.print("Enter c : ");
c = scanner.nextFloat();
System.out.print("Enter d : ");
d = scanner.nextFloat();
// fraction addition formula ((a*d)+(b*c))/(b*d)
System.out.print("Fraction Addition : [( " + a + " * " + d + " )+( " + b + " * " + c + " ) / ( " + b + " * "
+ d + " )] = " + (((a * d) + (b * c)) / (b * d)));
import java.util.*;
class FractionSubtraction
public static void main(String args[])
float a,b,c,d;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a : ");
a = scanner.nextFloat();
System.out.print("Enter b : ");
b = scanner.nextFloat();
System.out.print("Enter c : ");
c = scanner.nextFloat();
System.out.print("Enter d : ");
d = scanner.nextFloat();
// fraction addition formula ((a*d)-(b*c))/(b*d)
System.out.print("Fraction subtraction : [( "+a+" * "+d+" )-( "+b+" * "+c+" ) / ( "+b+"
* "+d+" )] = "+(((a*d)-(b*c))/(b*d)));
import java.util.*;
class GCDExample
public static void main(String args[])
//Enter two number whose GCD needs to be calculated.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number to find GCD : ");
int number1 = scanner.nextInt();
System.out.print("Enter second number to find GCD : ");
int number2 = scanner.nextInt();
System.out.println("GCD of two numbers " + number1 + " and " + number2 + " is :" +
findGCD(number1, number2));
//find GCD of two number using Euclid's method
private static int findGCD(int number1, int number2)
//base case
if (number2 == 0)
return number1;
return findGCD(number2, number1 % number2);
import java.util.Scanner;
class GCDLCM
public static void main(String args[])
int x, y;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the two numbers: ");
x = sc.nextInt();
y = sc.nextInt();
System.out.println("GCD of two numbers is : " + gcd(x, y));
System.out.println("LCM of two numbers is : " + lcm(x, y));
static int gcd(int x, int y)
int r = 0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while (a % b != 0)
r = a % b;
a = b;
b = r;
return r;
static int lcm(int x, int y)
int a;
a = (x > y) ? x : y; // a is greater number
while (true)
if (a % x == 0 && a % y == 0)
return a;
}
++a;
import java.util.*;
class HarmonicSeries
public static void main(String args[])
int num, i = 1;
double rst = 0.0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for length of series");
num = in.nextInt();
while (i <= num)
System.out.print("1/" + i + " +");
rst = rst + (double) 1 / i;
i++;
System.out.println("\n\nSum of Harmonic Series is " + rst);
}
import java.io.*;
class HexToDecimal
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter hex no. to convert in Decimal : ");
String strHexNumber = br.readLine();
/*
* to convert hexadecimal number to decimal number use,
* int parseInt method of Integer wrapper class.
* Pass 16 as redix second argument.
*/
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println("Hexadecimal number converted to decimal number");
System.out.println("Decimal number is : " + decimalNumber);
import java.util.Scanner;
class MultiplicationTable
public static void main(String args[])
{
int n, c;
System.out
.println("Enter an integer to print it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of " + n + " is :-");
for (c = 1; c <= 10; c++)
System.out.println(n + "*" + c + " = " + (n * c));
import java.util.Scanner;
class Tables {
public static void main(String args[]) {
int a, b, c, d;
System.out
.println("Enter range of numbers to print their multiplication table");
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
for (c = a; c <= b; c++) {
System.out.println("Multiplication table of " + c);
for (d = 1; d <= 10; d++) {
System.out.println(c + "*" + d + " = " + (c * d));
import java.io.*;
class OctalToDecimal
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Octal no. to convert in Decimal : ");
String number = br.readLine();
/*
to convert Octal number to decimal number use,
int parseInt method of Integer wrapper class.
Pass 8 as redix second argument.
*/
int decimalNumber = Integer.parseInt(number, 8);
System.out.println("Octal number converted to decimal number");
System.out.println("Decimal number is : " + decimalNumber);
}
}
/*
Pythagorean Triplet:
c*c = a*a + b*b
*/
class PythagoreanTriplet
public static void main(String s[]) throws Exception
System.out.println("Pythagorean Triplet: ");
for (int a = 1; a <= 50; a++)
for (int b = 1; b <= 50; b++)
int csquared = a * a + b * b;
double croot = Math.sqrt(csquared);
if (croot == Math.ceil(croot))
System.out.println(a + " " + b + " " + (int) croot);
class QuadraticEquation
public static void main(String[] args)
{
/*
* Suppose our Quadratic Equation to be solved is 2x2 + 6x + 4 = 0 .
* (Assuming that both roots are real valued)
* General form of a Quadratic Equation is ax2 + bx + c = 0 where 'a' is
* not equal to 0
* Hence a = 2, b = 6 and c = 4.
*/
int a = 2;
int b = 6;
int c = 4;
// Finding out the roots
double temp1 = Math.sqrt(b * b - 4 * a * c);
double root1 = (-b + temp1) / (2 * a);
double root2 = (-b - temp1) / (2 * a);
System.out
.println("The roots of the Quadratic Equation \"2x2 + 6x + 4 = 0\" are "
+ root1 + " and " + root2);
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class SquareRoot
{
public static void main(String[] args) throws IOException
int number = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number");
//read a string entered by user
String line = br.readLine();
//Handle exception when a string does not contain a number
try
//Convert a string into number
number = Integer.parseInt(line);
catch (NumberFormatException exception)
System.out.println("Please enter a valid number");
//Find square root of a number
double squareRoot = Math.sqrt(number);
//print square root
System.out.println("Square root of a number " + number + "=" + squareRoot);
}
}
import java.util.*;
class Cylinder
public static void main(String[] args)
double PI = 3.14;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Radius: ");
double r = sc.nextDouble();
System.out.print("Enter Height: ");
double h = sc.nextDouble();
double volume = PI * r * r * h;
double area = 2 * PI * r * (r + h);
System.out.println("Volume of Cylinder: " + volume);
System.out.println("Area of Cylinder: " + area);
import java.awt.*;
import javax.swing.JFrame;
class CanvasExample extends Canvas
public void paint(Graphics g)
{
Toolkit t = Toolkit.getDefaultToolkit();
Image i = t.getImage("bugs.gif");
g.drawImage(i, 10, 10, this);
public static void main(String[] args)
CanvasExample m = new CanvasExample();
JFrame f = new JFrame("Canvas Example");
f.add(m);
f.setSize(300, 300);
f.setVisible(true);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutDemo extends JFrame implements ActionListener
CardLayout card;
JButton b1, b2, b3;
Container c;
CardLayoutDemo()
c = getContentPane();
//create CardLayout object with 40 horizontal space and 30 vertical space
card = new CardLayout(40, 30);
c.setLayout(card);
b1 = new JButton("Card 1.");
b2 = new JButton("Card 2.");
b3 = new JButton("Card 3.");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a", b1);
c.add("b", b2);
c.add("c", b3);
public void actionPerformed(ActionEvent e)
card.next(c);
public static void main(String args[])
CardLayoutDemo cl = new CardLayoutDemo();
cl.setSize(400, 400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
import java.awt.*;
import javax.swing.JFrame;
public class CanvasExample extends Canvas {
public void paint(Graphics g) {
Toolkit t = Toolkit.getDefaultToolkit();
Image i = t.getImage("bugs.gif");
g.drawImage(i, 10, 10, this);
public static void main(String[] args) {
CanvasExample m = new CanvasExample();
JFrame f = new JFrame("Canvas Example");
f.add(m);
f.setSize(300, 300);
f.setVisible(true);
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class ExitButtonExample extends JFrame
public ExitButtonExample()
{
initUI();
private void initUI()
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quitButton = new JButton("Exit");
quitButton.setBounds(90, 60, 80, 30);
quitButton.addActionListener(new ActionListener()
@Override
public void actionPerformed(ActionEvent event)
System.exit(0);
});
panel.add(quitButton);
setTitle("Exit Button Example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
@Override
public void run()
ExitButtonExample ex = new ExitButtonExample();
ex.setVisible(true);
});
import java.awt.*;
import javax.swing.*;
class FlowLayoutDemo
FlowLayoutDemo()
JFrame f = new JFrame();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300, 300);
f.setVisible(true);
public static void main(String args[])
new FlowLayoutDemo();
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
class GridBaglayoutDemo extends Applet
protected void makeButton(String name, GridBagLayout gridbag, GridBagConstraints gbc)
Button b = new Button(name);
gridbag.setConstraints(b, gbc);
b.setBackground(Color.lightGray);
add(b);
public void init()
{
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setFont(new Font("Elephanta", Font.PLAIN, 20));
setLayout(gridbag);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0; //first column
gbc.gridy = 0; //first row
makeButton("Button1", gridbag, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
makeButton("Button2", gridbag, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
makeButton("Button3", gridbag, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 40; //make this component tall
gbc.gridwidth = 3; //3 column wide
gbc.gridx = 0;
gbc.gridy = 1; //second row
makeButton("Button4", gridbag, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 0; //reset to default
gbc.anchor = GridBagConstraints.PAGE_END; //bottom of space
gbc.insets = new Insets(20, 0, 0, 0); //top padding
gbc.gridx = 1; //aligned with button 2
gbc.gridwidth = 2; //2 columns wide
gbc.gridy = 2; //third row
makeButton("Button5", gridbag, gbc);
public static void main(String s[])
Frame f = new Frame("GridBagLayout Demo");
GridBaglayoutDemo gbl = new GridBaglayoutDemo();
gbl.init();
f.add("Center", gbl);
f.pack();
f.setSize(f.getPreferredSize());
f.show();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
System.exit(0);
});
import java.awt.*;
import javax.swing.*;
class MyGridLayoutExample
JFrame f;
MyGridLayoutExample()
f = new JFrame("GridLayout Example");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);
f.setLayout(new GridLayout(3, 3));
// setting grid layout of 3 rows and 3 columns
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args)
new MyGridLayoutExample();
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class JButtonExample extends JFrame
JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
JButtonExample() // the frame constructor
super("JButton Example");
setBounds(100, 100, 300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane(); // inherit main frame
con.add(panel); // JPanel containers default to FlowLayout
button.setMnemonic('P'); // associate hotkey to button
panel.add(button);
button.requestFocus();
setVisible(true); // make frame visible
}
public static void main(String args[])
new JButtonExample();
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
class AboutDialog extends JDialog
public AboutDialog()
initUI();
public final void initUI()
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(0, 10)));
//place the icon in the CLASSPATH
ImageIcon icon = new ImageIcon("icon.png");
JLabel label = new JLabel(icon);
label.setAlignmentX(0.5f);
add(label);
add(Box.createRigidArea(new Dimension(0, 10)));
JLabel name = new JLabel("Java Programs, 2.2.6");
name.setFont(new Font("Serif", Font.BOLD, 13));
name.setAlignmentX(0.5f);
add(name);
add(Box.createRigidArea(new Dimension(0, 50)));
JButton close = new JButton("Close");
close.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
dispose();
});
close.setAlignmentX(0.5f);
add(close);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("About Java Programs");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(300, 200);
setVisible(true);
public static void main(String[] args)
new AboutDialog();
import javax.swing.*;
class JFrameHelloWorld
private static void createAndShowGUI()
// Create and set up the window.
JFrame frame = new JFrame("HelloWorld");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setting the height, width and position
//of the frame
frame.setBounds(100, 100, 200, 100);
// Add the "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
// Display the window.
frame.setVisible(true);
public static void main(String[] args)
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGUI();
});
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
class JMenuBarExample
private static void createAndShowGUI()
//Create and set up the window.
JFrame frame = new JFrame("JMenuBarExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args)
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGUI();
}
});
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;
class JOptionPaneDemo extends JFrame implements ActionListener
Container contentPane = null;
private JButton jbnDialog;
String ButtonLabels;
private JRadioButton[] dialogTypeButtons;
private JRadioButton[] messageTypeButtons;
private int[] messageTypes = {JOptionPane.PLAIN_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, JOptionPane.QUESTION_MESSAGE,
JOptionPane.WARNING_MESSAGE, JOptionPane.ERROR_MESSAGE};
private ButtonGroup messageTypeButtonGroup, buttonTypeButtonGroup,
dialogTypeButtonGroup;
private JRadioButton[] optionTypeButtons;
private int[] OptionTypes = {JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION,
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.OK_CANCEL_OPTION};
public static void main(String[] args)
new JOptionPaneDemo();
}
public JOptionPaneDemo()
super("JOptionPane Demo");
addWindowListener(new WindowListener());
contentPane = getContentPane();
contentPane.setLayout(new GridLayout(0, 1));
JPanel jplButton = new JPanel();
jbnDialog = new JButton("Show an Option Pane");
jbnDialog.addActionListener(this);
jplButton.add(jbnDialog);
contentPane.add(jplButton);
createRadioButtonGroupings();
ButtonLabels = "Button1 Button2 Button3";
pack();
setVisible(true);
public void createRadioButtonGroupings()
JPanel jplDialogType = new JPanel();
dialogTypeButtonGroup = new ButtonGroup();
dialogTypeButtons = new JRadioButton[]{new JRadioButton("Show Message", true), new
JRadioButton("Get Confirmation"), new JRadioButton("Collect Input"), new JRadioButton("Present
Options")};
for (int i = 0; i < dialogTypeButtons.length; i++)
dialogTypeButtonGroup.add(dialogTypeButtons[i]);
jplDialogType.add(dialogTypeButtons[i]);
contentPane.add(jplDialogType);
JPanel jplMessageType = new JPanel();
messageTypeButtonGroup = new ButtonGroup();
messageTypeButtons = new JRadioButton[]{new JRadioButton("Plain"), new
JRadioButton("Information", true), new JRadioButton("Question"), new JRadioButton("Warning"),
new JRadioButton("Error")};
for (int i = 0; i < messageTypeButtons.length; i++)
messageTypeButtonGroup.add(messageTypeButtons[i]);
jplMessageType.add(messageTypeButtons[i]);
contentPane.add(jplMessageType);
JPanel jplButtonType = new JPanel();
buttonTypeButtonGroup = new ButtonGroup();
optionTypeButtons = new JRadioButton[]{new JRadioButton("Default", true), new
JRadioButton("Yes/No"), new JRadioButton("Yes/No/Cancel"), new JRadioButton("OK/Cancel")};
for (int i = 0; i < optionTypeButtons.length; i++)
buttonTypeButtonGroup.add(optionTypeButtons[i]);
jplButtonType.add(optionTypeButtons[i]);
contentPane.add(jplButtonType);
// Windows Listener for Window Closing
public class WindowListener extends WindowAdapter
public void windowClosing(WindowEvent event)
System.exit(0);
public void actionPerformed(ActionEvent event)
{
/*
* dialogTypeButtons =
* new JRadioButton[] { new JRadioButton("Show Message", true),
* new JRadioButton("Get Confirmation"),
* new JRadioButton("Collect Input"),
* new JRadioButton("Present Options") };
*/
if (dialogTypeButtons[0].isSelected())
JOptionPane.showMessageDialog(this, "Show Message", "Simple Dialog", getMessageType());
else if (dialogTypeButtons[1].isSelected())
JOptionPane.showConfirmDialog(this, "Get Confirmation", "Simple Dialog", getButtonType(),
getMessageType());
else if (dialogTypeButtons[2].isSelected())
JOptionPane.showInputDialog(this, "Collect Input", "Simple Dialog", getMessageType(), null,
null, null);
else if (dialogTypeButtons[3].isSelected())
JOptionPane.showOptionDialog(this, "Present Options", "Simple Dialog", getButtonType(),
getMessageType(), null, substrings(ButtonLabels), null);
private int getAssociatedType(AbstractButton[] buttons, int[] types)
{
for (int i = 0; i < buttons.length; i++)
if (buttons[i].isSelected())
return (types[i]);
return (types[0]);
private int getMessageType()
return (getAssociatedType(messageTypeButtons, messageTypes));
private int getButtonType()
return (getAssociatedType(optionTypeButtons, OptionTypes));
private String[] substrings(String string)
StringTokenizer tok = new StringTokenizer(string);
String[] substrings = new String[tok.countTokens()];
for (int i = 0; i < substrings.length; i++)
substrings[i] = tok.nextToken();
return (substrings);
import javax.swing.JOptionPane;
class JOptionDemo
public static void main(String[] args)
String fullName = " ";
String strAge = " ";
int age = 0;
fullName = JOptionPane.showInputDialog(null, "Enter your full name: ");
JOptionPane.showMessageDialog(null, "Your full name is " + fullName);
strAge = JOptionPane.showInputDialog(null, " Enter your age: ");
age = Integer.parseInt(strAge);
JOptionPane.showConfirmDialog(null, age, "Is this your real age?",
JOptionPane.OK_CANCEL_OPTION);
JOptionPane.showMessageDialog(null, "Your age is " + age + ".");
import java.awt.*;
import javax.swing.*;
class JScrollPaneDemo extends JApplet
Container c;
JPanel panel;
public void init()
{
c = getContentPane();
c.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridLayout(20, 20));
int b = 1;
for (int i = 0; i < 20; i++)
for (int j = 0; j < 20; j++)
panel.add(new JButton("Button" + b));
b++;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(panel, v, h);
c.add(jsp, "Center");
/*
<applet code = "JScrollPaneDemo" width = "250" height = "250">
</applet>
*/
import javax.swing.*;
class JTableDemo
JFrame f;
JTableDemo()
f = new JFrame();
String data[][] = {
{"101", "ABC", "10000"},
{"102", "DEF", "20000"},
{"103", "XYZ", "30000"}};
String column[] = {"ID", "NAME", "SALARY"};
JTable jt = new JTable(data, column);
jt.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(jt);
f.add(sp);
f.setSize(300, 400);
f.setVisible(true);
public static void main(String args[])
new JTableDemo();
import java.awt.Color;
import javax.swing.*;
class TextAreaExample
JTextArea area;
JFrame f;
TextAreaExample()
f = new JFrame();
area = new JTextArea(300, 300);
area.setBounds(10, 30, 300, 300);
area.setBackground(Color.black);
area.setForeground(Color.white);
area.setText("This is a TextArea.");
f.add(area);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
public static void main(String[] args)
new TextAreaExample();
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
class LoginView
public static void main(String[] args)
JFrame frame = new JFrame("Demo application");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
private static void placeComponents(JPanel panel)
panel.setLayout(null);
JLabel userLabel = new JLabel("User");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 40, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 40, 160, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
JButton registerButton = new JButton("register");
registerButton.setBounds(180, 80, 80, 25);
panel.add(registerButton);
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
class MultipleEventSources extends JFrame
JLabel statusbar;
public MultipleEventSources()
initUI();
public final void initUI()
JPanel panel = new JPanel();
statusbar = new JLabel("Click on any button");
statusbar.setBorder(BorderFactory
.createEtchedBorder(EtchedBorder.RAISED));
panel.setLayout(null);
JButton close = new JButton("Button 1");
close.setBounds(40, 30, 90, 25);
close.addActionListener(new ButtonListener());
JButton open = new JButton("Button 2");
open.setBounds(40, 80, 90, 25);
open.addActionListener(new ButtonListener());
JButton find = new JButton("Button 3");
find.setBounds(40, 130, 90, 25);
find.addActionListener(new ButtonListener());
JButton save = new JButton("Button 4");
save.setBounds(40, 180, 90, 25);
save.addActionListener(new ButtonListener());
panel.add(close);
panel.add(open);
panel.add(find);
panel.add(save);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setTitle("Multiple Event Sources");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent e)
JButton o = (JButton) e.getSource();
String label = o.getText();
statusbar.setText(" " + label + " button clicked");
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
public void run()
MultipleEventSources ms = new MultipleEventSources();
ms.setVisible(true);
});
import javax.swing.JFrame;
class SimpleJFrameExample extends JFrame
public SimpleJFrameExample()
setTitle("Simple JFrame Example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
public static void main(String[] args)
SimpleJFrameExample ex = new SimpleJFrameExample();
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TooltipExample extends JFrame {
public TooltipExample() {
initUI();
private void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
panel.setToolTipText("This is panel");
JButton btn = new JButton("Button");
btn.setBounds(100, 60, 100, 30);
btn.setToolTipText("This is a button");
panel.add(btn);
setTitle("Tooltip");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TooltipExample ex = new TooltipExample();
ex.setVisible(true);
});
//The continue keyword can be used in any of
//the loop control structures. It causes the
//loop to immediately jump to the next iteration
//of the loop.
//In a for loop, the continue keyword causes
//flow of control to immediately jump to the
//update statement.
//In a while loop or do/while loop, flow of
//control immediately jumps to the Boolean
//expression.
class ContinueExample
public static void main(String args[])
{
int[] numbers = {10, 20, 30, 40, 50};
for (int x : numbers)
if (x == 30)
continue;
System.out.print(x);
System.out.print("\n");
class DoWhileLoop
public static void main(String args[])
int x = 1;
do
System.out.println("value of x : " + x);
x++;
while (x < 10);
class ForEachExample
{
public static void main(String args[])
int[] intArray = new int[]{1, 2, 3, 4, 5, 6};
for (int a : intArray)
System.out.print(a + " ");
class WhileLoop
public static void main(String args[])
int x = 1;
while (x < 10)
System.out.println("value of x : " + x);
x++;
class LogBase10Value
public static void main(String a[])
System.out.println("Base 10 logarithm value of 15 is: " + Math.log10(25));
}
class CeilValue
public static void main(String[] args)
System.out.println("Ceiling value of 55: " + Math.ceil(55));
System.out.println("Ceiling value of -67.8: " + Math.ceil(-67.8));
System.out.println("Ceiling value of 29.5: " + Math.ceil(29.5));
class CubeRoot
public static void main(String a[])
System.out.println("Cube root of 10: " + Math.cbrt(27));
System.out.println("Cube root of 625: " + Math.cbrt(125));
System.out.println("Cube root of 1090: " + Math.cbrt(1000));
class ExponentialValue
public static void main(String a[])
System.out.println("Exponential value of 1: " + Math.exp(1));
System.out.println("Exponential value of 3: " + Math.exp(3));
System.out.println("Exponential value of 9: " + Math.exp(9));
class HypotenuseValue
{
public static void main(String[] args)
int side1 = 50;
int side2 = 30;
System.out.println("The length of hypotenuse is: " + Math.hypot(side1, side2));
class MyCopySign
public static void main(String a[])
System.out.println("After copying sign from -10, the value is: "
+ Math.copySign(46.8, -90));
System.out.println("After copying sign from -3, the value is: "
+ Math.copySign(-23.1, 45));
class NextAfterValue
public static void main(String a[])
System.out.println("Next after value of 10 in the direction of 7: "
+ Math.nextAfter(9, 6));
System.out.println("Next after value of 10 in the direction of 12: "
+ Math.nextAfter(13, 18));
}
class NextUpValue
public static void main(String a[])
System.out.println("Next up value for 48.5 is: " + Math.nextUp(48.5));
class SigNumValue
public static void main(String a[])
System.out.println("Signum value of 30.2 is: " + Math.signum(30.2));
System.out.println("Signum value of 0 is: " + Math.signum(0));
System.out.println("Signum value of -28.63 is: " + Math.signum(-28.63));
class MathPower
public static void main(String a[])
System.out.println("5 to the power of 3 is: " + Math.pow(5, 3));
System.out.println("6.4 to the power of 6 is: " + Math.pow(6.4, 6));
System.out.println("7.3 to the power of 1.2 is: " + Math.pow(7.3, 1.2));
class LogValue
public static void main(String a[])
System.out.println("Natural logarithm value of 50 is: " + Math.log(50));
}
class RadTodeg
public static void main(String a[])
System.out.println("Radiance 4.0 in degrees: " + Math.toDegrees(4.0));
System.out.println("Radiance 6.0 in degrees: " + Math.toDegrees(6.0));
class CosValue
public static void main(String a[])
System.out.println("Value of cos(0) is: " + Math.cos(0));
System.out.println("Value of cos(45) is: " + Math.cos(45));
System.out.println("Value of cos(90) is: " + Math.cos(90));
class SineValue
public static void main(String a[])
System.out.println("Value of sin(90) is: " + Math.sin(0));
System.out.println("Value of sin(45) is: " + Math.sin(45));
System.out.println("Value of sin(30) is: " + Math.sin(90));
class TanValue
{
public static void main(String a[])
System.out.println("Value of tan(0) is: " + Math.tan(0));
System.out.println("Value of tan(45) is: " + Math.tan(45));
System.out.println("Value of tan(90) is: " + Math.tan(90));
import java.math.*;
import java.io.*;
class BigIntegerDemo
public static int f = 0;
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any number to find its factorial : ");
f = Integer.parseInt(br.readLine());
BigInteger fact = fact(f);
System.out.println("fact("+f+") = " + fact);
System.out.println("fact("+f+").longValue() = " + fact.longValue());
System.out.println("fact("+f+").intValue() = " + fact.intValue());
int powerOfTwoCount = 0;
BigInteger two = BigInteger.valueOf(2);
while (fact.compareTo(BigInteger.ZERO) > 0 && fact.mod(two).equals(BigInteger.ZERO))
powerOfTwoCount++;
fact = fact.divide(two);
System.out.println("fact("+f+") powers of two = " + powerOfTwoCount);
private static BigInteger fact(long n)
BigInteger result = BigInteger.ONE;
for (long i = 2; i <= n; i++)
result = result.multiply(BigInteger.valueOf(i));
return result;
class Bike
String name;
int cc, model, days, r;
Bike(String name, int cc, int model, int days)
this.name = name;
this.cc = cc;
this.model = model;
this.days = days;
public void rent()
{
if (name == "abc" && cc == 100 && model == 1)
if (days == 1)
r = 500;
System.out.println(r);
else if (days == 2)
r = 400;
System.out.println(r);
else if (days >= 3)
r = 350;
System.out.println(r);
else if (name == "xyz" && cc == 125 && model == 2)
if (days == 1)
r = 600;
System.out.println(r);
else if (days == 2)
r = 500;
System.out.println(r);
}
else if (days >= 3)
r = 500;
System.out.println(r);
else if (name == "pqr" && cc == 150 && model == 3)
if (days == 1)
r = 800;
System.out.println(r);
else if (days == 2)
r = 700;
System.out.println(r);
else if (days >= 3)
r = 850;
System.out.println(r);
public static void main(String[] args)
Bike b = new Bike("pqr", 150, 3, 4);
System.out.print("Rent is : ");
b.rent();
import java.io.*;
class BinaryAddition
public static void main(String s[]) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter number1: ");
int num1 = Integer.parseInt(br.readLine());
int num4 = num1;
System.out.print("\nEnter number2: ");
int num2 = Integer.parseInt(br.readLine());
int num5 = num2;
int k = 1;
int dec1 = 0, dec2 = 0;
while (num1 != 0)
dec1 = dec1 + (num1 % 10) * k;
k = k * 2;
num1 = num1 / 10;
k = 1;
while (num2 != 0)
dec2 = dec2 + (num2 % 10) * k;
k = k * 2;
num2 = num2 / 10;
int num3 = dec1 + dec2;
String str1 = Integer.toBinaryString(num3);
System.out.print("\nAddition of " + num4 + " + " + num5 + " = " + str1);
System.out.println();
class MyBasicBoolean
public static void main(String a[])
//create Boolean using boolean primitive type
boolean b1 = true;
Boolean bObj1 = new Boolean(b1);
System.out.println("Wrapper class Boolean output: "+bObj1);
//create Boolean using string value
Boolean bObj2 = new Boolean("false");
System.out.println("Wrapper class Boolean output: "+bObj2);
//how to get primitive boolean value from wrapper class
System.out.println(bObj1.booleanValue());
}
import java.util.*;
import java.text.*;
class CalendarTask
public static void main(String args[]) throws Exception
printCalendar(2016, 2);
static void printCalendar(int year, int nCols)
if (nCols < 1 || nCols > 12)
throw new IllegalArgumentException("Illegal column width.");
Calendar date = new GregorianCalendar(year, 0, 1);
int nRows = (int) Math.ceil(12.0 / nCols);
int offs = date.get(Calendar.DAY_OF_WEEK) - 1;
int w = nCols * 24;
String[] monthNames = new DateFormatSymbols(Locale.US).getMonths();
String[][] mons = new String[12][8];
for (int m = 0; m < 12; m++)
String name = monthNames[m];
int len = 11 + name.length() / 2;
String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len);
mons[m][0] = String.format(format, name, "");
mons[m][1] = " Su Mo Tu We Th Fr Sa";
int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int d = 1; d < 43; d++)
boolean isDay = d > offs && d <= offs + dim;
String entry = isDay ? String.format(" %2s", d - offs) : " ";
if (d % 7 == 1)
mons[m][2 + (d - 1) / 7] = entry;
else
mons[m][2 + (d - 1) / 7] += entry;
offs = (offs + dim) % 7;
date.add(Calendar.MONTH, 1);
System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]");
System.out.printf("%" + (w / 2 + 4) + "s%n%n", year);
for (int r = 0; r < nRows; r++)
for (int i = 0; i < 8; i++)
for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++)
System.out.printf(" %s", mons[c][i]);
System.out.println();
}
System.out.println();
class Number
int x;
class CallByValue
public static void main(String[] args)
int y = 4;
//call by value
increase(y);
//call by reference
Number n = new Number();
n.x = 3;
System.out.println("Value of x before increment " + n.x);
increment(n);
System.out.println("Value of x after increment " + n.x);
private static void increase(int y)
System.out.println("pass by value and increment result : " + y++);
public static void increment(Number n)
{
n.x = n.x + 1;
class CommandLineExample
// arugments entered in command line are
// passed in main(String args[]) method
public static final void main(String args[])
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "] -> " + args[i]);
import java.io.*;
class VowelsConsonants
public static void main(String[] args) throws Exception
String str;
int vowels = 0, num = 0, blanks = 0, cons = 0;
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a String : ");
str = br.readLine();
for (int i = 0; i < str.length(); i++)
ch = str.charAt(i);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' ||
ch == 'u' || ch == 'U')
vowels++;
else if (Character.isDigit(ch))
num++;
else if (Character.isWhitespace(ch))
blanks++;
else
cons++;
System.out.println("Vowels : " + vowels);
System.out.println("Numbers : " + num);
System.out.println("Blanks : " + blanks);
System.out.println("Consonants : " + cons);
class StaticExample
static int st = 0;
int ns = 0;
StaticExample()
{
ns++;
System.out.println(ns);
public static void main(String args[])
//Non-Static variables requires object to get accessed in Static method
System.out.println("Counter with non-static variable:");
StaticExample s = new StaticExample();
StaticExample s1 = new StaticExample();
StaticExample s2 = new StaticExample();
//Static variables can be accessed without reference(object) in Static method
System.out.println("\nCounter with static variable:");
for (int i = 0; i < 3; i++)
st++;
System.out.println(st);
import java.util.*;
import java.text.DecimalFormat;
class CurrencyConverter
public static void main(String[] args)
{
double rupee, dollar, pound, code, euro, yen;
DecimalFormat f = new DecimalFormat("##.###");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the currency code 1:Rupees\n2:Dollar\n3:Pound\n4:Euro\n5:Yen");
code = sc.nextInt();
//For Rupees Conversion
if (code == 1)
System.out.println("Enter amount in rupees");
rupee = sc.nextFloat();
dollar = rupee / 66;
System.out.println("Dollar : " + f.format(dollar));
pound = rupee / 98;
System.out.println("Pound : " + f.format(pound));
euro = rupee / 72;
System.out.println("Euro : " + f.format(euro));
yen = rupee / 0.55;
System.out.println("Yen : " + f.format(yen));
//For Dollar Conversion
else if (code == 2)
System.out.println("Enter amount in dollar");
dollar = sc.nextFloat();
rupee = dollar * 66;
System.out.println("Rupees : " + f.format(rupee));
pound = dollar * 0.67;
System.out.println("Pound : " + f.format(pound));
euro = dollar * 0.92;
System.out.println("Euro : " + f.format(euro));
yen = dollar * 120.90;
System.out.println("Yen : " + f.format(yen));
//For Pound Conversion
else if (code == 3)
System.out.println("Enter amount in Pound");
pound = sc.nextFloat();
rupee = pound * 98;
System.out.println("Rupees : " + f.format(rupee));
dollar = pound * 1.49;
System.out.println("Dollar : " + f.format(dollar));
euro = pound * 1.36;
System.out.println("Euro : " + f.format(euro));
yen = pound * 179.89;
System.out.println("Yen : " + f.format(yen));
//For Euro Conversion
else if (code == 4)
System.out.println("Enter amount in Euro");
euro = sc.nextFloat();
rupee = euro * 72;
System.out.println("Rupees : " + f.format(rupee));
dollar = euro * 1.09;
System.out.println("Dollar : " + f.format(dollar));
pound = euro * 0.73;
System.out.println("Pound : " + f.format(pound));
yen = euro * 131.84;
System.out.println("Yen : " + f.format(yen));
//For Yen Conversion
else if (code == 5)
System.out.println("Enter amount in Yen");
yen = sc.nextFloat();
rupee = yen * 0.55;
System.out.println("Rupees : " + f.format(rupee));
dollar = yen * 0.01;
System.out.println("Dollar : " + f.format(dollar));
pound = yen * 0.01;
System.out.println("Pound : " + f.format(pound));
euro = yen * 0.01;
System.out.println("Euro : " + f.format(euro));
else
System.out.println("Invalid Code");
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
class Dates
public static void main(final String[] args)
Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed
DateFormatSymbols symbols = new DateFormatSymbols(); //names for our months and
weekdays
//plain numbers way
System.out.println(now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" +
now.get(Calendar.DATE));
//words way
System.out.print(symbols.getWeekdays()[now.get(Calendar.DAY_OF_WEEK)] + ", ");
System.out.print(symbols.getMonths()[now.get(Calendar.MONTH)] + " ");
System.out.println(now.get(Calendar.DATE) + ", " + now.get(Calendar.YEAR));
//using DateFormat
Date date = new Date();
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(format1.format(date));
DateFormat format2 = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
System.out.println(format2.format(date));
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
class TimeZoneExample
public static void main(String[] args)
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids)
System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
System.out.println("\nTotal TimeZone ID " + ids.length);
}
private static String displayTimeZone(TimeZone tz)
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
- TimeUnit.HOURS.toMinutes(hours);
// avoid -4:-30 issue
minutes = Math.abs(minutes);
String result = "";
if (hours > 0)
result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
else
result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
return result;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
class EmailValidation
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter email id : ");
String email = br.readLine();
boolean result = isValidEmail(email);
if (result)
System.out.print(email + " is valid email address.");
else
System.out.print(email + " is not a valid email address.");
public static boolean isValidEmail(String email)
String s = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-
z]{2,})$";
Pattern emailPattern = Pattern.compile(s);
Matcher m = emailPattern.matcher(email);
return m.matches();
class FizzBuzz
public static void main(String[] args)
for (int i = 1; i <= 100; i++)
if (i % 15 == 0)
{
System.out.println("FizzBuzz");
else if (i % 3 == 0)
System.out.println("Fizz");
else if (i % 5 == 0)
System.out.println("Buzz");
else
System.out.println(String.valueOf(i));
import java.text.SimpleDateFormat;
import java.util.Date;
class Main
public static void main(String[] args)
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h");
System.out.println("hour in h format : " + sdf.format(date));
}
}
class Animal
//Dog inherits Animal
class Dog1 extends Animal
public static void main(String args[])
Dog1 d = new Dog1();
System.out.println("d is instanceof Animal: ");
System.out.println(d instanceof Animal);//true
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
class KeyboardMacroDemo
public static void main(String args[])
final JFrame frame = new JFrame();
String directions = "<html><b>Ctrl-S</b> to show frame title<br>"
+ "<b>Ctrl-H</b> to hide it</html>";
frame.add(new JLabel(directions));
frame.addKeyListener(new KeyAdapter()
public void keyReleased(KeyEvent e)
if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S)
frame.setTitle("Hello there");
else if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H)
frame.setTitle("");
});
frame.pack();
frame.setVisible(true);
import java.util.*;
class LargestNumber
public static void main(String args[])
int num1, num2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers : ");
num1 = sc.nextInt();
num2 = sc.nextInt();
if (num1 >= num2)
System.out.println("\nLargest Number is : " + num1);
else
System.out.println("\nLargest Number is : " + num2);
import java.io.*;
class LeapYear
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter year : ");
//year we want to check
int year = Integer.parseInt(br.readLine());
//if year is divisible by 4, it is a leap year
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
System.out.println("Year " + year + " is a leap year");
else
System.out.println("Year " + year + " is not a leap year");
import java.util.*;
class Marksheet
public static void main(String[] args)
int marks;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your marks");
marks = sc.nextInt();
if (marks >= 75 && marks <= 100)
System.out.println("Your grade is A");
else if (marks >= 60 && marks < 75)
System.out.println("Your grade is B");
else if (marks >= 50 && marks < 60)
System.out.println("Your grade is C");
}
else if (marks >= 40 && marks < 50)
System.out.println("Your grade is D");
else if (marks < 40)
System.out.println("Your grade is Fail");
class MyRintEx
public static void main(String args[])
System.out.println("rint value of 13.345 is: " + Math.rint(13.345));
System.out.println("rint value of 38.482 is: " + Math.rint(38.482));
System.out.println("rint value of 46.65 is: " + Math.rint(46.65));
import java.util.*;
class GuessGame
public static void main(String[] args)
Random r = new Random();
int numberoftries = 0;
int numbertoguess = r.nextInt(50);
boolean f = false;
int guess;
Scanner sc = new Scanner(System.in);
try
while(f == false)
System.out.println("Guess number between 1-50");
guess = sc.nextInt();
numberoftries++;
if(guess > 1 && guess < 50)
if(guess == numbertoguess)
f = true;
else if(guess > numbertoguess)
System.out.println("Guess is too high");
else if(guess < numbertoguess)
System.out.println("Guess is too low");
else
throw new Exception();
System.out.println("\nYou win");
System.out.println("Number was : "+numbertoguess);
System.out.println("Number of tries : "+numberoftries);
catch(Exception e)
System.out.println("Number is either numeric or out of range(1-50)");
import java.awt.*;
import javax.swing.*;
class Pendulum extends JPanel implements Runnable
private double angle = Math.PI / 2;
private int length;
public Pendulum(int length)
this.length = length;
setDoubleBuffered(true);
@Override
public void paint(Graphics g)
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
int ballX = anchorX + (int) (Math.sin(angle) * length);
int ballY = anchorY + (int) (Math.cos(angle) * length);
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
public void run()
double angleAccel, angleVelocity = 0, dt = 0.1;
while (true)
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try
{
Thread.sleep(15);
catch (InterruptedException ex)
@Override
public Dimension getPreferredSize()
return new Dimension(2 * length + 50, length / 2 * 3);
public static void main(String[] args)
JFrame f = new JFrame("Pendulum");
Pendulum p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}
class MyBooleanConstants
public static void main(String a[])
System.out.println("Boolean object corresponding to the primitive value :"
+ Boolean.FALSE);
System.out.println("Boolean object corresponding to the primitive value :"
+ Boolean.TRUE);
class Alphabets
public static void main(String args[])
char c = 'A';
do
System.out.println(c);
c++;
while (c <= 'Z');
import java.util.*;
class PrintCurrentDateandTime
public static void main(String args[])
{
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
System.out.println("Current date is " + day + "/" + (month + 1) + "/" + year);
System.out.println("Current time is " + hour + " : " + minute + " : " + second);
import java.util.*;
class RemoveZero
public static void main(String args[])
int a, x, b;
char z;
String n, k = "", str;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
str = sc.next();
x = str.length();
for (int i = 0; i < x; i++)
z = str.charAt(i);
if (z == '0')
else
k += z;
System.out.println("Numbers without zero : " + k);
//Scanner Class is used to get input from user
import java.util.Scanner;
class ScannerClassExample
public static void main(String args[])
int intNum;
long longNum;
float floatNum;
double doubleNum;
String line;
String str;
Scanner in = new Scanner(System.in);
System.out.print("Enter line ");
line = in.nextLine();
System.out.print("Enter string ");
str = in.next();
System.out.print("Enter integer ");
intNum = in.nextInt();
System.out.print("Enter long ");
longNum = in.nextLong();
System.out.print("Enter float ");
floatNum = in.nextFloat();
System.out.print("Enter double ");
doubleNum = in.nextDouble();
System.out.println("\nEntered details are as follows: ");
System.out.println("Line: " + line);
System.out.println("String: " + str);
System.out.println("Integer: " + intNum);
System.out.println("Long: " + longNum);
System.out.println("Float: " + floatNum);
System.out.println("Double: " + doubleNum);
import java.util.*;
class SquareRootWithoutInbuiltFunction
public static void main(String args[])
{
int number;
double t, squareroot;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
number = sc.nextInt();
//Logic to find square root of a number without sqrt function
squareroot = number / 2;
do
t = squareroot;
squareroot = (t + (number / t)) / 2;
while ((t - squareroot) != 0);
System.out.println("Square Root of a Number is : " + squareroot);
import java.util.*;
class StackDemo
static void showpush(Stack st, int a)
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st)
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
public static void main(String args[])
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try
showpop(st);
catch (EmptyStackException e)
System.out.println("empty stack");
}
}
class MyStringToBoolean
public static void main(String a[])
String strBool = "true";
Boolean bool = Boolean.parseBoolean(strBool);
System.out.println(bool);
class TestStatic
static class InnerClass
public static void InnerMethod()
System.out.println("Static Inner Class!");
public static void main(String args[])
TestStatic.InnerClass.InnerMethod();
import java.io.*;
class Validation
public static void main(String args[]) throws Exception
{
String username, password;
String user1, pass1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Login Details");
System.out.println("Enter username");
username = br.readLine();
System.out.println("Enter password");
password = br.readLine();
System.out.println("Enter details for validation");
System.out.println();
System.out.println("Enter username");
user1 = br.readLine();
System.out.println("Enter password");
pass1 = br.readLine();
if (user1.equals(username) && pass1.equals(password))
System.out.println("You are a valid user");
else
System.out.println("You are not a valid user");
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.text.DateFormat;
class ZodiacSigns
public static void main(String[] args)
System.out.println(df.format(calendar.getTime()));
int day = 0;
int month = 0;
int year = 0;
while (true)
// Read in a date
System.out.print("Enter the year: ");
year = readInt();
while (true)
System.out.print("Enter the month number January is 1, December is 12: ");
month = readInt();
// Change month to zero-based and validate
if (validMonth(--month))
break;
while (true)
{
System.out.print("Enter the day in the month: ");
day = readInt();
if (validDay(day, month, year))
break;
// determine the sign
calendar.set(year, month, day);
// Match the year for the sign start dates
for (int i = 0; i < signStartDates.length; ++i)
signStartDates[i].set(GregorianCalendar.YEAR, year);
for (int i = 0; i < signStartDates.length; ++i)
if (calendar.after(signStartDates[i]) && calendar.before(
signStartDates[(i + 1) % signStartDates.length]))
System.out.println(df.format(calendar.getTime()) + " is in the sign of " + signs[i]);
break;
// Try another date?
System.out.println("Do you want to try another date(Enter Y or N)?");
if (!yes())
break;
}
}
// Validate the month value
private static boolean validMonth(int month)
if (month >= 0 && month <= 11)
return true;
else
System.out.println("The month value must be from 1 to 12. Try again.");
return false;
// Validate the day value for the month and year
private static boolean validDay(int day, int month, int year)
/* A valid day must be:
- between 1 and 31
- less than 31 when the month is April, June, September, or November
- less than 29 when the month is February and it is not a leap year
- less than 30 when the month is February and it is a leap year
*/
if (day < 0 || day > 31)
System.out.println("Day values must be between 1 and 31. Try again.");
return false;
if (day > 30 && (month == 3 || month == 5 || month == 8 || month == 10))
System.out.println(
"Day values must be less than 31 when the month" + " is " + MONTH_NAMES[month] + ".
Try again.");
return false;
if (day > 28 && month == 1 && !calendar.isLeapYear(year))
System.out.println(year + " is not a leap year so day values must be less than 29. Try again.");
return false;
if (day > 29 && month == 1 && calendar.isLeapYear(year))
return false;
return true;
// Reads an integer from the keyboard
private static int readInt()
int value = 0;
while (true)
try
value = Integer.parseInt(in.readLine().trim());
return value;
}
catch (NumberFormatException e)
System.out.println("Invalid input. Try again.");
catch (IOException e)
System.out.println("Error reading for the keyboard." + e.getMessage());
private static boolean yes()
String str = null;
while (true)
try
str = in.readLine().trim();
catch (IOException e)
System.out.println("Error reading for the keyboard." + e.getMessage());
if (str.equalsIgnoreCase("Y"))
return true;
else if (str.equalsIgnoreCase("N"))
{
break;
else
System.out.print("Invalid input. Try again. Enter Y or N: ");
return false;
// Keyboard input
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Names for Zodiac signs and start dates. Remember - months start at zero.
private static String[] signs = {"Aquarius", "Pisces", "Aries", "Taurus", "Gemini", "Cancer", "Leo",
"Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn"};
private static GregorianCalendar[] signStartDates = {
new GregorianCalendar(2002, 0, 20), // Aquarius start date
new GregorianCalendar(2002, 1, 19), // Pisces start date
new GregorianCalendar(2002, 2, 21), // Aries start date
new GregorianCalendar(2002, 3, 20), // Taurus start date
new GregorianCalendar(2002, 4, 21), // Gemini start date
new GregorianCalendar(2002, 5, 21), // Cancer start date
new GregorianCalendar(2002, 6, 23), // Leo start date
new GregorianCalendar(2002, 7, 23), // Virgo start date
new GregorianCalendar(2002, 8, 23), // Libra start date
new GregorianCalendar(2002, 9, 23), // Scorpio start date
new GregorianCalendar(2002, 10, 22), // Sagittarius start date
new GregorianCalendar(2002, 11, 22), // Capricorn start date
};
private static GregorianCalendar calendar = new GregorianCalendar();
private static final String[] MONTH_NAMES = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November", "December"};
// Date formatter for displaying dates
private static DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
//Amicable Number
import java.util.Scanner;
class AmicableNumber
public static void main(String[] args)
int a, b;
Scanner in = new Scanner(System.in);
System.out.println("Enter two Numbers:");
a = in.nextInt();
b = in.nextInt();
boolean flag = check(a, b);
if (flag)
System.out.println("The numbers are amicable");
else
{
System.out.println("The numbers are not amicable");
static boolean check(int a, int b)
int s = 0, i;
for (i = 1; i < a; i++)
if (a % i == 0)
s = s + i;
if (s == b)
s = 0;
for (i = 1; i < b; i++)
if (b % i == 0)
s = s + i;
if (s == a)
return true;
else
return false;
return false;
}
}
import java.util.*;
class ArmstrongNumber
public static void main(String args[])
int n, sum = 0, temp, r;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number to check if it is an armstrong number");
n = in.nextInt();
temp = n;
while (temp != 0)
r = temp % 10;
sum = sum + r * r * r;
temp = temp / 10;
if (n == sum)
System.out.println("Entered number is an armstrong number.");
else
System.out.println("Entered number is not an armstrong number.");
import java.util.Scanner;
class AutomorphicNumber
{
public static void main(String[] args)
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int input = scanner.nextInt();
int square = input * input;
String inputAsString = input + "";
String squareAsString = square + "";
if (squareAsString.endsWith(inputAsString))
System.out.println(input + " is Automorphic Number");
else
System.out.println(input + " is Not an Automorphic number");
/*Buzz number is such a number which is either completely
divisible by 7 or extreme right side digit of the number is 7*/
import java.io.*;
class BuzzNumber
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a;
public void show() throws Exception
System.out.print("Enter the number:");
a = Integer.parseInt(br.readLine());
/*Checks if the entered number is divisible
by 7 or extreme right is 7*/
if (a % 10 == 7 || a % 7 == 0)
System.out.println("Entered number is a Buzz number.");
else
System.out.println("Entered number is not a Buzz number.");
public static void main(String args[]) throws Exception
BuzzNumber bn = new BuzzNumber();
bn.show();
import java.util.*;
class Prime
public static void main(String args[])
int n, i, res;
boolean flag = true;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter a No.");
n = sc.nextInt();
for (i = 2; i <= n / 2; i++)
res = n % i;
if (res == 0)
flag = false;
break;
if (flag)
System.out.println(n + " is Prime Number");
else
System.out.println(n + " is not Prime Number");
import java.io.*;
class AmicableNumber
static boolean check(int a, int b)
int s = 0, i;
for (i = 1; i < a; i++)
if (a % i == 0)
s = s + i;
}
if (s == b)
s = 0;
for (i = 1; i < b; i++)
if (b % i == 0)
s = s + i;
if (s == a)
return true;
else
return false;
return false;
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter 1st no. : ");
int a = Integer.parseInt(br.readLine());
System.out.print("Enter 2nd no. : ");
int b = Integer.parseInt(br.readLine());
if (check(a, b))
{
System.out.print(a + " and " + b + " are Amicable Number");
else
System.out.print(a + " and " + b + " are not Amicable Number");
class CommnElements
public static void main(String args[])
int[] arr1 = {1, 3, 7, 8};
int[] arr2 = {9, 5, 7, 2, 1, 4, 8};
System.out.println("Common Elements are:");
for (int i = 0; i < arr1.length; i++)
for (int j = 0; j < arr2.length; j++)
if (arr1[i] == arr2[j])
System.out.println(arr1[i]);
import java.util.Scanner;
class CompareStrings
public static void main(String args[])
String s1, s2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
s1 = in.nextLine();
System.out.println("Enter the second string");
s2 = in.nextLine();
if (s1.compareTo(s2) > 0)
System.out.println("First string is greater than second.");
else if (s1.compareTo(s2) < 0)
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
import java.io.*;
import java.util.*;
class NumberToWord
private static final String[] specialNames = {
"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"};
private static final String[] tensNames = {
"",
" ten", " twenty", " thirty", " forty", " fifty",
" sixty", " seventy", " eighty", " ninety"};
private static final String[] numNames = {
"", " one", " two", " three", " four", " five", " six",
" seven", " eight", " nine", " ten", " eleven", " twelve",
" thirteen", " fourteen", " fifteen", " sixteen",
" seventeen", " eighteen", " nineteen"};
private String convertLessThanOneThousand(int number)
String current;
if (number % 100 < 20)
current = numNames[number % 100];
number /= 100;
else
current = numNames[number % 10];
number /= 10;
current = tensNames[number % 10] + current;
number /= 10;
if (number == 0)
return current;
return numNames[number] + " hundred" + current;
public String convert(int number)
if (number == 0)
return "zero";
String prefix = "";
if (number < 0)
number = -number;
prefix = "negative";
String current = "";
int place = 0;
do
int n = number % 1000;
if (n != 0)
String s = convertLessThanOneThousand(n);
current = s + specialNames[place] + current;
place++;
number /= 1000;
while (number > 0);
return (prefix + current).trim();
public static void main(String[] args)
System.out.print("Enter a number: ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println();
NumberToWord obj = new NumberToWord();
System.out.println(num + " = " + obj.convert(num));
import java.text.DecimalFormat;
import java.io.*;
class EnglishNumberToWords
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
private static String convertLessThanOneThousand(int number)
String soFar;
if (number % 100 < 20)
soFar = numNames[number % 100];
number /= 100;
else
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
if (number == 0)
return soFar;
return numNames[number] + " hundred" + soFar;
public static String convert(long number)
// 0 to 999 999 999 999
if (number == 0)
return "zero";
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0, 3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3, 6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9, 12));
String tradBillions;
switch (billions)
case 0:
tradBillions = "";
break;
case 1:
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
break;
default:
tradBillions = convertLessThanOneThousand(billions)
+ " billion ";
String result = tradBillions;
String tradMillions;
switch (millions)
{
case 0:
tradMillions = "";
break;
case 1:
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
break;
default:
tradMillions = convertLessThanOneThousand(millions)
+ " million ";
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands)
case 0:
tradHundredThousands = "";
break;
case 1:
tradHundredThousands = "one thousand ";
break;
default:
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " thousand ";
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
public static void main(String[] args) throws Exception
String number = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number to display in words : ");
number = br.readLine();
System.out.println("\n\t" + number + " IN WORDS\n\n" +
EnglishNumberToWords.convert(Integer.parseInt(number)));
import java.io.*;
class Disarium
public void show(int n)
int c = 1, rev, sum, x;
x = n;
sum = 0;
rev = 0;
while (n > 0)
rev = rev * 10 + n % 10;
n = n / 10;
}
while (rev > 0)
sum = sum + (int) Math.pow(rev % 10, c);
c++;
rev = rev / 10;
if (sum == x)
System.out.println(x + " is DISARIUM number");
else
System.out.println(x + " is not DISARIUM number");
public static void main(String args[]) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number to check its DISARIUM no. or not : ");
Disarium ob = new Disarium();
ob.show(Integer.parseInt(br.readLine()));
import java.io.*;
class DuckNumber
public static void main(String args[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any number : ");
String n = br.readLine();
int l = n.length();
int c = 0;
char ch;
for (int i = 1; i < l; i++)
ch = n.charAt(i);
if (ch == '0')
c++;
char f = n.charAt(0);
if (c > 0 && f != '0')
System.out.println("It is a duck number");
else
System.out.println("It is not a duck number");
import java.util.Scanner;
class Factorial
public static void main(String args[])
int fact = 1;
int number = 0;
System.out.println("Enter a number to print its factorial");
Scanner in = new Scanner(System.in);
number = in.nextInt();
for (int i = 1; i <= number; i++)
fact = i * fact;
System.out.println("The factorial of " + number + " is " + fact);
import java.util.*;
class FactorialExample
public static void main(String args[])
int a;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter no. for factorial : ");
a = scanner.nextInt();
System.out.println("Factorial of " + a + " is " + fact(a));
static int fact(int n)
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
import java.io.*;
class Factors
public static void main(String args[]) throws IOException
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
int a, i;
System.out.print("Enter the number : ");
a = Integer.parseInt(buf.readLine());
System.out.print("\n");
System.out.print("The factors are : ");
for (i = 1; i <= a / 2; i++)
if (a % i == 0)
System.out.print(i + ",");
System.out.print(a);
import java.io.*;
import java.lang.*;
class Fibonacci
public static void main(String args[]) throws IOException
if (args.length == 1)
int n = Integer.parseInt(args[0]);
int a = 0, b = 1, c = 0, i = 0;
while (i < n)
System.out.print(c + "\t");
a = b;
b = c;
c = a + b;
i++;
else
System.out.println("You havent supplied the arguments: {Usage : java fibonacci 34 } to print
the first 34 fibonacci numbers.");
import java.util.Scanner;
class Fibonacci
static int fibo(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.print("Enter fibonacci Term :");
int n = sc.nextInt();
System.out.println("Fibonacci Series is :\n");
for (int i = 0; i < n; i++)
System.out.print(fibo(i) + "\t");
import java.util.Scanner;
class OddOrEven
public static void main(String args[])
int x;
System.out.println("Enter an integer to check if it is odd or even ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if (x % 2 == 0)
System.out.println("You entered an even number.");
else
System.out.println("You entered an odd number.");
import java.util.*;
class PerfectSquare
public static void main(String[] args)
int start, end, n, sum = 0;
float s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter starting value of the range");
start = sc.nextInt();
System.out.println("Enter ending value of the range");
end = sc.nextInt();
System.out.println("The Perfect Square numbers present in the range " + start + " to " + end + "
are : ");
for (int i = start; i < end; i++)
s = (float) Math.sqrt(i);
n = (int) Math.floor(s);
if (s == n)
System.out.print(" " + i);
sum += i;
System.out.println(
"\nSum of the perfect square numbers between the range " + start + " to " + end + " are : "
+ sum);
import java.io.*;
import java.math.*;
class ResultantPalindrome
static int i = 1;
public void addNum(String num)
BigInteger a, b, c;
a = new BigInteger(num);
b = new BigInteger(reverse(num));
System.out.println("Step " + (i++) + "\t->\t" + a + " + " + b + " = " + (a.add(b)));
resultantPalindrome(a.add(b) + "");
public void resultantPalindrome(String num)
{
if (num.equals(reverse(num)))
System.out.println("\nResultant Palindrome : " + num);
else
addNum(num);
public String reverse(String num)
StringBuffer sb = new StringBuffer(num);
return sb.reverse().toString();
public static void main(String args[])
InputStreamReader istream = new InputStreamReader(System.in);
BufferedReader num = new BufferedReader(istream);
String palindrome = null;
System.out.print("Enter number for Resultant Palindrome : ");
try
palindrome = num.readLine();
catch (IOException e)
System.out.println(e.getMessage());
System.out.println("");
ResultantPalindrome rp = new ResultantPalindrome();
rp.resultantPalindrome(palindrome);
class FloorValue
public static void main(String a[])
System.out.println("Floor value of 50: " + Math.floor(50));
System.out.println("Floor value of 23.8: " + Math.floor(23.8));
System.out.println("Floor value of -46.5: " + Math.floor(-46.5));
import java.util.Scanner;
class Greatest
public static void main(String argn[])
Scanner data = new Scanner(System.in);
int num, i, temp, max;
// Reading numbers want to be read
System.out.print("Enter the range:");
num = data.nextInt();
System.out.println("Enter " + num + " number");
// Reading 1st number
max = data.nextInt();
// Reading other number
for (i = 1; i < num; i++)
temp = data.nextInt();
if (temp < max)
continue;
else
// largest number
max = temp;
System.out.println("Largest Number is " + max);
import java.util.Scanner;
class HailStone
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args)
System.out.println("This program will generate the HailStone sequence. ");
System.out.print("Enter a number: ");
int num = MyScanner.nextInt();
while (num > 1)
if (num % 2 == 0)
num /= 2; //Dividing num by 2 if it is even
System.out.print(num + "\t");
}
else
num = (num * 3) + 1; // Adding num*3 + 1 to num if the num is odd
System.out.print(num + "\t");
import java.io.*;
class HappyNumber
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
HappyNumber()
n = 0;
void getnum(int num)
n = num;
int sum_sq_digits(int x)
if (x == 0)
return 0;
else
{
int d = x % 10;
return (d * d + sum_sq_digits(x / 10));
void isHappyNumber()
int a = sum_sq_digits(n);
while (a > 9)
a = sum_sq_digits(a);
if (a == 1)
System.out.print(n + " is a Happy Number");
else
System.out.print(n + " is not a Happy Number");
public static void main(String args[]) throws IOException
HappyNumber ob = new HappyNumber();
System.out.print("Enter any number: ");
int b = Integer.parseInt(br.readLine());
ob.getnum(b);
ob.isHappyNumber();
import java.util.*;
class HCFandLCM
{
public static void main(String Args[])
System.out.println("Enter 2 numbers");
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int h = 1;
int p = m * n;
for (int i = 2; i < p; i++)
if ((m % i == 0) && (n % i == 0))
h = i;
int l = p / h;
System.out.println("HCF=" + h + " and LCM=" + l);
import java.util.*;
class KaprekarNumber
int digitcount(int x)
{
int digit = 0;
while (x != 0)
digit++;
x /= 10;
return digit;
public static void main(String args[])
int n, quo, rem, sq, temp;
int digits;
Scanner sc = new Scanner(System.in);
KaprekarNumber ob = new KaprekarNumber();
System.out.print("Enter number : ");
n = sc.nextInt();
sq = n * n;
digits = ob.digitcount(n * n);
quo = sq / (int) Math.pow(10, digits / 2);
rem = sq % (int) Math.pow(10, digits / 2);
temp = quo + rem;
if (temp == n)
System.out.print("\nIt is a Kaprekar number \n");
else
System.out.print("\nNot a kaprekar number");
}
import java.io.*;
class KeithNumber
public static void main(String args[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number : ");
int n = Integer.parseInt(br.readLine());
int copy = n;
String s = Integer.toString(n);
//finding the number of digits (d) in the number
int d = s.length();
//array for storing the terms of the series
int arr[] = new int[n];
for (int i = d - 1; i >= 0; i--)
//storing the digits of the number in the array
arr[i] = copy % 10;
copy = copy / 10;
int i = d, sum = 0;
//finding the sum till it is less than the number
while (sum < n)
sum = 0;
//loop for generating and adding the previous 'd' terms
for (int j = 1; j <= d; j++)
sum = sum + arr[i - j];
//storing the sum in the array
arr[i] = sum;
i++;
//if sum is equal to the number, then it is a Keith number
if (sum == n)
System.out.println(n + " is a Keith Number");
else
System.out.println(n + " is a not a Keith Number");
import java.io.*;
class KrishnaMurthyNumber
int fact(int n)
int i, fact = 1;
for (i = 1; i <= n; i++)
fact = fact * i;
}
return fact;
public static void main(String[] arg) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number : ");
int number = Integer.parseInt(br.readLine());
KrishnaMurthyNumber kmn = new KrishnaMurthyNumber();
if (kmn.isKrishnaMurthy(number))
System.out.println(number + " is a Krishna Murthy Number");
else
System.out.println(number + " is not a Krishna Murthy Number");
boolean isKrishnaMurthy(int number)
int temp, k = 0;
int n = number;
while (number > 0)
temp = number % 10;
k = k + fact(temp);
number = number / 10;
}
if (k == n)
return true;
else
return false;
import java.util.Scanner;
class LargestOfThreeNumbers
public static void main(String args[])
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if (x > y && x > z)
System.out.println("First number is largest.");
else if (y > x && y > z)
System.out.println("Second number is largest.");
else if (z > x && z > y)
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct.");
import java.io.*;
class LargestSmallest
public static void main(String args[]) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter number of elements: ");
int num = Integer.parseInt(br.readLine());
int arr[] = new int[num];
System.out.println("\nEnter " + num + " elements: ");
for (int i = 0; i < num; i++)
arr[i] = Integer.parseInt(br.readLine());
for (int i = 0; i < (num - 1); i++)
for (int j = 0; j <= i; j++)
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
System.out.print("\nHighest number: " + arr[num - 1]);
System.out.print("\nSmallest number: " + arr[0]);
System.out.println();
/*
In Lucas Series, each subsequent number is the sum of the previous two,
and here the first two numbers are 2 and 1.
*/
import java.util.*;
class LucasSeries
public static void main(String[] args)
int num1, num2, limit, add;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit of elements");
limit = sc.nextInt();
num1 = 2;
num2 = 1;
System.out.println("\nLucas Series:");
while (limit >= num1)
System.out.print(num1 + " ");
add = num1 + num2;
num1 = num2;
num2 = add;
// Program added on request of Ravindrala Stivastav
import java.io.*;
class MagicNumber
private int input() throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any number : ");
return Integer.parseInt(br.readLine());
public boolean isMagic(int n)
int sum = 0, flag, d = 0;
do
flag = 0;
while (n % 10 == 0)
n /= 10;
while (n % 10 != 0 || n > 0)
sum += (n % 10);
n /= 10;
if (sum >= 10)
n = sum;
sum = 0;
else
flag = 1;
while (flag == 0);
if (sum == 1)
return true;
else
return false;
public static void main(String args[]) throws Exception
MagicNumber mn = new MagicNumber();
int num = mn.input();
if (mn.isMagic(num))
System.out.println(num + " is a Magic Number");
else
System.out.println(num + " is not a Magic Number");
import java.io.*;
class NeonNumber
public static void main(String args[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num;
int square;
int sum = 0;
System.out.print("Enter any number : ");
num = Integer.parseInt(br.readLine());
square = num * num; //squaring the number
String sqs = Integer.toString(square);
for (int i = 0; i < sqs.length(); i++)
sum += Integer.parseInt(sqs.substring(i, i + 1));
if (sum == num) //checking if the sum of the square is equal to the number entered
System.out.println(num + " is a Neon Number");
else
System.out.println(num + " is not a Neon number");
import java.util.*;
class Niven_number
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = sc.nextInt();
int c = n, d, sum = 0;
//finding sum of digits
while (c > 0)
d = c % 10;
sum = sum + d;
c = c / 10;
if (n % sum == 0)
System.out.println("\n" + n + " is a Niven Number.");
else
System.out.println("\n" + n + " is not a Niven Number.");
}
//A palindrome is a word, phrase, number, or other sequence of symbols or elements,
//whose meaning may be interpreted the same way in either forward or reverse direction.
import java.util.Scanner;
class Palindrome
public static void main(String args[])
int number = 0;
int reverse = 0;
int numCopy = 0;
System.out.println("Enter a number to check if it is a Palindrome");
Scanner in = new Scanner(System.in);
number = in.nextInt();
numCopy = number;
while (numCopy > 0)
int digit = numCopy % 10;
numCopy = numCopy / 10;
reverse = (reverse * 10) + digit;
if (number == reverse)
System.out.println("The number " + number + " is a Palindrome.");
else
System.out.println("The number " + number + " is not a Palindrome.");
class PalindromePrime
public static void main(String[] args)
int count = 1;
System.out.println("Palindrome Primes are:\n");
for (int i = 2; ; i++)
if ((isPrime(i)) && (isPalindrome(i)))
System.out.print(i + " ");
if (count % 10 == 0)
System.out.println();
if (count == 20)
break;
count++;
}
}
public static boolean isPrime(int num)
if ((num == 1) || (num == 2))
return true;
for (int i = 2; i <= num / 2; i++)
if (num % i == 0)
return false;
return true;
static int reversal(int num)
int result = 0;
while (num != 0)
int lastDigit = num % 10;
result = result * 10 + lastDigit;
num /= 10;
}
return result;
static boolean isPalindrome(int num)
return num == reversal(num);
import java.io.*;
class PerfectNumber
public static void main(String args[]) throws IOException
int n, s = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Entre a number : ");
n = Integer.parseInt(br.readLine());
for (int x = 1; x < n; x++)
if (n % x == 0)
s = s + x;
if (s == n)
System.out.println("It is perfect number");
else
System.out.println("It is not perfect number");
}
import java.io.*;
class PrimeFactors
private boolean prime(int a)
boolean b = true;
for (int i = 2; i <= (a / 2); i++)
if (a % i == 0)
b = false;
return b;
public static void main(String args[]) throws IOException
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Number: ");
int a = Integer.parseInt(in.readLine());
PrimeFactors o = new PrimeFactors();
System.out.print("Prime Factors of " + a + " are : ");
for (int i = 1; i <= (a / 2); i++)
if (a % i == 0)
boolean b = o.prime(i);
if (b == true)
System.out.print(i + " ");
import java.util.*;
class PrimeNumbers
public static void main(String args[])
int n, status = 1, num = 3;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of prime numbers you want");
n = in.nextInt();
if (n >= 1)
System.out.println("First " + n + " prime numbers are :-");
System.out.println(2);
for (int count = 2; count <= n; )
for (int j = 2; j <= Math.sqrt(num); j++)
if (num % j == 0)
status = 0;
break;
if (status != 0)
System.out.println(num);
count++;
status = 1;
num++;
import java.util.Scanner;
class PrimorialNumber
public static void main(String[] args)
int num;
System.out.print("Enter a number : ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
int res = 2, flag = 0;
String str = "2";
for (int i = 3; i <= num; i++)
flag = 0;
for (int j = 2; j < i; j++)
if (i % j == 0)
flag = 1;
break;
if (flag != 1)
res *= i;
str = str + "*" + i;
System.out.println(num + "#= " + str + "=" + res);
//Generate random number in between the given value
import java.util.*;
class RandomNumber
public static void main(String args[])
Random r = new Random();
//Printing 10 Random number between 0 to 1000
for (int i = 0; i < 9; i++)
{
System.out.println(r.nextInt(1000));
import java.util.Scanner;
class ReverseNum
public static void main(String[] args)
int reverse = 0, number = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number to Reverse:");
number = sc.nextInt();
sc.close();
while (number != 0)
reverse = (reverse * 10) + (number % 10);
number = number / 10;
System.out.println("Result: " + reverse);
import java.io.*;
class RomanToDecimal
public static void romanToDecimal(java.lang.String romanNumber)
{
int decimal = 0;
int lastNumber = 0;
String romanNumeral = romanNumber.toUpperCase();
for (int x = romanNumeral.length() - 1; x >= 0; x--)
char convertToDecimal = romanNumeral.charAt(x);
switch (convertToDecimal)
case 'M':
decimal = processDecimal(1000, lastNumber, decimal);
lastNumber = 1000;
break;
case 'D':
decimal = processDecimal(500, lastNumber, decimal);
lastNumber = 500;
break;
case 'C':
decimal = processDecimal(100, lastNumber, decimal);
lastNumber = 100;
break;
case 'L':
decimal = processDecimal(50, lastNumber, decimal);
lastNumber = 50;
break;
case 'X':
decimal = processDecimal(10, lastNumber, decimal);
lastNumber = 10;
break;
case 'V':
decimal = processDecimal(5, lastNumber, decimal);
lastNumber = 5;
break;
case 'I':
decimal = processDecimal(1, lastNumber, decimal);
lastNumber = 1;
break;
System.out.println("Decimal number : " + decimal);
public static int processDecimal(int decimal, int lastNumber, int lastDecimal)
if (lastNumber > decimal)
return lastDecimal - decimal;
else
return lastDecimal + decimal;
public static void main(java.lang.String args[])
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Roman Number : ");
String roman = null;
try
roman = br.readLine();
catch (IOException e)
System.out.println(e.getMessage());
romanToDecimal(roman);
import java.io.*;
class SpecialNumber
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int num;
private void input() throws Exception
System.out.print("Enter the Number to check for Special Number : ");
num = Integer.parseInt(br.readLine());
public boolean isSpecial(int n)
{
int spec = 0, temp = n;
while (temp % 10 != 0)
spec += factorial(temp % 10);
temp /= 10;
if (spec == n)
return true;
else
return false;
private int factorial(int n)
if ((n == 1) || (n == 0))
return 1;
else
return (n * factorial(n - 1));
public static void main(String args[]) throws Exception
SpecialNumber obj = new SpecialNumber();
obj.input();
if (obj.isSpecial(num))
System.out.print(num + " is a Special Number");
else
System.out.print(num + " is not a Special Number");
}
import java.util.Scanner;
class SquareRoot
public static void main(String[] args)
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number");
n = sc.nextInt();
System.out.println(Math.sqrt(n));
//Sunny Number: when 1 is added to a number, then the square root of it will be a whole number.
import java.util.*;
class SunnyNumber
public static void main(String[] args)
int n, n1;
double x;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number");
n = sc.nextInt();
n1 = n + 1;
x = Math.sqrt(n1);
if ((int) x == x)
System.out.println("Number is a Sunny Number");
else
System.out.println("Number is not a Sunny Number");
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Swapping
public static void main(String ars[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a = 10;
int b = 15;
System.out.println("Values before swipe :");
System.out.println("a=" + a + " and b=" + b);
//------Method 1 Using add and subtract -----
a = a + b;
b = a - b;
a = a - b;
System.out.println("---- Using Method 1 ----");
System.out.println("a=" + a + " and b=" + b);
//------Method 2 Using XOR operation------
a = 10;
b = 15;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("---- Using Method 2 ----");
System.out.println("a=" + a + " and b=" + b);
//-----Method 3 Using Multiplication and division----
a = 10;
b = 15;
a = a * b;
b = a / b;
a = a / b;
System.out.println("---- Using Method 3 ----");
System.out.println("a=" + a + " and b=" + b);
//-----Method 4 Using formula a=b-a+(b=a) -----
/*
Working of Formula :
System first evaluates (b=a) expression based on BODMAS rule
then b-a expression
So a=15-10+(10)=15 and b=10
*/
a = 10;
b = 15;
a = b - a + (b = a);
System.out.println("---- Using Method 4 ----");
System.out.println("a=" + a + " and b=" + b);
import java.util.Scanner;
class SwapNumbers
public static void main(String args[])
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = " + x + "\ny = " + y);
temp = x;
x = y;
y = temp;
System.out.println("After Swapping\nx = " + x + "\ny = " + y);
class TopTwoMaxNumber
public void printTwoMaxNumbers(int[] nums)
int maxOne = 0;
int maxTwo = 0;
for (int n : nums)
if (maxOne < n)
maxTwo = maxOne;
maxOne = n;
else if (maxTwo < n)
maxTwo = n;
System.out.println("First Max Number: " + maxOne);
System.out.println("Second Max Number: " + maxTwo);
}
public static void main(String args[])
int num[] = {65, 34, 27, 8, 33, 10, 89, 45};
TopTwoMaxNumber ttmn = new TopTwoMaxNumber();
ttmn.printTwoMaxNumbers(num);
import java.util.*;
import java.io.*;
class Tribonacci
public static void main(String args[])
Scanner sc = new Scanner(System.in);
System.out.print("Enter number till u want Tribonacci series: ");
int n = sc.nextInt();
int a = 0, b = 0, c = 1;
int d = a + b + c;
System.out.println("\nTribonacci Series: ");
System.out.print(a + "\t" + b + "\t" + c);
for (int i = 4; i <= n; i++)
System.out.print("\t" + d);
a = b;
b = c;
c = d;
d = a + b + c;
}
System.out.println();
class TwinPrimes
public static void main(String args[])
String primeNo = "";
int j = 0;
int LastPrime = 1;
System.out.println("Twin Primes are:");
for (int i = 1; i < 100; i++)
for (j = 2; j < i; j++)
if (i % j == 0)
break;
if (i == j)
primeNo += i + " ";
if ((i - LastPrime) == 2)
{
System.out.println("(" + (i - 2) + "," + i + ")");
LastPrime = i;
System.out.println("Prime Numbers are: " + primeNo);
import java.io.*;
class UniqueNumber
public static void main(String args[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any number : ");
int n = Integer.parseInt(br.readLine());
String s = Integer.toString(n); //converting the number into String form
int l = s.length();
int flag = 0; /* loop for checking whether there are repeated digits */
for (int i = 0; i < l - 1; i++)
for (int j = i + 1; j < l; j++)
if (s.charAt(i) == s.charAt(j)) //if any digits match, then we know it is not a Unique Number
flag = 1;
break;
}
}
if (flag == 0)
System.out.println(s + " is a Unique Number");
else
System.out.println(s + " is Not a Unique Number");
abstract class Shape
abstract void draw();
class Rectangle extends Shape
void draw()
System.out.println("Draw Rectangle");
class Traingle extends Shape
void draw()
System.out.println("Draw Traingle");
}
class AbstractTest
public static void main(String args[])
Shape s1 = new Rectangle();
s1.draw();
s1 = new Traingle();
s1.draw();
class AddressDetails
int flatno;
String blgd;
String city;
AddressDetails(int flatno, String blgd)
this.flatno = flatno;
this.blgd = blgd;
AddressDetails(int flatno, String blgd, String city)
//now no need to initialize id and name
this(flatno, blgd);
this.city = city;
}
void display()
System.out.println(flatno + " " + blgd + " " + city);
public static void main(String args[])
AddressDetails e1 = new AddressDetails(01, "abc");
AddressDetails e2 = new AddressDetails(02, "def", "mumbai");
e1.display();
e2.display();
//This is a simple example of a Class.
//This program shows the structure of a class.
// class name
class Circle
double radius = 2.3; // variables
String color = "white";
// methods
double getRadius()
// method body
return radius; //return statement
}
String getColor()
// method body
return color; //return statement
//This example shows how to create an object
//of a class and call its methods
class CircleDemo
public static void main(String[] args)
//Creating an object
CircleTest c = new CircleTest();
//accessing object method with dot(.) operator
String color = c.getColor();
//print color
System.out.println(color);
// class name
class CircleTest
double radius = 2.3; // variables
String color = "white color";
// methods
double getRadius()
// method body
return radius; //return statement
String getColor()
// method body
return color; //return statement
class Student
String student_name;
public Student(String student_name)
this.student_name = student_name;
public String getName()
return student_name;
}
class ConstructorTest
public static void main(String args[])
Student t = new Student("John Doe");
System.out.println(t.student_name);
System.out.println(t.getName());
class Constructor1
int id;
String name;
int age;
Constructor1(int i, String n)
id = i;
name = n;
Constructor1(int i, String n, int a)
id = i;
name = n;
age = a;
void display()
System.out.println(id + " " + name + " " + age);
}
public static void main(String[] args)
Constructor1 co = new Constructor1(1, "Sam");
Constructor1 co1 = new Constructor1(2, "Roy", 25);
co.display();
co1.display();
class EncapsulationExample
private String manufacturer;
private String operating_system;
public String model;
private int cost;
// Constructor to set properties/characteristics of object
EncapsulationExample(String manufac, String operatSys, String mod, int cst)
this.manufacturer = manufac;
this.operating_system = operatSys;
this.model = mod;
this.cost = cst;
// Method to get access Model property of Object
public String getModel()
return this.model;
}
public String getManufacturer()
return this.manufacturer;
public int getcost()
return this.cost;
public String getOperatingSystem()
return this.operating_system;
public static void main(String[] args)
EncapsulationExample en = new EncapsulationExample("Microsoft",
"Windows", "2007", 500);
System.out.println("Manufacturer: " + en.getManufacturer());
System.out.println("OS: " + en.getOperatingSystem());
System.out.println("Model: " + en.getModel());
System.out.println("Cost: " + en.getcost());
interface A
public void methodA();
interface B extends A
{
public void methodB();
interface C extends A
public void methodC();
class D implements B, C
public void methodA()
System.out.println("MethodA");
public void methodB()
System.out.println("MethodB");
public void methodC()
System.out.println("MethodC");
public static void main(String args[])
D obj1 = new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
class Parent
String name;
class Inheritance extends Parent
String name;
public void displaydetails()
//refers to parent class member
super.name = "Parent";
name = "Child";
System.out.println(super.name + " and " + name);
public static void main(String[] args)
Inheritance obj = new Inheritance();
obj.displaydetails();
class Box
double width;
double height;
double depth;
Box()
Box(double w, double h, double d)
width = w;
height = h;
depth = d;
void getVolume()
System.out.println("Volume is : " + width * height * depth);
class MatchBox extends Box
double weight;
MatchBox()
MatchBox(double w, double h, double d, double m)
super(w, h, d);
weight = m;
public static void main(String args[])
MatchBox mb1 = new MatchBox(10, 20, 30, 40);
mb1.getVolume();
System.out.println("width of MatchBox is " + mb1.width);
System.out.println("height of MatchBox is " + mb1.height);
System.out.println("depth of MatchBox is " + mb1.depth);
System.out.println("weight of MatchBox is " + mb1.weight);
class Parent
String name = "Class A";
public String getName()
return name;
class Child extends Parent
String address = "Thane, Mumbai";
public String getAddress()
{
return address;
public static void main(String[] args)
Child obj = new Child();
System.out.println(obj.getName());
System.out.println(obj.getAddress());
//Java doesn't support Multiple Inheritance
//To achieve multiple inheritance Java has Interface
interface MyInterface
public String hello = "Hello";
public void sayHello();
interface MyOtherInterface
public void sayGoodbye();
class MyInterfaceImpl implements MyInterface, MyOtherInterface
public void sayHello()
{
System.out.println("Hello");
public void sayGoodbye()
System.out.println("Goodbye");
public static void main(String args[])
MyInterfaceImpl obj = new MyInterfaceImpl();
obj.sayHello();
obj.sayGoodbye();
class MethodOverloading
public void display(int number)
System.out.println("Integer value: " + number);
public void display(float number)
System.out.println("Float value: " + number);
public void display(char character)
System.out.println("Character value: " + character);
}
}
class MethodOverloadingTest
public static void main(String args[])
MethodOverloading ob = new MethodOverloading();
ob.display(20);
ob.display(0.33f);
ob.display('z');
class A
void display()
System.out.println("A");
class B extends A
void display()
System.out.println("B");
}
class C extends A
void display()
System.out.println("C");
class MethodOverridingTest
public static void main(String[] args)
A a = new A();
B b = new B();
C c = new C();
a.display();
b.display();
c.display();
//The following Bicycle class is one possible
//implementation of a bicycle
//This class shows how to use methods in a class
class BicycleDemo
public static void main(String[] args)
// Create two different
// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
class Bicycle
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue)
cadence = newValue;
}
void changeGear(int newValue)
gear = newValue;
void speedUp(int increment)
speed = speed + increment;
void applyBrakes(int decrement)
speed = speed - decrement;
void printStates()
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear);
class Car
public Car()
System.out.println("Class Car");
public void vehicleType()
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car
public Maruti()
System.out.println("Class Maruti");
public void brand()
System.out.println("Brand: Maruti");
public void speed()
System.out.println("Max: 90Kmph");
class Maruti800 extends Maruti
public Maruti800()
System.out.println("Maruti Model: 800");
public void speed()
System.out.println("Max: 80Kmph");
public static void main(String args[])
Maruti800 obj = new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
class ParameterizedConstructor
ParameterizedConstructor(int num1, int num2)
int addition;
addition = num1 + num2;
System.out.println("Addition of Numbers: " + addition);
public static void main(String args[])
ParameterizedConstructor p = new ParameterizedConstructor(30, 40);
class Demo
// constructor with parameters
Demo(int num1, int num2)
int addition;
addition = num1 + num2;
System.out.println("Addition of Numbers : " + addition);
public static void main(String args[])
{
Demo p = new Demo(30, 40);
class SuperClass
void display()
System.out.println("Hello Superclass ");
class Polymorphism extends SuperClass
void display()
System.out.println("Hello Subclass ");
public static void main(String args[])
//This is called upcasting
SuperClass s = new Polymorphism();
s.display();
import java.io.*;
class Student
private int roll_no;
private String name;
void get_data(int roll_no, String name)
this.roll_no = roll_no;
this.name = name;
void display()
System.out.print("\nThe Student Details are:");
System.out.print("\nRoll no: " + roll_no);
System.out.print("\nName: " + name);
class Marks extends Student
private int mark1, mark2;
Marks(int mark1, int mark2)
this.mark1 = mark1;
this.mark2 = mark2;
void display_marks()
System.out.print("\nMarks1: " + mark1);
System.out.print("\nMarks2: " + mark2);
float avg;
avg = (mark1 + mark2) / 2;
System.out.println("\nAverage: " + avg);
class SingleInheritance
public static void main(String s[]) throws Exception
int roll_no, mark1, mark2;
String name;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter Roll_no: ");
roll_no = Integer.parseInt(br.readLine());
System.out.print("\nEnter Name: ");
name = br.readLine();
System.out.print("\nEnter Marks1: ");
mark1 = Integer.parseInt(br.readLine());
System.out.print("\nEnter Marks2: ");
mark2 = Integer.parseInt(br.readLine());
Marks m = new Marks(mark1, mark2);
m.get_data(roll_no, name);
m.display();
m.display_marks();
class Superclass
//Final variable
final int i = 10;
//final method
final void display()
System.out.println("Super Class Method");
System.out.println("\nValue of final variable : " + i);
class FinalKeyword extends Superclass
public static void main(String args[])
FinalKeyword obj = new FinalKeyword();
obj.display();
class Wrapper
public static void main(String args[])
byte b = 3;
int i = 10;
float f = 4.5f;
double d = 90.7;
//data types to objects - wrapping
Byte b_obj = new Byte(b);
Integer i_obj = new Integer(i);
Float f_obj = new Float(f);
Double d_obj = new Double(d);
// printing the values from objects
System.out.println("Values of Wrapper objects ");
System.out.println("Byte object : " + b_obj);
System.out.println("Integer object : " + i_obj);
System.out.println("Float object : " + f_obj);
System.out.println("Double object : " + d_obj);
// objects to data types (retrieving data types from objects) - unwrapping
byte bv = b_obj.byteValue();
int iv = i_obj.intValue();
float fv = f_obj.floatValue();
double dv = d_obj.doubleValue();
//printing the values from data types
System.out.println("\nUnwrapped values ");
System.out.println("byte value : " + bv);
System.out.println("int value : " + iv);
System.out.println("float value : " + fv);
System.out.println("double value : " + dv);
}
/*
01
101
0101
10101
*/
class BinaryPattern
public static void main(String s[])
int i, j;
int count = 1;
for (i = 1; i <= 5; i++)
for (j = 1; j <= i; j++)
System.out.format("%d", count++ % 2);
if (j == i && i != 5)
System.out.println("");
if (i % 2 == 0)
count = 1;
else
count = 0;
class ChristmasTree
{
public static final int segments = 4;
public static final int height = 4;
public static void main(String[] args)
makeTree();
public static void makeTree()
int maxStars = 2 * height + 2 * segments - 3;
String maxStr = "";
for (int l = 0; l < maxStars; l++)
maxStr += " ";
for (int i = 1; i <= segments; i++)
for (int line = 1; line <= height; line++)
String starStr = "";
for (int j = 1; j <= 2 * line + 2 * i - 3; j++)
starStr += "*";
for (int space = 0; space <= maxStars - (height + line + i); space++)
starStr = " " + starStr;
}
System.out.println(starStr);
for (int i = 0; i <= maxStars / 2; i++)
System.out.print(" ");
System.out.println(" " + "*" + " ");
for (int i = 0; i <= maxStars / 2; i++)
System.out.print(" ");
System.out.println(" " + "*" + " ");
for (int i = 0; i <= maxStars / 2 - 3; i++)
System.out.print(" ");
System.out.println(" " + "*******");
class ChristmasTreePattern
public static void main(String[] arg)
{
drawChristmasTree(4);
private static void drawChristmasTree(int n)
for (int i = 0; i < n; i++)
triangle(i + 1, n);
private static void triangle(int n, int max)
for (int i = 0; i < n; i++)
for (int j = 0; j < max - i - 1; j++)
System.out.print(" ");
for (int j = 0; j < i * 2 + 1; j++)
System.out.print("X");
System.out.println("");
/*
Enter no of characters:7
Enter String:PROGRAM
PR
PRO
PROG
PROGR
PROGRA
PROGRAM
PROGRA
PROGR
PROG
PRO
PR
*/
import java.io.*;
class DiamondPattern
public static void main(String s[]) throws Exception
int i, j, k, n;
String s1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no of characters:");
n = Integer.parseInt(br.readLine());
System.out.println("Enter String:");
s1 = br.readLine();
for (i = 0; i < n; i++)
for (j = 0; j < (n - i); j++)
System.out.print(" ");
for (k = 0; k <= i; k++)
System.out.print(s1.charAt(k));
System.out.print(" ");
System.out.print("\n");
for (i = (n - 2); i >= 0; i--)
for (j = 0; j < (n - i); j++)
System.out.print(" ");
for (k = 0; k <= i; k++)
System.out.print(s1.charAt(k));
System.out.print(" ");
System.out.print("\n");
}
}
import java.util.Scanner;
class FloydTriangle
public static void main(String args[])
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of rows of floyd's triangle : ");
n = in.nextInt();
System.out.println("Floyd's triangle :-");
for (c = 1; c <= n; c++)
for (d = 1; d <= c; d++)
System.out.print(num + " ");
num++;
System.out.println();
/*------------------
12
123
1234
12345
-------------------*/
class NumberPat1
public static void main(String arg[])
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= i; j++)
System.out.print(j);
System.out.println();
import java.util.*;
class Pattern
public static void main(String[] args)
int i, j, k = 1, l, n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of levels of pattern");
n = sc.nextInt();
System.out.println("\nPattern is : \n");
for (i = 1; i <= n; i++)
l = i;
for (j = 1; j <= k; j++)
if (j >= i + 1)
System.out.print(--l);
else
System.out.print(j);
k = k + 2;
System.out.println(" ");
/*------------------
54321
5432
543
54
-------------------*/
class NumberPat2
public static void main(String arg[])
for (int i = 1; i <= 5; i++)
for (int j = 5; j >= i; j--)
System.out.print(j);
System.out.println();
/*------------------
12345
1234
123
12
1
-------------------*/
class NumberPat3
public static void main(String arg[])
for (int i = 1, r = 5; i <= 5; i++, r--)
for (int j = 1; j <= r; j++)
System.out.print(j);
System.out.println();
/*------------------
12
123
1234
12345
1234
123
12
1
-------------------*/
class NumberPat4
public static void main(String arg[])
int ck = 0, c = 2;
while (c > 0)
if (ck == 0)
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= i; j++)
System.out.print(j);
System.out.println();
ck++;
}
else
for (int i = 1, r = 5 - 1; i <= 5 - 1; i++, r--)
for (int j = 1; j <= r; j++)
System.out.print(j);
System.out.println();
c--;
/*------------------
12345
1234
123
12
12
123
1234
12345
-------------------*/
class NumberPat5
public static void main(String arg[])
int ck = 0, c = 2;
while (c > 0)
if (ck == 0)
for (int i = 1, r = 5; i <= 5; i++, r--)
for (int j = 1; j <= r; j++)
System.out.print(j);
System.out.println();
}
ck++;
else
for (int i = 2; i <= 5; i++)
for (int j = 1; j <= i; j++)
System.out.print(j);
System.out.println();
c--;
class NumberPat6
public static void main(String arg[])
{
for(int i=1;i<=5;i++)
for(int j=1;j<=i;j++)
System.out.print(i);
System.out.println();
/*
23
456
7890
12345
*/
class NumberPat7
public static void main(String arg[])
int t = 1;
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= i; j++)
if (t == 10)
t = 0;
System.out.print(t++);
System.out.println();
import java.util.Scanner;
class Pattern
public static void main(String args[])
int n, i, j;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows ");
n = sc.nextInt();
for (i = 1; i <= n; i++)
for (j = i; j <= n; j++)
if (i % 2 == 0)
System.out.print("0");
else
System.out.print("1");
System.out.println();
}
}
class PrintPattern
public static void main(String args[])
int n = 5;
for (int i = 1; i <= n; i++)
int j = n - i;
while (j > 0)
System.out.print(" ");
j--;
j = 1;
while (j <= i)
System.out.print(" " + j);
j++;
j = i - 1;
while (j > 0)
System.out.print(" " + j);
j--;
j = n - i;
while (j > 0)
{
System.out.print(" ");
j--;
System.out.println();
import java.util.*;
class Pascal
public static final int ROW = 12;
private static int max = 0;
public static void main(String[] args)
int[][] pascal = new int[ROW + 1][];
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
for (int i = 2; i <= ROW; i++)
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++)
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
String str = Integer.toString(pascal[i][j]);
int len = str.length();
if (len > max)
max = len;
for (int i = 1; i <= ROW; i++)
for (int k = ROW; k > i; k--)
System.out.format("%-" + max + "s", " ");
for (int j = 1; j < pascal[i].length - 1; j++)
System.out.format("%-" + (max + max) + "s", pascal[i][j]);
System.out.println();
import java.io.*;
class NumberPayramid
public static void main(String[] args) throws Exception
int row;
int i, j, k;
int x = 1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter number of rows : ");
row = Integer.parseInt(br.readLine());
for (i = 1; i <= row; i++)
for (k = 1; k <= row - i; k++)
System.out.print(" ");
for (j = k + 1; j <= row; j++)
System.out.print(x);
for (int l = row; l > k - 1; l--)
System.out.print(x);
x++;
System.out.println("");
import java.io.*;
class SpiralNumberPattern
public static void main(String args[]) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter no. for spiral pattern : ");
int INPUT = Integer.parseInt(br.readLine());
final int LEFT = 1;
final int DOWN = 2;
final int RIGHT = 3;
final int UP = 4;
int[][] patt = new int[INPUT][INPUT];
//initial position
int x = 0;
int y = 0;
//initial direction
int Direction = LEFT;
//Master Loop
for (int i = 0; i < INPUT * INPUT; i++)
int temp = i + 1;
//Checking boundaries
if (y > INPUT - 1)
Direction = DOWN;
x++;
y--;
i--;
continue;
else if (x > INPUT - 1)
Direction = RIGHT;
x--;
y--;
i--;
continue;
else if (y < 0)
Direction = UP;
y++;
x--;
i--;
continue;
else if (x < 0)
Direction = LEFT;
y++;
x++;
i--;
continue;
if (patt[x][y] == 0)
patt[x][y] = temp;
}
else
if (Direction == LEFT)
Direction = DOWN;
y--;
else if (Direction == DOWN)
Direction = RIGHT;
x--;
else if (Direction == RIGHT)
Direction = UP;
y++;
else
Direction = LEFT;
x++;
i--;
switch (Direction)
case LEFT:
y++;
break;
case DOWN:
x++;
break;
case RIGHT:
y--;
break;
case UP:
x--;
break;
// Print Grid Array
for (int i = 0; i < INPUT; i++)
for (int k = 0; k < INPUT; k++)
if (patt[i][k] <= 9)
System.out.print(" " + patt[i][k] + " ");
else
System.out.print(patt[i][k] + " ");
System.out.println();
/*
2 2
3 3
4 4
3 3
2 2
*/
class SquareKitePattern
public static void main(String args[])
int i, j, k;
for (i = 1; i <= 4; i++)
for (j = 4; j >= (i - 1) * 2 - 1; j--)
System.out.print(" ");
System.out.print(i);
for (j = 2; j <= (i - 1) * 4; j++)
System.out.print(" ");
if (i > 1)
System.out.print(i);
System.out.print("\n");
for (i = 3; i >= 1; i--)
for (j = 4; j >= (i - 1) * 2 - 1; j--)
System.out.print(" ");
System.out.print(i);
for (j = 2; j <= (i - 1) * 4; j++)
{
System.out.print(" ");
if (i > 1)
System.out.print(i);
System.out.print("\n");
/*----------------------------
*****
****
***
**
**
***
****
*****
----------------------------*/
class StarPattern3
public static void main(String arg[])
for (int i = 1; i <= 5; i++)
{
for (int j = i; j <= 5; j++)
System.out.print("*");
System.out.println();
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= i; j++)
System.out.print("*");
System.out.println();
/*---------------------------
**
****
******
********
**********
---------------------------*/
class StarPattern4
{
public static void main(String arg[])
int num = 12;
int f = 2;
int g = num - 1;
for (int i = 1; i <= (num / 2); i++)
for (int j = 1; j <= num; j++)
if (j >= f && j <= g)
System.out.print(" ");
else
System.out.print("*");
f = f + 1;
g = g - 1;
System.out.println();
/*------------------
**
***
****
*****
*****
****
***
**
-------------------*/
class StarPattern5
public static void main(String arg[])
for (int i = 1; i <= 5; i++)
for (int j = 1; j <= i; j++)
System.out.print("*");
}
System.out.println();
for (int i = 1; i <= 5; i++)
for (int j = i; j <= 5; j++)
System.out.print("*");
System.out.println();
import java.io.*;
class Triangle
public static void main(String arg[])
InputStreamReader istream = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(istream);
System.out.println("Enter Triangle Size : ");
int num = 0;
try
num = Integer.parseInt(read.readLine());
}
catch (Exception Number)
System.out.println("Invalid Number!");
for (int i = 1; i <= num; i++)
for (int j = 1; j < num - (i - 1); j++)
System.out.print(" ");
for (int k = 1; k <= i; k++)
System.out.print("*");
for (int k1 = 1; k1 < k; k1 += k)
System.out.print("*");
System.out.println();
import java.util.Scanner;
class LinearSearch
public static void main(String args[])
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
if (array[c] == search) // Searching element is present
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
if (c == n) // Searching element is absent
System.out.println(search + " is not present in array.");
import java.util.*;
class BubbleSortInDescendingOrder
public static void main(String args[])
int n, c, d, swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort");
n = in.nextInt();
int array[] = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
for (c = 0; c < (n - 1); c++)
for (d = 0; d < n - c - 1; d++)
{
if (array[d] < array[d + 1])
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
System.out.println("Sorted list of numbers");
for (c = 0; c < n; c++)
System.out.println(array[c]);
import java.util.*;
class EnumerationSort {
public static void main(String[] args) {
/*
Creates random data for sorting source. Will use java.util.Vector
to store the random integer generated.
*/
Random random = new Random();
Vector<Integer> data = new Vector<Integer>();
for (int i = 0; i < 10; i++) {
data.add(Math.abs(random.nextInt()));
/*
Get the enumeration from the vector object and convert it into
a java.util.List. Finally we sort the list using
Collections.sort() method.
*/
Enumeration enumeration = data.elements();
List<Integer> list = Collections.list(enumeration);
Collections.sort(list);
//
// Prints out all generated number after sorted.
//
for (Integer number : list) {
System.out.println("number = " + number);
//The exchange sort compares the first element with each element of the array, making a swap
where is necessary.
import java.util.*;
class ExchangeSort
public static void main(String[] args)
int[] array;
int i, j, temp, size;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array");
size = sc.nextInt();
array = new int[size];
System.out.println("Enter the elements of array : ");
for (i = 0; i < size; i++)
array[i] = sc.nextInt();
//Exchange sort
for (i = 0; i < (size - 1); i++)
for (j = (i + 1); j < size; j++)
if (array[i] > array[j])
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
System.out.println("Sorted Array is : ");
for (i = 0; i < size; i++)
System.out.print(array[i] + " ");
class HeapSort
public static void main(String a[])
int i;
int arr[] = {1, 3, 4, 5, 2};
System.out.println("\nHeap Sort\n---------------");
System.out.println("\nUnsorted Array\n---------------");
for (i = 0; i < arr.length; i++)
System.out.print(" " + arr[i]);
for (i = arr.length; i > 1; i--)
fnSortHeap(arr, i - 1);
System.out.println("\n\nSorted array\n---------------");
for (i = 0; i < arr.length; i++)
System.out.print(" " + arr[i]);
public static void fnSortHeap(int array[], int arr_ubound)
int i, o;
int lChild, rChild, mChild, root, temp;
root = (arr_ubound - 1) / 2;
for (o = root; o >= 0; o--)
for (i = root; i >= 0; i--)
lChild = (2 * i) + 1;
rChild = (2 * i) + 2;
if ((lChild <= arr_ubound) && (rChild <= arr_ubound))
if (array[rChild] >= array[lChild])
mChild = rChild;
else
mChild = lChild;
else
if (rChild > arr_ubound)
mChild = lChild;
else
mChild = rChild;
if (array[i] < array[mChild])
temp = array[i];
array[i] = array[mChild];
array[mChild] = temp;
temp = array[0];
array[0] = array[arr_ubound];
array[arr_ubound] = temp;
return;
class InsertionSortExample
static int step = 1;
public static void main(String[] args)
int[] input = {7, 21, 91, 43, 23, 17, 34, 9, 1};
insertionSort(input);
private static void printNumbers(int[] input)
{
System.out.println("Step " + step);
System.out.println("-----------------------------");
step++;
for (int i = 0; i < input.length; i++)
System.out.print(input[i] + ", ");
System.out.println("\n");
public static void insertionSort(int array[])
int n = array.length;
for (int j = 1; j < n; j++)
int key = array[j];
int i = j - 1;
while ((i > -1) && (array[i] > key))
array[i + 1] = array[i];
i--;
array[i + 1] = key;
printNumbers(array);
}
}
class MergeSort
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String a[])
int[] inputArr = {32, 27, 51, 89, 1, 98, 9, 28, 65, 0};
MergeSort mms = new MergeSort();
mms.sort(inputArr);
for (int i : inputArr)
System.out.print(i);
System.out.print(" ");
public void sort(int inputArr[])
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
private void mergeParts(int lowerIndex, int middle, int higherIndex)
for (int i = lowerIndex; i <= higherIndex; i++)
tempMergArr[i] = array[i];
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
if (tempMergArr[i] <= tempMergArr[j])
array[k] = tempMergArr[i];
i++;
else
{
array[k] = tempMergArr[j];
j++;
k++;
while (i <= middle)
array[k] = tempMergArr[i];
k++;
i++;
import java.util.Comparator;
import java.util.Arrays;
class SortFruitObject
public static void main(String args[])
Fruit[] fruits = new Fruit[4];
Fruit pineappale = new Fruit("Pineapple", "Pineapple description", 70);
Fruit apple = new Fruit("Apple", "Apple description", 100);
Fruit orange = new Fruit("Orange", "Orange description", 80);
Fruit banana = new Fruit("Banana", "Banana description", 90);
fruits[0] = pineappale;
fruits[1] = apple;
fruits[2] = orange;
fruits[3] = banana;
Arrays.sort(fruits);
int i = 0;
for (Fruit temp : fruits)
System.out.println("fruits " + ++i + " : " + temp.getFruitName() + ", Quantity " + "\t: " +
temp.getQuantity());
class Fruit implements Comparable<Fruit>
private String fruitName;
private String fruitDesc;
private int quantity;
public Fruit(String fruitName, String fruitDesc, int quantity)
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}
public String getFruitName()
return fruitName;
public void setFruitName(String fruitName)
this.fruitName = fruitName;
public String getFruitDesc()
return fruitDesc;
public void setFruitDesc(String fruitDesc)
this.fruitDesc = fruitDesc;
public int getQuantity()
return quantity;
public void setQuantity(int quantity)
this.quantity = quantity;
public int compareTo(Fruit compareFruit)
{
int compareQuantity = ((Fruit) compareFruit).getQuantity();
//ascending order
return this.quantity - compareQuantity;
//descending order
//return compareQuantity - this.quantity;
public static Comparator<Fruit> FruitNameComparator
= new Comparator<Fruit>()
public int compare(Fruit fruit1, Fruit fruit2)
String fruitName1 = fruit1.getFruitName().toUpperCase();
String fruitName2 = fruit2.getFruitName().toUpperCase();
//ascending order
return fruitName1.compareTo(fruitName2);
//descending order
//return fruitName2.compareTo(fruitName1);
};
class QuickSort
public static void main(String a[])
{
int i;
int array[] = {12, 9, 4, 99, 120, 1, 3, 10, 13};
System.out.println("Quick Sort\n\n");
System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
quick_srt(array, 0, array.length - 1);
System.out.print("\nValues after the sort:\n\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
public static void quick_srt(int array[], int low, int n)
int lo = low;
int hi = n;
if (lo >= n)
{
return;
int mid = array[(lo + hi) / 2];
while (lo < hi)
while (lo < hi && array[lo] < mid)
lo++;
while (lo < hi && array[hi] > mid)
hi--;
if (lo < hi)
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
if (hi < lo)
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo + 1 : lo, n);
class SelectionSortExample
public static int[] doSelectionSort(int[] arr)
for (int i = 0; i < arr.length - 1; i++)
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
return arr;
public static void main(String a[])
{
int[] arr1 = {102, 34, 2, 56, 76, 5, 88, 42};
int[] arr2 = doSelectionSort(arr1);
for (int i : arr2)
System.out.print(i);
System.out.print(", ");
import java.util.*;
class SelectionSortDesc
public static void main(String[] args)
int[] num;
int size;
Scanner scanner = new Scanner(System.in);
System.out.print("No. of elements to sort :");
size = scanner.nextInt();
num = new int[size];
for (int i = 0; i < size; i++)
num[i] = scanner.nextInt();
int sorted_array[] = sort(num);
System.out.println("Selection Sort in Descending order : ");
for (int i = 0; i < sorted_array.length; i++)
{
System.out.print(sorted_array[i] + "\t");
public static int[] sort(int[] num)
int i, j, first, temp;
for (i = num.length - 1; i > 0; i--)
first = 0; //initialize to subscript of first element
for (j = 1; j <= i; j++) //locate smallest element between positions 1 and i.
if (num[j] < num[first])
first = j;
temp = num[first]; //swap smallest found with element in position i.
num[first] = num[i];
num[i] = temp;
return num;
class ShellSort
private long[] data;
private int len;
public ShellSort(int max)
data = new long[max];
len = 0;
}
public void insert(long value)
data[len] = value;
len++;
public void display()
for (int j = 0; j < len; j++)
System.out.print(data[j] + " ");
System.out.println("");
public void shellSort()
int inner, outer;
long temp;
// find initial value of h
int h = 1;
while (h <= len / 3)
h = h * 3 + 1; // (1, 4, 13, 40, 121, ...)
while (h > 0) // decreasing h, until h=1
{
// h-sort the file
for (outer = h; outer < len; outer++)
temp = data[outer];
inner = outer;
// one subpass (eg 0, 4, 8)
while (inner > h - 1 && data[inner - h] >= temp)
data[inner] = data[inner - h];
inner -= h;
data[inner] = temp;
h = (h - 1) / 3; // decrease h
public static void main(String[] args)
int maxSize = 10;
ShellSort arr = new ShellSort(maxSize);
for (int j = 0; j < maxSize; j++)
long n = (int) (java.lang.Math.random() * 99);
arr.insert(n);
}
System.out.print("Unsorted List:\n");
arr.display();
arr.shellSort();
System.out.print("-------------------------\n");
System.out.print("Sorted List:\n");
arr.display();
import java.util.Scanner;
/* Class SkipListTest */
class SkipList
public static void main(String[] args)
int n;
Scanner scan = new Scanner(System.in);
/* Creating object of SkipList */
SkipList1 sl = new SkipList1(100000000);
System.out.println("Enter no of elements to enter");
n = scan.nextInt();
/* Perform list operations */
do
System.out.println("Enter integer element to insert");
sl.insert(scan.nextInt());
/* Display List */
sl.printList();
n--;
while (n > 0);
/* Class SkipNode */
class SkipNode
int element;
SkipNode right;
SkipNode down;
/* Constructor */
public SkipNode(int x)
this(x, null, null);
/* Constructor */
public SkipNode(int x, SkipNode rt, SkipNode dt)
element = x;
right = rt;
down = dt;
/* Class SkipList */
class SkipList1
{
private SkipNode header;
private int infinity;
private SkipNode bottom = null;
private SkipNode tail = null;
/* Constructor */
public SkipList1(int inf)
infinity = inf;
bottom = new SkipNode(0);
bottom.right = bottom.down = bottom;
tail = new SkipNode(infinity);
tail.right = tail;
header = new SkipNode(infinity, tail, bottom);
/* Function to insert element */
public void insert(int x)
SkipNode current = header;
bottom.element = x;
while (current != bottom)
while (current.element < x)
current = current.right;
/* If gap size is 3 or at bottom level and must insert, then promote middle element */
if (current.down.right.right.element < current.element)
current.right = new SkipNode(current.element, current.right, current.down.right.right);
current.element = current.down.right.element;
else
current = current.down;
/* Raise height of skiplist if necessary */
if (header.right != tail)
header = new SkipNode(infinity, tail, header);
/* Function to get node at a position */
private int elementAt(SkipNode t)
return t == bottom ? 0 : t.element;
/* Function to print list */
public void printList()
System.out.print("\nSkiplist = ");
SkipNode current = header;
while (current.down != bottom)
current = current.down;
while (current.right != tail)
System.out.print(current.element + " ");
current = current.right;
System.out.println();
}
}
import java.util.*;
class Sorting
public static void main(String[] args)
int num, i, j, temp;
int[] asc;
int[] des;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements:");
num = sc.nextInt();
asc = new int[num];
des = new int[num];
System.out.println("Enter " + num + " numbers: ");
//Sorting numbers in ascending order
for (i = 0; i < num; i++)
asc[i] = sc.nextInt();
des[i] = asc[i];
for (i = 0; i < (num - 1); i++)
for (j = 0; j < (num - i - 1); j++)
{
if (asc[j] > asc[j + 1])
temp = asc[j];
asc[j] = asc[j + 1];
asc[j + 1] = temp;
//Sorting numbers in descending order
for (i = 0; i < (num - 1); i++)
for (j = 0; j < (num - i - 1); j++)
if (des[j] < des[j + 1])
temp = des[j];
des[j] = des[j + 1];
des[j + 1] = temp;
System.out.println("Sorted list of numbers in ascending order:");
for (i = 0; i < num; i++)
System.out.print(" " + asc[i]);
System.out.println("\n \nSorted list of numbers in descending order:");
for (i = 0; i < num; i++)
{
System.out.print(" " + des[i]);
class CharToASCII
public static int CharToASCII(final char character)
return (int) character;
public static char ASCIIToChar(final int ascii)
return (char) ascii;
public static void main(String args[])
char a = 'a';
int i = 65;
System.out.println("Char to ASCII : " + a + " ascii is " + CharToASCII(a));
System.out.println("ASCII to char : " + i + " char is " + ASCIIToChar(i));
class StringCase
{
public static void main(String args[])
String str = "Java Programs With Output";
//toUpperCase() method converts the complete string in upper case
String strUpper = str.toUpperCase();
//toLowerCase() method converts the complete string in lower case
String strLower = str.toLowerCase();
//printing changed case string
System.out.println("Upper Case: " + strUpper);
System.out.println("Lower Case: " + strLower);
import java.util.*;
class Palindrome
public static void main(String args[])
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
{
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
import java.util.Scanner;
class PigLatin
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
final String vowels = "aeiouAEIOU";
System.out.println("Enter done to exit...");
System.out.print("Enter your word : ");
String word = sc.nextLine();
while (!word.equalsIgnoreCase("done"))
String beforVowel = "";
int cut = 0;
while (cut < word.length() && !vowels.contains("" + word.charAt(cut)))
beforVowel += word.charAt(cut);
cut++;
if (cut == 0)
{
cut = 1;
word += word.charAt(0) + "w";
System.out.println("PigLatin : " + word.substring(cut) + beforVowel + "ay");
System.out.print("Enter your word : ");
word = sc.nextLine();
import java.io.*;
class PunctuationMark
public static void main(String[] args) throws Exception
String str;
int i, punct = 0, letter = 0, spaces = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String : ");
str = br.readLine();
for (i = 0; i < str.length(); i++)
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
letter++;
}
else if (ch == ' ' || ch == '\t')
spaces++;
else
punct++;
System.out.println("Number of letter in the string is : " + letter);
System.out.println("Number of spaces in the string is : " + spaces);
System.out.println("Number of punctuation marks in the string is : " + punct);
import java.util.*;
class Demo
public static void main(String s[])
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter string: ");
String s1 = sc.nextLine();
System.out.print("\nEnter char: ");
char c = sc.next(".").charAt(0);
int count = 0;
char strarr[] = s1.toCharArray();
for (int i = 0; i < strarr.length; i++)
if (strarr[i] == c)
count++;
System.out.println("\nNo of Occurence found: " + count);
import java.util.Scanner;
class CountWords
public static int countWords(String str)
String words[] = str.split(" ");
int count = words.length;
return count;
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = in.nextLine();
System.out.print("Your sentence has " + countWords(sentence)
+ " words.");
//Close Scanner to avoid memory leak
in.close();
import java.util.Scanner;
class SubstringsOfAString
public static void main(String args[])
String string, sub;
int i, c, length;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
length = string.length();
System.out.println("Substrings of \"" + string + "\" are :-");
for (c = 0; c < length; c++)
for (i = 1; i <= length - c; i++)
sub = string.substring(c, c + i);
System.out.println(sub);
}
}
class FormatString
public static void main(String a[])
String str = "This is formatted %s example.";
System.out.println(String.format(str, "string"));
String str1 = "We are adding number %d to string.";
System.out.println(String.format(str1, 10));
class HtmlTagRemover
public static void main(String a[])
String text = "<p>This tags going to disappear.</p>";
System.out.println(text);
text = text.replaceAll("\\<.*?\\>", "");
System.out.println(text);
import java.util.Scanner;
class LongestWord
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string : ");
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++)
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ')
if (word.length() > maxlength)
maxword = new String(word);
maxlength = word.length();
word = "";
i++;
System.out.println("longest word is " + maxword);
import java.io.*;
class VowelsInString
{
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String : ");
String str = br.readLine();
int noofvowels = 0;
for (int i = 0; i < str.length(); i++)
if ((str.toLowerCase().charAt(i) == 'a') || (str.toLowerCase().charAt(i) == 'e') ||
(str.toLowerCase().charAt(i) == 'i') || (str.toLowerCase().charAt(i) == 'o') ||
(str.toLowerCase().charAt(i) == 'u'))
noofvowels++;
System.out.print("Number of vowels in " + str + " : " + noofvowels);
import java.util.Scanner;
class Permutation
public static void main(String args[])
System.out.print("Please enter the string for permutation : ");
Scanner in = new Scanner(System.in);
String original = in.nextLine();
System.out.println("\nResults are :");
permute(original);
public static void permute(String input)
int inputLength = input.length();
boolean[] used = new boolean[inputLength];
StringBuffer outputString = new StringBuffer();
char[] in = input.toCharArray();
doPermute(in, outputString, used, inputLength, 0);
public static void doPermute(char[] in, StringBuffer outputString,
boolean[] used, int inputLength, int level)
if (level == inputLength)
System.out.println(outputString.toString());
return;
for (int i = 0; i < inputLength; ++i)
if (used[i])
continue;
outputString.append(in[i]);
used[i] = true;
doPermute(in, outputString, used, inputLength, level + 1);
used[i] = false;
outputString.setLength(outputString.length() - 1);
import java.io.*;
class RepeatStringName
public static void main(String args[]) throws Exception
int i, n;
String strName = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name: ");
strName = br.readLine();
System.out.println("\nEnter the number of times you want to print your name: ");
n = Integer.parseInt(br.readLine());
System.out.println();
for (i = 0; i < n; i++)
System.out.print(strName + " ");
class StringRecursiveReversal
String reverse = "";
public String reverseString(String str)
if (str.length() == 1)
return str;
else
reverse += str.charAt(str.length() - 1)
+ reverseString(str.substring(0, str.length() - 1));
return reverse;
public static void main(String a[])
StringRecursiveReversal srr = new StringRecursiveReversal();
System.out.println("Result: " + srr.reverseString("Java Programs With Output"));
import java.util.*;
class ReverseString
public static void main(String args[])
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: " + reverse);
import java.io.*;
class ReverseSentence
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter sentence : ");
String str = br.readLine();
String words[] = str.split(" ");
System.out.println("Reverse Sentence : ");
for (int i = words.length - 1; i >= 0; i--)
System.out.print(words[i] + " ");
}
}
import java.util.ArrayList;
import java.io.*;
class ReverseSentence
public static void main(String args[]) throws Exception
System.out.print("Enter sentence : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String sentence = br.readLine();
ArrayList al = new ArrayList();
al = recursiveReverseMethod(sentence, al);
al.trimToSize();
StringBuilder sb = new StringBuilder();
for (int i = al.size() - 1; i >= 0; i--)
sb.append(al.get(i) + " ");
System.out.println("Reverse of Sentence : " + sb);
public static ArrayList recursiveReverseMethod(String sentence, ArrayList al)
int index = sentence.indexOf(" ");
al.add(sentence.substring(0, index));
sentence = sentence.substring(index + 1);
if (sentence.indexOf(" ") == -1)
al.add(sentence.substring(0));
return al;
}
return recursiveReverseMethod(sentence, al);
import java.io.*;
class ReverseWordIntheSentence
public static void main(String[] args) throws Exception
int strLen, i, j;
String str;
String reverse = "", temp = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter string: ");
str = br.readLine();
strLen = str.length() - 1;
for (i = 0; i <= strLen; i++)
temp += str.charAt(i);
if ((str.charAt(i) == ' ') || (i == strLen))
for (j = temp.length() - 1; j >= 0; j--)
reverse += temp.charAt(j);
if ((j == 0) && (i != strLen))
reverse += " ";
temp = "";
System.out.println("\nReverse of " + str + " : " + reverse);
import java.util.Arrays;
class SingleStringSort
public static void main(String[] args)
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println("Pre-sorting string : " + original);
System.out.println("Sorted string : " + sorted);
import java.util.*;
class AlphabeticalOrder
public static void main (String[] args)
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter : ");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
names[i] = s1.nextLine();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (names[i].compareTo(names[j])>0)
temp = names[i];
names[i] = names[j];
names[j] = temp;
System.out.println("Names in Sorted Order : ");
for (int i = 0; i < n; i++)
{
System.out.println(names[i]);
class StringConcat
public static void main(String args[])
String s1 = "Hello";
String s2 = "FreeIT";
//Concatenation
String s3 = s1.concat(s2);
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
String s4 = "Hello";
//checking equals
if (s4.equals(s1))
System.out.println("s4 is equal to s1");
else
System.out.println("s4 is not equal to s1");
}
}
class StringConcatWithPlus
public static void main(String[] args)
String s1 = "Hi ";
String s2 = "Programming Hub";
String s3 = null;
String s4 = null;
//Concatenating two String Objects
s3 = s1 + s2;
//Concatenating Strings Dynamically
s4 = "This is " + "New String";
System.out.println("s3 = " + s3);
System.out.println("s4 = " + s4);
class StringEqualsTest {
public static void main(String[] args) {
String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println("== comparison : " + (s1 == s5));
System.out.println("== comparison : " + (s1 == s2));
System.out.println("Using equals method : " + s1.equals(s2));
System.out.println("== comparison : " + (s3 == s4));
System.out.println("Using equals method : " + s3.equals(s4));
class StringLength
static int i, c, res;
static int length(String s)
try
for (i = 0, c = 0; 0 <= i; i++, c++)
s.charAt(i);
catch (Exception e)
//Array index out of bounds and array index out of range are different exceptions
System.out.print("length is ");
// we can not put return statement in catch
return c;
public static void main(String args[])
System.out.println("Original String is : Programming Hub");
res = StringLength.length("Programming Hub");
System.out.println(res);
class StringExampleTwo
public static void main(String args[])
String s1 = " Universe ";
System.out.println("s1 = " + s1);
//Display String Length
System.out.println("The length of s1 is: " + s1.length());
//Removing extra spaces from s1
String s2 = s1.trim();
System.out.println("s2 = " + s2);
System.out.println("The length of s2 is: " + s2.length());
class StringReverse
public static void main(String args[])
String s = "abcdef";
char c[] = s.toCharArray();
System.out.print("Reverse String : ");
for (int i = c.length - 1; i >= 0; i--)
System.out.print(c[i]);
class StringStartWith
public static void main(String a[])
String str = "This is a Demo.";
System.out.println("Is this string starts with \"This\"? " + str.startsWith("This"));
System.out.println("Is this string starts with \"Demo\"? " + str.startsWith("Demo"));
/*
String Tokenizer example
This example shows how a Java StringTokenizer can be used to break a string
into tokens.
*/
import java.util.StringTokenizer;
class StringTokenizerExample
public static void main(String[] args)
//create StringTokenizer object
StringTokenizer st = new StringTokenizer("Java StringTokenizer Example");
//iterate through tokens
while (st.hasMoreTokens())
System.out.println(st.nextToken());
class StringBuilderDemo
public static void main(String args[])
StringBuilder sb = new StringBuilder("java ");
//now original string is changed
sb.append("is best");
System.out.println(sb);
System.out.println(sb.length());
//allocated capacity
System.out.println(sb.capacity());
StringBuilder sb1 = new StringBuilder("Android");
sb1.insert(7, " is cool");
System.out.println(sb1);
StringBuilder sb2 = new StringBuilder("He is Superstar");
sb2.replace(3, 5, "was");
System.out.println(sb2);
StringBuilder sb3 = new StringBuilder("Hello");
sb3.delete(1, 3);
//prints Hlo
System.out.println(sb3);
sb3.deleteCharAt(0);
System.out.println(sb3);
StringBuilder sb4 = new StringBuilder("java");
sb4.reverse();
System.out.println(sb4);
StringBuilder sb5 = new StringBuilder("java ");
System.out.println(sb5.charAt(0));
sb5.setCharAt(0, 'k');
System.out.println(sb5);
StringBuilder sb6 = new StringBuilder("He is Superstar");
String s = sb6.substring(6, 11);
System.out.println(s);
s = sb6.substring(6);
System.out.println(s);
import java.util.Arrays;
import java.io.*;
class SortString
public static void main(String args[]) throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// create a Java String array
String[] names = null;
System.out.print("How many names you want to sort : ");
int size = Integer.parseInt(br.readLine());
names = new String[size];
for (int i = 0; i < size; i++)
System.out.print("Enter " + (i + 1) + " name : ");
names[i] = br.readLine();
// sort the array, using the sort method of the Arrays class
Arrays.sort(names);
System.out.println("Sorted names -> ");
// print the sorted results
for (String name : names)
System.out.println("\t" + name);
class Test
public static void main(String[] args)
int sum = 0;
String str = "sha12bhu467";
//replace all character to "" except decimals
str = str.replaceAll("\\D+", "");
System.out.println(str);
char c[] = str.toCharArray();
for (int i = 0; i < c.length; i++)
sum += Character.getNumericValue(c[i]);
System.out.println("Your sum :)" + " " + sum);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class ComboBoxDemo extends JPanel
implements ActionListener
JLabel picture;
public ComboBoxDemo()
super(new BorderLayout());
ArrayList<String> listPet = new ArrayList<String>();
listPet.add("Bird");
listPet.add("Cat");
listPet.add("Dog");
listPet.add("Rabbit");
listPet.add("Pig");
//Create the combo box, select the item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(listPet.toArray());
petList.setSelectedIndex(4);
petList.addActionListener(this);
//Set up the picture.
picture = new JLabel();
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
updateLabel(listPet.get(petList.getSelectedIndex()));
picture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
//The preferred size is hard-coded to be the width of the
//widest image and the height of the tallest image + the border.
//A real program would compute this.
picture.setPreferredSize(new Dimension(177, 122 + 10));
//Lay out the demo.
add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
/**
* Listens to the combo box.
*/
public void actionPerformed(ActionEvent e)
JComboBox cb = (JComboBox) e.getSource();
String petName = (String) cb.getSelectedItem();
updateLabel(petName);
protected void updateLabel(String name)
picture.setText(name);
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI()
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ComboBoxDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args)
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGUI();
});
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JListDemo extends JFrame
// Instance attributes used in this example
private JPanel topPanel;
private JList listbox;
// Constructor of main frame
public JListDemo()
// Set the frame characteristics
setTitle("JList Demo");
setSize(300, 150);
setBackground(Color.gray);
// Create a panel to hold all other components
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
// Create some items to add to the list
String listData[] =
"Java",
"Python",
"Polymer",
"PHP"
};
// Create a new listbox control
listbox = new JList(listData);
topPanel.add(listbox, BorderLayout.CENTER);
// Main entry point for this example
public static void main(String args[])
// Create an instance of the test application
JListDemo mainFrame = new JListDemo();
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JMenuBarExample implements Runnable, ActionListener
private JLabel message;
private JFrame frame;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu editMenu;
private JMenuItem openMenuItem;
private JMenuItem cutMenuItem;
private JMenuItem copyMenuItem;
private JMenuItem pasteMenuItem;
public static void main(String[] args)
SwingUtilities.invokeLater(new JMenuBarExample());
public void run()
frame = new JFrame("Java JMenubar Example");
menuBar = new JMenuBar();
message = new JLabel();
message.setHorizontalAlignment(JLabel.CENTER);
// build the File menu
fileMenu = new JMenu("File");
openMenuItem = new JMenuItem("Open");
fileMenu.add(openMenuItem);
// build the Edit menu
editMenu = new JMenu("Edit");
cutMenuItem = new JMenuItem("Cut");
copyMenuItem = new JMenuItem("Copy");
pasteMenuItem = new JMenuItem("Paste");
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
//set listener
openMenuItem.addActionListener(this);
cutMenuItem.addActionListener(this);
copyMenuItem.addActionListener(this);
pasteMenuItem.addActionListener(this);
// add menus to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
// put the menubar on the frame
frame.setJMenuBar(menuBar);
frame.add(message, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(400, 300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//handles the click event on JMenutem
public void actionPerformed(ActionEvent ev)
String textOnMenu = ((JMenuItem) ev.getSource()).getText();
message.setText(textOnMenu + " menu item clicked.");
class MultiThreads
public static void main(String[] args)
System.out.println(Thread.currentThread().getName());
for (int i = 0; i < 10; i++)
new Thread("" + i)
public void run()
System.out.println("Thread: " + getName() + " running");
}.start();
}
public class Multiplicatin_Table implements Runnable{
private int number;
public Multiplicatin_Table(int number) {
this.number=number;
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <= 10; i++) {
System.out.printf("%s: %d * %d = %d\n", Thread.currentThread().getName(),
number, i, i * number);
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("I will print table of 1 to 5 ");
for (int i = 1; i <= 5; i++) {
Multiplicatin_Table mul = new Multiplicatin_Table(i);
Thread thread = new Thread(mul);
thread.start();
}
import java.lang.*;
class ThreadDemo implements Runnable
Thread t;
ThreadDemo()
// thread created
t = new Thread(this, "Admin Thread");
// set thread priority
t.setPriority(1);
// print thread created
System.out.println("thread = " + t);
// this will call run() function
t.start();
public void run()
// returns this thread's priority.
System.out.println("Thread priority = " + t.getPriority());
public static void main(String args[])
new ThreadDemo();
class SetThreadName
{
public static void main(String[] args)
//get currently running thread object
Thread currentThread = Thread.currentThread();
System.out.println(currentThread);
//To set name of thread, use
//void setName(String threadName) method of
//Thread class.
currentThread.setName("Set Thread Name Example");
//To get the name of thread use,
//String getName() method of Thread class.
System.out.println("Thread Name : " + currentThread.getName());
class SimpleRunnable implements Runnable
public void run()
System.out.println("Hello from a thread!");
public static void main(String args[])
(new Thread(new SimpleRunnable())).start();
class CallThread
{
void call(String msg)
System.out.print("[" + msg);
try
Thread.sleep(1000);
catch (InterruptedException e)
System.out.println("Interrupted");
System.out.println("]");
// File Name : Caller.java
class Caller implements Runnable
String msg;
CallThread target;
Thread t;
public Caller(CallThread targ, String s)
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run()
synchronized (target)
// synchronized block
target.call(msg);
class SyncExample
public static void main(String args[])
CallThread target = new CallThread();
Caller ob1 = new Caller(target, "Thread A");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "Thread B");
// wait for threads to end
try
ob1.t.join();
ob2.t.join();
ob3.t.join();
catch (InterruptedException e)
{
System.out.println("Interrupted");
class ThreadDeadLock
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[])
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
private static class ThreadDemo1 extends Thread
public void run()
synchronized (Lock1)
System.out.println("Thread 1: Holding lock 1...");
try
Thread.sleep(10);
catch (InterruptedException e)
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2)
System.out.println("Thread 1: Holding lock 1 & 2...");
private static class ThreadDemo2 extends Thread
public void run()
synchronized (Lock2)
System.out.println("Thread 2: Holding lock 2...");
try
Thread.sleep(10);
catch (InterruptedException e)
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1)
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
class TwoThreadsExample
public static void main(String[] args)
new SimpleThread("Thread A").start();
new SimpleThread("Thread B").start();
class SimpleThread extends Thread
public SimpleThread(String str)
super(str);
public void run()
for (int i = 0; i < 5; i++)
System.out.println(i + " " + getName());
try
sleep((int) (Math.random() * 1000));
catch (InterruptedException e)
{
System.out.println("Exit! " + getName());
import java.util.Vector;
class BasicVectorOperations
public static void main(String a[])
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
System.out.println(vct);
//adding element at specified index
vct.add(2, "Random");
System.out.println(vct);
//getting elements by index
System.out.println("Element at index 3 is: " + vct.get(3));
//getting first element
System.out.println("The first element of this vector is: " + vct.firstElement());
//getting last element
System.out.println("The last element of this vector is: " + vct.lastElement());
//how to check vector is empty or not
System.out.println("Is this vector empty? " + vct.isEmpty());
import java.util.Vector;
class VectorClone
public static void main(String a[])
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
System.out.println("Actual vector:" + vct);
Vector<String> copy = (Vector<String>) vct.clone();
System.out.println("Cloned vector:" + copy);
import java.util.Vector;
class CopyVectorToArray
public static void main(String a[])
Vector<String> vct = new Vector<String>();
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
System.out.println("Actual vector:"+vct);
String[] copyArr = new String[vct.size()];
vct.copyInto(copyArr);
System.out.println("Copied Array content:");
for(String str:copyArr)
System.out.println(str);
import java.util.Vector;
class ClearVector
public static void main(String a[])
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
System.out.println("Actual vector:" + vct);
vct.clear();
System.out.println("After clear vector:" + vct);
import java.util.Enumeration;
import java.util.Vector;
class VectorEnumeration
public static void main(String a[])
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
Enumeration<String> enm = vct.elements();
while (enm.hasMoreElements())
System.out.println(enm.nextElement());
import java.util.Iterator;
import java.util.Vector;
class VectorIterator
public static void main(String a[])
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
Iterator<String> itr = vct.iterator();
while (itr.hasNext())
System.out.println(itr.next());
import java.util.Vector;
import java.util.*;
class VectorExample
public static void main(String[] args)
int n, index;
Vector v = new Vector();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of vector ");
n = sc.nextInt();
//Add Elements in the vector
System.out.println("Enter the elements in the vector");
for (index = 0; index < n; index++)
v.add(sc.nextInt());
}
//Displaying the elements
System.out.println("The elements are: ");
for (index = 0; index < n; index++)
System.out.print(v.get(index) + " ");
//Removing element from vector
System.out.println("\nEnter the index of the element to remove");
v.remove(sc.nextInt());
System.out.println("After removing, the remaining elements in the vector are:");
//display elements of Vector
for (index = 0; index < v.size(); index++)
System.out.print(v.get(index) + " ");
import java.util.List;
import java.util.Vector;
class VectorSubRange
public static void main(String a[])
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
vct.add("Click");
System.out.println("Actual vector:" + vct);
List<String> list = vct.subList(2, 4);
System.out.println("Sub List: " + list);