Interview Q and A
Odd numbers and even numbers
import java.util.Scanner;
class OddOrEven
{
public static void main(String args[])
{
int x;
System.out.println("Enter an integer 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.");
}
}
o/p
Enter
an integer to check if it is odd or even
3
You
entered an odd number.
Enter
an integer to check if it is odd or even
430
You
entered an even number.
Java program to convert Fahrenheit to Celsius
import java.util.*;
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("Temperatue in Celsius = " + temperatue);
}
}
Enter
temperatue in Fahrenheit
180
Temperatue
in Celsius = 82.22222
Java program to find largest of three number
import java.util.Scanner;
class LargestOfThreeNumbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
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.");
}
}
Enter
three integers
9
6
11
Third number is largest.
java program to find factorial
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);
}
}
}
Enter
an integer to calculate it's factorial
5
Factorial
of 5 is = 120
Java program to print Floyd's triangle
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();
}
}
}
Enter
the number of rows of floyd's triangle you want
3
Floyd's
triangle :-
1
2
3
4
5 6
Java program to reverse a string
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);
}
}
Enter
a string to reverse
anji
Reverse
of entered string is: ijna
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());
}
}
nuf si gnimmargorp avaJ
Java program to check palindrome
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.");
}
}
Enter
a string to check if it is a palindrome
ana
Entered
string is a palindrome.
Enter
a string to check if it is a palindrome
java
Entered
string is not a palindrome.
Another method to check palindrome:
mport 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");
}
}
}
Java program to reverse number
import java.util.Scanner;
class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
System.out.println("Enter the 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 number is "+reverse);
}
}
Java program to compare two strings
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.");
}
}
Enter
the first string
java
Enter
the second string
java
Both
strings are equal.
Enter
the first string
java
Enter
the second string
lara
java
First
string is smaller than second.
Java program to find all substrings of a string
import java.util.Scanner;
class SubstringsOfAString
{
public static void main(String args[])
{
String string, sub;
int i, c, length;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
length = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
for( c = 0 ; c < length ; c++ )
{
for( i = 1 ; i <= length - c ; i++ )
{
sub = string.substring(c, c+i);
System.out.println(sub);
}
}
}
}
Enter
a string to print it's all substrings
JAVA
Substrings
of "JAVA" are :-
J
JA
JAV
JAVA
A
AV
AVA
V
VA
A
Java program for linear search
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, 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 value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
Enter
number of elements
3
Enter
3 integers
4
5
6
Enter
value to find
5
5
is present at location 2.
Java program for binary search
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, 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 value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Java program to display date and time, print date and time using java program
import java.util.*;
class GetCurrentDateAndTime
{
public static void main(String args[])
{
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
System.out.println("Current date is "+day+"/"+(month+1)+"/"+year);
System.out.println("Current time is "+hour+" : "+minute+" : "+second);
}
}
Java program to generate random numbers
import java.util.*;
class RandomNumbers {
public static void main(String[] args) {
int c;
Random t = new Random();
// random integers in [0, 100]
for (c = 1; c <= 10; c++) {
System.out.println(t.nextInt(100));
}
}
}
Java program to perform garbage collection
mport java.util.*;
class GarbageCollection
{
public static void main(String s[]) throws Exception
{
Runtime rs = Runtime.getRuntime();
System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
}
}
Java program to get ip address
import java.net.InetAddress;
class IPAddress
{
public static void main(String args[]) throws Exception
{
System.out.println(InetAddress.getLocalHost());
}
}
Java program to multiply two matrices
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
System.out.println("Product of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}
Java program to open Notepad
import java.util.*;
import java.io.*;
class Notepad {
public static void main(String[] args) {
Runtime rs = Runtime.getRuntime();
try {
rs.exec("notepad");
}
catch (IOException e) {
System.out.println(e);
}
}
}
How to delete temporary file in java?
package
com.java2novice.files;
import
java.io.BufferedWriter;
import
java.io.File;
import
java.io.FileWriter;
import
java.io.IOException;
public
class MyTempDelete {
public
static void main(String a[]){
File
tempFile = null;
BufferedWriter
writer = null;
try
{
tempFile
= File.createTempFile("MyTempFile", ".tmp");
writer
= new BufferedWriter(new FileWriter(tempFile));
writer.write("Writing
data into temp file!!!");
}
catch (IOException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try{
if(writer
!= null) writer.close();
}catch(Exception
ex){}
}
System.out.println("Stored
data in temporary file.");
/*
*
Write your application logic here
*
Once your application done with the temp data,
*
delete the temp file
*/
//below
method deletes the temp file on program exists.
tempFile.deleteOnExit();
//below
method deletes the temp file immediately
//tempFile.delete();
}
}
How to remove multiple spaces in a string in Java?
package
com.myjava.string;
import
java.util.StringTokenizer;
public
class MyStrRemoveMultSpaces {
public
static void main(String a[]){
String
str = "String With
Multiple Spaces";
StringTokenizer
st = new StringTokenizer(str, " ");
StringBuffer
sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append("
");
}
System.out.println(sb.toString().trim());
}
}
How to replace string characters in java?
package
com.myjava.string;
public
class MyStringReplace {
public
static void main(String a[]){
String
str = "This is an example string";
System.out.println("Replace
char 's' with 'o':"
+str.replace('s',
'o'));
System.out.println("Replace
first occurance of string\"is\" with \"ui\":"
+str.replaceFirst("is",
"ui"));
System.out.println("Replacing
\"is\" every where with \"no\":"
+str.replaceAll("is",
"no"));
}
}
Finding the Big number
mport java.util.Scanner;
class Tables
{
public static void main(String args[])
{
int a, b, c, d;
System.out.println("Enter range of numbers to print their multiplication table");
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
for (c = a; c <= b; c++) {
System.out.println("Multiplication table of "+c);
for (d = 1; d <= 10; d++) {
System.out.println(c+"*"+d+" = "+(c*d));
}
}
}
}
Printing the stars
class Stars
{
public static void main(String[] args) {
int row, numberOfStars;
for (row = 1; row <= 10; row++) {
for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
System.out.print("*");
}
System.out.println(); // Go to next line
}
}
}
Printing the Alphabetical order
class Alphabets
{
public static void main(String args[])
{
char ch;
for( ch = 'a' ; ch <= 'z' ; ch++ )
System.out.println(ch);
}
}
Finding
big number
import java.util.Scanner;
import java.math.BigInteger;
class AddingLargeNumbers {
public static void main(String[] args) {
String number1, number2;
Scanner in = new Scanner(System.in);
System.out.println("Enter first large number");
number1 = in.nextLine();
System.out.println("Enter second large number");
number2 = in.nextLine();
BigInteger first = new BigInteger(number1);
BigInteger second = new BigInteger(number2);
System.out.println("Addition = " + first.add(second));
}
}
How to get line count from a string?
package
com.java2novice.string;
public
class MyStringLineCounter {
public
static int getLineCount(String text){
return
text.split("[\n|\r]").length;
}
public
static void main(String a[]){
String
str = "line1\nline2\nline3\rline4";
System.out.println(str);
int
count = getLineCount(str);
System.out.println("line
count: "+count);
}
}
Write a program to find perfect number or not.
public
class IsPerfectNumber {
public
boolean isPerfectNumber(int number){
int
temp = 0;
for(int
i=1;i<=number/2;i++){
if(number%i
== 0){
temp
+= i;
}
}
if(temp
== number){
System.out.println("It
is a perfect number");
return
true;
}
else {
System.out.println("It
is not a perfect number");
return
false;
}
}
public
static void main(String a[]){
IsPerfectNumber
ipn = new IsPerfectNumber();
System.out.println("Is
perfect number: "+ipn.isPerfectNumber(28));
}
}
Write a program to find the sum of the first 1000 prime numbers.
package
com.primesum;
public
class Main {
public
static void main(String args[]){
int
number = 2;
int
count = 0;
long
sum = 0;
while(count
< 1000){
if(isPrimeNumber(number)){
sum
+= number;
count++;
}
number++;
}
System.out.println(sum);
}
private
static boolean isPrimeNumber(int number){
for(int
i=2; i<=number/2; i++){
if(number
% i == 0){
return
false;
}
}
return
true;
}
}
Write a program to convert string to number without using Integer.parseInt() metho
public
class MyStringToNumber {
public
static int convert_String_To_Number(String numStr){
char
ch[] = numStr.toCharArray();
int
sum = 0;
//get
ascii value for zero
int
zeroAscii = (int)'0';
for(char
c:ch){
int
tmpAscii = (int)c;
sum
= (sum*10)+(tmpAscii-zeroAscii);
}
return
sum;
}
public
static void main(String a[]){
System.out.println("\"3256\"
== "+convert_String_To_Number("3256"));
System.out.println("\"76289\"
== "+convert_String_To_Number("76289"));
System.out.println("\"90087\"
== "+convert_String_To_Number("90087"));
}
}
Write a program to get a line with max word count from the given file.
import
java.io.BufferedReader;
import
java.io.DataInputStream;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.util.ArrayList;
import
java.util.List;
public
class MaxWordCountInLine {
private
int currentMaxCount = 0;
private
List<String> lines = new ArrayList<String>();
public
void readMaxLineCount(String fileName){
FileInputStream
fis = null;
DataInputStream
dis = null;
BufferedReader
br = null;
try
{
fis
= new FileInputStream(fileName);
dis
= new DataInputStream(fis);
br
= new BufferedReader(new InputStreamReader(dis));
String
line = null;
while((line
= br.readLine()) != null){
int
count = (line.split("\\s+")).length;
if(count
> currentMaxCount){
lines.clear();
lines.add(line);
currentMaxCount
= count;
}
else if(count == currentMaxCount){
lines.add(line);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{
if(br
!= null) br.close();
}catch(Exception
ex){}
}
}
public
int getCurrentMaxCount() {
return
currentMaxCount;
}
public
void setCurrentMaxCount(int currentMaxCount) {
this.currentMaxCount
= currentMaxCount;
}
public
List<String> getLines() {
return
lines;
}
public
void setLines(List<String> lines) {
this.lines
= lines;
}
public
static void main(String a[]){
MaxWordCountInLine
mdc = new MaxWordCountInLine();
mdc.readMaxLineCount("/Users/ngootooru/MyTestFile.txt");
System.out.println("Max
number of words in a line is: "+mdc.getCurrentMaxCount());
System.out.println("Line
with max word count:");
List<String>
lines = mdc.getLines();
for(String
l:lines){
System.out.println(l);
}
}
}
Find out middle index where sum of both ends are equal.
public
class FindMiddleIndex {
public
static int findMiddleIndex(int[] numbers) throws Exception {
int
endIndex = numbers.length - 1;
int
startIndex = 0;
int
sumLeft = 0;
int
sumRight = 0;
while
(true) {
if
(sumLeft > sumRight) {
sumRight
+= numbers[endIndex--];
}
else {
sumLeft
+= numbers[startIndex++];
}
if
(startIndex > endIndex) {
if
(sumLeft == sumRight) {
break;
}
else {
throw
new Exception(
"Please
pass proper array to match the requirement");
}
}
}
return
endIndex;
}
public
static void main(String a[]) {
int[]
num = { 2, 4, 4, 5, 4, 1 };
try
{
System.out.println("Starting
from index 0, adding numbers till index "
+
findMiddleIndex(num) + " and");
System.out.println("adding
rest of the numbers can be equal");
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Write a program to convert decimal number to binary format
public
class DecimalToBinary {
public
void printBinaryFormat(int number){
int
binary[] = new int[25];
int
index = 0;
while(number
> 0){
binary[index++]
= number%2;
number
= number/2;
}
for(int
i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public
static void main(String a[]){
DecimalToBinary
dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Write a program to find maximum repeated words from a file
import
java.io.BufferedReader;
import
java.io.DataInputStream;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
import
java.util.HashMap;
import
java.util.List;
import
java.util.Map;
import
java.util.Set;
import
java.util.StringTokenizer;
import
java.util.Map.Entry;
public
class MaxDuplicateWordCount {
public
Map<String, Integer> getWordCount(String fileName){
FileInputStream
fis = null;
DataInputStream
dis = null;
BufferedReader
br = null;
Map<String,
Integer> wordMap = new HashMap<String, Integer>();
try
{
fis
= new FileInputStream(fileName);
dis
= new DataInputStream(fis);
br
= new BufferedReader(new InputStreamReader(dis));
String
line = null;
while((line
= br.readLine()) != null){
StringTokenizer
st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
String
tmp = st.nextToken().toLowerCase();
if(wordMap.containsKey(tmp)){
wordMap.put(tmp,
wordMap.get(tmp)+1);
}
else {
wordMap.put(tmp,
1);
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{if(br
!= null) br.close();}catch(Exception ex){}
}
return
wordMap;
}
public
List<Entry<String, Integer>> sortByValue(Map<String, Integer>
wordMap){
Set<Entry<String,
Integer>> set = wordMap.entrySet();
List<Entry<String,
Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort(
list, new Comparator<Map.Entry<String, Integer>>()
{
public
int compare( Map.Entry<String, Integer> o1, Map.Entry<String,
Integer> o2 )
{
return
(o2.getValue()).compareTo( o1.getValue() );
}
}
);
return
list;
}
public
static void main(String a[]){
MaxDuplicateWordCount
mdc = new MaxDuplicateWordCount();
Map<String,
Integer> wordMap = mdc.getWordCount("C:/MyTestFile.txt");
List<Entry<String,
Integer>> list = mdc.sortByValue(wordMap);
for(Map.Entry<String,
Integer> entry:list){
System.out.println(entry.getKey()+"
==== "+entry.getValue());
}
}
}
Write a program to find sum of each digit in the given number using recursion
public
class MyNumberSumRec {
int
sum = 0;
public
int getNumberSum(int number){
if(number
== 0){
return
sum;
}
else {
sum
+= (number%10);
getNumberSum(number/10);
}
return
sum;
}
public
static void main(String a[]){
MyNumberSumRec
mns = new MyNumberSumRec();
System.out.println("Sum
is: "+mns.getNumberSum(223));
}
}
Write a program to find the given number is Armstrong number or not?
public
class MyArmstrongNumber {
public
boolean isArmstrongNumber(int number){
int
tmp = number;
int
noOfDigits = String.valueOf(number).length();
int
sum = 0;
int
div = 0;
while(tmp
> 0)
{
div
= tmp % 10;
int
temp = 1;
for(int
i=0;i<noOfDigits;i++){
temp
*= div;
}
sum
+= temp;
tmp
= tmp/10;
}
if(number
== sum) {
return
true;
}
else {
return
false;
}
}
public
static void main(String a[]){
MyArmstrongNumber
man = new MyArmstrongNumber();
System.out.println("Is
371 Armstrong number? "+man.isArmstrongNumber(371));
System.out.println("Is
523 Armstrong number? "+man.isArmstrongNumber(523));
System.out.println("Is
153 Armstrong number? "+man.isArmstrongNumber(153));
}
}
Write a program to check the given number is binary number or not?
public
class MyBinaryCheck {
public
boolean isBinaryNumber(int binary){
boolean
status = true;
while(true){
if(binary
== 0){
break;
}
else {
int
tmp = binary%10;
if(tmp
> 1){
status
= false;
break;
}
binary
= binary/10;
}
}
return
status;
}
public
static void main(String a[]){
MyBinaryCheck
mbc = new MyBinaryCheck();
System.out.println("Is
1000111 binary? :"+mbc.isBinaryNumber(1000111));
System.out.println("Is
10300111 binary? :"+mbc.isBinaryNumber(10300111));
}
}
No comments:
Post a Comment