Java Programming Concepts and Examples

Classified in Computers

Written at on English with a size of 10.2 KB.

Palindrome

  1. Start
  2. Read the string
  3. Calculate the length of the string
  4. Initialize rev
  5. Initialize i=length=1
  6. Repeat until i>=0
    1. rev=rev+char at position I of the string
    2. i=i-1
  7. If string=rev:print “palindrome”
  8. Else print “not palindrome”
  9. Stop

import java.util.Scanner; import java.util.Scanner; class Test { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.print("Enter the String:"); String str = sc.nextLine(); int flag = 0; int len = str.length(); for(int i=0;i


Inheritance

  1. Create a class employee with given variables and method print the salary
  2. Create two sub classes of class employee named officer and manager include the variable specilaization in officer class and department in manager class
  3. Create a class with main function inside the main function do the following steps
  4. Create an object of officer class and assign appropriate values to variables
  5. Create an object of manager class and assign appropriate values to variables
  6. Print the values of variables using object
  7. Invoke the function print salary () using objects to print the salary.

import java.util.Scanner; class Employee { String name="RAMU"; String address="MEA"; int age = 23, phn_no=123456789,salary=500000; void printsalary() { System.out.println("Salary :" + salary); } } class Officer extends Employee { String spcln="coding"; } class Manager extends Employee { String dpt="Training"; } class inher { public static void main(String args[]) { Officer s=new Officer();Manager k=new Manager(); System.out.println(s.name+" "+s.address+""+k.age+" "+k.phn_no+" ");System.out.println(s.spcln);System.out.println(k.dpt); k.printsalary(); } }


Polymorphism

  1. Create a class shape with method no of sides() without definition
  2. Create 3 Subclasses of shape namely rectangle,triangle,hexagon
  3. Define method of sides () in all these subclasses rectangle & hexagon that display the sides 4,3,6 respectivly
  4. Invoke the no of sides () by creating reference variable of class shape which refers of each sub classes

import java.util.Scanner; abstract class Shapes{ abstract void numberOfSides(); } class Triangle extends Shapes{ void numberOfSides(){ System.out.println(" Triangle have 3 Sides"); } } class Rectangle extends Shapes{  void numberOfSides(){  System.out.println(" Rectangle have 4 Sides");  } } class Hexagon extends Shapes{  void numberOfSides(){  System.out.println(" Hexagon have 6 Sides"); } } public class Shape{  public static void main(String args[]){ Triangle triangle = new Triangle();  Rectangle rectangle = new Rectangle(); Hexagon hexagon = new Hexagon(); triangle.numberOfSides(); rectangle.numberOfSides(); hexagon.numberOfSides(); } }


Read and Write

  1. Start
  2. Put step3456 in try block
  3. Create an object for file reader class named “fout “for “copy.text”
  4. While (i=fin,readn)!=-1do
  5. fout.write(i) end while
  6. Close file fin and fout
  7. Catch (file not found excpt ioexcept er){print error message in object er}
  8. Stop

import java.io.*; class FileReadWrite{ public static void main(String[] args){ try{ FileWriter fout = new FileWriter("sample.txt"); fout.write("Hello World"); fout.close(); FileReader fin = new FileReader("sample.txt"); int i; while((i=fin.read())!=-1){ System.out.print((char)i); } fin.close(); }catch(FileNotFoundException e){
 System.out.println(e.getMessage()); }catch(IOException e){ System.out.println(e.getMessage()); } } }


IntegerSum

  1. Start
  2. Try {
  3. FileReader fin = new file reader(“text.txt”);
  4. BufferedReader br=new buffer Reader(fin)
  5. Input values =br.read line()
  6. For (elements inputvalues.split(1))
  7. Print element
  8. Sum=sum+integer.parseInt(element) end for
  9. Print sum
  10. Close file ”fin”}
  11. Catch (IOException/number format exception e) { print e get message()}
  12. Stop

import java.io.*; import java.util.StringTokenizer; class FileIntegerSum{ public static void main(String[] args){ try{ FileWriter fw = new FileWriter("integers.txt"); fw.write("1 2 3 4 5 6 7 8 9"); fw.close(); FileReader fr = new FileReader("integers.txt"); BufferedReader br = new BufferedReader(fr); String inputValues = br.readLine(); StringTokenizer st = new StringTokenizer(inputValues," "); int sum = 0; while(st.hasMoreTokens()){ String temp = st.nextToken(); System.out.println(temp); sum += Integer.parseInt(temp); } System.out.println("sum is : "+sum); fr.close();  }catch(IOException e){ System.out.println(e.getMessage()); }catch(NumberFormatException e){ System.out.println("Not a valid number in file"); } } }

Frequency

  1. Start
  2. Read a string
  3. Store the length of the string in len
  4. Read a character
  5. Initialize s=0,i=0
  6. Compare each character in the string with the entered character
  7. If match occurs increment the value of s
  8. Update value of I by i++
  9. Repeat step678 until I
  10. Print the value of s
  11. Stop

import java.util.Scanner; class Main{ public static void main(String args[]){  Scanner sc = new Scanner(System.in);  int noOfOccurrence = 0; System.out.println("Enter a word"); String word = sc.nextLine(); System.out.println("Enter a letter to be checked for the no.of occurrence"); char letter = sc.nextLine().charAt(0); for( int i = 0 ; i

ExptnHnling 1.start 2.read the integer a,b from user 3.try result=divide (a,b) then print result 4.catch [arithematic exception e]then print erget message() 5.finally print “program closing” 6.stop

import java.util.Scanner; class DivisionByZeroException extends Exception{ String message; DivisionByZeroException(String message this.message=message; }}class ExceptionSample {static float divide(int a,int b) throws DivisionByZeroException{if(b==0){ throw new DivisionByZeroException("Cant divide by zero");}return a/b;}public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter first Number"); int firstNum = sc.nextInt(); System.out.println("Enter second Number"); int secondNum = sc.nextInt();try { float result=divide(firstNum,secondNum); System.out.println("result is :"+result);}catch (DivisionByZeroException e) {System.out.println(e.message);}finally{ System.out.println("Program Closing");}}}

Binary// 1.start 2.read the length of the array to n 3.read the values in ascending order into array a[] of size n 4.read elelmnt to search variable key 5.high=n- 1,low=0 6.if (high>=low){ 6.1mid=(low+high/2) 6.2if (a [mid]==key)6.2print elemnt found at mid+1 pos 6.3else if(a[mid]>key)6.3.1 low=0,high=mid-1 6.4else 6.4.1 low=mid+1 7.end if 8.stop

import java.util.Scanner; public class BinarySearch { public static void main(String[] args) { int i,j,temp,n,key,pos=-1; Scanner sc = new Scanner(System.in); System.out.println("Enter Length of array"); n = sc.nextInt(); int[] a = new int[n]; System.out.println("Enter Values in Ascending order"); for(i=0;i=low){ int mid = (low + high)/2; if(a[mid] == key)System.out.println("Element found at position"+(mid+1)); else if (a[mid] > key)binarySearch(a,low,mid-1,key); else binarySearch(a,mid+1,high,key); }else{ System.out.println("Element not found "); } }}


ThreadSyn// 1.print ”c” msg 2.try thread sleep(1000),catch(exception e) 3.print “c” algorithm class syncthread (msg) extends thread 1.assign msg field of class with values passed through constructor 2.override sum metthod of class thread and invoke print delayed(msg) algorithm main(msg[]) 1.start  2.create a object for syncthread class and pass message to the constructors 3.invoke start method of that object 4.stop

class Display{ public synchronized void print(String msg){ System.out.print("["+msg); try{Thread.sleep(1000);}catch(Exception e){ System.out.println(e.getMessage()); } System.out.println("]"); } } class SyncThread extends Thread{ private Display d; private String msg; public SyncThread(Display d,String msg){ this.d=d;this.msg = msg; } public void run(){ d.print(msg);} }class ThreadSync{ public static void main(String args[]){ Display d = new Display(); SyncThread t1 = new SyncThread(d,"Hello"); SyncThread t2 = new SyncThread(d,"World"); t1.start(); t2.start(); } }

QuickSort// algorithm quicksort(a[],low,high) 1.start 2.if low algorithm partition(a[],low,high) 1.start 2.x=a[high] 3i=low-1 4for(j=low;j

import java.util.Scanner; class QuickSort{ public static void quickSort(String A[],int p,int r){ if(p

MatrixMUL// 1.start 2.enter the row,size and column size of the first matrix 3.’’’’’’’second matrix 4.enter the elements of first matrix 5.’’’’’’’’’’second matrix 6.set aloop upto row 7.set an inner loop for column 8.mulpily the 1stand 2ndmatrix and store them in 3rd matrix 9.print the matrix and final matrix 10.stop

import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner (System.in); System.out.println ("Enter size of first row"); int r1 = sc.nextInt (); System.out.println ("Enter size of first colomn"); int c1 = sc.nextInt (); System.out.println ("Enter size of second row"); int r2 = sc.nextInt (); System.out.println ("Enter size of second colomn"); int c2 = sc.nextInt (); int a1[][] = new int[r1][c1]; int a2[][] = new int[r2][c2]; int c[][] = new int[r1][c2]; System.out.println ("Enter elemnts first matrix"); for (int i = 0; i  System.out.println( "\nMultiplication Not Possible"); return; } for(int i = 0; i

Entradas relacionadas: