Category Archives: Programming Test

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");
		}
		timesList.add(timeFormat);
		m=m+interval;
		}

	}
	//To match the time
	timeFormat=String.format("%02d:%02d %s", 0,0,"AM");
	timesList.add(timeFormat);
	//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

Advertisements

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.

See Also: Java Program : How to convert units?

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


Please enter :
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();
		strList.add("Facing");
		strList.add("Issues");
		strList.add("On");
		strList.add("IT");
		//duplicate
		strList.add("Facing");
		strList.add("IT");

		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]

See Also:

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

Ways to Read Input from Keyboard/User/Console by Java Program


Java Support 4 Ways of  read  input from keyboard:

  • Scanner Class (In java.util package)
  • BufferReader and InputStreamReader (java.io package)
  • DataInputStream (Java.io package)
  • Console Class (Some IDE doesn’t support it For Example : Eclipse)

How Data Accepts from Keyboard ?

For accepting data from keyboard by console we need three objects:

  1. System.in
  2. InputStreamReader
  3. BufferedReader

The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.Then the InputStreamReader reads bytes and decodes them into characters.Then finally BufferedReader object reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

 

InputStreamReader and BufferedReader are classes of java.io package.

Below Java Program showing all four ways of taking user input from console.

 

 

package program.common;

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

public class UserInputWays {

	public static void main(String[] args) {
		Way1ByScanner();
		System.out.println("=====================================================");
		Way2ByBufferReader();
		System.out.println("=====================================================");
		Way3ByDataStream();
		System.out.println("=====================================================");
		Way4ByConsole();
		System.out.println("=====================================================");
	}

	private static void Way1ByScanner() {
		System.out.println("Way 1 : By Scanner Class");
		Scanner scan = new Scanner(System.in);

		System.out.println("Enter a text string");
		String s = scan.nextLine();
		System.out.println("You entered text string " + s);

		System.out.println("Enter an integer value");
		int a = scan.nextInt();
		System.out.println("You entered integer value " + a);

		System.out.println("Enter a float value");
		float b = scan.nextFloat();
		System.out.println("You entered float value " + b);

	}

	private static void Way2ByBufferReader() {
		System.out.println("Way 2 : By BufferReader and InputStreamReader");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Enter a text string");
			String s = br.readLine();
			System.out.println("You entered text string " + s);

			System.out.println("Enter an integer value");
			int a = Integer.parseInt(br.readLine());
			System.out.println("You entered integer value " + a);

			System.out.println("Enter a float value");
			float b = Float.parseFloat(br.readLine());
			System.out.println("You entered float value " + b);

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

	private static void Way3ByDataStream() {
		System.out.println("Way 3 : By DataStream");
		try {
			DataInputStream dis = new DataInputStream(System.in);

			System.out.println("Enter a text string");
			String s = dis.readLine();
			System.out.println("You entered text string " + s);

			System.out.println("Enter an integer value");
			int a = dis.readInt();
			System.out.println("You entered integer value " + a);

			System.out.println("Enter a float value");
			float b = dis.readFloat();
			System.out.println("You entered float value " + b);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Eclipse doesn't support Console Class to test that use command prompt
	 */
	private static void Way4ByConsole() {
		System.out.println("Way 4 : By Console Class");
		try
		{
		Console console = System.console();

		System.out.println("Enter a text string");
		String s = console.readLine();
		System.out.println("You entered text string " + s);

		System.out.println("Enter an integer value");
		int a = Integer.parseInt(console.readLine());
		System.out.println("You entered integer value " + a);

		System.out.println("Enter a float value");
		float b = Float.parseFloat(console.readLine());
		System.out.println("You entered float value " + b);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

}

Output

Way 1 : By Scanner Class
Enter a text string
saurabh Gupta
You entered text string saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 2 : By BufferReader and InputStreamReader
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 35
Enter a float value
80.2
You entered float value 80.2
=====================================================
Way 3 : By DataStream
Enter a text string
Saurabh Gupta
You entered text string Saurabh Gupta
Enter an integer value
35
You entered integer value 859114762
Enter a float value
80.2
You entered float value 4.2004693E-5
=====================================================
Way 4 : By Console Class
Enter a text string
=====================================================
java.lang.NullPointerException
	at program.common.UserInputWays.Way4ByConsole(UserInputWays.java:91)
	at program.common.UserInputWays.main(UserInputWays.java:19)

More

For more 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

 

Floyd Triangle Java Program


This is Java Program to print Floyd triangle of continuous numbers based on inserted users numbers of rows.

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();
      }
   }
}

output

Enter the number of rows of floyd's triangle you want
7
Floyd's triangle :-
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

More

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

Multiplication Table Java Program


This Java program is for print Multiplication table of Input Number.

import java.util.Scanner;

class MultiplicationTable
{
   public static void main(String args[])
   {
      int n, c;
      System.out.println("Enter an integer value to display it's multiplication table");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
      System.out.println("Multiplication table of "+n+" is :-");

      for ( c = 1 ; c <= 10 ; c++ )
         System.out.println(n+"*"+c+" = "+(n*c));
   }
}

Output

Enter an integer value to display it's multiplication table

13
Multiplication table of 13 is :-
13*1 = 13
13*2 = 26
13*3 = 39
13*4 = 52
13*5 = 65
13*6 = 78
13*7 = 91
13*8 = 104
13*9 = 117
13*10 = 130

More

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

 

Largest of Three Numbers


This java program is to easily find out largest number in three integers values. But that is not optimize way if numbers are more than that better follow other algorithms.

lass LargestOfThreeNumbers {
	public static void main(String args[]) {
		int x, y, z;

		Scanner in = new Scanner(System.in);
		System.out.println("Please Enter First integer");
		x = in.nextInt();
		System.out.println("Please Enter Second integer");
		y = in.nextInt();
		System.out.println("Please Enter Third integer");
		z = in.nextInt();

		if (x > y && x > z)
			System.out.println("First number is largest.");
		else if (y > x && y > z)
			System.out.println("Second number is largest.");
		else if (z > x && z > y)
			System.out.println("Third number is largest.");
		else
			System.out.println("Entered numbers are not distinct.");
	}
}

Output

Please Enter First integer
10
Please Enter Second integer
20
Please Enter Third integer
5
Second number is largest.

More

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

Palindrome Java Program


Palindrome Definition

“A String is palindrome if it remains unchanged when reversed.”

For Example : String “dad” is a palindrome as reverse of “dad” is “dad” whereas
“program” is not a palindrome. Some other palindrome strings are “nitin”,”mom”, “madam”, “abcba” etc.

Below is simple Java program to check input String is Palindrom or not.

class Palindrome1 {
	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.");

	}
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

In above program you find out very simple way to check input string is palindrome but in below program you will see to check palindrome string with minimum number of operations because here dividing text in half size and compare with rest of part of String.

import java.util.*;

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

    System.out.println("Enter a string to check if it is a palindrome");
    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("Entered string is a palindrome.");
    }
    else {
      System.out.println("Entered string is not a palindrome.");
    }
  }
}

Output

Enter a string to check if it is a palindrome
nitin
Entered string is a palindrome.

Enter a string to check if it is a palindrome
Saurabh
Entered string is not a palindrome.

More

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

Prime Numbers Java program


Prime Number Definition

                 “A whole number greater than 1 that is divisible only by itself and 1”.
A prime number will always have factors as 1 and itself. A factor is a whole numbers that can be divided evenly into another number. If Number is having more than two factors are called composite numbers.
The number 1 is neither prime nor a composite Number.
Smallest prime number is 2 and others are in sequence as 2,3,5,7,11,13,17,19,13,29  etc…

Benefit

  • prime numbers are very useful in cryptography.
  • The mathematicians used prime numbers to develop new areas of mathematics, like number theory and knot theory, which developers use today.
This java program prints  number of prime numbers as required from the user.
import java.util.*;

class PrimeNumbers
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();

      if (n &gt;= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count &lt;=n ;  )
      {
         for ( int j = 2 ; j &lt;= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }
   }
}

Output

Enter the number of prime numbers you want
5
First 5 prime numbers are :-
2
3
5
7
11
Enter the number of prime numbers you want

10
First 10 prime numbers are :-
2
3
5
7
11
13
17
19
23
29

More

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

Odd and Even Java Program


This java program finds if a number is odd or even.

If the number is divisible by 2 then it will be even, otherwise it is odd. We use Java modulus operator to find remainder in our program.

class OddOrEvenNumber{
	public static void main(String args[]) {<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
		int x;
		System.out.println("Enter an integer value to check if it is odd or even ");
		Scanner in = new Scanner(System.in);
		x = in.nextInt();

		if (x % 2 == 0)
			System.out.println("You entered an even number.");
		else
			System.out.println("You entered an odd number.");
	}
}

Output

Enter an integer value to check if it is odd or even
16
You entered an even number.

Enter an integer value to check if it is odd or even
125
You entered an odd number.

More

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

How to Reverse Number by Java Program?


Here in below program logic you will see how can be reverse number by using multiplication, reminder and division operations.

In this  below program follow steps for reverse number:

  1. Reverse number initialize with zero.
  2. Run loop till number of digits in insert number.
  3. Take reminder of number by mod 10.
  4. Add this reminder value with reverse number .
  5. Multiply this reverse number with 10 .
  6. Divide insert number by 10 and steps 2 to 6 repeat continuously.
import java.util.Scanner;

class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;

      System.out.println("Enter the integer number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();

      while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }

      System.out.println("Reverse of entered integer number is "+reverse);
   }
}

Output

Enter the integer number to reverse
12345
Reverse of entered integer number is 54321

Enter the integer number to reverse

54535251
Reverse of entered integer number is 15253545

 

 

More

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

 

How to Prints Alphabets by Java Loops


Here you will see, How to prints Alphabets through Java all loops (for, While and do while). In these loops we are just increments char value and characters are increment continuously.

public class PrintAlphabets {

	public static void main(String[] args) {
		// By for Loop
		char ch;
		for (ch = 'a'; ch <= 'z'; ch++) {
			System.out.print(ch + " ");
		}
		System.out.println();

		// By While loop
		char c = 'a';

		while (c <= 'z') {
			System.out.print(c + " ");
			c++;
		}
		System.out.println();

		// By do while loop
		c = 'A';

		do {
			System.out.print(c + " ");
			c++;
		} while (c <= 'Z');
	}

}

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

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.

How to Swap two Numbers with and with out temporary variable.


Here I will show you how you can swap two numbers A=20 and B=10 with and without temporary variables as A=10 and B=20.

Swap Numbers with Temporary Variable

I will take one more temporary variable as temp to keep value of B so that during  copy of value A to B value of B is in temp and now we can copy value of temp to A. As below

temp=B       (This state : A=20, B=10, temp=10)

B=A;            (This state : A=20, B=20, temp=10)

A=temp      (This state : A=10, B=20, temp=10)

By applying above logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers without Temporary Variable

There are two ways two swap two numbers without using any temporary variable.

Addition and Subtraction

Here you will see how to swap numbers A=20 and B=10 by using addition and subtraction operations.

A=A+B           (This state : A=30, B=10)

B=A-B           (This state : A=30, B=20)

A=A-B           (This state : A=10, B=20)

By applying above addition and subtraction logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Multiplication and Division

Here you will see how to swap numbers A=20 and B=10 by using multiplication and division operations.

A=A*B           (This state : A=200, B=10)

B=A/B           (This state : A=200, B=20)

A=A/B           (This state : A=10, B=20)

By applying above multiplication and division logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers Java Program

package test;

import java.util.Scanner;

public class SwapNumbers {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Please Enter First Number");
		int A=scan.nextInt();

		System.out.println("Please Enter Second Number");
		int B=scan.nextInt();

		//swap Numbers with temporary variable
		swapNumbersWithTemp(A,B);
		//swap Numbers without temporary variable : Add and Sub
		swapNumbersWithoutTempAddSub(A,B);
		//swap Numbers without temporary variable : Mul and Div
		swapNumbersWithoutTempMulDiv(A,B);
	}

	private static void swapNumbersWithTemp(int A, int B)
	{
		int temp=B;
		B=A;
		A=temp;

		System.out.println("Numbers after swap with temporary variables");
		System.out.println("A="+A+"and B="+B);
	}

	private static void swapNumbersWithoutTempAddSub(int A, int B)
	{
		A=A+B;
		B=A-B;
		A=A-B;

		System.out.println("Numbers after swap without temporary variables: Add and Sub operation");
		System.out.println("A="+A+"and B="+B);
	}

	private static void swapNumbersWithoutTempMulDiv(int A, int B)
	{
		A=A*B;
		B=A/B;
		A=A/B;

		System.out.println("Numbers after swap without temporary variables: MUl and Div operation");
		System.out.println("A="+A+"and B="+B);
	}

}

Output

Please Enter First Number
20
Please Enter Second Number
10
Numbers after swap with temporary variables
A=10and B=20
Numbers after swap without temporary variables: Add and Sub operation
A=10and B=20
Numbers after swap without temporary variables: MUl and Div operation
A=10and B=20
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><span 			

 

 

More Info

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