Java
Java
import java.util.*;
class AddTwoMatrix
int m, n;
this.first = first;
this.second = second;
this.m = m;
this.n = n;
int m, n, c, d;
m = in.nextInt();
n = in.nextInt();
first[c][d] = in.nextInt();
second[c][d] = in.nextInt();
System.out.print(first[c][d] + "\t");
System.out.println();
}
System.out.println("\nElements of Second matrix is : ");
System.out.print(second[c][d] + "\t");
System.out.println();
//call by reference
int c, d;
System.out.print(sum[c][d] + "\t");
System.out.println();
class ArrayCopyExample
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a',
System.out.println(new String(copyTo));
class ArrayCopyExample
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a',
System.out.println(new String(copyTo));
class ArrayCopyOfRangeExample {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a',
System.out.println(new String(copyTo));
class ArrayExample
int[] anArray;
anArray[0] = 100;
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;
class ArrayOfArraysAnimalDemo
{
System.out.print(animals[i][0] + ": ");
System.out.println();
class ArrayOperations
double total = 0;
total += myList[i];
max = myList[i];
import java.util.Arrays;
class ArraySort
// sorting array
Arrays.sort(iArr);
System.out.println(iArr[i]);
}
}
import java.io.*;
class ArrayAverage
//define an array
int[] numbers = new int[]{10, 20, 15, 25, 16, 60, 100};
int sum = 0;
import java.util.*;
class ArrayBasic
int[] arr;
int size, i;
Scanner sc = new Scanner(System.in);
size = sc.nextInt();
arr[i] = sc.nextInt();
import java.util.Scanner;
class Matrix_Create {
Scanner scan;
int matrix[][];
void create() {
scan = new Scanner(System.in);
System.out.println("Matrix Creation");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
for(int j=0; j
<column ; j++) {
matrix[i][j] =scan.nextInt();
void display() {
System.out.println();
class CreateAndDisplayMatrix {
args[]) {
obj.create();
obj.display();
class DisplayArrayForEach
System.out.println(element);
}
import java.util.*;
import java.text.DecimalFormat;
class DoubleMatrix
double[][] a;
double[] s;
row = sc.nextInt();
col = sc.nextInt();
a = new double[row][col];
s = new double[col];
a[i][j] = sc.nextDouble();
}
System.out.println("Double Matrix is : ");
System.out.println();
s[k] = sum;
k++;
sum = 0;
class PassingArraystoFunction
int[] a;
int size;
size = sc.nextInt();
a = new int[size];
a[i] = sc.nextInt();
addElements(a, size);
}
public static void addElements(int[] a , int size)
int sum = 0;
sum += a[i];
import java.util.*;
class ClosestValue
int a[];
int find;
int closest = 0;
a = new int[size];
a[i] = sc.nextInt();
System.out.println();
find = sc.nextInt();
for (int i : a)
closest = i;
distance = distanceI;
import java.io.*;
class MagicMatrix
int n = Integer.parseInt(br.readLine());
if (n > 5)
else
int i, j, k, t;
A[i][j] = 0;
if (n % 2 != 0)
i = 0;
j = n / 2;
k = 1;
while (k <= n * n)
A[i][j] = k++;
i = i + 2;
j--;
i = n - 1;
j = 0;
i = i + 2;
j--;
else
k = 1;
A[i][j] = k++;
j = n - 1;
t = A[i][i];
A[i][i] = A[j][j];
A[j][j] = t;
t = A[i][j];
A[i][j] = A[j][i];
A[j][i] = t;
j--;
System.out.print(A[i][j] + "\t");
System.out.println();
import java.util.Scanner;
class MatrixAddition {
Scanner scan;
void create() {
System.out.println("Matrix Addition");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
matrix1[i][j] = scan.nextInt();
matrix2[i][j] = scan.nextInt();
void display() {
System.out.print("\t" + matrix1[i][j]);
}
System.out.println();
System.out.print("\t" + matrix2[i][j]);
System.out.println();
void add() {
System.out.println();
class MatrixAdditionExample {
obj.create();
obj.display();
obj.add();
import java.util.Scanner;
class MatrixMultiplication
int m, n, p, q, sum = 0, c, d, k;
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
first[c][d] = in.nextInt();
p = in.nextInt();
q = in.nextInt();
if (n != p)
else
second[c][d] = in.nextInt();
}
multiply[c][d] = sum;
sum = 0;
System.out.print(multiply[c][d] + "\t");
System.out.print("\n");
}
import java.util.Scanner;
System.out.println();
System.out.println();
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);
result[i][j] = s.nextInt();
return result;
return result;
return result;
System.out.println();
import java.util.Scanner;
class Matrix_Subtraction {
Scanner scan;
void create() {
System.out.println("Matrix Subtraction");
row = Integer.parseInt(scan.nextLine());
column = Integer.parseInt(scan.nextLine());
matrix1 = new int[row][column];
matrix1[i][j] = scan.nextInt();
matrix2[i][j] = scan.nextInt();
void display() {
System.out.print("\t" + matrix1[i][j]);
System.out.println();
System.out.print("\t" + matrix2[i][j]);
System.out.println();
void sub() {
System.out.print("\t" + sub[i][j]);
System.out.println();
class MatrixSubtractionExample {
obj.create();
obj.display();
obj.sub();
class MergeArrayDemo
Integer a[]={1,2,3,4};
Integer b[]={5,6,7,0};
for(int i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
for(int i=0;i<b.length;i++)
System.out.print(b[i]+"\t");
for(int i=0;i<both.length;i++)
System.out.print(both[i]+"\t");
System.arraycopy(a, 0, c, 0, aLen);
return c;
import java.util.*;
class MiddleValue
int[] a;
double t;
size = sc.nextInt();
a = new int[size];
a[i] = sc.nextInt();
//Sorting
swap = a[j];
a[j + 1] = swap;
if (size % 2 == 0)
n = (size + 1) / 2;
else
}
import java.util.*;
class MirrorMatrix
row = in.nextInt();
column = in.nextInt();
matrix[i][j] = in.nextInt();
System.out.print(matrix[i][j] + "\t");
System.out.println("");
class MissingNumberArray
int a[] = {0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 21, 23};
findMissingNumbers(a, position);
if (position == a.length - 1)
return;
count++;
break;
if (flag)
flag = false;
findMissingNumbers(a, position);
class MultiDimArrayExample
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));
try
name = br.readLine();
emp_id = Integer.parseInt(br.readLine());
salary = Integer.parseInt(br.readLine());
catch (Exception e)
System.out.print("\n" + e);
class ObjectArray
int i;
emp[i].get_data();
emp[i].display();
import java.io.*;
class SortArray
int m = Integer.parseInt(br.readLine());
System.out.print("\nEnter the no. of columns: "); //enter number of columns
int n = Integer.parseInt(br.readLine());
System.out.println();
A[i][j] = Integer.parseInt(br.readLine());
System.out.print(A[i][j] + "\t");
System.out.println();
int t = 0;
{
for (int y = 0; y < n; y++)
t = A[x][y];
A[x][y] = A[i][j];
A[i][j] = t;
System.out.print(A[i][j] + "\t");
System.out.println();
import java.util.*;
class ArraySortingDemo
iArr[i] = in.nextInt();
// sorting array
Arrays.sort(iArr);
{
System.out.println("Number = " + number);
import java.io.*;
import java.util.*;
class SymmetricMatrix
int m, n, c, d;
m = in.nextInt();
n = in.nextInt();
if (m == n)
matrix[c][d] = in.nextInt();
}
transpose = new int[n][m];
transpose[d][c] = matrix[c][d];
System.out.print(transpose[c][d] + "\t");
System.out.print("\n");
if (matrix[c][d] != transpose[c][d])
break;
if (d != m)
break;
}
if (c == n)
System.out.println("Symmetric matrix.");
else
import java.util.*;
class TransposeMatrix
int i,j;
int r = sc.nextInt();
int c = sc.nextInt();
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
a[i][j] = sc.nextInt();
for(i=0;i<r;i++)
for(j=0;j<c;j++)
if(i<j)
a[j][i] = a[i][j];
a[i][j] = temp;
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.*;
Label lbl1,lbl2;
public FontTextLabel()
setLayout(new FlowLayout());
// construct Label
add(lbl1);
add(lbl2);
lbl1.setFont(myFont);
setTitle("AWT Elements");
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args)
// allocating an instance
import java.awt.*;
Label lblCount;
public LabelExample()
setLayout(new FlowLayout());
// construct Label
add(lblCount);
setTitle("AWT Elements");
setSize(200, 200);
setVisible(true);
{
// allocating an instance
import java.io.*;
class BufferedReaderExample
String str;
int i;
float f;
double d;
long l;
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());
class CommandLineArgs
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = Integer.parseInt(args[2]);
} else if (b > c) {
} else {
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
class ArrayListBasics
al.add("Java");
al.add("C");
al.add("C++");
al.add("php");
al.add("python");
al.add("css");
// add
al.add("html");
al.add(1, "Android");
System.out.println();
al.remove("php");
// Size of ArrayList
System.out.print("Size of ArrayList after removing php :" + al.size());
System.out.println();
System.out.println();
// list to array
Object[] a = al.toArray();
System.out.print("Array :");
System.out.println();
// change element
al.set(6, "Javascript");
System.out.println();
Collections.sort(al);
System.out.println();
//Index
al.clear();
System.out.print(al + " " + "Is list empty after clear :" + al.isEmpty());
import java.util.HashMap;
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();
//remove
hm.remove(2);
hm.remove(6, "html");
System.out.println("Size after remove operation :" + hm.size());
//replace
hm.replace(5, "jquery");
hm.clear();
import java.util.HashSet;
class HashSetBasic
hs.add("Java");
hs.add("Android");
hs.add("Php");
hs.add("Ajax");
System.out.println(hs);
hs.add("Python");
System.out.println(hs);
hs.remove("Php");
// Size of HashSet
System.out.println();
// HashSet to array
Object[] a = hs.toArray();
System.out.print("Array :");
System.out.println();
hs.clear();
System.out.print(hs + " " + "Is HashSet empty after clear :" + hs.isEmpty());
import java.util.TreeSet;
{
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);
//first element
//last element
//TreeSet to Array
Object[] a = ts.toArray();
System.out.print("Array :");
System.out.println();
// descending Set
System.out.println();
ts.remove(11);
//Size of TreeSet
ts.clear();
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
hm.put(1, "android");
hm.put(2, "java");
hm.put(3, "php");
hm.put(4, "c++");
hm.put(5, "javascript");
System.out.println();
while (iterator.hasNext())
System.out.println();
{
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
System.out.println();
+ hm.get(key));
import java.util.HashSet;
import java.util.Iterator;
class HashSetTest
al.add("Java");
al.add("Android");
al.add("Php");
al.add("Ajax");
System.out.println(al);
// Using Iterator
while (itr.hasNext())
{
System.out.println();
import java.util.Iterator;
import java.util.PriorityQueue;
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
while (itr.hasNext())
System.out.println();
System.out.println("head:" + queue.element());
System.out.println("head:" + queue.peek());
queue.remove();
queue.poll();
queue.remove("css");
{
System.out.print(object + " ");
System.out.println();
queue.clear();
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
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);
return (o2.getValue()).compareTo(o1.getValue());
});
import java.util.Map;
import java.util.TreeMap;
//TreeMap is sorted
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;
ts.add("java");
ts.add("php");
ts.add("android");
ts.add("css");
System.out.println(ts);
//using Iterator
while (itr.hasNext())
System.out.println();
{
System.out.print(string + " ");
import java.util.Scanner;
class Node
public Node()
next = null;
prev = null;
data = 0;
data = d;
next = n;
prev = p;
{
next = n;
prev = p;
return next;
return prev;
data = d;
return data;
}
class linkedList
public linkedList()
start = null;
end = null;
size = 0;
return size;
{
Node nptr = new Node(val, null, null);
if(start == null)
start = nptr;
end = start;
else
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
size++;
if(start == null)
start = nptr;
end = start;
else
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
size++;
}
if (pos == 1)
insertAtStart(val);
return;
if (i == pos)
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
ptr = ptr.getLinkNext();
size++ ;
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-- ;
if (i == pos)
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
if (size == 0)
System.out.print("empty\n");
return;
if (start.getLinkNext() == null)
System.out.println(start.getData() );
return;
ptr = start.getLinkNext();
ptr = ptr.getLinkNext();
System.out.print(ptr.getData()+ "\n");
}
public class DoublyLinkedList
char ch;
do
switch (choice)
case 1 :
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.print("Enter integer element to insert : ");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4 :
int p = scan.nextInt() ;
System.out.print("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
break;
case 6 :
break;
default :
break;
}
// Display List
list.display();
ch = scan.next().charAt(0);
import java.io.*;
class Stack
private char[] a;
m = max;
a = new char[m];
top = -1;
a[++top] = key;
return (a[top--]);
}
public char peek()
return (a[top]);
class Evaluation
private Stack s;
input = str;
s = new Stack(str.length());
int 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())
return output;
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:
while (!s.isEmpty())
return output;
char ch = input.charAt(i);
s.push(ch);
f.push('0');
else
f.pop();
if (f.isEmpty())
break;
if (!f.isEmpty())
f.pop();
f.push('1');
return output;
while (!s.isEmpty())
{
if (opTop == x)
s.push(opTop);
break;
else
int prec2;
prec2 = 1;
else
prec2 = 2;
s.push(opTop);
break;
s.push(opTop);
break;
else
if (x == ')')
else
}
}
s.push(opThis);
while (!s.isEmpty())
char ch = s.pop();
if (ch == x)
break;
else
if (x == ')')
output = ch + output;
else
class BinaryTreeTraversal
int n;
Evaluation ev;
System.out.println("MENU");
n = Integer.parseInt(br.readLine());
switch (n)
case 1:
s = br.readLine();
ev = new Evaluation(s);
break;
case 2:
s = br.readLine();
ev = new Evaluation(s);
break;
case 3:
s = br.readLine();
ev = new Evaluation(s);
default:
System.out.println("Invalid input");
System.out.println("Press y to continue");
check = br.readLine();
import java.util.*;
class Node
public Node()
link = null;
data = 0;
data = d;
link = n;
link = n;
data = d;
return link;
return data;
class linkedQueue
public linkedQueue()
{
front = null;
rear = null;
size = 0;
return size;
if (rear == null)
front = nptr;
rear = nptr;
else
rear.setLink(nptr);
rear = rear.getLink();
}
size++;
if (isEmpty())
front = ptr.getLink();
if (front == null)
rear = null;
size--;
return ptr.getData();
if (isEmpty())
return front.getData();
System.out.print("\nQueue = ");
if (size == 0)
System.out.print("Empty\n");
return;
ptr = ptr.getLink();
System.out.println();
class LinkedQueueImplement
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("5. Size");
do
switch (choice)
case 1:
lq.insert(scan.nextInt());
break;
case 2:
try
catch (Exception e)
break;
case 3:
try
catch (Exception e)
break;
case 4:
break;
case 5:
break;
default:
break;
// display queue
lq.display();
ch = scan.next().charAt(0);
import java.util.Scanner;
class Node
public Node()
link = null;
data = 0;
data = d;
link = n;
link = n;
data = d;
return link;
return data;
// Class linkedList
class linkedList
public linkedList()
start = null;
end = null;
size = 0;
return size;
size++;
if (start == null)
start = nptr;
end = start;
else
nptr.setLink(start);
start = nptr;
size++;
if (start == null)
start = nptr;
end = start;
else
end.setLink(nptr);
end = nptr;
pos = pos - 1;
if (i == pos)
ptr.setLink(nptr);
nptr.setLink(tmp);
break;
ptr = ptr.getLink();
size++;
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;
if (i == pos)
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
ptr = ptr.getLink();
size--;
if (size == 0)
System.out.print("empty\n");
return;
if (start.getLink() == null)
System.out.println(start.getData());
return;
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
char ch;
do
switch (choice)
case 1:
System.out.println("Enter integer element to insert");
list.insertAtStart(scan.nextInt());
break;
case 2:
list.insertAtEnd(scan.nextInt());
break;
case 3:
System.out.println("Enter position");
System.out.println("Invalid position\n");
else
list.insertAtPos(num, pos);
break;
case 4:
System.out.println("Enter position");
int p = scan.nextInt();
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5:
break;
case 6:
break;
default:
break;
/* Display List */
list.display();
ch = scan.next().charAt(0);
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Stack
Stack(int size)
top = -1;
if (top == item.length - 1)
{
System.out.println("Stack is Full");
else
item[++top] = data;
int popItem()
if (top < 0)
System.out.println("Stack Underflow");
return 0;
else
return item[top--];
void displayAll()
System.out.print(item[i] + "\t");
System.out.println("");
}
class StackDemo
int choice;
System.out.print("1).Push\n2).Pop\n3).Display\n4).Exit\n");
do
choice = Integer.parseInt(is.readLine());
switch (choice)
case 1:
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");
class MyOwnException
try
MyOwnException.myTest(null);
if (str == null)
public MyAppException()
super();
super(message);
this.message = message;
}
super(cause);
@Override
return message;
@Override
return message;
import java.util.Scanner;
class DivisionByZero
{
public static void main(String[] args)
int a, b, result;
a = input.nextInt();
b = input.nextInt();
// try block
try
result = a / b;
// catch block
catch (ArithmeticException e)
}
import java.net.MalformedURLException;
import java.net.URL;
class MyMultipleCatchBlocks
mmcb.execute(1);
mmcb.execute(2);
try
if (i == 1)
getIntValue("7u");
else
getUrlObj("www.junksite.com");
}
+ nfe.getMessage());
+ mue.getMessage());
return Integer.parseInt(num);
}
class MyExplicitThrow
try
System.out
+ met.getStringSize("WRONG"));
+ met.getStringSize(null));
{
System.out.println("Exception message: " + ex.getMessage());
if (str == null)
return str.length();
class UsingFinally
try
int a = 3 / 0;
System.out.println(a);
}
catch (Exception e)
System.out.println(e);
finally
import java.net.MalformedURLException;
import java.net.URL;
class MyTryBlockOnly
try
finally
{
import java.io.IOException;
class UsingThrows
m();
void p()
try
{
n();
catch (Exception e)
System.out.println("exception handled");
obj.p();
System.out.println("normal flow...");
import java.io.*;
class CopyFile
FileReader in = null;
FileWriter out = null;
try
in = new FileReader("input.txt");
int c;
out.write(c);
finally
if (in != null)
in.close();
if (out != null)
out.close();
import java.io.*;
class CreateDirectoryTest
if (new File("docs").mkdir())
else
import java.io.*;
class CreateFileTest
try
if (new File("output.txt").createNewFile())
else
catch (IOException e)
System.err.println(e.getMessage());
import java.io.File;
return exists;
import java.io.File;
class FileDeleteTest
return exists;
System.out.println("The following " + type + " called " + filename + (deleteFile(filename) ? " was
deleted." : " does not exist."));
}
test("file", "Main.java");
import java.io.*;
class ReadBinaryFile
try
int total = 0;
int nRead = 0;
while ((nRead = inputStream.read(buffer)) != -1)
System.out.println(new String(buffer));
total += nRead;
// ex.printStackTrace();
finally
try
if (inputStream != null)
inputStream.close();
}
}
catch (IOException e)
import java.io.*;
class ReadFile
try
{
System.out.println(line);
// ex.printStackTrace();
finally
try
if (bufferedReader != null)
bufferedReader.close();
catch (IOException e)
import java.io.*;
class Employee implements java.io.Serializable
class SerializeDemo
e.id = 007;
e.number = 5893254;
try
out.writeObject(e);
out.close();
fileOut.close();
catch (IOException i)
i.printStackTrace();
}
}
import java.io.*;
class WriteBinaryFile
try
bufferedWriter.write("Hello there,");
bufferedWriter.newLine();
bufferedWriter.close();
}
// ex.printStackTrace();
finally
try
if (bufferedWriter != null)
bufferedWriter.close();
catch (IOException e)
import java.io.*;
class WriteFile
{
// The name of the file to open.
try
bufferedWriter.write("Hello there,");
bufferedWriter.newLine();
// ex.printStackTrace();
finally
try
{
if (bufferedWriter != null)
bufferedWriter.close();
catch (IOException e)
class CalculateCircleAreaExample
int radius = 3;
/*
*/
import java.util.Scanner;
class AreaOfRectangle
//Area = length*width;
import java.util.*;
class AreaOfSquare
side = sc.nextInt();
import java.util.*;
class BinaryCalculator
import java.io.*;
class BinaryToDecimal
/*
*/
import java.io.*;
class BinaryToOctal
num = br.readLine();
import java.util.Scanner;
class CalculateMean
int counter;
float mean;
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:");
inputNum = NumScanner.nextInt();
System.out.println();
System.out.println("The mean of the " + counter + " numbers you entered is " + mean);
import java.lang.*;
import java.util.Scanner;
class CalculateInterest
p = s.nextDouble();
n = s.nextDouble();
si = (p * n * r) / 100;
ci = p * Math.pow(1.0 + r / 100.0, n) - p;
import java.util.Scanner;
import java.io.*;
class Calculator
int choice;
int x = 0;
int y = 0;
int sum;
PrintStream out;
Scanner input;
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");
choice = input.nextInt();
choice = input.nextInt();
if (choice != 99)
{
System.out.println("Please enter 2 numbers only: ");
x = input.nextInt();
y = input.nextInt();
switch (choice)
case 1:
break;
case 2:
break;
case 3:
case 4:
try
catch (Exception e)
System.out
break;
case 5:
break;
case 6:
break;
input.close();
System.out.println("Ending program...");
catch (Exception e)
e.printStackTrace();
int sum;
int sum;
return sum;
int sum;
return sum;
int sum;
return sum;
}
public int mod(int num1, int num2)
int sum;
return sum;
int sum = 1;
if (exp == 0)
sum = 1;
exp--;
return sum;
}
import java.util.*;
class CelsiustoFahrenheit
double temperature;
temperature = in.nextInt();
import java.util.Scanner;
class DecimalToBinary
if (n == 0)
return "0";
while (n > 0)
{
int rem = n % 2;
n = n / 2;
return binary;
import java.util.*;
class FahrenheitToCelsius
float temperature;
temperature = in.nextInt();
import java.util.*;
class FractionAdding
float a, b, c, d;
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();
System.out.print("Fraction Addition : [( " + a + " * " + d + " )+( " + b + " * " + c + " ) / ( " + b + " * "
+ d + " )] = " + (((a * d) + (b * c)) / (b * d)));
import java.util.*;
class FractionSubtraction
float a,b,c,d;
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();
import java.util.*;
class GCDExample
System.out.println("GCD of two numbers " + number1 + " and " + number2 + " is :" +
findGCD(number1, number2));
//base case
if (number2 == 0)
return number1;
import java.util.Scanner;
class GCDLCM
int x, y;
x = sc.nextInt();
y = sc.nextInt();
System.out.println("GCD of two numbers is : " + gcd(x, y));
int r = 0, a, b;
r = b;
while (a % b != 0)
r = a % b;
a = b;
b = r;
return r;
int a;
while (true)
if (a % x == 0 && a % y == 0)
return a;
}
++a;
import java.util.*;
class HarmonicSeries
int num, i = 1;
num = in.nextInt();
i++;
}
import java.io.*;
class HexToDecimal
/*
*/
import java.util.Scanner;
class MultiplicationTable
{
int n, c;
System.out
n = in.nextInt();
import java.util.Scanner;
class Tables {
int a, b, c, d;
System.out
a = in.nextInt();
b = in.nextInt();
import java.io.*;
class OctalToDecimal
/*
*/
}
}
/*
Pythagorean Triplet:
*/
class PythagoreanTriplet
int csquared = a * a + b * b;
if (croot == Math.ceil(croot))
class QuadraticEquation
{
/*
* not equal to 0
* Hence a = 2, b = 6 and c = 4.
*/
int a = 2;
int b = 6;
int c = 4;
System.out
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class SquareRoot
{
int number = 0;
System.out.println("Enter a number");
try
number = Integer.parseInt(line);
}
}
import java.util.*;
class Cylinder
double PI = 3.14;
double r = sc.nextDouble();
double h = sc.nextDouble();
double volume = PI * r * r * h;
import java.awt.*;
import javax.swing.JFrame;
{
Toolkit t = Toolkit.getDefaultToolkit();
Image i = t.getImage("bugs.gif");
f.add(m);
f.setSize(300, 300);
f.setVisible(true);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
CardLayout card;
Container c;
CardLayoutDemo()
c = getContentPane();
c.setLayout(card);
b1 = new JButton("Card 1.");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a", b1);
c.add("b", b2);
c.add("c", b3);
card.next(c);
cl.setSize(400, 400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
import java.awt.*;
import javax.swing.JFrame;
Toolkit t = Toolkit.getDefaultToolkit();
Image i = t.getImage("bugs.gif");
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;
public ExitButtonExample()
{
initUI();
getContentPane().add(panel);
panel.setLayout(null);
quitButton.addActionListener(new ActionListener()
@Override
System.exit(0);
});
panel.add(quitButton);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
@Override
ex.setVisible(true);
});
import java.awt.*;
import javax.swing.*;
class FlowLayoutDemo
FlowLayoutDemo()
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300, 300);
f.setVisible(true);
new FlowLayoutDemo();
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
gridbag.setConstraints(b, gbc);
b.setBackground(Color.lightGray);
add(b);
{
GridBagLayout gridbag = new GridBagLayout();
setLayout(gridbag);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridx = 2;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbl.init();
f.add("Center", gbl);
f.pack();
f.setSize(f.getPreferredSize());
f.show();
f.addWindowListener(new WindowAdapter()
System.exit(0);
});
import java.awt.*;
import javax.swing.*;
class MyGridLayoutExample
JFrame f;
MyGridLayoutExample()
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.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;
super("JButton Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(button);
button.requestFocus();
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;
public AboutDialog()
initUI();
label.setAlignmentX(0.5f);
add(label);
name.setAlignmentX(0.5f);
add(name);
close.addActionListener(new ActionListener()
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);
new AboutDialog();
import javax.swing.*;
class JFrameHelloWorld
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
javax.swing.SwingUtilities.invokeLater(new Runnable()
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
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
greenMenuBar.setOpaque(true);
yellowLabel.setOpaque(true);
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable()
createAndShowGUI();
}
});
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;
String ButtonLabels;
new JOptionPaneDemo();
}
public JOptionPaneDemo()
super("JOptionPane Demo");
addWindowListener(new WindowListener());
contentPane = getContentPane();
jbnDialog.addActionListener(this);
jplButton.add(jbnDialog);
contentPane.add(jplButton);
createRadioButtonGroupings();
pack();
setVisible(true);
dialogTypeButtonGroup.add(dialogTypeButtons[i]);
jplDialogType.add(dialogTypeButtons[i]);
contentPane.add(jplDialogType);
messageTypeButtonGroup.add(messageTypeButtons[i]);
jplMessageType.add(messageTypeButtons[i]);
contentPane.add(jplMessageType);
buttonTypeButtonGroup.add(optionTypeButtons[i]);
jplButtonType.add(optionTypeButtons[i]);
contentPane.add(jplButtonType);
System.exit(0);
{
/*
* dialogTypeButtons =
*/
if (dialogTypeButtons[0].isSelected())
else if (dialogTypeButtons[1].isSelected())
else if (dialogTypeButtons[2].isSelected())
else if (dialogTypeButtons[3].isSelected())
if (buttons[i].isSelected())
return (types[i]);
return (types[0]);
substrings[i] = tok.nextToken();
return (substrings);
import javax.swing.JOptionPane;
class JOptionDemo
int age = 0;
age = Integer.parseInt(strAge);
import java.awt.*;
import javax.swing.*;
Container c;
JPanel panel;
c = getContentPane();
c.setLayout(new BorderLayout());
int b = 1;
b++;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
c.add(jsp, "Center");
/*
</applet>
*/
import javax.swing.*;
class JTableDemo
JFrame f;
JTableDemo()
f = new JFrame();
String data[][] = {
f.add(sp);
f.setSize(300, 400);
f.setVisible(true);
new JTableDemo();
import java.awt.Color;
import javax.swing.*;
class TextAreaExample
JTextArea area;
JFrame f;
TextAreaExample()
f = new JFrame();
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);
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
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
panel.setLayout(null);
panel.add(userLabel);
panel.add(userText);
panel.add(passwordLabel);
panel.add(passwordText);
panel.add(loginButton);
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();
statusbar.setBorder(BorderFactory
.createEtchedBorder(EtchedBorder.RAISED));
panel.setLayout(null);
close.addActionListener(new ButtonListener());
open.addActionListener(new ButtonListener());
find.addActionListener(new ButtonListener());
JButton save = new JButton("Button 4");
save.addActionListener(new ButtonListener());
panel.add(close);
panel.add(open);
panel.add(find);
panel.add(save);
add(panel);
add(statusbar, BorderLayout.SOUTH);
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
{
SwingUtilities.invokeLater(new Runnable()
ms.setVisible(true);
});
import javax.swing.JFrame;
public SimpleJFrameExample()
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public TooltipExample() {
initUI();
getContentPane().add(panel);
panel.setLayout(null);
panel.setToolTipText("This is panel");
btn.setToolTipText("This is a button");
panel.add(btn);
setTitle("Tooltip");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
@Override
ex.setVisible(true);
});
//update statement.
//expression.
class ContinueExample
if (x == 30)
continue;
System.out.print(x);
System.out.print("\n");
class DoWhileLoop
int x = 1;
do
x++;
class ForEachExample
{
public static void main(String args[])
class WhileLoop
int x = 1;
x++;
class LogBase10Value
class CeilValue
class CubeRoot
class ExponentialValue
class HypotenuseValue
{
class MyCopySign
+ Math.copySign(46.8, -90));
+ Math.copySign(-23.1, 45));
class NextAfterValue
+ Math.nextAfter(9, 6));
+ Math.nextAfter(13, 18));
}
class NextUpValue
class SigNumValue
class MathPower
class LogValue
class RadTodeg
class CosValue
class SineValue
class TanValue
{
public static void main(String a[])
import java.math.*;
import java.io.*;
class BigIntegerDemo
f = Integer.parseInt(br.readLine());
int powerOfTwoCount = 0;
powerOfTwoCount++;
fact = fact.divide(two);
result = result.multiply(BigInteger.valueOf(i));
return result;
class Bike
String name;
this.name = name;
this.cc = cc;
this.model = model;
this.days = days;
if (days == 1)
r = 500;
System.out.println(r);
else if (days == 2)
r = 400;
System.out.println(r);
r = 350;
System.out.println(r);
if (days == 1)
r = 600;
System.out.println(r);
else if (days == 2)
r = 500;
System.out.println(r);
}
r = 500;
System.out.println(r);
if (days == 1)
r = 800;
System.out.println(r);
else if (days == 2)
r = 700;
System.out.println(r);
r = 850;
System.out.println(r);
b.rent();
import java.io.*;
class BinaryAddition
int k = 1;
while (num1 != 0)
k = k * 2;
k = 1;
while (num2 != 0)
k = k * 2;
System.out.println();
class MyBasicBoolean
boolean b1 = true;
System.out.println(bObj1.booleanValue());
}
import java.util.*;
import java.text.*;
class CalendarTask
printCalendar(2016, 2);
if (d % 7 == 1)
mons[m][2 + (d - 1) / 7] = entry;
else
mons[m][2 + (d - 1) / 7] += entry;
date.add(Calendar.MONTH, 1);
System.out.println();
}
System.out.println();
class Number
int x;
class CallByValue
int y = 4;
//call by value
increase(y);
//call by reference
n.x = 3;
increment(n);
n.x = n.x + 1;
class CommandLineExample
import java.io.*;
class VowelsConsonants
String str;
char ch;
str = br.readLine();
for (int i = 0; i < str.length(); i++)
ch = str.charAt(i);
vowels++;
else if (Character.isDigit(ch))
num++;
else if (Character.isWhitespace(ch))
blanks++;
else
cons++;
class StaticExample
static int st = 0;
int ns = 0;
StaticExample()
{
ns++;
System.out.println(ns);
st++;
System.out.println(st);
import java.util.*;
import java.text.DecimalFormat;
class CurrencyConverter
{
double rupee, dollar, pound, code, euro, yen;
code = sc.nextInt();
if (code == 1)
rupee = sc.nextFloat();
else if (code == 2)
else if (code == 3)
pound = sc.nextFloat();
else if (code == 4)
euro = sc.nextFloat();
else if (code == 5)
yen = sc.nextFloat();
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
Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed
//words way
//using DateFormat
System.out.println(format1.format(date));
System.out.println(format2.format(date));
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
class TimeZoneExample
System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
}
private static String displayTimeZone(TimeZone tz)
- TimeUnit.HOURS.toMinutes(hours);
minutes = Math.abs(minutes);
if (hours > 0)
else
return result;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
class EmailValidation
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if (result)
else
String s = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-
z]{2,})$";
Matcher m = emailPattern.matcher(email);
return m.matches();
class FizzBuzz
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
}
}
class Animal
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
class KeyboardMacroDemo
frame.add(new JLabel(directions));
frame.addKeyListener(new KeyAdapter()
frame.setTitle("Hello there");
frame.setTitle("");
});
frame.pack();
frame.setVisible(true);
import java.util.*;
class LargestNumber
num2 = sc.nextInt();
else
import java.io.*;
class LeapYear
else
System.out.println("Year " + year + " is not a leap year");
import java.util.*;
class Marksheet
int marks;
marks = sc.nextInt();
}
else if (marks >= 40 && marks < 50)
class MyRintEx
import java.util.*;
class GuessGame
int numberoftries = 0;
boolean f = false;
int guess;
Scanner sc = new Scanner(System.in);
try
while(f == false)
guess = sc.nextInt();
numberoftries++;
if(guess == numbertoguess)
f = true;
else
System.out.println("\nYou win");
System.out.println("Number was : "+numbertoguess);
catch(Exception e)
import java.awt.*;
import javax.swing.*;
this.length = length;
setDoubleBuffered(true);
@Override
g.setColor(Color.WHITE);
while (true)
repaint();
try
{
Thread.sleep(15);
@Override
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}
class MyBooleanConstants
+ Boolean.FALSE);
+ Boolean.TRUE);
class Alphabets
char c = 'A';
do
System.out.println(c);
c++;
import java.util.*;
class PrintCurrentDateandTime
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 time is " + hour + " : " + minute + " : " + second);
import java.util.*;
class RemoveZero
int a, x, b;
char z;
System.out.println("Enter a number");
str = sc.next();
x = str.length();
z = str.charAt(i);
if (z == '0')
else
k += z;
import java.util.Scanner;
class ScannerClassExample
int intNum;
long longNum;
float floatNum;
double doubleNum;
String line;
String str;
Scanner in = new Scanner(System.in);
line = in.nextLine();
str = in.next();
intNum = in.nextInt();
longNum = in.nextLong();
floatNum = in.nextFloat();
doubleNum = in.nextDouble();
import java.util.*;
class SquareRootWithoutInbuiltFunction
int number;
double t, squareroot;
System.out.println("Enter a Number");
number = sc.nextInt();
squareroot = number / 2;
do
t = squareroot;
import java.util.*;
class StackDemo
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println(a);
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
System.out.println(bool);
class TestStatic
TestStatic.InnerClass.InnerMethod();
import java.io.*;
class Validation
System.out.println("Enter username");
username = br.readLine();
System.out.println("Enter password");
password = br.readLine();
System.out.println();
System.out.println("Enter username");
user1 = br.readLine();
System.out.println("Enter password");
pass1 = br.readLine();
else
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.text.DateFormat;
class ZodiacSigns
System.out.println(df.format(calendar.getTime()));
int day = 0;
int month = 0;
int year = 0;
while (true)
// Read in a date
year = readInt();
while (true)
month = readInt();
if (validMonth(--month))
break;
while (true)
{
day = readInt();
break;
signStartDates[i].set(GregorianCalendar.YEAR, year);
signStartDates[(i + 1) % signStartDates.length]))
break;
if (!yes())
break;
}
}
return true;
else
return false;
- between 1 and 31
- less than 29 when the month is February and it is not a leap year
*/
return false;
System.out.println(
"Day values must be less than 31 when the month" + " is " + MONTH_NAMES[month] + ".
Try again.");
return false;
System.out.println(year + " is not a leap year so day values must be less than 29. Try again.");
return false;
return false;
return true;
int value = 0;
while (true)
try
value = Integer.parseInt(in.readLine().trim());
return value;
}
catch (NumberFormatException e)
catch (IOException e)
while (true)
try
str = in.readLine().trim();
catch (IOException e)
if (str.equalsIgnoreCase("Y"))
return true;
else if (str.equalsIgnoreCase("N"))
{
break;
else
return false;
// Keyboard input
// 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"};
};
//Amicable Number
import java.util.Scanner;
class AmicableNumber
int a, b;
a = in.nextInt();
b = in.nextInt();
if (flag)
else
{
System.out.println("The numbers are not amicable");
int s = 0, i;
if (a % i == 0)
s = s + i;
if (s == b)
s = 0;
if (b % i == 0)
s = s + i;
if (s == a)
return true;
else
return false;
return false;
}
}
import java.util.*;
class ArmstrongNumber
n = in.nextInt();
temp = n;
while (temp != 0)
r = temp % 10;
sum = sum + r * r * r;
if (n == sum)
else
import java.util.Scanner;
class AutomorphicNumber
{
if (squareAsString.endsWith(inputAsString))
else
import java.io.*;
class BuzzNumber
a = Integer.parseInt(br.readLine());
if (a % 10 == 7 || a % 7 == 0)
else
bn.show();
import java.util.*;
class Prime
int n, i, res;
res = n % i;
if (res == 0)
flag = false;
break;
if (flag)
else
import java.io.*;
class AmicableNumber
int s = 0, i;
if (a % i == 0)
s = s + i;
}
if (s == b)
s = 0;
if (b % i == 0)
s = s + i;
if (s == a)
return true;
else
return false;
return false;
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
if (check(a, b))
{
else
class CommnElements
if (arr1[i] == arr2[j])
System.out.println(arr1[i]);
import java.util.Scanner;
class CompareStrings
s1 = in.nextLine();
s2 = in.nextLine();
if (s1.compareTo(s2) > 0)
else
import java.io.*;
import java.util.*;
class NumberToWord
"",
" ten", " twenty", " thirty", " forty", " fifty",
"", " one", " two", " three", " four", " five", " six",
" seven", " eight", " nine", " ten", " eleven", " twelve",
String current;
number /= 100;
else
number /= 10;
number /= 10;
if (number == 0)
return current;
return numNames[number] + " hundred" + current;
if (number == 0)
return "zero";
if (number < 0)
number = -number;
prefix = "negative";
int place = 0;
do
if (n != 0)
String s = convertLessThanOneThousand(n);
place++;
number /= 1000;
System.out.println();
import java.text.DecimalFormat;
import java.io.*;
class EnglishNumberToWords
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
String soFar;
if (number % 100 < 20)
number /= 100;
else
number /= 10;
number /= 10;
if (number == 0)
return soFar;
if (number == 0)
return "zero";
snumber = df.format(number);
// XXXnnnnnnnnn
// nnnXXXnnnnnn
// nnnnnnXXXnnn
// nnnnnnnnnXXX
String tradBillions;
switch (billions)
case 0:
tradBillions = "";
break;
case 1:
tradBillions = convertLessThanOneThousand(billions)
break;
default:
tradBillions = convertLessThanOneThousand(billions)
String tradMillions;
switch (millions)
{
case 0:
tradMillions = "";
break;
case 1:
tradMillions = convertLessThanOneThousand(millions)
break;
default:
tradMillions = convertLessThanOneThousand(millions)
String tradHundredThousands;
switch (hundredThousands)
case 0:
tradHundredThousands = "";
break;
case 1:
break;
default:
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
number = br.readLine();
import java.io.*;
class Disarium
x = n;
sum = 0;
rev = 0;
while (n > 0)
n = n / 10;
}
c++;
if (sum == x)
else
ob.show(Integer.parseInt(br.readLine()));
import java.io.*;
class DuckNumber
int l = n.length();
int c = 0;
char ch;
ch = n.charAt(i);
if (ch == '0')
c++;
char f = n.charAt(0);
else
import java.util.Scanner;
class Factorial
int fact = 1;
int number = 0;
number = in.nextInt();
fact = i * fact;
import java.util.*;
class FactorialExample
int a;
a = scanner.nextInt();
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
import java.io.*;
class Factors
int a, i;
a = Integer.parseInt(buf.readLine());
System.out.print("\n");
if (a % i == 0)
System.out.print(i + ",");
System.out.print(a);
import java.io.*;
import java.lang.*;
class Fibonacci
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
import java.util.Scanner;
class Fibonacci
{
if (n == 0)
return 0;
if (n == 1)
return 1;
else
int n = sc.nextInt();
System.out.print(fibo(i) + "\t");
import java.util.Scanner;
class OddOrEven
int x;
x = in.nextInt();
if (x % 2 == 0)
else
import java.util.*;
class PerfectSquare
float s;
start = sc.nextInt();
end = sc.nextInt();
System.out.println("The Perfect Square numbers present in the range " + start + " to " + end + "
are : ");
s = (float) Math.sqrt(i);
n = (int) Math.floor(s);
if (s == n)
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;
BigInteger a, b, c;
a = new BigInteger(num);
b = new BigInteger(reverse(num));
resultantPalindrome(a.add(b) + "");
{
if (num.equals(reverse(num)))
else
addNum(num);
return sb.reverse().toString();
try
palindrome = num.readLine();
catch (IOException e)
System.out.println(e.getMessage());
System.out.println("");
ResultantPalindrome rp = new ResultantPalindrome();
rp.resultantPalindrome(palindrome);
class FloorValue
import java.util.Scanner;
class Greatest
num = data.nextInt();
max = data.nextInt();
// Reading other number
temp = data.nextInt();
continue;
else
// largest number
max = temp;
import java.util.Scanner;
class HailStone
if (num % 2 == 0)
System.out.print(num + "\t");
}
else
System.out.print(num + "\t");
import java.io.*;
class HappyNumber
int n;
HappyNumber()
n = 0;
n = num;
int sum_sq_digits(int x)
if (x == 0)
return 0;
else
{
int d = x % 10;
void isHappyNumber()
int a = sum_sq_digits(n);
while (a > 9)
a = sum_sq_digits(a);
if (a == 1)
else
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");
int m = sc.nextInt();
int n = sc.nextInt();
int h = 1;
int p = m * n;
h = i;
int l = p / h;
import java.util.*;
class KaprekarNumber
int digitcount(int x)
{
int digit = 0;
while (x != 0)
digit++;
x /= 10;
return digit;
int digits;
n = sc.nextInt();
sq = n * n;
if (temp == n)
else
import java.io.*;
class KeithNumber
int n = Integer.parseInt(br.readLine());
int copy = n;
String s = Integer.toString(n);
int d = s.length();
int i = d, sum = 0;
sum = 0;
arr[i] = sum;
i++;
if (sum == n)
else
import java.io.*;
class KrishnaMurthyNumber
int fact(int n)
int i, fact = 1;
fact = fact * i;
}
return fact;
if (kmn.isKrishnaMurthy(number))
else
int temp, k = 0;
int n = number;
k = k + fact(temp);
if (k == n)
return true;
else
return false;
import java.util.Scanner;
class LargestOfThreeNumbers
int x, y, z;
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
else
import java.io.*;
class LargestSmallest
arr[i] = Integer.parseInt(br.readLine());
{
int temp = arr[j];
arr[j + 1] = temp;
System.out.println();
/*
In Lucas Series, each subsequent number is the sum of the previous two,
*/
import java.util.*;
class LucasSeries
limit = sc.nextInt();
num1 = 2;
num2 = 1;
System.out.println("\nLucas Series:");
num1 = num2;
num2 = add;
import java.io.*;
class MagicNumber
return Integer.parseInt(br.readLine());
do
flag = 0;
while (n % 10 == 0)
n /= 10;
while (n % 10 != 0 || n > 0)
sum += (n % 10);
n /= 10;
n = sum;
sum = 0;
else
flag = 1;
if (sum == 1)
return true;
else
return false;
else
import java.io.*;
class NeonNumber
int num;
int square;
int sum = 0;
num = Integer.parseInt(br.readLine());
if (sum == num) //checking if the sum of the square is equal to the number entered
import java.util.*;
class Niven_number
int n = sc.nextInt();
int c = n, d, sum = 0;
while (c > 0)
d = c % 10;
sum = sum + d;
c = c / 10;
if (n % sum == 0)
else
//whose meaning may be interpreted the same way in either forward or reverse direction.
import java.util.Scanner;
class Palindrome
int number = 0;
int reverse = 0;
int numCopy = 0;
number = in.nextInt();
numCopy = number;
if (number == reverse)
else
System.out.println("The number " + number + " is not a Palindrome.");
class PalindromePrime
int count = 1;
if (count % 10 == 0)
System.out.println();
if (count == 20)
break;
count++;
}
}
return true;
if (num % i == 0)
return false;
return true;
int result = 0;
while (num != 0)
num /= 10;
}
return result;
import java.io.*;
class PerfectNumber
int n, s = 0;
n = Integer.parseInt(br.readLine());
if (n % x == 0)
s = s + x;
if (s == n)
else
import java.io.*;
class PrimeFactors
boolean b = true;
if (a % i == 0)
b = false;
return b;
int a = Integer.parseInt(in.readLine());
if (a % i == 0)
boolean b = o.prime(i);
if (b == true)
import java.util.*;
class PrimeNumbers
n = in.nextInt();
if (n >= 1)
System.out.println(2);
if (num % j == 0)
status = 0;
break;
if (status != 0)
System.out.println(num);
count++;
status = 1;
num++;
import java.util.Scanner;
class PrimorialNumber
int num;
num = in.nextInt();
flag = 0;
for (int j = 2; j < i; j++)
if (i % j == 0)
flag = 1;
break;
if (flag != 1)
res *= i;
import java.util.*;
class RandomNumber
{
System.out.println(r.nextInt(1000));
import java.util.Scanner;
class ReverseNum
number = sc.nextInt();
sc.close();
while (number != 0)
import java.io.*;
class RomanToDecimal
{
int decimal = 0;
int lastNumber = 0;
switch (convertToDecimal)
case 'M':
lastNumber = 1000;
break;
case 'D':
lastNumber = 500;
break;
case 'C':
lastNumber = 100;
break;
case 'L':
lastNumber = 50;
break;
case 'X':
decimal = processDecimal(10, lastNumber, decimal);
lastNumber = 10;
break;
case 'V':
lastNumber = 5;
break;
case 'I':
lastNumber = 1;
break;
else
try
roman = br.readLine();
catch (IOException e)
System.out.println(e.getMessage());
romanToDecimal(roman);
import java.io.*;
class SpecialNumber
num = Integer.parseInt(br.readLine());
while (temp % 10 != 0)
temp /= 10;
if (spec == n)
return true;
else
return false;
if ((n == 1) || (n == 0))
return 1;
else
obj.input();
if (obj.isSpecial(num))
else
}
import java.util.Scanner;
class SquareRoot
int n;
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
int n, n1;
double x;
System.out.println("Enter number");
n = sc.nextInt();
n1 = n + 1;
x = Math.sqrt(n1);
if ((int) x == x)
else
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Swapping
int a = 10;
int b = 15;
b = a - b;
a = a - b;
a = 10;
b = 15;
a = a ^ b;
b = a ^ b;
a = a ^ b;
a = 10;
b = 15;
a = a * b;
b = a / b;
a = a / b;
/*
Working of Formula :
*/
a = 10;
b = 15;
a = b - a + (b = a);
import java.util.Scanner;
class SwapNumbers
int x, y, temp;
x = in.nextInt();
y = in.nextInt();
System.out.println("Before Swapping\nx = " + x + "\ny = " + y);
temp = x;
x = y;
y = temp;
class TopTwoMaxNumber
int maxOne = 0;
int maxTwo = 0;
if (maxOne < n)
maxTwo = maxOne;
maxOne = n;
maxTwo = n;
}
public static void main(String args[])
ttmn.printTwoMaxNumbers(num);
import java.util.*;
import java.io.*;
class Tribonacci
int n = sc.nextInt();
int a = 0, b = 0, c = 1;
int d = a + b + c;
System.out.print("\t" + d);
a = b;
b = c;
c = d;
d = a + b + c;
}
System.out.println();
class TwinPrimes
int j = 0;
int LastPrime = 1;
if (i % j == 0)
break;
if (i == j)
if ((i - LastPrime) == 2)
{
LastPrime = i;
import java.io.*;
class UniqueNumber
int n = Integer.parseInt(br.readLine());
int l = s.length();
int flag = 0; /* loop for checking whether there are repeated digits */
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)
else
void draw()
System.out.println("Draw Rectangle");
void draw()
System.out.println("Draw Traingle");
}
class AbstractTest
s1.draw();
s1 = new Traingle();
s1.draw();
class AddressDetails
int flatno;
String blgd;
String city;
this.flatno = flatno;
this.blgd = blgd;
this(flatno, blgd);
this.city = city;
}
void display()
e1.display();
e2.display();
// class name
class Circle
// methods
double getRadius()
// method body
}
String getColor()
// method body
class CircleDemo
//Creating an object
//print color
System.out.println(color);
// class name
class CircleTest
// methods
double getRadius()
// method body
String getColor()
// method body
class Student
String student_name;
this.student_name = student_name;
return student_name;
}
class ConstructorTest
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;
id = i;
name = n;
age = a;
void display()
}
public static void main(String[] args)
co.display();
co1.display();
class EncapsulationExample
this.manufacturer = manufac;
this.operating_system = operatSys;
this.model = mod;
this.cost = cst;
return this.model;
}
public String getManufacturer()
return this.manufacturer;
return this.cost;
return this.operating_system;
interface A
interface B extends A
{
interface C extends A
class D implements B, C
System.out.println("MethodA");
System.out.println("MethodB");
System.out.println("MethodC");
obj1.methodA();
obj1.methodB();
obj1.methodC();
class Parent
String name;
String name;
super.name = "Parent";
name = "Child";
obj.displaydetails();
class Box
double width;
double height;
double depth;
Box()
width = w;
height = h;
depth = d;
void getVolume()
double weight;
MatchBox()
super(w, h, d);
weight = m;
mb1.getVolume();
class Parent
return name;
return address;
System.out.println(obj.getName());
System.out.println(obj.getAddress());
interface MyInterface
interface MyOtherInterface
{
System.out.println("Hello");
System.out.println("Goodbye");
obj.sayHello();
obj.sayGoodbye();
class MethodOverloading
}
}
class MethodOverloadingTest
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
A a = new A();
B b = new B();
C c = new C();
a.display();
b.display();
c.display();
//implementation of a bicycle
class BicycleDemo
// 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;
cadence = newValue;
}
void changeGear(int newValue)
gear = newValue;
void printStates()
class Car
public Car()
System.out.println("Class Car");
}
}
public Maruti()
System.out.println("Class Maruti");
System.out.println("Brand: Maruti");
System.out.println("Max: 90Kmph");
public Maruti800()
System.out.println("Max: 80Kmph");
obj.brand();
obj.speed();
class ParameterizedConstructor
int addition;
class Demo
int addition;
{
Demo p = new Demo(30, 40);
class SuperClass
void display()
void display()
s.display();
import java.io.*;
class Student
this.roll_no = roll_no;
this.name = name;
void display()
this.mark1 = mark1;
this.mark2 = mark2;
void display_marks()
class SingleInheritance
String name;
roll_no = Integer.parseInt(br.readLine());
name = br.readLine();
mark1 = Integer.parseInt(br.readLine());
mark2 = Integer.parseInt(br.readLine());
m.get_data(roll_no, name);
m.display();
m.display_marks();
class Superclass
//Final variable
//final method
obj.display();
class Wrapper
byte b = 3;
int i = 10;
float f = 4.5f;
double d = 90.7;
byte bv = b_obj.byteValue();
int iv = i_obj.intValue();
float fv = f_obj.floatValue();
double dv = d_obj.doubleValue();
}
/*
01
101
0101
10101
*/
class BinaryPattern
int i, j;
int count = 1;
if (j == i && i != 5)
System.out.println("");
if (i % 2 == 0)
count = 1;
else
count = 0;
class ChristmasTree
{
makeTree();
starStr += "*";
for (int space = 0; space <= maxStars - (height + line + i); space++)
System.out.println(starStr);
System.out.print(" ");
System.out.print(" ");
System.out.print(" ");
class ChristmasTreePattern
{
drawChristmasTree(4);
triangle(i + 1, n);
System.out.print(" ");
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
int i, j, k, n;
String s1;
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++)
System.out.print(" ");
System.out.print(s1.charAt(k));
System.out.print(" ");
System.out.print("\n");
System.out.print(" ");
System.out.print(s1.charAt(k));
System.out.print(" ");
System.out.print("\n");
}
}
import java.util.Scanner;
class FloydTriangle
int n, num = 1, c, d;
n = in.nextInt();
num++;
System.out.println();
/*------------------
12
123
1234
12345
-------------------*/
class NumberPat1
System.out.print(j);
System.out.println();
import java.util.*;
class Pattern
int i, j, k = 1, l, n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.println("\nPattern is : \n");
l = i;
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
System.out.print(j);
System.out.println();
/*------------------
12345
1234
123
12
1
-------------------*/
class NumberPat3
System.out.print(j);
System.out.println();
/*------------------
12
123
1234
12345
1234
123
12
1
-------------------*/
class NumberPat4
int ck = 0, c = 2;
while (c > 0)
if (ck == 0)
System.out.print(j);
System.out.println();
ck++;
}
else
System.out.print(j);
System.out.println();
c--;
/*------------------
12345
1234
123
12
12
123
1234
12345
-------------------*/
class NumberPat5
int ck = 0, c = 2;
while (c > 0)
if (ck == 0)
System.out.print(j);
System.out.println();
}
ck++;
else
System.out.print(j);
System.out.println();
c--;
class NumberPat6
{
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
int t = 1;
if (t == 10)
t = 0;
System.out.print(t++);
System.out.println();
import java.util.Scanner;
class Pattern
int n, i, j;
n = sc.nextInt();
if (i % 2 == 0)
System.out.print("0");
else
System.out.print("1");
System.out.println();
}
}
class PrintPattern
int n = 5;
int j = n - i;
while (j > 0)
System.out.print(" ");
j--;
j = 1;
while (j <= i)
j++;
j = i - 1;
while (j > 0)
j--;
j = n - i;
while (j > 0)
{
System.out.print(" ");
j--;
System.out.println();
import java.util.*;
class Pascal
pascal[1][1] = 1;
System.out.println();
import java.io.*;
class NumberPayramid
int row;
int i, j, k;
int x = 1;
System.out.print(" ");
System.out.print(x);
System.out.print(x);
x++;
System.out.println("");
import java.io.*;
class SpiralNumberPattern
final int UP = 4;
//initial position
int x = 0;
int y = 0;
//initial direction
//Master Loop
int temp = i + 1;
//Checking boundaries
if (y > INPUT - 1)
Direction = DOWN;
x++;
y--;
i--;
continue;
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--;
Direction = RIGHT;
x--;
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;
if (patt[i][k] <= 9)
else
System.out.println();
/*
2 2
3 3
4 4
3 3
2 2
*/
class SquareKitePattern
int i, j, k;
System.out.print(" ");
System.out.print(i);
System.out.print(" ");
if (i > 1)
System.out.print(i);
System.out.print("\n");
System.out.print(" ");
System.out.print(i);
System.out.print(" ");
if (i > 1)
System.out.print(i);
System.out.print("\n");
/*----------------------------
*****
****
***
**
**
***
****
*****
----------------------------*/
class StarPattern3
{
for (int j = i; j <= 5; j++)
System.out.print("*");
System.out.println();
System.out.print("*");
System.out.println();
/*---------------------------
**
****
******
********
**********
---------------------------*/
class StarPattern4
{
int f = 2;
int g = num - 1;
System.out.print(" ");
else
System.out.print("*");
f = f + 1;
g = g - 1;
System.out.println();
/*------------------
**
***
****
*****
*****
****
***
**
-------------------*/
class StarPattern5
System.out.print("*");
}
System.out.println();
System.out.print("*");
System.out.println();
import java.io.*;
class Triangle
int num = 0;
try
num = Integer.parseInt(read.readLine());
}
System.out.println("Invalid Number!");
System.out.print(" ");
System.out.print("*");
System.out.print("*");
System.out.println();
import java.util.Scanner;
class LinearSearch
n = in.nextInt();
array[c] = in.nextInt();
search = in.nextInt();
break;
import java.util.*;
class BubbleSortInDescendingOrder
int n, c, d, swap;
n = in.nextInt();
array[c] = in.nextInt();
{
if (array[d] < array[d + 1])
swap = array[d];
array[d + 1] = swap;
System.out.println(array[c]);
import java.util.*;
class EnumerationSort {
/*
*/
data.add(Math.abs(random.nextInt()));
/*
Get the enumeration from the vector object and convert it into
Collections.sort() method.
*/
Collections.sort(list);
//
//
//The exchange sort compares the first element with each element of the array, making a swap
where is necessary.
import java.util.*;
class ExchangeSort
int[] array;
size = sc.nextInt();
array[i] = sc.nextInt();
//Exchange sort
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
class HeapSort
int i;
System.out.println("\nHeap Sort\n---------------");
System.out.println("\nUnsorted Array\n---------------");
fnSortHeap(arr, i - 1);
System.out.println("\n\nSorted array\n---------------");
for (i = 0; i < arr.length; i++)
int i, o;
root = (arr_ubound - 1) / 2;
lChild = (2 * i) + 1;
rChild = (2 * i) + 2;
mChild = rChild;
else
mChild = lChild;
else
else
mChild = rChild;
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
int[] input = {7, 21, 91, 43, 23, 17, 34, 9, 1};
insertionSort(input);
System.out.println("-----------------------------");
step++;
System.out.println("\n");
int n = array.length;
int i = j - 1;
array[i + 1] = array[i];
i--;
array[i + 1] = key;
printNumbers(array);
}
}
class MergeSort
int[] inputArr = {32, 27, 51, 89, 1, 98, 9, 28, 65, 0};
mms.sort(inputArr);
System.out.print(i);
System.out.print(" ");
this.array = inputArr;
this.length = inputArr.length;
{
if (lowerIndex < higherIndex)
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
tempMergArr[i] = array[i];
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
array[k] = tempMergArr[i];
i++;
else
{
array[k] = tempMergArr[j];
j++;
k++;
array[k] = tempMergArr[i];
k++;
i++;
import java.util.Comparator;
import java.util.Arrays;
class SortFruitObject
fruits[1] = apple;
fruits[2] = orange;
fruits[3] = banana;
Arrays.sort(fruits);
int i = 0;
System.out.println("fruits " + ++i + " : " + temp.getFruitName() + ", Quantity " + "\t: " +
temp.getQuantity());
super();
this.fruitName = fruitName;
this.fruitDesc = fruitDesc;
this.quantity = quantity;
}
public String getFruitName()
return fruitName;
this.fruitName = fruitName;
return fruitDesc;
this.fruitDesc = fruitDesc;
return quantity;
this.quantity = quantity;
//ascending order
//descending order
= new Comparator<Fruit>()
//ascending order
return fruitName1.compareTo(fruitName2);
//descending order
//return fruitName2.compareTo(fruitName1);
};
class QuickSort
{
int i;
System.out.println("Quick Sort\n\n");
System.out.println();
System.out.println();
int lo = low;
int hi = n;
if (lo >= n)
{
return;
lo++;
hi--;
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
int T = hi;
hi = lo;
lo = T;
}
class SelectionSortExample
int index = i;
index = j;
arr[index] = arr[i];
arr[i] = smallerNumber;
return arr;
System.out.print(i);
System.out.print(", ");
import java.util.*;
class SelectionSortDesc
int[] num;
int size;
size = scanner.nextInt();
num[i] = scanner.nextInt();
{
System.out.print(sorted_array[i] + "\t");
first = j;
num[first] = num[i];
num[i] = temp;
return num;
class ShellSort
len = 0;
}
public void insert(long value)
data[len] = value;
len++;
System.out.println("");
long temp;
int h = 1;
temp = data[outer];
inner = outer;
inner -= h;
data[inner] = temp;
h = (h - 1) / 3; // decrease h
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
int n;
n = scan.nextInt();
do
sl.insert(scan.nextInt());
/* Display List */
sl.printList();
n--;
/* Class SkipNode */
class SkipNode
int element;
SkipNode right;
SkipNode down;
/* Constructor */
public SkipNode(int x)
/* Constructor */
element = x;
right = rt;
down = dt;
/* Class SkipList */
class SkipList1
{
/* Constructor */
infinity = inf;
tail.right = tail;
bottom.element = x;
current = current.right;
/* If gap size is 3 or at bottom level and must insert, then promote middle element */
else
current = current.down;
if (header.right != tail)
System.out.print("\nSkiplist = ");
current = current.down;
current = current.right;
System.out.println();
}
}
import java.util.*;
class Sorting
int[] asc;
int[] des;
num = sc.nextInt();
asc[i] = sc.nextInt();
des[i] = asc[i];
{
if (asc[j] > asc[j + 1])
temp = asc[j];
asc[j + 1] = temp;
temp = des[j];
des[j + 1] = temp;
class CharToASCII
char a = 'a';
int i = 65;
class StringCase
{
public static void main(String args[])
import java.util.*;
class Palindrome
original = in.nextLine();
{
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
else
import java.util.Scanner;
class PigLatin
while (!word.equalsIgnoreCase("done"))
int cut = 0;
beforVowel += word.charAt(cut);
cut++;
if (cut == 0)
{
cut = 1;
word = sc.nextLine();
import java.io.*;
class PunctuationMark
String str;
str = br.readLine();
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
letter++;
}
else if (ch == ' ' || ch == '\t')
spaces++;
else
punct++;
import java.util.*;
class Demo
String s1 = sc.nextLine();
char c = sc.next(".").charAt(0);
int count = 0;
char strarr[] = s1.toCharArray();
if (strarr[i] == c)
count++;
import java.util.Scanner;
class CountWords
return count;
+ " words.");
//Close Scanner to avoid memory leak
in.close();
import java.util.Scanner;
class SubstringsOfAString
int i, c, length;
string = in.nextLine();
length = string.length();
System.out.println(sub);
}
}
class FormatString
System.out.println(String.format(str, "string"));
System.out.println(String.format(str1, 10));
class HtmlTagRemover
System.out.println(text);
System.out.println(text);
import java.util.Scanner;
class LongestWord
int l = str.length();
int maxlength = 0;
maxlength = word.length();
word = "";
i++;
import java.io.*;
class VowelsInString
{
public static void main(String[] args) throws Exception
int noofvowels = 0;
noofvowels++;
import java.util.Scanner;
class Permutation
char[] in = input.toCharArray();
if (level == inputLength)
System.out.println(outputString.toString());
return;
if (used[i])
continue;
outputString.append(in[i]);
used[i] = true;
used[i] = false;
outputString.setLength(outputString.length() - 1);
import java.io.*;
class RepeatStringName
int i, n;
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();
class StringRecursiveReversal
if (str.length() == 1)
return str;
else
reverse += str.charAt(str.length() - 1)
return reverse;
import java.util.*;
class ReverseString
original = in.nextLine();
import java.io.*;
class ReverseSentence
}
}
import java.util.ArrayList;
import java.io.*;
class ReverseSentence
al = recursiveReverseMethod(sentence, al);
al.trimToSize();
al.add(sentence.substring(0, index));
al.add(sentence.substring(0));
return al;
}
import java.io.*;
class ReverseWordIntheSentence
int strLen, i, j;
String str;
str = br.readLine();
strLen = str.length() - 1;
temp += str.charAt(i);
reverse += temp.charAt(j);
temp = "";
import java.util.Arrays;
class SingleStringSort
Arrays.sort(chars);
import java.util.*;
class AlphabeticalOrder
int n;
String temp;
Scanner s = new Scanner(System.in);
n = s.nextInt();
names[i] = s1.nextLine();
if (names[i].compareTo(names[j])>0)
temp = names[i];
names[i] = names[j];
names[j] = temp;
System.out.println(names[i]);
class StringConcat
String s1 = "Hello";
String s2 = "FreeIT";
//Concatenation
String s3 = s1.concat(s2);
String s4 = "Hello";
//checking equals
if (s4.equals(s1))
else
}
}
class StringConcatWithPlus
String s3 = null;
String s4 = null;
s3 = s1 + s2;
class StringEqualsTest {
String s1 = "abc";
String s2 = s1;
String s5 = "abc";
class StringLength
try
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 ");
return c;
System.out.println(res);
class StringExampleTwo
String s2 = s1.trim();
class StringReverse
String s = "abcdef";
System.out.print(c[i]);
class StringStartWith
/*
This example shows how a Java StringTokenizer can be used to break a string
into tokens.
*/
import java.util.StringTokenizer;
class StringTokenizerExample
while (st.hasMoreTokens())
System.out.println(st.nextToken());
class StringBuilderDemo
sb.append("is best");
System.out.println(sb);
System.out.println(sb.length());
//allocated capacity
System.out.println(sb.capacity());
System.out.println(sb1);
sb2.replace(3, 5, "was");
System.out.println(sb2);
sb3.delete(1, 3);
//prints Hlo
System.out.println(sb3);
sb3.deleteCharAt(0);
System.out.println(sb3);
sb4.reverse();
System.out.println(sb4);
System.out.println(sb5.charAt(0));
sb5.setCharAt(0, 'k');
System.out.println(sb5);
System.out.println(s);
s = sb6.substring(6);
System.out.println(s);
import java.util.Arrays;
import java.io.*;
class SortString
names[i] = br.readLine();
// sort the array, using the sort method of the Arrays class
Arrays.sort(names);
System.out.println("\t" + name);
class Test
int sum = 0;
sum += Character.getNumericValue(c[i]);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
implements ActionListener
JLabel picture;
public ComboBoxDemo()
super(new BorderLayout());
listPet.add("Cat");
listPet.add("Dog");
listPet.add("Rabbit");
listPet.add("Pig");
petList.setSelectedIndex(4);
petList.addActionListener(this);
picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
picture.setHorizontalAlignment(JLabel.CENTER);
updateLabel(listPet.get(petList.getSelectedIndex()));
picture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
//widest image and the height of the tallest image + the border.
add(petList, BorderLayout.PAGE_START);
add(picture, BorderLayout.PAGE_END);
/**
* Listens to the combo box.
*/
updateLabel(petName);
picture.setText(name);
/**
* event-dispatching thread.
*/
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(newContentPane);
frame.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable()
createAndShowGUI();
});
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public JListDemo()
setSize(300, 150);
setBackground(Color.gray);
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
String listData[] =
"Java",
"Python",
"Polymer",
"PHP"
};
topPanel.add(listbox, BorderLayout.CENTER);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
SwingUtilities.invokeLater(new JMenuBarExample());
message.setHorizontalAlignment(JLabel.CENTER);
fileMenu.add(openMenuItem);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
//set listener
openMenuItem.addActionListener(this);
cutMenuItem.addActionListener(this);
copyMenuItem.addActionListener(this);
pasteMenuItem.addActionListener(this);
menuBar.add(fileMenu);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.add(message, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MultiThreads
System.out.println(Thread.currentThread().getName());
new Thread("" + i)
}.start();
}
public class Multiplicatin_Table implements Runnable{
this.number=number;
@Override
number, i, i * number);
thread.start();
}
import java.lang.*;
Thread t;
ThreadDemo()
// thread created
t.setPriority(1);
t.start();
new ThreadDemo();
class SetThreadName
{
public static void main(String[] args)
System.out.println(currentThread);
//Thread class.
class CallThread
{
System.out.print("[" + msg);
try
Thread.sleep(1000);
catch (InterruptedException e)
System.out.println("Interrupted");
System.out.println("]");
String msg;
CallThread target;
Thread t;
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
synchronized (target)
// synchronized block
target.call(msg);
class SyncExample
try
ob1.t.join();
ob2.t.join();
ob3.t.join();
catch (InterruptedException e)
{
System.out.println("Interrupted");
class ThreadDeadLock
T1.start();
T2.start();
synchronized (Lock1)
try
Thread.sleep(10);
catch (InterruptedException e)
}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2)
synchronized (Lock2)
try
Thread.sleep(10);
catch (InterruptedException e)
synchronized (Lock1)
}
}
class TwoThreadsExample
super(str);
try
catch (InterruptedException e)
{
import java.util.Vector;
class BasicVectorOperations
vct.add("First");
vct.add("Second");
vct.add("Third");
System.out.println(vct);
vct.add(2, "Random");
System.out.println(vct);
import java.util.Vector;
class VectorClone
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
import java.util.Vector;
class CopyVectorToArray
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
System.out.println("Actual vector:"+vct);
vct.copyInto(copyArr);
for(String str:copyArr)
System.out.println(str);
import java.util.Vector;
class ClearVector
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
vct.clear();
import java.util.Enumeration;
import java.util.Vector;
class VectorEnumeration
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
while (enm.hasMoreElements())
System.out.println(enm.nextElement());
import java.util.Iterator;
import java.util.Vector;
class VectorIterator
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
while (itr.hasNext())
System.out.println(itr.next());
import java.util.Vector;
import java.util.*;
class VectorExample
int n, index;
n = sc.nextInt();
v.add(sc.nextInt());
}
v.remove(sc.nextInt());
import java.util.List;
import java.util.Vector;
class VectorSubRange
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");
vct.add("Click");