The document contains Java code examples for applets, file handling, formulas, and a calculator program. It includes 3 applet examples that draw lines, display text, and extend the Applet class. It also includes examples of reading and writing binary and text files, calculating the area of a circle, mean, and includes a calculator program that allows addition, subtraction, multiplication, division, modulus, and power operations.
The document contains Java code examples for applets, file handling, formulas, and a calculator program. It includes 3 applet examples that draw lines, display text, and extend the Applet class. It also includes examples of reading and writing binary and text files, calculating the area of a circle, mean, and includes a calculator program that allows addition, subtraction, multiplication, division, modulus, and power operations.
The document contains Java code examples for applets, file handling, formulas, and a calculator program. It includes 3 applet examples that draw lines, display text, and extend the Applet class. It also includes examples of reading and writing binary and text files, calculating the area of a circle, mean, and includes a calculator program that allows addition, subtraction, multiplication, division, modulus, and power operations.
JavaRocksApplet import java.applet.Applet; import java.awt.Graphics; import java.awt.Font; import java.awt.Color; /* <applet code = "JavaRocksApplet.class" width = 400 height = 200> </applet> */ public class JavaRocksApplet extends Applet { public void paint( Graphics screen ) { Font f = new Font( "TimesRoman", Font.ITALIC, 36 ); screen.setFont( f ); Color c = new Color( 40, 80, 120 ); screen.setColor( c ); screen.drawString( "Java Rocks!!", 100, 60 ); } }
SimpleApplet import java.applet.*; import java.awt.*; //Following example demonstrates how to create a //basic Applet by extrnding Applet Class.You will //need to embed another HTML code to run this program. public class SimpleApplet extends Applet{
public void paint(Graphics g){
g.drawString("Hello Applet",50,30);
} } //Now compile the above code and call the generated //class in your HTML code as follows: /*-------------------------- <HTML> <HEAD> </HEAD> <BODY> <div > <APPLET CODE="SimpleApplet.class" WIDTH="600" HEIGHT="400"> </APPLET> </div> </BODY> </HTML> ---------------------------*/
FILE HANDILING ReadBinaryFile import java.io.*; public 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) { TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 2
} } } }
ReadFile import java.io.*; public 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) {
}
} } }
WriteBinaryFile import java.io.*; public 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) { } } } }
WriteBinaryFile import java.io.*; public 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(); } TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 3
} catch (IOException e) { } } } } FORMULA CalculateCircleArea public 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); } }
CalculateMean import java.util.Scanner; public 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); } }
Calculator import java.util.Scanner; import java.io.*; public 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); TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 4
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; } }
HarmonicSeries 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); } }
QuadraticEquation public 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); } }
LOOPS BreakExample //The break keyword is used to stop the entire loop. //The break keyword must be used inside any loop or //a switch statement. //The break keyword will stop the execution of the //innermost loop and start executing the next line of //code after the block. public class BreakExample { public static void main(String args[]) { int[] numbers = { 10, 20, 30, 40, 50 }; for (int x : numbers) { if (x == 30) { break;//control comes out of loop } TeachJava2ME,EE,SE 2014
ContinueExample //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. public 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"); } } }
DoWhileLoop public class DoWhileLoop { public static void main(String args[]) { int x = 1; do { System.out.println("value of x : " + x); x++;
} while (x < 10); } }
ForLoop public class ForLoop { public static void main(String args[]) { for (int i = 1; i < 10; i++) { System.out.println("value of i : " + i); } } }
ForEachExample public 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+" "); } } }
WhileLoop public class WhileLoop { public static void main(String args[]) { int x = 1; while (x < 10) { System.out.println("value of x : " + x); x++; } } }
NUMBERS ArmstrongNumber 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."); } }
Factorial import java.util.Scanner; public class Factorial { public static void main(String args[]) { int fact = 1; int number = 0; System.out.println("Enter a number to print its factorial"); TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 6
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); } } 23. 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,i=0; while(i<n) { c=a+b; System.out.print(c +"\t"); a=b; b=c; i++; } } else{ System.out.println("You havent supplied the arguments: {Usage : java fibonacci 34 } to print the first 34 fibonacci numbers."); } } }
OddOrEven
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."); } }
HCFandLCM 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); } }
LargestOfThreeNumbers 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."); } }
Palindrome import java.util.Scanner; public 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) TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 7
System.out.println("The number "+number+" is a Palindrome."); else System.out.println("The number "+number+" is not a Palindrome.");
} }
PalindromePrime public 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;
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++; } } }
RandomNumber import java.util.*; public 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++) TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 8
{ System.out.println(r.nextInt(1000)); }
} }
TwinPrimes class TwinPrimes { public static void main(String args[]) { String primeNo = ""; int j = 0; int LastPrime = 1; System.out.println("Twin Primes are:\n"); for (int i = 1; i < 100; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { break; } } if (i == j) { primeNo += i + "\n"; if ((i - LastPrime) == 2) { System.out.println("(" + (i - 2) + "," + i + ")"); } LastPrime = i; } } System.out.println("\nPrime Numbers are:\n\n" + primeNo); } }
OBJECT ORIANTED PROGRAMMING Abstract abstract class Games { public abstract void start(); public void stop() { System.out.println("Stopping game in abstract class"); } } class GameA extends Games { @Override public void start() { System.out.println("Starting Game A"); } } class GameB extends Games { @Override public void start() { System.out.println("Starting Game B"); } } public class AbstractExample { public static void main(String[] args) {
Games A = new GameA(); Games B = new GameB(); A.start(); A.stop(); B.start(); B.stop(); } }
Abstract 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 public class Circle { // class name double radius = 2.3; // variables String color = "white"; // methods double getRadius() { // method body
Class public 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 CircleTest { // class name double radius = 2.3; // variables String color = "white color"; // methods double getRadius() { TeachJava2ME,EE,SE 2014
Constructor class Student { String student_name; public Student(String student_name) { this.student_name = student_name; } public String getName() { return student_name; } } public 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()); } }
Encapsulation public 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()); } }
Inheritance 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); } } public 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); } }
Inheritance 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()); } }
MethodOverloading class MethodOverloading { public void display(int number) { System.out.println("Integer value: " + number); } TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 10
public void display(float number) { System.out.println("Float value: " + number); } public void display(char character) { System.out.println("Character value: " + character); } } public class MethodOverloadingTest { public static void main(String args[]) { MethodOverloading ob = new MethodOverloading(); ob.display(20); ob.display(0.33f); ob.display('z'); } }
MethodOverriding 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"); } } public 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(); } }
Method public 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); } }
SEARCH
BinarySearch import java.util.*; public class BinarySearch { public static void main(String[] args) { int[] intArray = new int[10]; int searchValue = 0, index;
System.out.println("Enter 10 numbers"); Scanner input = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) { intArray[i] = input.nextInt(); }
System.out.print("Enter a number to search for: "); searchValue = input.nextInt(); index = binarySearch(intArray, searchValue);
if (index != -1) { System.out.println("Found at index: " + index); } else { System.out.println("Not Found"); }
} TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 11
static int binarySearch(int[] search, int find) { int start, end, midPt; start = 0; end = search.length - 1;
if (search[midPt] == find) { return midPt; } else if (search[midPt] < find) { start = midPt + 1; } else { end = midPt - 1; } }
return -1; } }
SORTINGS BubbleSort import java.util.Scanner;
class BubbleSort { 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]) /* For descending order use < */ { 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]); } }
HeapSort public 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---------------");
} 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++;
TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 13
} else {
array[k] = tempMergArr[j]; j++;
}
k++; }
while (i <= middle) {
array[k] = tempMergArr[i]; k++; i++;
} } }
QuickSort public 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); } }
ShellSort public 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); } TeachJava2ME,EE,SE 2014
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex; int j = higherIndex; // calculate pivot number, I am taking pivot as middle index number int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2]; // Divide into two arrays while (i <= j) { /** * In each iteration, we will identify a number from left side which * is greater then the pivot value, and also we will identify a number * from right side which is less then the pivot value. Once the search * is done, then we exchange both numbers. */ while (array[i] < pivot) { i++; } while (array[j] > pivot) { j--; } if (i <= j) { exchangeNumbers(i, j); //move index to next position on both sides i++; j--; } } // call quickSort() method recursively if (lowerIndex < j) quickSort(lowerIndex, j); if (i < higherIndex) quickSort(i, higherIndex); }
private void exchangeNumbers(int i, int j) { TeachJava2ME,EE,SE 2014
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++; }
} }
CompareStrings 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."); } }
SubstringsOfAString 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(); TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 16
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); } } } }
GetCurrentThread public class GetCurrentThread { public static void main(String args[]) { Thread t = Thread.currentThread(); t.setName("MainThread"); System.out.println("Id of current thread is: "+t.getId()); System.out.println("Name of current thread is: "+t.getName()); System.out.println("Priority of current thread is: "+t.getPriority()); } }
MultiThreads public class MultiThreads { public static void main(String[] args) {
FindEvenOrOddNumber public class FindEvenOrOddNumber {
public static void main(String[] args) {
//create an array of 10 numbers int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
for(int i=0; i < numbers.length; i++){
/* * use modulus operator to check if the number is even or odd. * If we divide any number by 2 and reminder is 0 then the number is * even, otherwise it is odd. */
if(numbers[i]%2 == 0) System.out.println(numbers[i] + " is even number."); else System.out.println(numbers[i] + " is odd number.");
System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); } }
/* Output of this program would be Largest Number is : 98 Smallest Number is : 23 */
MatrixMultiplication 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"); } } } }
TransposeAMatrix import java.util.Scanner;
class TransposeAMatrix { 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 TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 20
matrix"); m = in.nextInt(); n = in.nextInt();
int 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();
int 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"); } } }
AddTwoMatrix import java.util.Scanner;
class AddTwoMatrix { 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]; int sum[][] = 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();
for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices
System.out.println("Sum of entered matrices:-");
for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) System.out.print(sum[c][d]+"\t");
System.out.println(); } } }
GarbageCollection import java.util.*;
class GarbageCollection { public static void main(String s[]) throws Exception { Runtime rs = Runtime.getRuntime(); System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory()); rs.gc(); System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory()); } }
public int findDuplicateNumber(List<Integer> numbers){
int highestNumber = numbers.size() - 1; int total = getSum(numbers); int duplicate = total - (highestNumber*(highestNumber+1)/2); return duplicate; }
public int getSum(List<Integer> numbers){
int sum = 0; for(int num:numbers){ sum += num; } return sum; }
public static void main(String a[]){ List<Integer> numbers = new ArrayList<Integer>(); for(int i=1;i<30;i++){ TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 21
numbers.add(i); } //add duplicate number into the list numbers.add(22); DuplicateNumber dn = new DuplicateNumber(); System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers)); } }
GetCurrentDateAndTime import java.util.*;
class GetCurrentDateAndTime { 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); } }
BinaryToDecimal public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0; int power = 0; while(true){ if(binary == 0){ break; } else { int tmp = binary%10; decimal += tmp*Math.pow(2, power); binary = binary/10; power++; } } return decimal; }
leapyears 95. class leapyears { public static void main(String[] args) { int i=2006; int n; for (n=1990; n<=i ; n++){ int l=n%4; if (l==0){ System.out.println("leap year: "+n); } } } }
106. Constructor Overloading: - Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. - Constructor is called automatically when class called. - Constructor has no any object and no return value. - Constructor has same name as Class name. - Class has more than one Constructor with different Argument.(See below Example) - The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. //------- Ex. class Box { double length,breadth,height; Room(double l,double b,double h) { length=l; breadth=b; height=h; } Box() { length=-1; breadth=-1; height=-1; } Box(double len) { length=breadth=height=len; } TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 22
double volume() { return length*breadth*height; } } class OverloadConstructors { public static void main(String args[]) { Box a=new Box(20,30,40); Box b=new Box(); Box c=new Box(10); double vol; vol=a.volume(); System.out.println("Volume of room a is " + vol); vol=b.volume(); System.out.println("Volume of room b is " + vol); vol=c.volume(); System.out.println("Volume of room c is " + vol); } } 107. What is Polymorphism ? Polymorphism means, One name many form. Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. 2 Types : i) Method(Function) OverLoading - At Compile Time ii) Overriding - At Run Time //-------------------------- Method(function) Overloading: //-------------------------- In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java. overloaded methods: - appear in the same class or a subclass - have the same name but, - have different parameter lists, and, - can have different return types. Ex: class OverLoading { public static void main(String[] ar) { FunOverload obj = new FunOverload(); obj.add(111,122); obj.add(\"String Pass: \", \"?\"); obj.add(11.5, 22.5); } } class FunOverload { /* void add(int a, int b) // 1 - A method with two parameters { int sum = a + b; System.out.println(\"Sum of a+b is :\"+sum); } */ void add(int a, int b, int c) { int sum = a + b + c; System.out.println(\"Sum of a+b+c is \"+sum); } void add(double a, double b) { double sum = a + b; System.out.println(\"Sum of a+b is \"+sum); } void add(String s1, String s2)
{ String s = s1+s2; System.out.println(s); } }
108. /* Write a program to Display Invert Triangle. Example: Input - 5 Output : 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 */ class InvertTriangle{ public static void main(String args[]){ int num = Integer.parseInt(args[0]); while(num > 0){ for(int j=1;j<=num;j++){ System.out.print(" "+num+" "); } System.out.print("\n"); num--; } }}
STRING /*This program includes the Strings Concepts */
/* In Strings the methods are * length() * charAt() * indexOf() * subString() * lastIndex() * toUppercase() * toLowercase() * equals() * equalIgnorecase() * compareTo() * concat() * split() * * Now the below program will explain about the String methods */ package coreJavaProgram; public class Strings { public static void main(String[] args) { // Defining two strings s1 and s2 String s1 = "bhanu"; String s2 = " PRAKASH E"; String s[]; TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 23
s = s2.split("A");
// String methods will explain below
// print the strings System.out.print(s1); System.out.println(s2); System.out.println();
// length() System.out.println("Length of s1: " + s1.length()); System.out.println("Length of s2: " + s2.length()); System.out.println();
// charAt() System.out.println("Char at 1th place in s2: " + s2.charAt(0)); System.out.println("Char at 5th place in s1: " + s1.charAt(4)); System.out.println();
// indexOf() System.out.println("Index of 1st char in s2: " + s2.indexOf(" ")); System.out.println("Index of 4rd char in s2: " + s1.indexOf("n")); System.out.println();
// subString() System.out.println("Sub String of s2 from index 0: " + s2.substring(0)); System.out.println("Sub String of s2 from index 0 to till 2: " + s2.substring(0, 3)); System.out.println("Sub String of s1 from index 1 to till 3: " + s1.substring(1, 4)); System.out.println(); // lastIndex()- here in prakash i have 2-a's so this method will give us // a index of "A" which is at last System.out.println("Last index a cahr in s2: " + s2.lastIndexOf("A")); System.out.println();
// toUppercase() System.out.println("Lower to upper case of s1: " + s1.toUpperCase()); System.out.println();
// toLowercase System.out.println("Upper case to Lower case of s2: "+ s2.toLowerCase()); System.out.println();
// equals() System.out.println("Print T/F if stings are equal or notequals:"+ s1.equals(s2)); System.out.println("Print T/F if stings are equal or notequals:"+ s1.equals("bhanu")); System.out.println();
// equalsIgnorecase() System.out.println("Print T/F if stings are equal or notequals ignore case:"+ s1.equalsIgnoreCase("BHANU")); System.out.println("Print T/F if stings are equal or notequals ignore case:"+ s2.equalsIgnoreCase("prakash")); System.out.println();
// compareTo()--i have doubt on this ??How it is comparing?? System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s1)); System.out.println();
// concat() System.out.println("Concatenate two strings s1 and s2: "+ s1.concat(s2)); System.out.println("Concatenate two strings s2 and s1: "+ s2.concat(s1)); System.out.println("Concatenate two strings s1 with another string: "+ s1.concat(" prakash")); System.out.println();
// split() System.out.print("It will omit char A and print rest of the string:");
for (int i = 0; i < s.length; i++) { System.out.print(s[i]); } System.out.println();
// trim() System.out.println("Remove space before and after the name of s2:"+ s2.trim()); System.out.println(); * From here onwards StringBuffer programs Note: in strings and * StringBuffers we have one method call append() and concat() both are * same but the difference is StringBuffer will allocate the memory at * the time of runtime but string will not so StringBuffer is a Mutable * String is a Immutable */ // Below is the example for append() and concat()
s1.concat(" Prakash"); System.out.println("Immutablility of Sting: " + s1); System.out.println();
StringBuffer sb = new StringBuffer("Bhanu"); sb.append(" Prakash"); System.out.println("Mutablility of StringBuffer: " + sb); System.out.println();
// reverse() System.out.println("Reverse of a string sb: " + sb.reverse()); System.out.println();
// insert() System.out.println("Insert a String at from 4: "+ sb.insert(4, " /p/ ")); System.out.println();
// toString() System.out.println("toString of a String is: " + sb.toString()); System.out.println();
// delete() System.out.println("To delete a string at 3 to 5:" + sb.delete(3, 6)); TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 24
System.out.println("To delete a particular char at 3:"+ sb.deleteCharAt(3));
/* * This is all about strings ...if i miss the any method you can include * in this program i have included almost all the methods that related * to Strings and StringBuffer The string methods can implement in * StringBuffer also. The difference between StringBuffer and Builder is * StringBuffer is Synchronized and StringBuilder is not */ } }
MathLogics /* To understand this program clearly please open in NPP initially later on you can import * this into eclipse * * In this program we have all the math logics that is print of * reverse,even,odd,prime numbers,factorial, fibonacci * Don't be confuse with this program you can see the headings of each and every program */ package coreJavaProgram; import java.util.Scanner; public class MathLogics { private static Scanner get;
// Main method will starts from here
public static void main(String[] args) {
// ::Program for Reverse of a Number:: Starts from here int reverse = 0, rem; get = new Scanner(System.in); System.out.print("Enter the number you want to reverse: "); int n = get.nextInt(); while (n != 0) { rem = reverse * 10; reverse = rem + n % 10; n = n / 10; } System.out.print("reverse of number is: " + reverse); System.out.println("\n"); // ::Program for Reverse of a Number:: Ends here
// ::Program for Even Number:: Starts from here System.out.print("Upto which number you want to print even numbers: "); int lim = get.nextInt(); for (long e = 2; e <= lim; e++) { if (e % 2 == 0) { System.out.print(e + " "); } } System.out.println("\n"); // ::Program for Even Number:: Ends here
// ::Program for Odd Number:: Starts from here System.out.print("Upto which number you want to print odd numbers: "); int odd = get.nextInt(); for (long o = 0; o <= odd; o++) { if (o % 2 == 1) { System.out.print(o + " "); } } System.out.println("\n"); // ::Program for Even Number:: Ends here
// ::Program for Prime Number:: Starts here System.out.print("Upto which number you want print to prime numbers: "); int prm = get.nextInt(); for (long pn = 0; pn < prm; pn++) { long np; for (np = 2; np < pn; np++) { long num = pn % np; if (num == 0) { break; } } if (pn == np) { System.out.print(pn + " "); } } System.out.println("\n"); // ::Program for Prime Number:: Ends here
// ::Program for Factorial of a Number:: Starts from here System.out.print("Enter a number: "); int a = get.nextInt(); long fact = 1; for (int fa = 1; fa <= a; fa++) { fact = fact * fa; } System.out.print("Factorial of " + a + " is : " + fact); System.out.println("\n"); // ::Program for Factorial of a Number:: Ends here
// ::Program for Fibonacci series:: Starts from here System.out.print("Fibonacci Series of "); int fb = get.nextInt(); int f1, f2 = 0, f3 = 1; for (int f = 1; f <= fb; f++) { System.out.print(" " + f3 + " "); f1 = f2; f2 = f3; f3 = f1 + f2; } // ::Program for Fibonacci series:: Ends here } // ::Program Main method:: Ends here }
TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 25
End Of General Programs
Answers for Assignment 1
4. write a program to print a array using while.
package aone; public class ArrayUsingWhile { public static void main(String[] args) { int[] a = { 10, 20, 30, 40, 50 }; int i = 0; System.out.print("The elements are: "); while (i < 5) { System.out.print(a[i] + " "); i++; } } }
Output: The elements are: 10 20 30 40 50
3. write a progarm to compare two strings. package aone; public class Compare2Strings { public static void main(String[] args) { String s1 = "Bhanu"; String s2 = "Prakash"; System.out.println("Comparing 'bhanu' with 'prakash': " + s1.compareTo(s2)); } } Output: Comparing 'bhanu' with 'prakash': -14
10. write a program to check a string contains fullstop ( . ) package aone;
Output: Is string contains fullstop: true Is string contains fullstop: false
9. write a program to check a string ends with abc package aone; public class EndsWithabc { public static void main(String[] args) { String s = "Bhanu Prakash"; String s2 = "bhanuprakashabc"; System.out.println("Is string is ends with abc: " + s.endsWith("abc")); System.out.println("Is string is ends with abc: " + s2.endsWith("abc")); } }
Output: Is string is ends with abc: false Is string is ends with abc: true
11. write a progarm to compare two strings are equal or not. package aone; public class EqualString { public static void main(String[] args) { //StringBuffer sb=new StringBuffer(); String s1="Bhanu"; String s2="Prakash"; String s3="Bhanu"; System.out.println("Is Bhanu and prakash are equal: "+s1.equals(s2)); System.out.println("Is Bhanu and Bhanu are equal: "+s1.equals(s3)); } }
Output: Is Bhanu and prakash are equal: false Is Bhanu and Bhanu are equal: true
15 write a program to remove spaces from a word package aone; public class RemoveSpace { public static void main(String[] args) { String s="I am a good boy"; String s1 = s.replaceAll("\\s", ""); System.out.println("With Space: "+s); System.out.println("Without Space: "+s1); } }
Output: With Space: I am a good boy Without Space: Iamagoodboy
7. Write a program to convert an integer to String package aone; public class Int2String { public static void main(String[] args) { int i = 419; String s = String.valueOf(i); System.out.println("The Interger is: " + i); System.out.println("The Int 2 String is: " + s); } }
Output: The String is: 123
18 Write a program to print the integer part of a double variable ; package aone; public class IntPartDouble { TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 26
public static void main(String[] args) { double d = 45.35355; int i = (int) d; System.out.println("The Double value is: " + d); System.out.println("Integer form Double value is: " + i); } }
Output: The Double value is: 45.35355 Integer form Double value is: 45
13 Write a program to find the minimum of two digit using Math class. package aone; public class MathMin { public static void main(String[] args) { int i = Math.min(10,20); System.out.println("Minimum of two numbers is: "+i); } }
Output: Minimum of two numbers is: 10
20. Write a program to identify the number of alphabets, digits other character in a String. package aone; public class Numberof { public static void main(String[] args) { String s = "::My Age is 23 & I am a Programmer::"; int i,lt = 0, dig = 0, sy = 0, sp = 0; char ch; for (i = 0; i < s.length(); i++) { ch = s.charAt(i); if (Character.isLetter(ch)) ++lt; else if (Character.isDigit(ch)) ++dig; else if (ch == ' ') ++sp; else ++sy; } System.out.println("Length of a String is: " + s.length()); System.out.println("No. of Letters=" + lt); System.out.println("No. of Digits=" + dig); System.out.println("No. of Spaces=" + sp); System.out.println("No. of Symbols=" + sy); } }
Output: Length of a String is: 36 No. of Letters=21 No. of Digits=2 No. of Spaces=8 No. of Symbols=5
8. Write a program to reverse a string. package aone; public class ReverseString { public static void main(String[] args) { StringBuffer sb = new StringBuffer("bhanu"); System.out.println("The Original String is: " + sb); System.out.println("The reverse of a string is: " + sb.reverse()); } }
Output: The Original String is: bhanu The reverse of a string is: unahb
16 write a program to convert a string into bytes package aone; public class String2Byte { public static void main(String[] args) { String s = "Ha ha i am converting into byte"; byte[] bytes = s.getBytes(); System.out.println("Text format: " + s); System.out.println("Byte format: " + bytes); } }
Output: Text format: Ha ha i am converting into byte Byte format: [B@604c9c17
6. Write a program to convert a string to integer. package aone; public class String2Int { public static void main(String[] args) { String s1 = "123"; int i = Integer.parseInt(s1); System.out.println("The String is: " + i); } }
Output: The String is: 123
1. Write a Program to print a String array? package aone; public class StringArray { public static void main(String[] args) { String s1[] = { "My", "Name", "is", "Bhanu", "Prakash" }; for (int i = 0; i < s1.length; i++) { System.out.print(s1[i] + " "); } } }
Output: My Name is Bhanu Prakash
5. write a program to print hello and hello world using switch statement. package aone; import java.util.Scanner; public class Switch { public static void main(String[] args) { String s1 = "Hello"; String s2 = "Hello World"; System.out.println("Which one do you want to print:"); System.out.println("1.Hello"); System.out.println("2.Hello World"); System.out.print("\nEnter your Choice 1 or 2:"); Scanner in = new Scanner(System.in); int i = in.nextInt(); TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 27
switch (i) { case 1: System.out.print("\nThank you for choosing 1\nHere is your answer: "+ s1); break; case 2: System.out.println("\nThank you for choosing 2\nHere is your answer: " + s2); break; default: System.out.print("\nSorry!! \nyou have entered wrong option"); } } }
Output:1 Which one do you want to print: 1.Hello 2.Hello World
Enter your Choice 1 or 2:2
Thank you for choosing 2 Here is your answer: Hello World
Output:2 Which one do you want to print: 1.Hello 2.Hello World
Enter your Choice 1 or 2:4
Sorry!! you have entered wrong option
Answers for Assignment 2
Print name and age using variables package atwo; public class NameAndAge { public static void main(String[] args) { int age=23; String name="Bhanu Prakash"; System.out.println("My name is "+name+"\ni am "+age+" years old "); } }
Output: My name is Bhanu Prakash i am 23 years old
High/Low number guessing game package atwo; import cs1.Keyboard; public class NumberGame { public static void main(String args[]) { // Asking for Challenge System.out.println("Whats Up!!\nAre you ready to guess which number i am thinking!!");
System.out.println("The number range between 0 to 100\nTry to guess it."); System.out.println(); boolean win = false; // if win is true loop will exit while (win == false) { System.out.print("\nEnter the Number:"); // reading int value from keyboard int g = Keyboard.readInt(); // Random number by using Math.randomrange between 0 to 100 int r = (int) (Math.random() * 100); // if the value is less than 0 if (g < 0) { System.out.println("Sorry!!\n"+ g+ " is not in my range\nYou can try in between 0 and 100"); // if the value is greater than 100 } else if (g > 100) { System.out.println("Sorry!!\n"+ g+ " is not in my range\nYou can try in between 0 and 100"); // if the value is equal to the system number } else if (g == r) {// win = true; System.out.println("Congragulation!! You are correct.\nThe number i was thinking is "+ r); // if the value is less than the system number } else if (g < r) { System.out.println(g + " is too low!\nPlease try Again!!");
// if the value is greater than the system number } else if (g > r) { System.out.println(g + " is too high!\nPlease try Again!!"); } } } }
Output: Whats Up!! Are you ready to guess which number i am thinking!! The number range between 0 to 100 Try to guess it.
Enter the Number:2 2 is too low! Please try Again!!
Print all prime numbers less than 100 package atwo; import java.util.Scanner; public class PrimNumber { public static void main(String[] args) { Scanner get=new Scanner(System.in); System.out.print("Upto which number you want print the prime numbers: "); int prm = get.nextInt(); for (long pn = 0; pn < prm; pn++) { TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 28
long np; for (np = 2; np < pn; np++) { long num = pn % np; if (num == 0) { break; } } if (pn == np) { System.out.print(pn + " "); } } System.out.println("\n"); } } Output: Upto which number you want print the prime numbers: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Chart with random numbers and a word package atwo; import java.util.Scanner; public class Box { public static void main(String[] args) { String b = "Bhanu"; System.out.println("What is the size of the chart? (1 to 10): "); Scanner s = new Scanner(System.in); int n = s.nextInt(); if (n <= 10) { for (int i = 0; i < n; i++) { System.out.print("\n"); box.hl(n); System.out.println("+"); for (int k = 0; k < n; k++) { int r=(int)(Math.random()*100000+1); int p=(int)(Math.random()*10000+1); System.out.print("|"); if(i==k) System.out.print(b); else if(i<k) System.out.print(r); else System.out.print(p+"*"); } System.out.print("|"); } System.out.print("\n"); box.hl(n); System.out.println("+"); } else { System.out.println("Sorry the number is out of range"); } } public static class box { static void hl(int n) { for (int h = 0; h < n; h++) { System.out.print("+"); for (int j = 0; j < 5; j++) { System.out.print("-"); } } } } } Output: What is the size of the chart? (1 to 10): 4
Fibonacci sequence using recursive function calls package atwo; import java.util.Scanner; public class Fibb { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.println("Enter number upto which Fibonacci series to print: "); int number = s.nextInt(); System.out.println("Fibonacci series upto " + number + " numbers is : "); for (int i = 1; i <= number; i++) { System.out.print(fibonacci2(i) + " "); } } public static int fibonacci(int number) { if (number == 1 || number == 2) { return 1; } return fibonacci(number - 1) + fibonacci(number - 2); }
public static int fibonacci2(int number) { if (number == 1 || number == 2) { return 1; } int fibo1 = 1, fibo2 = 1, fibonacci = 1; for (int i = 3; i <= number; i++) { fibonacci = fibo1 + fibo2; fibo1 = fibo2; fibo2 = fibonacci; } return fibonacci; } } Output: Enter number upto which Fibonacci series to print: 10 Fibonacci series upto 10 numbers is : 1 1 2 3 5 8 13 21 34 55
Fibonacci sequence using loops and an array package atwo; public class FibAry { public static void main(String[] args) { int[] fibonacciNumbers = new int[30]; fibonacciNumbers[0] = 0; fibonacciNumbers[1] = 1; for (int index = 2; index < fibonacciNumbers.length; ++index) { TeachJava2ME,EE,SE 2014
Draw a box around a text string package atwo; import tio.Console; public class TextBox { public static void main(String[] args) { System.out.print("Please Enter name: "); String k = Console.in.readLine(); System.out.print("please Eneter Age: "); int age = Console.in.readInt(); int n = k.length() + 16; boxLine.hl(n); System.out.print("|"); for (int i = 0; i < n; i++) { System.out.print(""); } boxText.String(k, age); System.out.println("|"); boxLine.hl(n); } public static class boxLine extends boxText { static void hl(int n) { System.out.print("+"); for (int j = 0; j < n; j++) { System.out.print("-"); } System.out.println("+"); } } public static class boxText { static void String(String k, int age) { System.out.print(k + " is " + age + " years old"); } } } Output: Please Enter name: bhanu please Eneter Age: 23 +---------------------+ |bhanu is 23 years old| +---------------------+
Print Pascal's Triangle package atwo; import java.awt.Component; public class PTraiangle { public static void main(String []args) { System.out.println("\nTriangle: "); int row = 11; long[][] triangle = new long[row][row]; int x = 1; while (x<row-1) { System.out.print(" "); x++; } triangle[1][1] = 1; System.out.print(triangle[1][1] + "\n");
for (int i = 2; i<row; i++) { x = i; while (x<row-1) { System.out.print(" "); x++; } for (int n = 1; n<row; n++) { triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n]; if (triangle[i][n]>0) { System.out.print(triangle[i][n] + " "); } } System.out.println(); } } public static Component createHorizontalGlue() { // TODO Auto-generated method stub return null; } }
TicTacToe strategy game package atwo; import tio.*;
public class TicTacToe {
static final int EMPTY = 0; static final int NONE = 0; static final int USER = 1; static final int COMPUTER = 2; static final int STALEMATE = 3; public static void main(String[] args) { int turn = USER; int[][] board = new int[3][3]; int move; int winner; System.out.println("This is a tic-tac-toe game"); System.out.println("You are playing against the computer!"); System.out.println("Enter 1-9 to indicate your move");
// Print the board print_board(board); TeachJava2ME,EE,SE 2014
Prepared By Bhanu Prakash 30
// While (game not over) while(true) { if(turn == USER) { System.out.println("Your move"); move = -1; while (move<0 || move>9 || board[move/3][move%3] != EMPTY) { System.out.println("Please enter your move(0-9): "); move = Console.in.readInt(); Console.in.readChar(); } } else { move = computer_move(board); System.out.println("Computer move: " + move); }
// Update the board board[(int)(move/3)][move%3] = turn;
// Return an X or O, depending upon whose move it was public static char printChar(int b) { switch(b) { case EMPTY: return ' '; case USER: return 'X'; case COMPUTER: return 'O'; } return ' '; }
// See if the game is over public static int checkWinner(int[][] board) { // Check if someone won // Check horizontals
return move; } } Output: This is a tic-tac-toe game You are playing against the computer! Enter 1-9 to indicate your move | | ----- | | ----- | | Your move Please enter your move(0-9): 5 | | ----- | |X ----- | | Computer move: 1 |O| ----- | |X ----- | | Your move Please enter your move(0-9):
public class StringL { public static class StringLength { static int i, c, res; static int length(String s) { try { for (i = 0, c = 0; i >= 0; i++, c++) s.charAt(i); } catch (Exception e)
{ System.out.print("length is: "); } return c; } public static void main(String args[]) throws IOException { System.out.print("Enter the string:"); Scanner get = new Scanner(System.in);
// BufferedReader br = new BufferedReader(new InputStreamReader( // System.in)); String a = get.nextLine(); res = StringLength.length(a); System.out.println(res); } } }