10/8/16

Core Java Programs for Practice

Java program to split number into digits


package demo;
import java.util.Scanner;
public class SplitNumber
{
 public static void main(String[] args)
 {
  int num, temp, factor = 1;
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number: ");
  num = sc.nextInt();
  temp = num;
  while (temp != 0) {
   temp = temp / 10;
   factor = factor * 10;
  }
  System.out.print("Each digits of given number are: ");
  while (factor > 1) {
   factor = factor / 10;
   System.out.print((num / factor) + " ");
   num = num % factor;
  }
 }
}

Output:

Enter a number: 4732
Each digits of given number are: 4 7 3 2
BUILD SUCCESSFUL (total time: 21 seconds)


Java program to swap two array.


package demo;
import java.util.Scanner;
public class SwappingArray
{
 public static void main(String[] args) 
 {
  int[] a = new int[10], b = new int[10], c = new int[10];
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter First array: ");
  for (int i = 0; i < 10; i++) {
   a[i] = sc.nextInt();
  }
  System.out.println("Enter Second array: ");
  for (int i = 0; i < 10; i++) {
   b[i] = sc.nextInt();
  }
  System.out.println("Arrays before swapping");
  System.out.println("First array: ");
  for (int i = 0; i < 10; i++) {
   System.out.print(a[i]);
  }
  System.out.println("Second array: ");
  for (int i = 0; i < 10; i++) {
   System.out.print(b[i]);
  }
  for (int i = 0; i < 10; i++) {            //write any swapping technique
   c[i] = a[i];
   a[i] = b[i];
   b[i] = c[i];
  }
  System.out.println("Arrays after swapping");
  System.out.println("First array: ");
  for (int i = 0; i < 10; i++) {
   System.out.print(a[i]);
  }
  System.out.println("Second array: ");
  for (int i = 0; i < 10; i++) {
   System.out.print(b[i]);
  }
 }
}

Output:

Enter First array: 
1
2
3
4
5
6
7
8
9
10

Enter Second array: 

11
22
3
44
55
66
77
55
22
33

Arrays before swapping


First array: 12345678910

Second array: 1122344556677552233

Arrays after swapping

First array: 1122344556677552233
Second array:  12345678910

BUILD SUCCESSFUL (total time: 27 seconds)

Java program to find NCR factor of given number.


Calculate the combinations for C(n,r) = n! / ( r!(n - r)! ). For 0 <= r <= n.

package demo;

import java.util.Scanner;
public class Ncr
{
 public static void main(String[] args)
 {
  Scanner sc = new Scanner(System.in);
  int n, r, ncr;
  System.out.print("Enter any two numbers-");
  n = sc.nextInt();
  r = sc.nextInt();
  ncr = fact(n) / (fact(r) * fact(n - r));
  System.out.print("The NCR factor of " + n + " and " + r + " is " + ncr);
 }

 public static int fact(int n) 

 {
  int i = 1;
  while (n != 0) {
   i = i * n;
   n--;
  }
  return i;
 }
}

Output:

Enter any two numbers- 5
3
The NCR factor of 5 and 3 is 10
BUILD SUCCESSFUL (total time: 5 seconds)

Java program to find generic root.


Generic RootIt sum of digits of a number unit we don't get a single digit.
Example:
Generic root of 4563: 4+5+6+3 = 18 since 18 is two digit numbers so 1 + 8 = 9
So, generic root of 4563 = 9


package demo;

import java.util.Scanner;
public class GenericRoot
{
 public static void main(String[] args)
 {
  Scanner sc = new Scanner(System.in);
  long num, sum = 0, r;
  System.out.print("Enter a number:-");
  num = sc.nextLong();
  while (num > 10) 
  {
   sum = 0;
   while (num != 0) 
   {
    r = num % 10;
    num = num / 10;
    sum += r;
   }
   if (sum > 10) 
   {
    num = sum;
   } else
   {
    break;
   }
  }
  System.out.println("Sum of the digits in single digit is: " + sum);
 }
}

Output:

Enter a number:-5555
Sum of the digits in single digit is: 2
BUILD SUCCESSFUL (total time: 6 seconds)

Java program to add two number without using addition operator.


package demo;
import java.util.Scanner;
public class Addition
{
 public static void main(String[] args) 
 {
  int a, b;
  int sum;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any two integers: ");
  a = sc.nextInt();
  b = sc.nextInt();
  sum = a - ~b - 1;
  System.out.print("Sum of two integers: " + sum);
 }
}

Output:

Enter any two integers: 20
50
Sum of two integers: 70
BUILD SUCCESSFUL (total time: 10 seconds)


Algorithm:

In c ~ is 1's complement operator. This is equivalent to:  
~a = -b + 1
So, a - ~b -1
= a-(-b + 1) + 1
= a + b – 1 + 1
= a + b

Java program to sum digits of a number.


package demo;
import java.util.Scanner;
public class SumOfDigits
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  int num, sum = 0, r;
  System.out.println("Enter a number: ");
  num = sc.nextInt();
  while (num != 0) {
   r = num % 10;
   num = num / 10;
   sum = sum + r;
  }
  System.out.print("Sum of digits of number:  " + sum);
 }
}

Output:
Enter a number: 32165
Sum of digits of number:  17
BUILD SUCCESSFUL (total time: 8 seconds)


Java program to reverse a number.


package demo;
import java.util.Scanner;
public class ReverseNumber
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  int num, r, reverse = 0;
  System.out.print("Enter any number: ");
  num = sc.nextInt();
  while (num != 0) 
  {
   r = num % 10;
   reverse = reverse * 10 + r;
   num = num / 10;
  }
  System.out.println("Reversed of number: " + reverse);
 }
}

Output:
Enter any number: 123789
Reversed of number: 987321
BUILD SUCCESSFUL (total time: 4 seconds)

Java program to find the frequency of one string in another string.


import java.util.Scanner;
public class WordFrequencyCounter {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        System.out.println("enter main string");
        String s = scan.nextLine();
        System.out.println("enter string to be searched");
        String f = scan.nextLine();
        s = s + " ";
        int l = s.length();
        char a;
        int c = 0;
        String s1 = "";
        for (int i = 0; i < l; i++) {
            a = s.charAt(i);
            if (a != ' ') {
                s1 = s1 + a;
            } else {
                if (s1.equalsIgnoreCase(f) == true) {
                    c++;
                }
                s1 = "";
            }
        }
        System.out.println("Frequency of the word " + f + " is " + c);
    }                                         
}

Output:
Enter main string
Umesh Kumar Kushwaha Kumar
enter string to be searched
Kumar
Frequency of the word Kumar is 2

Java program to remove vowels from a string.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveVowels
{
 public static void main(String args[]) throws IOException {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String str1, str2 = "";
   char ch, ch1;
   int i, len;
   System.out.println("Enter the Sentence:");
   str1 = br.readLine();
   len = str1.length();
   for (i = 0; i < len; i++) {
    ch = str1.charAt(i);
    ch1 = Character.toLowerCase(ch);
    switch (ch1) {
     case 'a':
     case 'e':
     case 'i':
     case 'o':
     case 'u':
      break;
     default:
      str2 = str2 + ch;
    }                           //switch ends
   }                            //for ends
   System.out.println("Modified string without vowels:" + str2);
  }                            //method ends
}

Output:

Enter the Sentence:
umesh kumar kushwaha
Modified string without vowels:msh kmr kshwh

Java program to remove common characters from two strings.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RemoveCommonDuplicateChar 
{
 public static void main(String args[]) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String s1, s2, s3 = "", s4 = "";
  int a[], b[], x = 0, y = 0;
  int len1, len2;
  char ch;
  int i, j;
  System.out.println("Enter the first sentence:");
  s1 = br.readLine().trim();
  System.out.println("Enter the second sentence:");
  s2 = br.readLine().trim();
  len1 = s1.length();
  len2 = s2.length();
  a = new int[len1];
  b = new int[len2];
  for (i = 0; i < len1; i++) {
   ch = s1.charAt(i);
   for (j = 0; j < len2; j++) {
    if (ch == s2.charAt(j)) {
     break;
    }
   }
   if (j != len2) {
    a[x++] = i;
    b[y++] = j;
   }
  }
  for (i = 0; i < len1; i++) {
   for (j = 0; j < x; j++) {
    if (i == a[j]) {
     break;
    }
   }
   if (j == x) {
    s3 = s3 + s1.charAt(i);
   }
  }
  for (i = 0; i < len2; i++) {
   for (j = 0; j < y; j++) {
    if (i == b[j]) {
     break;
    }
   }
   if (j == y) {
    s4 = s4 + s2.charAt(i);
   }
  }
  System.out.println("Original string1=" + s1 + " Modified string1=" + s3);
  System.out.println("Original string2=" + s2 + " Modified string2=" + s4);
 }
}

Output:

Enter the first sentence:
Umesh Kumar Kushwaha
Enter the second sentence:
Rahul Kumar Singh
Original string1=Umesh Kumar Kushwaha Modified string1=Uessw
Original string2=Rahul Kumar Singh Modified string2=Rlua Singh

Java program to finding Shortest and Longest Words in a String.

import java.io.BufferedReader;
class FindMinMaxString {
 public static void main(String args[]) {
  findMethod("My name is Umesh Kushwaha");
 }
 static public void findMethod(String s) {
  String str = s + " ";
  char ch = ' ';
  int len = str.length(), l = 0;
  int min = len, max = 0;
  String shortest_word = "", longest_word = "", word = "";
  for (int i = 0; i < len; i++) {
   ch = str.charAt(i);
   if (ch != ' ') {
    word += ch;
   }                                     //if ends
   else {
    l = word.length();
    if (l < min) {
     min = l;
     shortest_word = word;
    }                                     //if ends
    if (l > max) {
     max = l;
     longest_word = word;
    }
    word = "";
   }
  }
  System.out.println("Shortest word = " + shortest_word + " with length " + min);
  System.out.println("Longest word = " + longest_word + " with length " + max);
 }
}

Output:

Shortest word = My with length 2
Longest word = Kushwaha with length 8

Java program to reverse a String without using direct method.

import java.io.BufferedReader;
public class ReverseOfString {
 public static String reverseString(String s)
 {
  int l = s.length();
  String backward = "";
  for (int i = l - 1; i >= 0; i--) 
 {
   backward = backward + s.charAt(i);
  }
  return backward;
 }
 public static void main(String args[]) {
  String backwards = reverseString("Umesh Kushwaha");
  System.out.println("Reverse String is " + backwards);
 }
}

Java program to input name, middle name and surname of a person and print only the initials.

Example.

Enter your name

Umesh Kumar Kushwaha
Initials are   U.K.K.

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
class InitialName {
 public static void main(String args[]) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter your name");
  String s = br.readLine(), s1 = "";
  s = " " + s;
  int len = s.length();
  char a;
  for (int i = 0; i < len; i++) {
   a = s.charAt(i);
   if (a == ' ') {
    s1 = s1 + s.charAt(i + 1) + ".";
   }
  }
  System.out.println("Initials are   " + s1);
 }
}

Output:

Enter your name
Umesh Kumar Kushwaha
Initials are   U.K.K.

Java program to remove duplicates characters from given String.


class RemoveDuplicate {
 public static void main(String args[]) {
  remove("123aa bbbcc  c2589  99oppq rtyyy");
 }
 static void remove(String s) {
  int l = s.length();
  int c;
  String org = s, s1 = "";
  for (int i = 0; i < (l - 1); i++) {
   s1 = s.substring(0, i + 1);
   c = 0;
   for (int j = i + 1; j < l; j++) {
    if (s.charAt(i) == s.charAt(j)) {
     c++;
     continue;
    } else
     s1 = s1 + s.charAt(j);
   }
   s = s1;
   s1 = "";
   if (c > 0)
    l -= c;
  }
  System.out.println("Original String:" + org);
  System.out.println("String after removing duplicates:  " + s);
 }
}


Output:


Original String:123aa bbbcc  c2589  99oppq rtyyy


String after removing duplicates:  123a bc589opqrty



Java program to count the occurrence of any character in given String.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

class CountFrequencyOfWord {

 public static void main(String args[]) {
  try {
   input();
  } catch (IOException ex) {
   Logger.getLogger(CountFrequencyOfWord .class.getName()).log(Level.SEVERE, null, ex);
  }
 }
 static void input() throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter a sentence");
  String s = br.readLine();
  System.out.println("Enter the letter ");
  char a = (char) br.read();
  int len = s.length();
  int c = 0;
  char x;
  for (int i = 0; i < len; i++) {
   x = Character.toLowerCase(s.charAt(i));
   if (x == a)
    c = c + 1;
  }
  System.out.println("Frequency of the letter  " + a + " in the sentence " + s + " is " + c);
 }
}


Output:


Enter a sentence

Hi my name is umesh
Enter the letter 
m
Frequency of the letter  m in the sentence "Hi my name is umesh" is 3

Java program to find palindromic substring in a string.

public class PalidrumSubString 
{
 public static void main(String args[]) 
 {
  String s = "my name rar kumar poop";
  String p[] = s.split(" ");
  String s2 = "";
  for (int j = 0; j < p.length; j++) 
  {
   for (int i = p[j].length() - 1; i >= 0; i--) 
   {
    char z = p[j].charAt(i);
    s2 = s2 + z;
   }

   if (p[j].equals(s2)) 
   {
    System.out.println(s2);
   }
   else 
   {
    s2 = "";
   }
  }
 }
}

Output:
rar
poop

Java program to accept a string and print each character of the string along with its ASCII code.

class CalculateAscii {
 public static void main(String args[]) {
  word("Umesh Kushwaha");
 }
 static void word(String s) {
  int len = s.length();
  int a;
  char a1;
  for (int i = 0; i < len; i++) {
   a1 = s.charAt(i);
   a = a1;
   System.out.println(a1 + "–>" + a);
  }
 }
}


Output:


U–>85

m–>109
e–>101
s–>115
h–>104
 –>32
K–>75
u–>117
s–>115
h–>104
w–>119
a–>97
h–>104
a–>97

Java program to find whether given no. is Armstrong or not.

Example :
Input - 153
Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */

class Armstrong {

 public static void main(String args[]) {
  int num = Integer.parseInt(args[0]);
  int n = num;                                   //use to check at last time
  int check = 0, remainder;
  while (num > 0) {
   remainder = num % 10;
   check = check + (int) Math.pow(remainder, 3);
   num = num / 10;
  }
  if (check == n)
   System.out.println(n + " is an Armstrong Number");
  else
   System.out.println(n + " is not a Armstrong Number");
 }
}


Output

153
153 is an Armstrong Number

Java program to Generate prime numbers between 1 & given number

/*
Prime Numbers Java Example
This Prime Numbers Java example shows how to generate prime numbers
between 1 and given number using for loop.
*/
public class GeneratePrimeNumbersExample {
 public static void main(String[] args) {
  int limit = 100;                       //define limit
  System.out.println("Prime numbers between 1 and " + limit);
  for (int i = 1; i < 100; i++) {    //loop through the numbers one by one
   boolean isPrime = true;       
   for (int j = 2; j < i; j++) {      //check to see if the number is prime
    if (i % j == 0) {
     isPrime = false;
     break;
    }
   }                                         // print the number
   if (isPrime)
    System.out.print(i + " ");
  }
 }
}

/*

Output of Prime Numbers example would be
Prime numbers between 1 and 100
1 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
*/

Java program to calculate Factorial of a number using recursion

/*
This program shows how to calculate
Factorial of a number using recursion function.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaFactorialUsingRecursion {
 public static void main(String args[]) throws NumberFormatException,
  IOException {
   System.out.println("Enter the number: ");    //get input from the user
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   int a = Integer.parseInt(br.readLine());
   int result = fact(a);            //call the recursive function to generate factorial
   System.out.println("Factorial of the number is: " + result);
  }
 static int fact(int b) {
  if (b <= 1)                           //if the number is 1 then return 1
   return 1;
  else                                    //else call the same function with the value - 1
   return b * fact(b - 1);
 }
}


/*

Output of this Java example would be
Enter the number:
5
Factorial of the number is: 120
*/

Java program to check Palindrome Number.

/*
This program shows how to check for in the given list of numbers
whether each number is palindrome or not
*/
public class JavaPalindromeNumberExample {
 public static void main(String[] args) {
  int numbers[] = new int[] {121,13,34,11,22,54};
  for (int i = 0; i < numbers.length; i++) {
   int number = numbers[i];
   int reversedNumber = 0;
   int temp = 0;
   /*
    * If the number is equal to it's reversed number, then
    * the given number is a palindrome number.
    *
    * For ex,121 is a palindrome number while 12 is not.
    */
   //reverse the number
   while (number > 0) {
    temp = number % 10;
    number = number / 10;
    reversedNumber = reversedNumber * 10 + temp;
   }
   if (numbers[i] == reversedNumber)
    System.out.println(numbers[i] + " is a palindrome");
   else
    System.out.println(numbers[i] + " not a palindrome ");
  }
 }
}


/*

Output of Java Palindrome Number Example would be
121 is a palindrome number
13 is not a palindrome number
34 is not a palindrome number
11 is a palindrome number
22 is a palindrome number
54 is not a palindrome number
*/

Java program to design a class account using the inheritance and static that show all function of bank and generate account number dyanamically.

import java.util.*;
class Bank {
 static int acc_no = 10001;
 float amt;
 public void display() {
  System.out.println("Account no :" + acc_no);
  System.out.println("Current Amount :" + amt);
 }
 public bank() {
  amt = 1000;
  System.out.println("Ur account no is " + acc_no);
  acc_no++;
 }
 public void getamt() {
  System.out.println("Current balance :" + amt);
 }
 public void withdraw(float x) {
  if (amt == 1000 || amt <= x) {
   System.out.println("Sorry u can't withdraw");
  } else {
   amt = amt - x;
   System.out.println("amount withdrawn :" + x);
   System.out.println("After withdrawl");
   getamt();
  }
 }
 public void deposit(float x) {
  if (x == 0.0)
   System.out.println("OOPS 0 can't be deposited");
  else {
   amt += x;
   System.out.println("After deposition");
   getamt();
  }
 }
 public static void main(String args[]) {
  Scanner sc = new Scanner(System.in);
  bank b1 = new bank();
  b1.deposit(0);
  b1.withdraw(120.5 f);
  b1.display();
  System.out.println("\n");
  bank b2 = new bank();
  b2.deposit(1000.0 f);
  b2.withdraw(150.5 f);
 }
}