ads

Saturday, February 13, 2016

Java program to check palindrome

Java palindrome program: Java program to check if a string is a palindrome or not. Remember a string is a palindrome if it remains unchanged when reversed, for example "dad" is a palindrome as reverse of "dad" is "dad" whereas "program" is not a palindrome. Some other palindrome strings are "mom", "madam", "abcba".

Java programming source code

import java.util.*;
 
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
 
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
 
int length = original.length();
 
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
 
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
 
}
}
Download Palindrome program class file.
Output of program:
palindrome
Another method to check palindrome:
import java.util.*;
 
class Palindrome
{
public static void main(String args[])
{
String inputString;
Scanner in = new Scanner(System.in);
 
System.out.println("Input a string");
inputString = in.nextLine();
 
int length = inputString.length();
int i, begin, end, middle;
 
begin = 0;
end = length - 1;
middle = (begin + end)/2;
 
for (i = begin; i <= middle; i++) {
if (inputString.charAt(begin) == inputString.charAt(end)) {
begin++;
end--;
}
else {
break;
}
}
if (i == middle + 1) {
System.out.println("Palindrome");
}
else {
System.out.println("Not a palindrome");
}
}
}
Both the above codes consider string as case sensitive, you can modify them so that they ignore the case of string. You can either convert both strings to lower or upper case for this. But do not modify original strings as they may be further required in program.

Interface in Java

Interface in Java: Java interfaces are like Java classes but they contain only static final constants and declaration of methods. Methods are not defined and classes which implements an interface must define the body of method(s) of interface(s). Final constants can't be modified once they are initialized; final, interface, extend and implements are Java keywords.
Declaration of interface:
interface InterfaceName {
// constants declaration
// methods declaration
}

Interface program in Java

In our program we create an interface named Info which contains a constant and a method declaration. We create a class which implements this interface by defining the method declared inside it.
interface Info {
static final String language = "Java";
public void display();
}
 
class Simple implements Info {
public static void main(String []args) {
Simple obj = new Simple();
obj.display();
}
 
// Defining method declared in interface
 
public void display() {
System.out.println(language + " is awesome");
}
}
Download Interface program class file.
Output of program:
Interface java example program output

Java program to compare two strings

This program compare strings i.e test whether two strings are equal or not, compareTo method of String class is used to test equality of two String class objects. compareTo method is case sensitive i.e "java" and "Java" are two different strings if you use compareTo method. If you wish to compare strings but ignoring the case then use compareToIgnoreCase method.

Java programming code

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.");
}
}
Download Compare strings program class file.
Output of program:
compare strings
String 'hello' is greater than 'Hello' as ASCII value of 'h' is greater than 'H'. To check two strings for equality you can use equals method which returns true if strings are equal otherwise false.

Java program to reverse a string

This java program reverses a string entered by the user. We use charAt method to extract characters from the string and append them in reverse order to reverse the entered string.

Java programming code

import java.util.*;
 
class ReverseString
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
 
System.out.println("Enter a string to reverse");
original = in.nextLine();
 
int length = original.length();
 
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
 
System.out.println("Reverse of entered string is: "+reverse);
}
}
Download Reverse string program class file.
Output of program:
reverse string

Reverse string using StringBuffer class

class InvertString
{
public static void main(String args[])
{
StringBuffer a = new StringBuffer("Java programming is fun");
System.out.println(a.reverse());
}
}
StringBuffer class contains a method reverse which can be used to reverse or invert an object of this class.

Java program to check armstrong number

This java program checks if a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number. Some Armstrong numbers are: 0, 1, 4, 5, 9, 153, 371, 407, 8208 etc.

Java programming code

import java.util.Scanner;
 
class ArmstrongNumber
{
public static void main(String args[])
{
int n, sum = 0, temp, remainder, digits = 0;
 
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
 
temp = n;
 
// Count number of digits
 
while (temp != 0) {
digits++;
temp = temp/10;
}
 
temp = n;
 
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
 
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
 
static int power(int n, int r) {
int c, p = 1;
 
for (c = 1; c <= r; c++)
p = p*n;
 
return p;
}
}
Download Armstrong number program class file.
Output of program:
Armstrong number java program output
Using one more loop in the above code you can generate Armstrong numbers from 1 to n(say) or between two integers (a to b).

Java program to print Floyd's triangle

This java program prints Floyd's triangle.

Java programming source code

import java.util.Scanner;
 
class FloydTriangle
{
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
 
System.out.println("Enter the number of rows of floyd's triangle you want");
n = in.nextInt();
 
System.out.println("Floyd's triangle :-");
 
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
 
System.out.println();
}
}
}
Download Floyd's triangle program class file.
Output of program:
Floyd triangle program
In Floyd triangle there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. This is a simple pattern to print but helpful in learning how to create other patterns. Key to develop pattern is using nested loops appropriately.

Java program to find factorial

This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed.

Java programming code

import java.util.Scanner;
 
class Factorial
{
public static void main(String args[])
{
int n, c, fact = 1;
 
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
 
n = in.nextInt();
 
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
 
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
Download Factorial program class file.
Output of program:
factorial program
You can also find factorial using recursion, in the code fact is an integer variable so only factorial of small numbers will be correctly displayed or which fits in 4 bytes. For large numbers you can use long data type.

Java program for calculating factorial of large numbers

Above program does not give correct result for calculating factorial of say 20. Because 20! is a large number and cant be stored in integer data type which is of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.
import java.util.Scanner;
import java.math.BigInteger;
 
class BigFactorial
{
public static void main(String args[])
{
int n, c;
BigInteger inc = new BigInteger("1");
BigInteger fact = new BigInteger("1");
 
Scanner input = new Scanner(System.in);
 
System.out.println("Input an integer");
n = input.nextInt();
 
for (c = 1; c <= n; c++) {
fact = fact.multiply(inc);
inc = inc.add(BigInteger.ONE);
}
 
System.out.println(n + "! = " + fact);
}
}
Download Big Factorial class file.
We run the above java program to calculate 100 factorial and following output is obtained.
Input an integer
100
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000