# Write a program to convert a non-negative integer number to its English words representation

In this program converting Non-negative numbers to English words through Java Program. You can use the same logic to implement with other languages like C, C++, C#, Python, etc.

This program is most frequently asked in programming label tests or interviews to check your logical skills. You can also utilize the same code while generating invoices, bills, reports where want to show sum, average, gross total etc. in form of words.

For Example :

## Java Program

To convert a number to English word core logic is to check 10th position of the number the add words for the same. Based on the range between billion to thousand then take reminder and add word (thousand, million or billion) etc. then further dividend of the number by the range and further pass for convert as long as not reaching to less than thousand. Finally, when numbers reach to between 1-20 take the words from map 1-20 range.

Source Code:

```package programming;

import java.text.DecimalFormat;

public class NNNumberToWordExample {
// array of string type for one digit numbers
private static final String[] doubleDigits = { "", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty",
" Seventy", " Eighty", " Ninety" };
// array of string for two digits numbers
private static final String[] singleDigit = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven",
" Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen",
" Seventeen", " Eighteen", " Nineteen" };

// converts a number to words (up to 1000)
private static String convertUptoThousand(int number) {
String soFar;
if (number % 100 < 20) {
soFar = singleDigit[number % 100];
number = number / 100;
} else {
soFar = singleDigit[number % 10];
number = number / 10;
soFar = doubleDigits[number % 10] + soFar;
number = number / 10;
}
if (number == 0)
return soFar;
return singleDigit[number] + " Hundred " + soFar;
}

// converts a long number (0 to 999999999) to string
public static String convertNumberToWord(long number) {
// checks whether the number is zero or not if number is zero return zero
if (number == 0) {
return "zero";
}
// convert long value to string
String num = Long.toString(number);
String pattern = "000000000000";
/**
* Convert to DecimalFormat using the specified pattern and also provides the
* symbols to default locale
*/
DecimalFormat decimalFormat = new DecimalFormat(pattern);
// format a number of the DecimalFormat
num = decimalFormat.format(number);
/**
* format: XXXnnnnnnnnn the subString() method returns a new string that is a
* substring of this string the substring begins at the specified beginIndex and
* extends to the character at index endIndex - 1 the parseInt() method converts
* the string into integer
*/
int billions = Integer.parseInt(num.substring(0, 3));
// format to: nnnXXXnnnnnn
int millions = Integer.parseInt(num.substring(3, 6));
// format to: nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(num.substring(6, 9));
// format to: nnnnnnnnnXXX
int thousands = Integer.parseInt(num.substring(9, 12));

switch (billions) {
case 0:
break;
case 1:
tradBillions = convertUptoThousand(billions) + " Billion ";
break;
default:
tradBillions = convertUptoThousand(billions) + " Billion ";
}

switch (millions) {
case 0:
break;
case 1:
tradMillions = convertUptoThousand(millions) + " Million ";
break;
default:
tradMillions = convertUptoThousand(millions) + " Million ";
}

switch (hundredThousands) {
case 0:
break;
case 1:
break;
default:
tradHundredThousands = convertUptoThousand(hundredThousands) + " Thousand ";
}

// removing extra space if any
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}

public static void main(String args[]) {
// Test cases to convert number to words
System.out.println(convertNumberToWord(5));
System.out.println(convertNumberToWord(89));
System.out.println(convertNumberToWord(656));
System.out.println(convertNumberToWord(1301));
System.out.println(convertNumberToWord(13512));
System.out.println(convertNumberToWord(567319));
System.out.println(convertNumberToWord(90908890));
System.out.println(convertNumberToWord(2000000000));
System.out.println(convertNumberToWord(569999999));
System.out.println(convertNumberToWord(3233000000L));
System.out.println(convertNumberToWord(5000000));
System.out.println(convertNumberToWord(333333333));
System.out.println(convertNumberToWord(5000400));
System.out.println(convertNumberToWord(600000));
System.out.println(convertNumberToWord(4000000));
}
}
```

## Output

```Five
Eighty Nine
Six Hundred Fifty Six
One Thousand Three Hundred One
Thirteen Thousand Five Hundred Twelve
Five Hundred Sixty Seven Thousand Three Hundred Nineteen
Ninety Million Nine Hundred Eight Thousand Eight Hundred Ninety
Two Billion
Five Hundred Sixty Nine Million Nine Hundred Ninety Nine Thousand Nine Hundred Ninety Nine
Three Billion Two Hundred Thirty Three Million
Five Million
Three Hundred Thirty Three Million Three Hundred Thirty Three Thousand Three Hundred Thirty Three
Five Million Four Hundred
Six Hundred Thousand
Four Million
```

Happy Learning !!!

# Java Program : Get all possible values of X such that A % X = B

Question:  Write a java program to get  all possible values of X such that A % X = B. Input two integers A and B. The task is to find the  all possible values X such that A % X = B. If there are infinite number of possible values then print -1.

Examples:

1. Input: A = 21, B = 5
Output: 2
8 and 16 are the only valid values for X.
2. Input: A = 5, B = 5
Output: -1
X can have any value > 5

# Algorithm

• Step 1: Ask the user to input values of A and B
• Step 2: Find out all possible factors of (A-B) which are greater than B
• Step 3: Use StringJoiner to print the possible value in comma separated form.

# Java Program

```public class Program1 {
public static void main(String[] args) {
System.out.println("Enter values of A and B to get possible values of X from expression A % X = B");

Scanner input = new Scanner(System.in);
System.out.print("Please Enter an integer A: ");
int A = input.nextInt();

System.out.print("Please Enter an integer B: ");
int B = input.nextInt();

System.out.println("Possible Values of X :" + getAllowedValues(A, B));
}

private static String getAllowedValues(int A, int B) {
//Use to print value in comma separated form
StringJoiner joiner = new StringJoiner(",");

if (A - B > 0) {
//find out all possible factor of(A-B) which are greater than B
for (int C = (A - B); C > 0 & C > B; C /= 2) {
if ((A - B) % C == 0)
}
} else {
}
return joiner.toString();
}

}
```

## Output

``````
Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 21
Please Enter an integer B: 5
Possible Values of X :16,8

Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 5
Please Enter an integer B: 5
Possible Values of X :-1

``````

# Mathematical Programming Test

Here are some most common formulae based mathematical programs. These programming test is basically for checking the mathematical knowledge and Java operator precedence to implement these formulae.

1. Program to calculate the area of rectangle
Input: Width = 10; Height = 5
Output:
Area of Rectangle = Width * Height
= 10 * 5
= 50
2. Program to calculate the volume of sphere
Input:Radius = 48; Pie = 3.14
Output:
= (4.0/3.0) * 3.14 * 48 * 48 * 48
= 463433.132812
3. Program find the area of the pentagon
Input:s = 13; a = 5;
Output:
Area of Pentagon = (5.0/2.0) * s * a
= (5.0/2.0) * 13 * 5
= 162.5
4. Program to find the area of parallelogram
Input:base = 4; height = 18;
Output:
Area of Parallelogram = base * height;
= 4 * 18
= 72
5. Program to find the area of square
Input:a = 13
Output:
Area of Square = a2
= 132
= 169
6. Program to find the surface area of sphere
Input:Radius = 37, Pie = 3.14
Output:
= 4 * 3.14 * 37 * 37
= 17210.285714
7. Program to find the volume of cone
Input:Radius = 38, Height = 35, Pie = 3.14
Output:
= 3.14 * 38 * 38 * 35/3
= 48766.666667
8. Program to find the volume of the cube
Input:side = 4
Output:
Volume of cube = side3
= 43
= 64
9. Program to find the volume of cylinder
Input:radius (r) = 38 , height (h) = 35
Output:
Volume of the cylinder = pie * radius2 * height
= 3.14 * 38* 38 * 35
= 146300.000000
10. Program to calculate the CGPA percentage
CGPA percentage is = (float)(9.5 * (CGPA));
Input:
CGPA = (Grades in all Subjects) / (Total Number of Subjects).
English = 9.1;
Hindi = 8.5;
Maths = 9.5;
Science =9.6;
SocialStudy = 8.6;
CGPA = (9.1+8.5+9.5+9.6+8.6)/(5.0);
Output:CGPA percentage is = 86.070000
11. Program to convert Celsius into Fahrenheit
Temperature in Fahrenheit = ((celsius * 9) / 5) + 32
Input:celsius= 12
Output:Temperature in Fahrenheit = 53.6
12. Program to convert days into years
Input:days= 799;
Output:
Number of years = days / 365;
= 799 / 365
= 2
13. Program to convert Fahrenheit into Celsius
Temperature in Celsius = ((Fahrenheit-32)*5)/9
Input:Fahrenheit = 54
Output:Temperature in Celsius= ((54-32)*5)/9 = 12.22222
14. Program to find the area of an equilateral triangle
Input:side (a) = 5
Output:
Area of Equilateral Triangle = ( 1.73 * a * a) / 4
= ( 1.73 * 5 * 5) / 4
= 10.81250
15. Program to find the area of a triangle
Input:b = 5; h = 12
Output:Area of Triangle = (b * h) / 2
= (5 * 12) / 2
= 30.0
16. Program to find the area of the right angle triangle
Input:b = 5; h = 8
Output:Area of Triangle = (b * h) / 2
= (5 * 8) / 2
= 20.0
17. Program to find the perimeter of the rectangle
Input:a = c = 5
b = d = 4
Output:Perimeter of Rectangle = 2 * ( a + b);
= 2 * (5 + 4)
= 18.00000
18. Program to find the simple interest
Simple Interest = (P × R × T) / 100
Input:P = 34000, R = 30,T = 5
where P = Principal Amount, R = Rate per Annum, T = Time (years)
Output: Simple Interest = 51000.000
19. Program to find the surface area of a cube
Surface Area Of Cube = 6 ( a * a )
Input:b = 5, h = 5
a (side) = length = breadth = height
Output:Surface Area Of Cube = 6 * 5 * 5=150.00000
20. Program to find the surface area of sphere
Input:l= 2, w = 3, h = 5;
where l = length, w = width and h = height.
Output:
Surface Area OfCuboid = 2 * (l * w+ w * h + h * l)
= 2 * (2 * 3 + 3 * 5 + 5 * 2)
= 62.00000
21. Program to find the surface area of the cylinder
Surface Area of Cylinder = 2 Π (r + h)
Input:r = 2.0, h = 5.0
Output:
Surface Area of Cylinder = 2 Π (r + h)
Here, r = radius, h = height, and Π ( pie ) = 3.14
= 2 * 3.14 * ( 2.0 + 5.0)
= 44.00000
22. Write a Java program to compute the area of a hexagon.
Area of a hexagon = (6 * s^2)/(4*tan(π/6))
where s is the length of a side
Input: Input the length of a side of the hexagon: 6
Output: The area of the hexagon is: 93.53074360871938
23. Write a Java program to compute the area of a polygon.
Area of a polygon = (n*s^2)/(4*tan(π/n))
where n is n-sided polygon and s is the length of a side
Input:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Output: The area is: 130.82084798405722
24. Write a Java program to compute the distance between two points on the surface of earth.
Distance between the two points [ (x1,y1) & (x2,y2)]
d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 – y2))
Radius of the earth r = 6371.01 Kilometers
Input:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 35.5
Input the longitude of coordinate 2: 25.5
Output: The distance between those points is: 1480.0848451069087 km

# Frequently Asked Algorithms & Java Programs

Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level programmers to check hands on with the code or not.

1. Write a program to print alphabet using java loop
Output:
a b c d e f g h i j k l m n o p q r s t u v w x y z
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2. Write a program to check odd or even number.
Input:  5
Output: Odd Number
3. Write a program to convert Fahrenheit to Celsius.
Input: 50
Output: 10.0
4. Write a java program to print fibonacci series without using recursion and using recursion.
Input: 12
Output: 0 1 1 2 3 5 8 13 21 34 55 89 144
5. Write a java program to check prime number.
Input: 42
Output: Not prime number
Input: 13
Output: Prime number
6. Write a java program to check palindrome number.
Input: 349
Output: Not palindrome number
Input: 1234321
Output: Palindrome number
7. Write a java program to print factorial of a number.
Input: 4
Output: 24
Input: 5
Output: 120
8. Write a java program to check Armstrong number.
Input: 153
Output: Armstrong number
Input: 22
Output: Not Armstrong number
9. Write a program to swap numbers without using third variable.
Input: 20 30
Output: 30 20
10. Write a program to reverse of number.
Input:    123456
Output: 654321
11. Write a program to find largest of three numbers.
Input: 10 30 40
Output: 40
12. Write a program to print Floyd triangle.
Input: 7
Output:

`1`
`2 3`
`4 5 6`
`7 8 9 10`
`11 12 13 14 15`
`16 17 18 19 20 21`
`22 23 24 25 26 27 28`

# Sorting Program

1. Write a java program to sort an array elements using bubble sort algorithm.
Input:    2 6 3 8 4 1 5 0
Output: 0 1 2 3 4 5 6 8
2. Write a java program to sort an array elements using selection sort algorithm.
Input:    2 6 3 8 4 1 5 0
Output: 0 1 2 3 4 5 6 8
3. Write a java program to sort an array elements using insertion sort algorithm.
Input:    2 6 3 8 4 1 5 0
Output: 0 1 2 3 4 5 6 8
4. Write a java program to sort an array elements using quick sort algorithm.
Input:    12 24 45 56 10 9 49 30 5 15
Output: 5 9 10 12 15 24 30 45 49 56
5. Write a java program to sort an array elements using heap sort algorithm.
Input:    2 6 3 8 4 1 5 0
Output: 0 1 2 3 4 5 6 8
6. Write a java program to sort an array elements using merge sort algorithm.
Input:    12 24 45 56 10 9 49 30 5 15
Output: 5 9 10 12 15 24 30 45 49 56
7. Write a java program to sort an array elements using shell sort algorithm.
Input:    2 6 3 8 4 1 5 0
Output: 0 1 2 3 4 5 6 8
8. Write a java program to sort an array elements using radix sort algorithm.
Input:   170 45 75 90 2 802 2 66
Output: 2 2 45 66 75 90 170 802
9. Write a java program to sort an array elements using bucket sort algorithm.
Input:   0.23 0.67 0.32 0.25 0.88 0.45 0.86 0.16 0.59 0.38 0.19 0.43 0.02
Output: 0.02 0.16 0.19 0.23 0.25 0.32 0.38 0.43 0.45 0.59 0.67 0.86 0.88
10. Write a java program to sort an array elements using counting sort algorithm.
Input:    2 6 3 2 8 4 8 1 5 3 1 4 0
Output: 0 1 1 2 2 3 3 4 4  5 6 8 8

# Fibonacci Series Java Program

“A fibonacci series is sequence of numbers, where each number is sum of the two preceding two numbers, Series initial two values are 1 , 1″

For Example : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144………

# Fibonacci Series Program

Here is program to get Fibonacci series number on particular position and print series up to that point. In this program using recursion to generate Fibonacci numbers, Here put base condition to terminate recursion as when number reach to 1 or 2  and for rest of the case work recursively for current number and previous one and then add it.

```import java.util.HashMap;
import java.util.Map;

public class FibonacciSeriesExample {

private static Map series = new HashMap();

public static void main(String[] args) {

// Get the 12th fibonacci number from series
System.out.println("Fibonacci 12 the position element :" + fibonacci(12));

System.out.println("Print Complete Fibonacci Series :");
printFibonacci(series);
}

public static int fibonacci(int fibIndex) {

// set base element of fibonacci series
if (fibIndex == 1 || fibIndex == 2) {
series.put(1, 1);
series.put(2, 1);
}

// execute fibonacci recursively until fibIndex reach to 1
if (series.containsKey(fibIndex)) {
return series.get(fibIndex);
} else {
int answer = fibonacci(fibIndex - 1) + fibonacci(fibIndex - 2);
}
}

public static void printFibonacci(Map series) {

for (Map.Entry entry : series.entrySet()) {
System.out.println(entry.getValue());
}
}
}

```

## Output

``````
Fabonnici 12 the position element :144
Print Complete Fabonni Series :
1
1
2
3
5
8
13
21
34
55
89
144

``````

# Merge Sort Program and Complexity (Big-O)

Mergesort is a comparison sort, same as quicksort and based on divide and conquer algorithm. It divides the original data set into smaller pieces of data set to solve the problem and then finally merge these small data sets.

## How Merge Sort Works

Merge sort works in the following way:

1. Merge sort, take middle index in data set and split into two collections : one collection for items left of middle index and second for right values of middle index.
2. Repeat step 1 as long as these collections size reach to one item only.
3. Now merge sort picks the items from smaller collections, sort them and merge to create new collection.
4. Repeat this sort and merge process until all small colection sort and merge not completed.
5. Finally will get single collection with sorted result.

## Points to Remember

• Data Structure: Array
• Best Time Complexity: Ω(n log(n))
• Average Time Complexity: Θ(n log(n))
• Worst Time Complexity: O(n log(n))
• Worst Space Complexity: O(n)

## Merge Sort Program

```public class MergeSort {

public int[] sort(int [] array){
mergeSort(array, 0, array.length-1);
return array;

}

private void mergeSort(int[] array, int first, int last) {

// Get mid position to divide problem into smaller size collections
int mid = (first + last) / 2;

//If first < last the array must be recursively sorted
if (first < last) {
mergeSort(array, first, mid);
mergeSort(array, mid + 1, last);
}

//merge solved collections to get solution to original problem
int a = 0, f = first, l = mid + 1;
int[] temp = new int[last - first + 1];

//decide the swapping of items
while (f <= mid && l <= last) {
temp[a++] = array[f] < array[l] ? array[f++] : array[l++];
}

while (f <= mid) {
temp[a++] = array[f++];
}

while (l <= last) {
temp[a++] = array[l++];
}

a = 0;
while (first <= last) {
array[first++] = temp[a++];
}
}

public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}

}

public static void main(String[] args) {

System.out.println("Original array before Merge sort");
int[] items = {12, 24, 45, 56, 10, 9, 49, 30, 5, 15};
printArray(items);

System.out.println("\n\nAfter Mergesort");
MergeSort merge = new MergeSort();
merge.sort(items);
printArray(items);

}
}
```

## Output

``````
Original array before Merge sort
12 24 45 56 10 9 49 30 5 15

After Mergesort
5 9 10 12 15 24 30 45 49 56
``````

# Data Structure and Algorithms Complexity (Big-O)

Big-O notation is a mathematical representation used to describe the complexity of a data structure and algorithm. There are two types of Complexity :

1. Time Complexity: Its measure based on steps need to follow for an algorithm.
2. Space Complexity: It measures the space required to perform an algorithm and data structure.

## Data Structure and Algorithm Decision

Data structure and algorithm decisions are based on the complexity of size and operations need to perform on data. Some algorithms perform better on a small set of data while others perform better for big data sets for certain operations.

These days Space Complexity is not big concerns but the main performance of an algorithm measures based on time complexity. We can make the decision to choose an algorithm based on below performance criteria with respect to Complexity.

 Complexity Performance O(1) Excellent O(log(n)) Good O(n) Fair O(n log(n)) Bad O(n^2) Horrible O(2^n) Horrible O(n!) Horrible

This post almost covers data structure and algorithms space and time Big-O complexities. Here you can also see time complexities for types of operations like access, search, insertion, and deletion.

## Data Structure Space and Time Complexity

 Data Structure Time Complexity Space Complexity Average Worst Access Search Insertion Deletion Array Θ(1) Θ(n) Θ(n) Θ(n) O(n) Stack Θ(n) Θ(n) Θ(1) Θ(1) O(n) Queue Θ(n) Θ(n) Θ(1) Θ(1) O(n) Singly-Linked List Θ(n) Θ(n) Θ(1) Θ(1) O(n) Doubly-Linked List Θ(n) Θ(n) Θ(1) Θ(1) O(n) Skip List Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n log(n)) Hash Table N/A Θ(1) Θ(1) Θ(1) O(n) Binary Search Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n) Cartesian Tree N/A Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n) B-Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n) Red-Black Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n) Splay Tree N/A Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n) AVL Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n) KD Tree Θ(log(n)) Θ(log(n)) Θ(log(n)) Θ(log(n)) O(n)

## Sorting Algorithms Space and Time Complexity

 Algorithm Time Complexity Space Complexity Best Average Worst Worst Quick Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(log(n)) Merge Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(n) Tim Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n) Heap Sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(1) Bubble Sort Ω(n) Θ(n^2) O(n^2) O(1) Insertion Sort Ω(n) Θ(n^2) O(n^2) O(1) Selection Sort Ω(n^2) Θ(n^2) O(n^2) O(1) Tree Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(n) Shell Sort Ω(n log(n)) Θ(n(log(n))^2) O(n(log(n))^2) O(1) Bucket Sort Ω(n+k) Θ(n+k) O(n^2) O(n) Radix Sort Ω(nk) Θ(nk) O(nk) O(n+k) Counting Sort Ω(n+k) Θ(n+k) O(n+k) O(k) Cube Sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)

# JAVA : Generate 15 Minute Time Interval AM/PM

In this program you can get list of in time interval with fixed difference Ex: 15 minute in AM and PM format.

Example

```import java.util.ArrayList;
import java.util.List;

public class GenerateTimeInterval {

public static void main(String[] args) {
int interval = 15; //minutes interval
List timesList=new ArrayList() ; // time array
String []ap = {"AM", "PM"}; // AM-PM
String timeFormat;
for(int h=0;h<24;h++)
{
for(int m=0;m<60;)
{
if(h<12)
{
timeFormat=String.format("%02d:%02d %s", h,m,"AM");
}
else
{
timeFormat=String.format("%02d:%02d %s", h,m,"PM");
}
m=m+interval;
}

}
//To match the time
timeFormat=String.format("%02d:%02d %s", 0,0,"AM");
//print timings
for(String time : timesList)
{
System.out.println(time);
}

}
}

```

Output

``````
00:00 AM
00:15 AM
00:30 AM
00:45 AM
01:00 AM
01:15 AM
01:30 AM
01:45 AM
02:00 AM
02:15 AM
02:30 AM
02:45 AM
03:00 AM
03:15 AM
03:30 AM
03:45 AM
04:00 AM
04:15 AM
04:30 AM
04:45 AM
05:00 AM
05:15 AM
05:30 AM
05:45 AM
06:00 AM
06:15 AM
06:30 AM
06:45 AM
07:00 AM
07:15 AM
07:30 AM
07:45 AM
08:00 AM
08:15 AM
08:30 AM
08:45 AM
09:00 AM
09:15 AM
09:30 AM
09:45 AM
10:00 AM
10:15 AM
10:30 AM
10:45 AM
11:00 AM
11:15 AM
11:30 AM
11:45 AM
12:00 PM
12:15 PM
12:30 PM
12:45 PM
13:00 PM
13:15 PM
13:30 PM
13:45 PM
14:00 PM
14:15 PM
14:30 PM
14:45 PM
15:00 PM
15:15 PM
15:30 PM
15:45 PM
16:00 PM
16:15 PM
16:30 PM
16:45 PM
17:00 PM
17:15 PM
17:30 PM
17:45 PM
18:00 PM
18:15 PM
18:30 PM
18:45 PM
19:00 PM
19:15 PM
19:30 PM
19:45 PM
20:00 PM
20:15 PM
20:30 PM
20:45 PM
21:00 PM
21:15 PM
21:30 PM
21:45 PM
22:00 PM
22:15 PM
22:30 PM
22:45 PM
23:00 PM
23:15 PM
23:30 PM
23:45 PM
00:00 AM

``````

# Java : How to convert seconds to Time?

In this blog, you will learn to convert seconds to time. An hour has 60*60=3600 seconds and a minute has 60 seconds.

Example
In this example helps you to convert total seconds to time as (hour, minute an d second). To show as text String convert these these values to String.

```public class ConvertSecondToTime {

public static void main(String[] args) {
long time = 180500700;
ConvertSecondToTime ts = new ConvertSecondToTime();
System.out.println("Inserted Total Seconds :"+time);
System.out.println(ts.secondsToTimeString(time));
}

public static String secondsToTimeString(long time) {
int seconds = (int) (time % 60);
int minutes = (int) ((time / 60) % 60);
int hours = (int) ((time / 3600) % 24);
String secondsTxt = (seconds < 10 ? "0" : "") + seconds;
String minutesTxt = (minutes < 10 ? "0" : "") + minutes;
String hoursTxt = (hours < 10 ? "0" : "") + hours;
return new String("Converted Time :"+ hoursTxt + " Hour : " + minutesTxt + " Minute :" + secondsTxt + " Second");
}
}
```

Output

``````
Inserted Total Seconds :180500700
Converted Time :03 Hour : 05 Minute :00 Second

``````

# Java : Convert Decimal to Binary

In this blog, you will learn to convert decimal number into binary string. The java.lang package provides api’s to convert a decimal number into a binary number.

Example
This program takes a decimal number from user as string and convert it to decimal number. toBinaryString() method takes an integer type value and returns its string representation of integer values which represents the data in binary. The base of binary number is 2.

```import java.util.Scanner;

public class ConvertDecimalToBinary {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

System.out.println("Enter the decimal value:");
String hex = scan.nextLine();
// convert String to Int
int i = Integer.parseInt(hex);
// convert integer to binary
String by = Integer.toBinaryString(i);
// print binary String
System.out.println("Binary: " + by);
}
}
```

Output

``````
Enter the decimal value:
12
Binary: 1100

Enter the decimal value:
200
Binary: 11001000
``````

# Java : How to convert GMT, CST, IST and PST timezone?

In this article, you will learn to convert a date to GMT, CST, EST and PST format.

• GMT : Greenwich Mean Time
• CST : Central Standard Time= GMT-5
• EST : Eastern Standard Time = GMT-6
• PST : Pacific Standard Time=GMT-7

Example
This example helps you in converting a date to  GMT, CST, EST and PST time on the console. The SimpleDateFormat() constructor uses the given pattern and date format symbols. Here we use the date format as gmtFormat for date format in GMT timezone same way can convert for CST, EST and PST. Then we have used getTimeZone() method to get the time of both the zones to be converted.

```import java.util.*;
import java.text.*;

public class ConvertTimeZoneFromGMT {

public static void main(String[] args) {
//Current Date and Time
Date date = new Date();

//GMT Format
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(date));

//CST Time
DateFormat cstFormat = new SimpleDateFormat();
TimeZone cstTime = TimeZone.getTimeZone("CST");
cstFormat.setTimeZone(cstTime);
System.out.println("CST Time: " + cstFormat.format(date));

//EST Time
DateFormat istFormat = new SimpleDateFormat();
TimeZone estTime = TimeZone.getTimeZone("EST");
estFormat.setTimeZone(estTime);
System.out.println("EST Time: " + estFormat.format(date));

// PST Time
DateFormat pstFormat = new SimpleDateFormat();
TimeZone pstTime = TimeZone.getTimeZone("PST");
pstFormat.setTimeZone(pstTime);
System.out.println("PST Time: " + pstFormat.format(date));

}
}
```

Output

``````
GMT Time: 3/22/19 8:39 AM
CST Time: 3/22/19 3:39 AM
EST Time: 3/22/19 2:09 PM
PST Time: 3/22/19 1:39 AM
``````

# Java Program : Convert Time Hour, Minute and Second

In this program converting one time unit value to hour, minute and second. Generally such type of questions asked in interview to check programming logic.

```import java.util.Scanner;

public class TimeConversion {
static int SECOND = 60*60;
static int MINUTE = 60;
static int HOUR = 1;

public static void main(String[] args) {

System.out.println("Please enter :\nh for hour\nm for minute \ns for second");
Scanner in = new Scanner(System.in);
System.out.println("Convert from:");
String fromUnit = in.nextLine();
System.out.println("Value:");
int val = in.nextInt();
String convertedTime = convertTime(fromUnit,val);
System.out.println("Converted Time :"+convertedTime);
}

private static String convertTime(String unit, int value)
{
int h=0,m=0,s=0,seconds=0;
//Convert to seconds
switch(unit)
{
case "h": seconds=value*SECOND;
break;
case "m": seconds=value*MINUTE;
break;
case "s": seconds=value;
break;
}

h=seconds/SECOND;
value=seconds%SECOND;

m=value/MINUTE;
value=value%MINUTE;

s=value/SECOND;

return h+" Hour "+m+" Minute "+s+" Second";
}
}
```

## Output

``````
h for hour
m for minute
s for second
Convert from:
m
Value:
60
Converted Time :1 Hour 0 Minute 0 Second

``````

# Java Program: How to convert Units?

In this program you will see, way to convert one length measuring unit to another unit.Generally such type of questions asked to check programming logics.

See Also : Java Program : Convert time hour minute and seconds

## Example

```import java.util.Scanner;

public class UnitConversionCalculator {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

System.out.println("Convert from:");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);

System.out.println("Convert to: ");
String toUnit = in.nextLine();
UnitConverter to = new UnitConverter(toUnit);

System.out.println("Value:");
double val = in.nextDouble();
//convert to meter
double meters = from.toMeters(val);
//convert meter to required unit
double converted = to.fromMeters(meters);

System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}

}

That is main class for unit conversion for length measurement.
public class UnitConverter {
static double INCHES = 39.37;
static double FEET = 3.28;
static double MILES = 0.00062;
static double MILLIMETERS = 1000;
static double CENTIMETERS = 100;
static double METERS = 1;
static double KILOMETERS = 0.001;

private double meters, converted;

String fromUnit, toUnit;

public UnitConverter(String afromUnit) {
fromUnit = afromUnit;
toUnit = afromUnit;
}

// method to convert given value to meter
public double toMeters(double val) {
if (toUnit.equals("in")) {
meters = (val / INCHES);
} else if (toUnit.equals("ft")) {
meters = (val / FEET);
} else if (toUnit.equals("mi")) {
meters = (val / MILES);
} else if (toUnit.equals("mm")) {
meters = (val / MILLIMETERS);
} else if (toUnit.equals("cm")) {
meters = (val/ CENTIMETERS);
} else if (toUnit.equals("m")) {
meters = (val / METERS);
} else {
meters = (val / KILOMETERS);
}
return meters;
}

// method to convert meter to required unit
public double fromMeters(double meters) {
if (fromUnit.equals("in")) {
converted = Math.round(INCHES * 100 * meters);
} else if (fromUnit.equals("ft")) {
converted = Math.round(FEET * 100 * meters);
} else if (fromUnit.equals("mi")) {
converted = Math.round(MILES * 100 * meters);
} else if (fromUnit.equals("mm")) {
converted = Math.round(MILLIMETERS * 100 * meters);
} else if (fromUnit.equals("cm")) {
converted = Math.round(CENTIMETERS * meters);
} else if (fromUnit.equals("m")) {
converted = Math.round(METERS * meters);
} else {
converted = Math.round(KILOMETERS * meters);
}
return converted;
}
}

Output
```
Convert from:
m
Convert to:
cm
Value:
1
1.0 m = 100.0 cm
```

# Java : How to remove duplicate elements from List?

Here you will see way to remove duplicate from ArrayList. I am using HashSet because it keeps unique values only.

See Also : Java : How to remove duplicate objects from List

Example

```import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateElements {
public static void main(String[] args) {
ListstrList=new ArrayList();
//duplicate

System.out.println("==========Before Duplicate Remove :"+strList.size());
for(String str:strList)
System.out.println(str);

//Convert ArrayList to HashSet
Set set=new HashSet(strList);
//Convert HashSet to ArrayList
strList=new ArrayList(set);

System.out.println("==========After Duplicate Remove :"+strList.size());
for(String str:strList)
System.out.println(str);
}
}

```

Output

``````
==========Before Duplicate Remove :6
Facing
Issues
On
IT
Facing
IT
==========After Duplicate Remove :4
Facing
Issues
IT
On
``````

# Java : How to remove duplicate objects from List

In this below example list having duplicate object of AccountTransaction which need to remove from list. Here I am using HashSet because it always keep unique records. Now question comes how to decide uniqueness of object. As you know contract between hashcode() and equals() method deciding uniqueness and equality of object.

Here used Comparable interface to sort values based on transaction date.

hashcode() and equals() contract :

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract.”

Example

```
import java.math.BigDecimal;
import java.util.Date;

public class AccountTransaction implements Comparable{
private Date date;
String transactionType;
private String reference;
private BigDecimal amount;

public AccountTransaction(Date date, String transactionType, String reference, BigDecimal amount) {
super();
this.date = date;
this.transactionType = transactionType;
this.reference = reference;
this.amount = amount;
}
//Overriding toString() method to print object
@Override
public String toString() {
return "AccountTransactions [date=" + date + ", transactionType=" + transactionType + ", reference=" + reference
+ ", amount=" + amount + "]";
}
//Overriding hashcode() and equals() method to check equality and uniqueness
//of objects
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((amount == null) ? 0 : amount.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountTransaction other = (AccountTransaction) obj;
if (amount == null) {
if (other.amount != null)
return false;
} else if (!amount.equals(other.amount))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
if (transactionType == null) {
if (other.transactionType != null)
return false;
} else if (!transactionType.equals(other.transactionType))
return false;
return true;
}
//Sort object by date
@Override
public int compareTo(AccountTransaction o) {

return this.getDate().compareTo(o.getDate());
}

//use getter and setter of properties
}

```

Here is the class having sample data which is having duplicate objects in list. calling removeDuplicate() method which is converting list to hashSet() to remove duplicate and then again converting to list then sorting by date.

```
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateObjects {

public static void main(String[] args) {
List transactionList = new ArrayList();
try {
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:50 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:48 AM"), "Account Debits", "Burger king",new BigDecimal("0.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:55 AM"), "Account Debits", "Papa Johns",new BigDecimal("2.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Debits", "Pizza hut",new BigDecimal("1.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200")));
//Duplicate record
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:52 AM"), "Account Debits", "Pizza hut",new BigDecimal("0.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:38 AM"), "Account Debits", "Burger king",new BigDecimal("1.56")));
transactionList.add(new AccountTransaction(getDate("2018-10-15 10:35 AM"), "Account Credits", "Chase Bank",new BigDecimal("200")));

System.out.println("Transactions before removing duplicate=============");
for(AccountTransaction transaction:transactionList)
System.out.println(transaction);
System.out.println("Transactions after removing duplicate=============");
transactionList=removeDuplicate(transactionList);
for(AccountTransaction transaction:transactionList)
System.out.println(transaction);

} catch (Exception ex) {
ex.printStackTrace();
}
}

private static List removeDuplicate(List transactionList)
{
//Convert List to Set
Set transactionSet=new HashSet(transactionList);
//Convert Set to Array List
transactionList=new ArrayList(transactionSet);

//Sort object by transaction date and time
Collections.sort(transactionList);

return transactionList;
}

private static Date getDate(String dateStr) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd HH:mm a").parse(dateStr);
}
}

```

Output

``````
Transactions before removing duplicate=============
AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
Transactions after removing duplicate=============
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Credits, reference=Chase Bank, amount=200]
AccountTransactions [date=Mon Oct 15 10:35:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:38:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=1.56]
AccountTransactions [date=Mon Oct 15 10:48:00 IST 2018, transactionType=Account Debits, reference=Burger king, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:50:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:52:00 IST 2018, transactionType=Account Debits, reference=Pizza hut, amount=0.56]
AccountTransactions [date=Mon Oct 15 10:55:00 IST 2018, transactionType=Account Debits, reference=Papa Johns, amount=2.56]
``````

# Linear Search Algorithm,Java Program and Complexity

Linear search also called sequential search is a way for finding a target value within a list. It sequentially checks each element from the list for the target value until a match is found or until all the elements have been searched.

## Algorithm

• Target value search start from the leftmost element of array[] and one by one compare target value with each element of array[]
• If target value matches with an element, return the index.
• If target value doesn’t match with any of elements, return -1.

## Complexity

• Best Case Performance O(1)
• Average Case Performance O(n)
• Worst Case Performance O(1)

Where O is BiG-O Notation and n is no of element in Array/List.

## Java Program for Linear Search of Element

```import java.util.Scanner;

class LinearSearch {
public static void main(String args[]) {
int c, n, targetValue, array[];

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)
array[c] = in.nextInt();

System.out.println("Enter target value to find");
targetValue = in.nextInt();

for (c = 0; c < n; c++) {
if (array[c] == targetValue)
{
System.out.println(targetValue + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n)
System.out.println(targetValue + " is not present in array.");
}
}

```

## Output

```Enter number of elements
10
Enter 10 integers
2
56
3
7
89
34
78
23
67
13
Enter target value to find
7
7 is present at location 4.

Enter number of elements
7
Enter 7 integers
12
45
34
78
23
87
90
Enter target value to find
32
32 is not present in array.

```

## More

For more DataStructure,Algorithms and Java Programing Test questions and sample code follow below links

# Fahrenheit To Celsius Java Program

This program is to convert Fahrenheit to Celsius temperature based on user input value. Below is mathematical formula for conversion from Fahrenheit to Celsius temperature .

T = 9*T/5 + 32 where T is temperature on Celsius scale.

```import java.util.Scanner;

class FahrenheitToCelsius {
public static void main(String[] args) {
float temperatue;
Scanner in = new Scanner(System.in);

System.out.println("Enter Temperatue in Fahrenheit");
temperatue = in.nextInt();

temperatue = ((temperatue - 32)*5)/9;

System.out.println("Converted Temperatue in Celsius = " + temperatue);
}
}
```

Outout

```Enter Temperatue in Fahrenheit
100
Converted Temperatue in Celsius = 37.77778

Enter Temperatue in Fahrenheit
50
Converted Temperatue in Celsius = 10.0

Enter Temperatue in Fahrenheit
75
Converted Temperatue in Celsius = 23.88889
```

## More

For more Algorithms and Java Programing Test questions and sample code follow below links

# Frequently Asked Algorithms and Programs in Interviews

Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level also in IT.