Core Java Examples For Practice

Core Java Examples for Practice

This section explains Core Java examples for beginners. User can practice these example in their local system. Also, students who started java as their programing skills will get help to enhance their skills.


Factor of a Number


This program will get to get the factor of given number.

Example:

Input Number: 9

Factors will be: 3x3
 import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.util.ArrayList;
  import java.util.List;

public class FactorOfNumber {
      public static void main(String[] args) throws NumberFormatException, IOException{
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Please Enhter a Number:");
          int a = Integer.parseInt(bufferedReader.readLine());
          List temp = factor(a);
          if(temp !=null){
              System.out.println("Factor of the number are:"+temp);
              for(int i=0;i<temp.size();i++){
                  System.out.println(temp.get(i));            
              }
          }else{
              System.out.println("This Number does not have any factory");
          }        
      }
      
      public static List factor(int a){
          List list = new ArrayList();
          for(int i=2;i<a;i++){
              if(a%i==0){
                  list.add(i);
              }
          }        
          return list;
      }

Fibonacci Series


This Example will explain Fibonacci Series. There are various way to write program in java, in Knowledgewala we are following simple and straight forward logic.

public class FibonacciSeries {
      public void fibonacci(int num){
          int a=0, b=1;
          int c;
          System.out.print(a + " "+b );
          for(int i=2;i<num;i++){
              c = a+b;
              a = b;
              b = c;
              System.out.print(" "+c);            
          }
      }
      public int recFibonacci(int a, int b){
          int c =a+b;
          return c;        
      }
      public static void main(String[] args){
          FibonacciSeries fib = new FibonacciSeries();
          fib.fibonacci(10);        
      }

}

Prime Number Generation


This example will explain prime number generation.

import java.util.Scanner;

public class PrimeNumber {
      public void primeNumber(int num){
          int count = 0;
          boolean flag = false;
          for(int i =2; i<=num;i++){
              for(int j=2;j<=i;j++){
                  if(i%j == 0 && j!=i){
                      flag = true;
                      break;                    
                  }
              }
              if(flag){
                  flag = false;
              }
              else if(!flag){
                  ++count;
                  System.out.println(i+" ");                
              }            
          }
          System.out.println("Total Count : "+ count);
      }
      public static void main(String args[]){
          Scanner scanner = new Scanner(System.in);
          System.out.println("Enter Upper Limit for Prime Number :");
          int num = scanner.nextInt();
          PrimeNumber primeNumber = new PrimeNumber();
          primeNumber.primeNumber(num);
      }
  }

Decimal Number Format


This program will format Decimal Number.

import java.util.LinkedList;
  import java.util.Scanner;

public class DecimalFormat {
      DecimalFormat decimalFormat = new DecimalFormat();
      public static void main(String[] args)throws NumberFormatException{
          Scanner keybrd = new Scanner(System.in); 
          System.out.println("Enter Any double value::");
          double num = keybrd.nextDouble();        
          double result = getCorrectDecimalFormat(num);
              System.out.println("Result::"+result);        
      }
      /**
       * This function will get the correct format of decimal number as per our requirement.
       * @param num
       * @return
       */
      public static double getCorrectDecimalFormat(double num){
          int numAsInt = (int)num;
          int decimalPart = (int)getDecimalPart(num);        
          int tempdecimal = decimalPart;        
          double temp1 = 0.0;
          double result = 0.0;
          LinkedList<Integer> list = new LinkedList<Integer>();
          if(tempdecimal>99){
              while(tempdecimal!=0){
                  list.add(tempdecimal%10);
                  tempdecimal = tempdecimal/10;
              }            
              int listSize = list.size();
              if(list.get(listSize-1)==9 && list.get(listSize-2)==9){
                  result = Math.round(num);
              }
              else if(list.get(listSize-2)==9){
                  temp1 = (list.get(listSize-1)+1)*10;
                  result = numAsInt+temp1/100;                
              }else{
                  temp1 =  list.get(listSize-1)*10+list.get(listSize-2)+1;
                  
                  result = numAsInt+temp1/100;
              }
          }else if(tempdecimal==0){
              result = numAsInt;
          }else{
              result = num;
          }        
          return result;        
      }
      
      
      /**
       * This function will break decimal part
       * @param num
       * @return
       */
      public static int getDecimalPart(double num) {
          String number = ""+num;        
          int decPart = 0;
          String decimalPart = "";        
          for (int i = 0; i < number.length(); i++) {
              if (number.charAt(i) == '.') {
                  i++;
                  while (i < number.length()) {
                      decimalPart += number.charAt(i);
                      if(i!=number.length()){
                          i++;
                      }                    
                  }
                  decPart = Integer.parseInt(decimalPart);
              }
          }
          return decPart;
      }
  }

Swapping of Two Number


import java.util.Scanner;

public class Swap {

    /**
       * @param args
       */
      public static void main(String[] args) {        
          Scanner scanner = new Scanner(System.in);
          System.out.println("Enter first Number :");
          int a = scanner.nextInt();
          System.out.println("Enter second Number :");
          int b = scanner.nextInt();        
          System.out.println("Before Swapping - "+"a:"+a + "b:"+b);
          Swap swap = new Swap();
          swap.swapFunction(a,b);
      }
      private void swapFunction(int a, int b){
          a = a+b;
          b= a-b;
          a= a-b;
          System.out.println("After Swapping - "+"a:"+a + "b:"+b);
      }
  }

Day and Month from a given Date


import java.util.Calendar;

public class DayAndMonthFromDate {
      
      public static void main(String [] args){
          Calendar cal = Calendar.getInstance();
          int day = cal.get(Calendar.DATE);
          int month = cal.get(Calendar.MONTH);
          int year = cal.get(Calendar.YEAR);
          int dow = cal.get(Calendar.DAY_OF_WEEK);
          int dom = cal.get(Calendar.DAY_OF_MONTH);
          int doy = cal.get(Calendar.DAY_OF_YEAR);
          System.out.println("Day Of the Month : "+day);
          System.out.println("Month  : "+month);
          System.out.println("Year  : "+year);
          System.out.println("----- Others -----" );        
          System.out.println("dow  :"+dow+"  dom : "+dom+"   doy : "+doy +"  "+getDayName(dow)+" Month Name :"+getMonthName(month));
          
      }
      /**
       * This method will return Day name of a particular day of the month.
       * @param dow
       * @return
       */
      private static String getDayName(int dow){
          switch(dow){
              case Calendar.SUNDAY:
                  return "sunday";
                  //break;
              case Calendar.MONDAY:
                  return "monday";
                  
              case Calendar.TUESDAY:
                  return "tuesday";
                  
              case Calendar.WEDNESDAY:
                  return "wedneshday";
                  
              case Calendar.THURSDAY:
                  return "thurday";
                  
              case Calendar.FRIDAY:
                  return "friday";
                  
              case Calendar.SATURDAY:
                  return "saturday";
                  
              default:
                   return "Day Does not Exist";                
          }
          
      }
      
      /**
       * This method will return month name of a particular month.
       * @param monthDay
       * @return
       */

    private static String getMonthName(int monthDay){
          switch(monthDay){
              case Calendar.JANUARY:
                  return "January";
              case Calendar.FEBRUARY:
                  return "Febuary";
              case Calendar.MARCH:
                  return "March";
              case Calendar.APRIL:
                  return "April";
              case Calendar.MAY:
                  return "May";
              case Calendar.JUNE:
                  return "June";
              case Calendar.JULY:
                  return "July";
              case Calendar.AUGUST:
                  return "August";
              case Calendar.SEPTEMBER:
                  return "September";
              case Calendar.OCTOBER:
                  return "October";
              case Calendar.NOVEMBER:
                  return "November";
              case Calendar.DECEMBER:
                  return "December";
              default:
                  return "Month Does not Exist";
              
          }
          
      }

}

Harmonic Series


 

public class HarmonicSeries {
      public Double harmonicSum(int numberOfSteps){
          Double total = 0.0;
          if(numberOfSteps >0){            
              while(numberOfSteps!=0){
                  total += (double)1/numberOfSteps;
                  numberOfSteps--;
              }
          }else{
              return null;
          }
          
          return total;
      }
      public static void main(String[] args){
          HarmonicSeries harmonicSeries = new HarmonicSeries();
          System.out.println("Welcome to Harmonic Serise Program");
          int numberOfSteps = 10;
          System.out.print("Harmonic Series Sum till "+numberOfSteps+" steps is : ");
          System.out.print(harmonicSeries.harmonicSum(numberOfSteps));
      }

}

Next Term of the Series


This program display next term in the series like 2,4,6,8.. next term is 10

public class NextTermOfSeries {
      public static void main(String[] args){
          System.out.println("Hello Next Term of the Series");
          System.out.println("Enter the Series Four First Term:");
          int first = 30,second = 15,third = 5,fourth = 2, fifth = 0;        
          if(first==0 && second == 0 && third ==0 && fourth ==0){
              System.out.println(fifth);
          }else if(first-second == second-third && second-third == third-fourth){
                  fifth = fourth+(fourth-third);
          }else if(first/second == second/third && second/third == third/fourth){
              fifth = fourth+(third/second);
          }else if(first-second == third-fourth){
              fifth = fourth+(third-second);
          }else{
              fifth = -1;
          }
          if(fifth != -1){
              System.out.println("Fifth element is :"+fifth);
          }else{
              System.out.println("*** Series is not recognized ****");
          }
          
      }

}

Palindrome Number


 

public class Palindrom {
      public String revString(String str){        
          String rvsString = "";
          for(int i=str.length()-1;i>=0;i--){
              rvsString+=str.charAt(i);            
          }
          return rvsString;        
      }
      public Boolean chkPalindrom(String s1, String s2){
          return s1.equals(s2);
      }
      public void plaindromForInt(int num){
          int temp = num;
          int revNum = 0;
          int count = 0;
          while(num>10){
              num = num/10;
              count++;
          }
          num = temp;
          int tempNum;
          while(num>10){
              tempNum = num%10;
              num = num/10;            
              revNum = revNum+tempNum*multipleOfTen(count);
              if(num<10){
                  revNum = revNum+num;
              }
              count--;
                          
          }
          if(temp == revNum){
              System.out.println("Palindrom Number");
          }else{
              System.out.println("Not a Palindrom Number");
          }
          
      }
      
      public int multipleOfTen(int count){
          int hundred = 1;
          for(int i=count;i>0;i--){
              hundred*=10;
          }
          return hundred;        
      }
      
      private int method(int num){
          int digit = 1;
          int temp = 0;
          int num1 = num;
          int count =0;
          while(num1>10){
              num1 = num1/10;
              count++;
          }
          digit = multipleOfTen(count);
          while(num!=0){
              temp = temp+(num%10)*digit;
              num = num/10;
              digit = digit/10;            
          }
          return temp;
      }
      public static void main(String[] args){
          System.out.println("Welcome to Palindrom Program.");
          Palindrom palindrom = new Palindrom();
          String name = "saras";
          /*if(palindrom.chkPalindrom(name,palindrom.revString(name))){
              System.out.println("String is Palindrom.");
          }else{
              System.out.println("String is not Palindrom.");
          }*/
          int num = 123;        
          //palindrom.plaindromForInt(num);
          if (palindrom.method(num)==num){
              System.out.println("ok");
          }else{
              System.out.println("false");
          }
      }
 

}

Reverse a Number


This example to reverse a given number.

Example. Input Number: 65421

                   Output Number: 12456

 

public class RevereseNumber {
       public static void main(String args[]){

         int num = 43355231;               //take argument as command line

         int remainder, result=0;

         while(num>0){

             remainder = num%10;

             result = result * 10 + remainder;

             num = num/10;

        }

        System.out.println("Reverse number is : "+result);

   }

}

Sum of Power of a Digit


This example will do the sum of power of a digit.

Example: input Number- 2^4

                  Output Number: 16

import java.util.Set;
  import java.util.TreeSet;

public class SumOfPowerOfDigit {
      public static void main(String[] args){
          System.out.println("The sum of fourth powers of their digits");
          long max = 10000000;
          long min = 10;
          System.out.println("Digits are :"+getDigits(min,max));
      }
      public static Set getDigits(long min, long max){
          Set set = new TreeSet();
          for(long i=min;i<max;i++){
              if(checkDigit(i)){
                  set.add(i);
              }
          }
          return set;
      }
      public static boolean checkDigit(long number){
          String tempNum = number+"";
          long sum = 0;
          for(int i=0;i<tempNum.length();i++){
              
              Integer temp = new Integer(tempNum.charAt(i)+"");
              sum += temp*temp*temp*temp*temp;
          }
          if(number == sum){
              return Boolean.TRUE.booleanValue();            
          }
          return Boolean.FALSE.booleanValue();
      }

}

Bubble Sort and Selection Sort


/*
  This program is an implementaion of Bubble Sort and Selection Sort.
  */
  package datastructure;
  import java.util.Scanner;
  public class BubbleSort {
  public static void main(String args[]){
  int a[] = {10,25,2,11,14};
  int n=a.length;
  Scanner scanner = new Scanner(System.in);
  System.out.println("Enter the option for sorting - -");
  System.out.println("1. Buuble Sort");
  System.out.println("2. Selection Sort");
  System.out.println("3. Intersion Sort");
  System.out.println("10. Exit");
  int c = scanner.nextInt();
  switch(c){
  case 1:
  bubbleSort(a,n);
  break;
  case 2:
  selectionSort(a, n);
  break;
  case 3:
  insetionSort(a,n);
  break;
  default:
  System.out.println("Not Valid option");
  System.exit(0);
  }
  }
  public static void bubbleSort(int[] a, int n){
  for(int i=1;i<n;i++){
  for(int j=0;j<n-i;j++){
  if(a[j]>a[j+1]){
  int temp = a[j];
  a[j] = a[j+1];
  a[j+1] = temp;
  }
  }
  }
  System.out.println("----- Bubble Sort ----");
  for(int b : a){
  System.out.println(b);
  }
  }
  public static void selectionSort(int[] a, int n){
  int pos,small;
  for(int i=0;i<n;i++){
  small = a[i];
  pos = i;
  for(int j=i+1;j<n;j++){
  if(small > a[j]){
  small = a[j];
  pos = j;
  }
  }
  int temp = a[pos];
  a[pos] = a[i];
  a[i] = temp;
  }
  System.out.println("----- Selectionn Sort ----");
  for(int b : a){
  System.out.println(b);
  }
  }
  public static void insetionSort(int[] a, int n){
  for(int i=1;i<n;i++){
  int temp = a[i];
  int j = i;
  while(j>0 && a[j-1] >=temp){
  a[j] = a[j-1];
  --j;
  }
  a[j] = temp;
  }
  System.out.println("----- Insertion Sort ----");
  for(int b : a){
  System.out.println(b);
  }
  }
  }

Quick Sort


/*
 This program is an implementaion of quick sort.
 */
 package algorithms;

public class QuickSort {
  int numbers[];
  int number;

public void sort(int[] values) {
  this.numbers = values;
  number = numbers.length;
  quichSortAlgo(0, number - 1);
  System.out.println("Sorted Arrays");
  for (int k : numbers) {
  System.out.println(k);
  }
  }

public int[] sortReturn(int[] values) {
  this.numbers = values;
  number = numbers.length;
  quichSortAlgo(0, number - 1);
  /*
  * for(int k : numbers){ System.out.println(k); }
  */
  return numbers;
  }

private void quichSortAlgo(int low, int high) {
  int i = low, j = high;
  int pivot = numbers[(low + high) / 2];
  while (i <= j) {
  while (numbers[i] < pivot) {
  i++;
  }
  while (numbers[j] > pivot) {
  j--;
  }
  if (i <= j) {
  exchange(i, j);
  i++;
  j--;
  }
  }
  if (low < j) {
  quichSortAlgo(low, j);
  }
  if (high > i) {
  quichSortAlgo(i, high);
  }
  }

private void exchange(int i, int j) {
  int temp = numbers[i];
  numbers[i] = numbers[j];
  numbers[j] = temp;
  }

public static void main(String args[]) {
  int values[] = { 10, 20, 5, 60 };
  QuickSort quickSort = new QuickSort();
  quickSort.sort(values);
  for (int value : values) {
  System.out.println(value);
  }
  }
  }

Get vowel from a string


/*
 This program is an implementaion of quick sort.
 */
 package algorithms;

public class QuickSort {
  int numbers[];
  int number;

public void sort(int[] values) {
  this.numbers = values;
  number = numbers.length;
  quichSortAlgo(0, number - 1);
  System.out.println("Sorted Arrays");
  for (int k : numbers) {
  System.out.println(k);
  }
  }

public int[] sortReturn(int[] values) {
  this.numbers = values;
  number = numbers.length;
  quichSortAlgo(0, number - 1);
  /*
  * for(int k : numbers){ System.out.println(k); }
  */
  return numbers;
  }

private void quichSortAlgo(int low, int high) {
  int i = low, j = high;
  int pivot = numbers[(low + high) / 2];
  while (i <= j) {
  while (numbers[i] < pivot) {
  i++;
  }
  while (numbers[j] > pivot) {
  j--;
  }
  if (i <= j) {
  exchange(i, j);
  i++;
  j--;
  }
  }
  if (low < j) {
  quichSortAlgo(low, j);
  }
  if (high > i) {
  quichSortAlgo(i, high);
  }
  }

private void exchange(int i, int j) {
  int temp = numbers[i];
  numbers[i] = numbers[j];
  numbers[j] = temp;
  }

public static void main(String args[]) {
  int values[] = { 10, 20, 5, 60 };
  QuickSort quickSort = new QuickSort();
  quickSort.sort(values);
  for (int value : values) {
  System.out.println(value);
  }
  }
  }
 

Restrict Double Number to 2 decimal place


This program helps to restrict double number to 2 places after decimal. Please find the program below –

package com.knowledgewala;

import java.text.DecimalFormat;

public class SampleDecimal2Place {

    public static void main(String[] args) {

        double kilobytes = 0.01358;

        System.out.println("kilobytes : " + kilobytes);

        double newKB = Math.round(kilobytes * 100.0) / 100.0;
         System.out.println("kilobytes (Math.round) : " + newKB);

        DecimalFormat df = new DecimalFormat("###.##");
         System.out.println("kilobytes (DecimalFormat) : "
                 + df.format(kilobytes));
     }
 }

Java IO : How to read input from console


This example helps to understand to take input from console while running java program.

This program will guide to get input from various ways which are given below –

java.io.Console instance
BufferedReader instance
Scanner instance

package com.knowledgewala;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class KWConsoleInputSamples {

    public static void main(String[] args) {
        usingConsoleReader();
        usingBufferedReader();
        usingScanner();
    }

    private static void usingConsoleReader() {
        Console console = null;
        String inputString = null;
        try {
            // creates a console object
            console = System.console();
            // if console is not null
            if (console != null) {
                // read line from the user input
                inputString = console.readLine("Name: ");
                // prints
                System.out.println("Name entered : " + inputString);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void usingBufferedReader() {
        System.out.println("Name: ");
        try {
            BufferedReader bufferRead = new BufferedReader(
                    new InputStreamReader(System.in));
            String inputString = bufferRead.readLine();

            System.out.println("Name entered : " + inputString);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static void usingScanner() {
        System.out.println("Name: ");

        Scanner scanIn = new Scanner(System.in);
        String inputString = scanIn.nextLine();

        scanIn.close();
        System.out.println("Name entered : " + inputString);
    }

}


Text To ExcelSheet


This program helps read text file and insert data into excel sheet. it uses excel open api to read and write data to excel sheet.

please find the program below –

package com.sample;

import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Scanner;

import org.apache.poi.hssf.usermodel.HSSFCell;
 import org.apache.poi.hssf.usermodel.HSSFRichTextString;
 import org.apache.poi.hssf.usermodel.HSSFRow;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
 import org.apache.poi.ss.usermodel.Cell;
 import org.apache.poi.ss.usermodel.Row;
 import org.apache.poi.ss.usermodel.Sheet;
 import org.apache.poi.ss.usermodel.Workbook;
 import org.apache.poi.ss.usermodel.WorkbookFactory;

public class TextToExcelFile {
     public static void main(String[] args) throws InvalidFormatException,
             IOException {
         ArrayList arr = new ArrayList();
         
          //reading file line by line in Java using BufferedReader      
         FileInputStream fis = null;
         BufferedReader reader = null;
      
         try {
             fis = new FileInputStream("C:\\Temp\\TEXT\\SLMB_file_layout.txt");
             reader = new BufferedReader(new InputStreamReader(fis));
          
             System.out.println("Reading File line by line using BufferedReader");
          
             String line = reader.readLine();
             while(line != null){
                 System.out.println(line);
                 arr.add(line);
                 line = reader.readLine();
             }          
          
         } catch (FileNotFoundException ex) {
             
         } catch (IOException ex) {
             
          
         }    
         
         System.out.println("Data From ArrayList");
         System.out.println(arr);

        System.out.println("Write data to an Excel Sheet");
         FileOutputStream fos = new FileOutputStream("C:/Temp/TEXT/SLMB_file_layout.xls");
         HSSFWorkbook workBook = new HSSFWorkbook();
         HSSFSheet spreadSheet = workBook.createSheet("emailExcel");
         
         int cellnumber = 0;
         for (int i = 0; i < arr.size(); i++) {        
             HSSFRow row = spreadSheet.createRow((short) i);
             String[] tempArray = arr.get(i).toString().split(" ");
             for (int j = 0; j < tempArray.length; j++) {
                 
                 HSSFCell cell = row.createCell(j);
                 System.out.println(tempArray[j].toString());
                 cell.setCellValue(tempArray[j].toString());
             }        
             
         }
         System.out.println("Done");
         workBook.write(fos);
         arr.clear();
         System.out.println("ReadIng From Excel Sheet");

        FileInputStream fis1 = null;
         fis1 = new FileInputStream("C:/Temp/TEXT/SLMB_file_layout.xls");

        HSSFWorkbook workbook = new HSSFWorkbook(fis1);
         HSSFSheet sheet = workbook.getSheetAt(0);
         Iterator rows = sheet.rowIterator();

        while (rows.hasNext()) {
             HSSFRow row1 = (HSSFRow) rows.next();
             Iterator cells = row1.cellIterator();
             while (cells.hasNext()) {
                 HSSFCell cell1 = (HSSFCell) cells.next();
                 arr.add(cell1);
             }
         }
         System.out.println(arr);

    }
 }

 

 

 

 

 

 

images1

2 thoughts on “Core Java Examples For Practice”

Leave a Reply

Your email address will not be published. Required fields are marked *