1.
Write a Java program to print 'Hello' on screen and your name
on a separate line.
Expected Output :
Hello
Alexandra Abramov
public class Exercise1 {
public static void main(String[] args) {
System.out.println("Hello\nAlexandra Abramov!");
2. Write a Java program to print the sum of two numbers.
Test Data:
74 + 36
Expected Output :
110
public class Exercise2 {
public static void main(String[] args) {
System.out.println(24+26);
3. Write a Java program to divide two numbers and print them on
the screen.
Test Data :
50/3
Expected Output :
16
public class Exercise3 {
public static void main(String[] args) {
System.out.println(50/3);
4. Write a Java program to print the results of the following
operations.
Test Data:
a. -5 + 8 * 6
b. (55+9) % 9
c. 20 + -3*5 / 8
d. 5 + 15 / 3 * 2 - 8 % 3
Expected Output :
43
1
19
13
public class Exercise4 {
public static void main(String[] args) {
System.out.println(-5 + 8 * 6);
System.out.println((55+9) % 9);
System.out.println(20 + -3*5 / 8);
System.out.println(5 + 15 / 3 * 2 - 8 % 3);
5. Write a Java program that takes two numbers as input and
displays the product of two numbers.
Test Data:
Input first number: 25
Input second number: 5
Expected Output :
25 x 5 = 125
import java.util.Scanner;
public class Exercise5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " x " + num2 + " = " + num1 * num2);
6. Write a Java program to print the sum (addition), multiply,
subtract, divide and remainder of two numbers.
Test Data:
Input first number: 125
Input second number: 24
Expected Output :
125 + 24 = 149
125 - 24 = 101
125 x 24 = 3000
125 / 24 = 5
125 mod 24 = 5
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
7. Write a Java program that takes a number as input and prints
its multiplication table up to 10.
Test Data:
Input a number: 8
Expected Output :
8x 1=8
8x 2 = 16
8x 3 = 24
...
8x 10 = 80
import java.util.Scanner;
public class Exercise7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int num1 = in.nextInt();
for (int i=0; i< 10; i++){
System.out.println(num1 + " x " + (i+1) + " = " +
(num1 * (i+1)));
}
}
8. Write a Java program to display the following pattern.
Sample Pattern :
J a v v a
J a a v v a a
J J aaaaa V V aaaaa
JJ a a V a a
public class Exercise8 {
public static void main(String[] args) {
System.out.println(" J a v v a ");
System.out.println(" J a a v v a a");
System.out.println("J J aaaaa V V aaaaa");
System.out.println(" JJ a a V a a");
9. Write a Java program to compute the specified expressions
and print the output.
Test Data:
((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5))
Expected Output
2.138888888888889
public class Exercise9 {
public static void main(String[] arg) {
System.out.println((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5));
10. Write a Java program to compute a specified formula.
Specified Formula :
4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11))
Expected Output
2.9760461760461765
public class Exercise10 {
public static void main(String[] args) {
double result = 4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) -
(1.0/11));
System.out.println(result); //
}
11. Write a Java program to print the area and perimeter of a
circle.
Test Data:
Radius = 7.5
Expected Output
Perimeter is = 47.12388980384689
Area is = 176.71458676442586
Why is the area of a circle of a circle pi times the square of
the radius?
public class Exercise11 {
private static final double radius = 7.5;
public static void main(String[] args) {
double perimeter = 2 * Math.PI * radius;
double area = Math.PI * radius * radius;
System.out.println("Perimeter is = " + perimeter);
System.out.println("Area is = " + area);
12. Write a Java program that takes three numbers as input to
calculate and print the average of the numbers.
import java.util.Scanner;
public class Exercise12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.print("Input third number: ");
int num3 = in.nextInt();
System.out.print("Input fourth number: ");
int num4 = in.nextInt();
System.out.print("Enter fifth number: ");
int num5 = in.nextInt();
System.out.println("Average of five numbers is: " +
(num1 + num2 + num3 + num4 + num5) / 5);
13. Write a Java program to print the area and perimeter of a
rectangle.
Test Data:
Width = 5.5 Height = 8.5
Expected Output
Area is 5.6 * 8.5 = 47.60
Perimeter is 2 * (5.6 + 8.5) = 28.20
public class Exercise13 {
public static void main(String[] strings) {
final double width = 5.6;
final double height = 8.5;
double perimeter = 2*(height + width);
double area = width * height;
System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f \
n", height, width, perimeter);
System.out.printf("Area is %.1f * %.1f = %.2f \n", width,
height, area);
14. Write a Java program to print an American flag on the
screen.
Expected Output
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
==============================================
==============================================
==============================================
==============================================
==============================================
==============================================
public class Exercise14 {
public static void main(String[] args)
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println(" * * * * *
==================================");
System.out.println("* * * * * *
==================================");
System.out.println("=====================================
=========");
System.out.println("=====================================
=========");
System.out.println("=====================================
=========");
System.out.println("=====================================
=========");
System.out.println("=====================================
=========");
System.out.println("=====================================
=========");
15. Write a Java program to swap two variables.
public class Exercise15 {
public static void main(String[] args) {
int a, b, temp;
a = 15;
b = 27;
System.out.println("Before swapping : a, b = "+a+", "+ + b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping : a, b = "+a+", "+ + b);
16. Write a Java program to print a face.
Expected Output
+"""""+
[| o o |]
| ^ |
| '-' |
+-----+
public class Exercise16 {
public static void main(String[] args)
System.out.println(" +\"\"\"\"\"+ ");
System.out.println("[| o o |]");
System.out.println(" | ^ | ");
System.out.println(" | '-' | ");
System.out.println(" +-----+ ");
17. Write a Java program to add two binary numbers.
Input Data:
Input first binary number: 10
Input second binary number: 11
Expected Output
Sum of two binary numbers: 101
import java.util.Scanner;
public class Exercise17 {
public static void main(String[] args)
long binary1, binary2;
int i = 0, remainder = 0;
int[] sum = new int[20];
Scanner in = new Scanner(System.in);
System.out.print("Input first binary number: ");
binary1 = in.nextLong();
System.out.print("Input second binary number: ");
binary2 = in.nextLong();
while (binary1 != 0 || binary2 != 0)
sum[i++] = (int)((binary1 % 10 + binary2 % 10 + remainder) % 2);
remainder = (int)((binary1 % 10 + binary2 % 10 + remainder) / 2);
binary1 = binary1 / 10;
binary2 = binary2 / 10;
if (remainder != 0) {
sum[i++] = remainder;
--i;
System.out.print("Sum of two binary numbers: ");
while (i >= 0) {
System.out.print(sum[i--]);
System.out.print("\n");
18. Write a Java program to multiply two binary numbers.
Input Data:
Input the first binary number: 10
Input the second binary number: 11
Expected Output
Product of two binary numbers: 110
import java.util.Scanner;
public class Exercise18 {
public static void main(String[] args)
long binary1, binary2, multiply = 0;
int digit, factor = 1;
Scanner in = new Scanner(System.in);
System.out.print("Input the first binary number: ");
binary1 = in.nextLong();
System.out.print("Input the second binary number: ");
binary2 = in.nextLong();
while (binary2 != 0)
digit = (int)(binary2 % 10);
if (digit == 1)
binary1 = binary1 * factor;
multiply = binaryproduct((int) binary1, (int) multiply);
else
binary1 = binary1 * factor;
binary2 = binary2 / 10;
factor = 10;
System.out.print("Product of two binary numbers: " + multiply+"\
n");
static int binaryproduct(int binary1, int binary2)
int i = 0, remainder = 0;
int[] sum = new int[20];
int binary_prod_result = 0;
while (binary1 != 0 || binary2 != 0)
sum[i++] = (binary1 % 10 + binary2 % 10 + remainder) % 2;
remainder = (binary1 % 10 + binary2 % 10 + remainder) / 2;
binary1 = binary1 / 10;
binary2 = binary2 / 10;
if (remainder != 0)
sum[i++] = remainder;
--i;
while (i >= 0)
binary_prod_result = binary_prod_result * 10 + sum[i--];
return binary_prod_result;
19. Write a Java program to convert an integer number to a
binary number.
Input Data:
Input a Decimal Number : 5
Expected Output
Binary number is: 101
import java.util.Scanner;
public class Exercise19 {
public static void main(String args[])
int dec_num, quot, i=1, j;
int bin_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Input a Decimal Number : ");
dec_num = scan.nextInt();
quot = dec_num;
while(quot != 0)
bin_num[i++] = quot%2;
quot = quot/2;
System.out.print("Binary number is: ");
for(j=i-1; j>0; j--)
System.out.print(bin_num[j]);
System.out.print("\n");
20. Write a Java program to convert a decimal number to a
hexadecimal number.
Input Data:
Input a decimal number: 15
Expected Output
Hexadecimal number is : F
import java.util.Scanner;
public class Exercise20 {
public static void main(String args[])
int dec_num, rem;
String hexdec_num="";
/* hexadecimal number digits */
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
Scanner in = new Scanner(System.in);
System.out.print("Input a decimal number: ");
dec_num = in.nextInt();
while(dec_num>0)
rem = dec_num%16;
hexdec_num = hex[rem] + hexdec_num;
dec_num = dec_num/16;
System.out.print("Hexadecimal number is : "+hexdec_num+"\
n");
21. Write a Java program to convert a decimal number to an
octal number.
Input Data:
Input a Decimal Number: 15
Expected Output
Octal number is: 17
import java.util.Scanner;
public class Exercise21 {
public static void main(String args[])
int dec_num, rem, quot, i=1, j;
int oct_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Input a Decimal Number: ");
dec_num = scan.nextInt();
quot = dec_num;
while(quot != 0)
oct_num[i++] = quot%8;
quot = quot/8;
System.out.print("Octal number is: ");
for(j=i-1; j>0; j--)
System.out.print(oct_num[j]);
System.out.print("\n");
22. Write a Java program to convert a binary number to a
decimal number.
Input Data:
Input a binary number: 100
Expected Output
Decimal Number: 4
import java.util.Scanner;
public class Exercise22 {
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
long binaryNumber, decimalNumber = 0, j = 1, remainder;
System.out.print("Input a binary number: ");
binaryNumber = sc.nextLong();
while (binaryNumber != 0)
remainder = binaryNumber % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryNumber = binaryNumber / 10;
System.out.println("Decimal Number: " + decimalNumber);
23. Write a Java program to convert a binary number to a
hexadecimal number.
Input Data:
Input a Binary Number: 1101
Expected Output
HexaDecimal value: D
import java.util.Scanner;
public class Exercise23 {
public static void main(String[] args)
int[] hex = new int[1000];
int i = 1, j = 0, rem, dec = 0, bin;
Scanner in = new Scanner(System.in);
System.out.print("Input a Binary Number: ");
bin = in.nextInt();
while (bin > 0) {
rem = bin % 2;
dec = dec + rem * i;
i = i * 2;
bin = bin / 10;
i = 0;
while (dec != 0) {
hex[i] = dec % 16;
dec = dec / 16;
i++;
System.out.print("HexaDecimal value: ");
for (j = i - 1; j >= 0; j--)
if (hex[j] > 9)
{
System.out.print((char)(hex[j] + 55)+"\n");
} else
System.out.print(hex[j]+"\n");
24. Write a Java program to convert a binary number to an octal
number.
Input Data:
Input a Binary Number: 111
Expected Output
Octal number: 7
import java.util.*;
public class Exercise24 {
public static void main(String[] args)
int binnum, binnum1,rem, decnum=0, quot, i=1, j;
int octnum[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Input a Binary Number : ");
binnum = scan.nextInt();
binnum1=binnum;
while(binnum > 0)
rem = binnum % 10;
decnum = decnum + rem*i;
//System.out.println(rem);
i = i*2;
binnum = binnum/10;
i=1;
quot = decnum;
while(quot > 0)
{
octnum[i++] = quot % 8;
quot = quot / 8;
System.out.print("Equivalent Octal Value of " +binnum1+ " is
:");
for(j=i-1; j>0; j--)
System.out.print(octnum[j]);
System.out.print("\n");
25. Write a Java program to convert a octal number to a decimal
number.
Input Data:
Input any octal number: 10
Expected Output
Equivalent decimal number: 8
import java.util.Scanner;
public class Exercise25 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
long octal_num, decimal_num = 0;
int i = 0;
System.out.print("Input any octal number: ");
octal_num = in.nextLong();
while (octal_num != 0)
{
decimal_num = (long)(decimal_num + (octal_num % 10) *
Math.pow(8, i++));
octal_num = octal_num / 10;
System.out.print("Equivalent decimal number: " +
decimal_num+"\n");
26. Write a Java program to convert a octal number to a binary
number.
Input Data:
Input any octal number: 7
Expected Output
Equivalent binary number: 111
import java.util.Scanner;
public class Exercise26 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
int[] octal_numvalues = {0, 1, 10, 11, 100, 101, 110, 111};
long octal_num, tempoctal_num, binary_num, place;
int rem;
System.out.print("Input any octal number: ");
octal_num = in.nextLong();
tempoctal_num = octal_num;
binary_num = 0;
place = 1;
while (tempoctal_num != 0)
rem = (int)(tempoctal_num % 10);
binary_num = octal_numvalues[rem] * place + binary_num;
tempoctal_num /= 10;
place *= 1000;
System.out.print("Equivalent binary number: " + binary_num+"\
n");
27. Write a Java program to convert a octal number to a
hexadecimal number.
Input Data:
Input a octal number : 100
Expected Output
Equivalent hexadecimal number: 40
import java.util.Scanner;
public class Exercise27 {
public static void main(String args[])
String octal_num, hex_num;
int decnum;
Scanner in = new Scanner(System.in);
System.out.print("Input a octal number : ");
octal_num = in.nextLine();
decnum = Integer.parseInt(octal_num, 8);
hex_num = Integer.toHexString(decnum);
System.out.print("Equivalent hexadecimal number: "+
hex_num+"\n");
28. Write a Java program to convert a hexadecimal value into a
decimal number.
Input Data:
Input a hexadecimal number: 25
Expected Output
Equivalent decimal number is: 37
import java.util.Scanner;
public class Exercise28 {
public static int hex_to_decimal(String s)
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
return val;
public static void main(String args[])
String hexdec_num;
int dec_num;
Scanner scan = new Scanner(System.in);
System.out.print("Input a hexadecimal number: ");
hexdec_num = scan.nextLine();
dec_num = hex_to_decimal(hexdec_num);
System.out.print("Equivalent decimal number is: " +
dec_num+"\n");
29. Write a Java program to convert a hexadecimal number into
a binary number.
Input Data:
Enter Hexadecimal Number : 37
Expected Output
Equivalent Binary Number is: 110111
import java.util.Scanner;
public class Exercise29 {
public static int hex_to_decimal(String s)
{
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
return val;
public static void main(String args[])
String hexdec_num;
int dec_num, i=1, j;
int bin_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexdec_num = scan.nextLine();
/* convert hexadecimal to decimal */
dec_num = hex_to_decimal(hexdec_num);
/* convert decimal to binary */
while(dec_num != 0)
bin_num[i++] = dec_num%2;
dec_num = dec_num/2;
System.out.print("Equivalent Binary Number is: ");
for(j=i-1; j>0; j--)
System.out.print(bin_num[j]);
System.out.print("\n");
30. Write a Java program to convert a hexadecimal value into an
octal number.
Input Data:
Input a hexadecimal number: 40
Expected Output
Equivalent of octal number is: 100
import java.util.Scanner;
public class Exercise30 {
public static int hex_to_decimal(String s)
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
return val;
public static void main(String args[])
String hexdec_num;
int dec_num, i=1, j;
int octal_num[] = new int[100];
Scanner in = new Scanner(System.in);
System.out.print("Input a hexadecimal number: ");
hexdec_num = in.nextLine();
// Convert hexadecimal to decimal
dec_num = hex_to_decimal(hexdec_num);
//Convert decimal to octal
while(dec_num != 0)
octal_num[i++] = dec_num%8;
dec_num = dec_num/8;
}
System.out.print("Equivalent of octal number is: ");
for(j=i-1; j>0; j--)
System.out.print(octal_num[j]);
System.out.print("\n");
31. Write a Java program to check whether Java is installed on
your computer.
Expected Output
Java Version: 1.8.0_71
Java Runtime Version: 1.8.0_71-b15
Java Home: /opt/jdk/jdk1.8.0_71/jre
Java Vendor: Oracle Corporation
Java Vendor URL: http://Java.oracle.com/
Java Class Path: .
public class Exercise31 {
public static void main(String[] args) {
System.out.println("\nJava Version:
"+System.getProperty("java.version"));
System.out.println("Java Runtime Version:
"+System.getProperty("java.runtime.version"));
System.out.println("Java Home:
"+System.getProperty("java.home"));
System.out.println("Java Vendor:
"+System.getProperty("java.vendor"));
System.out.println("Java Vendor URL:
"+System.getProperty("java.vendor.url"));
System.out.println("Java Class Path:
"+System.getProperty("java.class.path")+"\n");
32. Write a Java program to compare two numbers.
Input Data:
Input first integer: 25
Input second integer: 39
Expected Output
25 != 39
25 < 39
25 <= 39
import java.util.Scanner;
public class Exercise32 {
public static void main( String args[] )
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
int number1; // first number to compare
int number2; // second number to compare
System.out.print( "Input first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Input second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
if ( number1 < number2 )
System.out.printf( "%d < %d\n", number1, number2 );
if ( number1 > number2 )
System.out.printf( "%d > %d\n", number1, number2 );
if ( number1 <= number2 )
System.out.printf( "%d <= %d\n", number1, number2 );
if ( number1 >= number2 )
System.out.printf( "%d >= %d\n", number1, number2 );
33. Write a Java program and compute the sum of an integer's
digits.
Input Data:
Input an integer: 25
Expected Output
The sum of the digits is: 7
import java.util.Scanner;
public class Exercise33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
long n = input.nextLong();
System.out.println("The sum of the digits is: " +
sumDigits(n));
public static int sumDigits(long n) {
int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
return sum;
34. Write a Java program to compute hexagon area.
Area of a hexagon = (6 * s^2)/(4*tan(π/6))
where s is the length of a side
Input Data:
Input the length of a side of the hexagon: 6
Expected Output
The area of the hexagon is: 93.53074360871938
import java.util.Scanner;
public class Exercise34 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input the length of a side of the hexagon:
");
double s = input.nextDouble();
System.out.print("The area of the hexagon is: " +
hexagonArea(s)+"\n");
public static double hexagonArea(double s) {
return (6*(s*s))/(4*Math.tan(Math.PI/6));
35. 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 Data:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Expected Output
The area is: 130.82084798405722
import java.util.Scanner;
public class Exercise35 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input the number of sides on the polygon:
");
int ns = input.nextInt();
System.out.print("Input the length of one of the sides: ");
double side = input.nextDouble();
System.out.print("The area is: " + polygonArea(ns, side)+"\
n");
}
public static double polygonArea(int ns, double side) {
return (ns * (side * side)) / (4.0 * Math.tan((Math.PI / ns)));
36. Write a Java program to compute the distance between two
points on the earth's surface.
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 Data:
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
Expected Output
The distance between those points is: 1480.0848451069087 km
import java.util.Scanner;
public class Exercise36 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input the latitude of coordinate 1: ");
double lat1 = input.nextDouble();
System.out.print("Input the longitude of coordinate 1: ");
double lon1 = input.nextDouble();
System.out.print("Input the latitude of coordinate 2: ");
double lat2 = input.nextDouble();
System.out.print("Input the longitude of coordinate 2: ");
double lon2 = input.nextDouble();
System.out.print("The distance between those points is: " +
distance_Between_LatLong(lat1, lon1, lat2, lon2) + " km\n");
// Points will be converted to radians before calculation
public static double distance_Between_LatLong(double lat1,
double lon1, double lat2, double lon2) {
lat1 = Math.toRadians(lat1);
lon1 = Math.toRadians(lon1);
lat2 = Math.toRadians(lat2);
lon2 = Math.toRadians(lon2);
double earthRadius = 6371.01; //Kilometers
return earthRadius * Math.acos(Math.sin(lat1)*Math.sin(lat2)
+ Math.cos(lat1)*Math.cos(lat2)*Math.cos(lon1 - lon2));
39. Write a Java program to create and display a unique three-
digit number using 1, 2, 3, 4. Also count how many three-digit
numbers are there.
Expected Output
123
124
...
431
432
Total number of the three-digit-number is 24
import java.util.Scanner;
public class Exercise39 {
public static void main(String[] args) {
int amount = 0;
for(int i = 1; i <= 4; i++){
for(int j = 1; j <= 4; j++){
for(int k = 1; k <= 4; k++){
if(k != i && k != j && i != j){
amount++;
System.out.println(i + "" + j + "" +
k);
}
}
System.out.println("Total number of the three-digit-
number is " + amount);
40. Write a Java program to list the available character sets in
charset objects.
Expected Output
List of available character sets:
Big5
Big5-HKSCS
CESU-8
EUC-JP
EUC-KR
GB18030
GB2312
GBK
...
x-SJIS_0213
x-UTF-16LE-BOM
X-UTF-32BE-BOM
X-UTF-32LE-BOM
x-windows-50220
x-windows-50221
x-windows-874
x-windows-949
x-windows-950
x-windows-iso2022jp
import java.nio.charset.Charset;
public class Exercise40 {
public static void main(String[] args) {
System.out.println("List of available character sets: ");
for (String str : Charset.availableCharsets().keySet()) {
System.out.println(str);
41. Write a Java program to print the ASCII value of a given
character.
Expected Output
The ASCII value of Z is :90
public class Exercise41 {
public static void main(String[] String) {
int chr = 'Z';
System.out.println("The ASCII value of Z is :"+chr);
42. Write a Java program to input and display your password.
Expected Output
Input your Password:
Your password was: abc@123
import java.io.Console;
public class Example42 {
public static void main(String[] args) {
Console cons;
if ((cons = System.console()) != null) {
char[] pass_ward = null;
try {
pass_ward = cons.readPassword("Input your
Password:");
System.out.println("Your password was: " +
new String(pass_ward));
} finally {
if (pass_ward != null) {
java.util.Arrays.fill(pass_ward, ' ');
} else {
throw new RuntimeException("Can't get
password...No console");
43. Write a Java program to print the following string in a
specific format (see output).
Sample Output
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
public class Example43 {
public static void main(String[] args) {
System.out.println("\nTwinkle, twinkle, little star, \n\tHow I
wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a
diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I
wonder what you are!\n\n");
}
44. Write a Java program that accepts an integer (n) and
computes the value of n+nn+nnn.
Sample Output:
Input number: 5
5 + 55 + 555
import java.util.Scanner;
public class Exercise44 {
public static void main(String[] args) {
int n;
char s1, s2, s3;
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
n = in .nextInt();
System.out.printf("%d + %d%d + %d%d%d\n", n, n, n, n, n, n);
45. Write a Java program to find the size of a specified file.
Sample Output:
/home/students/abc.txt : 0 bytes
/home/students/test.txt : 0 bytes
import java.util.Scanner;
import java.io.File;
public class Exercise45 {
public static void main(String[] args) {
System.out.println("/home/students/abc.txt : " + new
File("abc.txt").length() + " bytes");
System.out.println("/home/students/test.txt : " + new
File("test.txt").length() + " bytes");
46. Write a Java program to display system time.
Sample Output:
Current Date time: Fri Jun 16 14:17:40 IST 2017
public class Exercise46 {
public static void main(String[] args){
System.out.format("\nCurrent Date time: %tc%n\n",
System.currentTimeMillis());
47. Write a Java program to display the current date and time in
a specific format.
Sample Output:
Now: 2017/06/16 08:52:03.066
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class Exercise47 {
public static void main(String args[]) {
SimpleDateFormat cdt = new
SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
cdt.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("G
MT")));
System.out.println("\nNow:
"+cdt.format(System.currentTimeMillis()));
}
48. Write a Java program to print odd numbers from 1 to 99.
Prints one number per line.
Sample Output:
1
3
5
7
9
11
....
91
93
95
97
99
import java.util.*;
public class Exercise48 {
public static void main(String[] args){
for (int i = 1; i < 100; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
49. Write a Java program to accept a number and check whether
the number is even or not. Prints 1 if the number is even or 0 if
odd.
Sample Output:
Input a number: 20
1
import java.util.*;
public class Exercise49 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int n = in.nextInt();
if (n % 2 == 0) {
System.out.println(1);
else {
System.out.println(0);
50. Write a Java program to print numbers between 1 and 100
divisible by 3, 5 and both.
Sample Output:
Divided by 3:
3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51,
54, 57
, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99,
Divided by 5:
5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80,
85, 90,
95,
Divided by 3 & 5:
15, 30, 45, 60, 75, 90,
public class Exercise50 {
public static void main(String args[]) {
System.out.println("\nDivided by 3: ");
for (int i=1; i<100; i++) {
if (i%3==0)
System.out.print(i +", ");
System.out.println("\n\nDivided by 5: ");
for (int i=1; i<100; i++) {
if (i%5==0) System.out.print(i +", ");
System.out.println("\n\nDivided by 3 & 5: ");
for (int i=1; i<100; i++) {
if (i%3==0 && i%5==0) System.out.print(i +", ");
System.out.println("\n");
51. Write a Java program to convert a string to an integer.
Sample Output:
Input a number(string): 25
The integer value is: 25
import java.util.*;
public class Exercise51 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input a number(string): ");
String str1 = in.nextLine();
int result = Integer.parseInt(str1);
System.out.printf("The integer value is: %d",result);
System.out.printf("\n");
52. Write a Java program to calculate the sum of two integers
and return true if the sum is equal to a third integer.
Sample Output:
Input the first number : 5
Input the second number: 10
Input the third number : 15
The result is: true
import java.util.*;
public class Exercise52 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.print("The result is: "+sumoftwo(x, y, z));
System.out.print("\n");
public static boolean sumoftwo(int p, int q, int r)
return ((p + q) == r || (q + r) == p || (r + p) == q);
53. Write a Java program that accepts three integers from the
user. It returns true if the second number is higher than the first
number and the third number is larger than the second number. If
"abc" is true, the second number does not need to be larger than
the first number.
Sample Output:
Input the first number : 5
Input the second number: 10
Input the third number : 15
The result is: true
import java.util.*;
public class Exercise53 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.print("The result is: "+test(x, y, z,true));
System.out.print("\n");
public static boolean test(int p, int q, int r, boolean xyz)
if(xyz)
return (r > q);
return (q > p && r > q);
54. Write a Java program that accepts three integers from the
user and returns true if two or more of them (integers) have the
same rightmost digit. The integers are non-negative.
Sample Output:
Input the first number : 5
Input the second number: 10
Input the third number : 15
The result is: true
import java.util.*;
public class Exercise54 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.print("The result is: "+test_last_digit(x, y,
z,true));
System.out.print("\n");
public static boolean test_last_digit(int p, int q, int r, boolean
xyz)
return (p % 10 == q % 10) || (p % 10 == r % 10) || (q % 10
== r % 10);
55. Write a Java program to convert seconds to hours, minutes
and seconds.
Sample Output:
Input seconds: 86399
23:59:59
import java.util.*;
public class Main {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input seconds: ");
int seconds = in.nextInt();
int S = seconds % 60;
int H = seconds / 60;
int M = H % 60;
H = H / 60;
System.out.print( H + ":" + M + ":" + S);
System.out.print("\n");
}
56. Write a Java program to find the number of values in a given
range divisible by a given value.
For example x = 5, y=20 and p =3, find the number of integers
within the range x..y and that are divisible by p i.e. { i :x ≤ i ≤ y, i
mod p = 0 }
Sample Output:
5
import java.util.*;
public class Exercise56 {
public static void main(String[] args){
int x = 5;
int y = 20;
int p = 3;
System.out.println(result(x,y,p));
public static int result(int x, int y, int p) {
if (x%p == 0)
return( y/p - x/p + 1);
return(y/p - x/p);
57. Write a Java program to accept an integer and count the
factors of the number.
Sample Output:
Input an integer: 25
3
import java.util.*;
public class Exercise57 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Input an integer: ");
int x = in.nextInt();
System.out.println(result(x));
public static int result(int num) {
int ctr = 0;
for(int i=1; i<=(int)Math.sqrt(num); i++) {
if(num%i==0 && i*i!=num) {
ctr+=2;
} else if (i*i==num) {
ctr++;
return ctr;
58. Write a Java program to capitalize the first letter of each
word in a sentence.
Sample Output:
Input a Sentence: the quick brown fox jumps over the lazy dog.
The Quick Brown Fox Jumps Over The Lazy Dog.
import java.util.*;
public class Exercise58 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Input a Sentence: ");
String line = in.nextLine();
String upper_case_line = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()) {
String word = lineScan.next();
upper_case_line +=
Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
System.out.println(upper_case_line.trim());
59. Write a Java program to convert a string into lowercase.
Sample Output:
Input a String: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
the quick brown fox jumps over the lazy dog.
import java.util.*;
public class Exercise59 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Input a String: ");
String line = in.nextLine();
line = line.toLowerCase();
System.out.println(line);
60. Write a Java program to find the penultimate (next to the
last) word in a sentence.
Sample Output:
Input a String: The quick brown fox jumps over the lazy dog.
Penultimate word: lazy
import java.util.*;
public class Exercise60 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Input a Sentence: ");
String line = in.nextLine();
String[] words = line.split("[ ]+");
System.out.println("Penultimate word:
"+words[words.length - 2]);
61. Write a Java program to reverse a word.
Sample Output:
Input a word: dsaf
Reverse word: fasd
import java.util.*;
public class Exercise61 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("\nInput a word: ");
String word = in.nextLine();
word = word.trim();
String result = "";
char[] ch=word.toCharArray();
for (int i = ch.length - 1; i >= 0; i--) {
result += ch[i];
System.out.println("Reverse word: "+result.trim());
62. Write a Java program that accepts three integer values and
returns true if one is 20 or more less than the others'
subtractions.
Sample Output:
Input the first number : 15
Input the second number: 20
Input the third number : 25
false
import java.util.*;
public class Exercise62 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.println((Math.abs(x - y) >= 20 || Math.abs(y - z) >=
20 || Math.abs(z - x) >= 20));
63. Write a Java program that accepts two integer values from
the user and returns the largest value. However if the two values
are the same, return 0 and find the smallest value if the two
values have the same remainder when divided by 6.
Sample Output:
Input the first number : 12
Input the second number: 13
Result: 13
import java.util.*;
public class Exercise63 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int a = in.nextInt();
System.out.print("Input the second number: ");
int b = in.nextInt();
System.out.println("Result: "+result(a, b));
public static int result(int x, int y)
if(x == y)
return 0;
if(x % 6 == y % 6)
return (x < y) ? x : y;
return (x > y) ? x : y;
64. Write a Java program that accepts two integer values
between 25 and 75 and returns true if there is a common digit in
both numbers.
Sample Output:
Input the first number : 35
Input the second number: 45
Result: true
import java.util.*;
public class Exercise64 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int a = in.nextInt();
System.out.print("Input the second number: ");
int b = in.nextInt();
System.out.println("Result: "+common_digit(a, b));
public static boolean common_digit(int p, int q)
if (p<25 || q>75)
return false;
int x = p % 10;
int y = q % 10;
p /= 10;
q /= 10;
return (p == q || p == y || x == q || x == y);
65. Write a Java program to calculate the modules of two
numbers without using any inbuilt modulus operator.
Sample Output:
Input the first number : 19
Input the second number: 7
5
import java.util.*;
public class Exercise65 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int a = in.nextInt();
System.out.print("Input the second number: ");
int b = in.nextInt();
int divided = a / b;
int result = a - (divided * b);
System.out.println(result);
66. Write a Java program to compute the sum of the first 100
prime numbers.
Sample Output:
Sum of the first 100 prime numbers: 24133
import java.util.*;
public class Exercise66 {
public static void main(String[] args)
int sum = 1;
int ctr = 0;
int n = 0;
while (ctr < 100) {
n++;
if (n % 2 != 0) {
// check if the number is even
if (is_Prime(n)) {
sum += n;
ctr++;
System.out.println("\nSum of the prime numbers till
100: "+sum);
public static boolean is_Prime(int n) {
for (int i = 3; i * i <= n; i+= 2) {
if (n % i == 0) {
return false;
return true;
67. Write a Java program to insert a word in the middle of
another string.
Insert "Tutorial" in the middle of "Python 3.0", so the result will
be Python Tutorial 3.0.
Sample Output:
Python Tutorial 3.0
import java.lang.*;
public class Exercise67 {
public static void main(String[] args)
String main_string = "Python 3.0";
String word = "Tutorial";
System.out.println(main_string.substring(0, 7) + word +
main_string.substring(6));
68. Write a Java program to create another string of 4 copies of
the last 3 characters of the original string. The original string
length must be 3 and above.
Sample Output:
3.03.03.03.0
import java.lang.*;
public class Exercise68 {
public static void main(String[] args)
String main_string = "Python 3.0";
String last_three_chars =
main_string.substring(main_string.length() - 3);
System.out.println(last_three_chars + last_three_chars +
last_three_chars + last_three_chars);
69. Write a Java program to extract the first half of a even
string.
Test Data: Python
Sample Output:
Pyt
import java.lang.*;
public class Exercise69 {
public static void main(String[] args)
String main_string = "Python";
System.out.println(main_string.substring(0,
main_string.length()/2));
70. Write a Java program to create a string in the form of
short_string + long_string + short_string from two strings. The
strings must not have the same length.
Test Data: Str1 = Python
Str2 = Tutorial
Sample Output:
PythonTutorialPython
import java.lang.*;
public class Exercise70 {
public static void main(String[] args)
String str1 = "Python";
String str2 = "Tutorial";
if(str1.length() >= str2.length())
System.out.println( str2+str1+str2);
else
System.out.println(str1+str2+str1);
71. Write a Java program to create the concatenation of the two
strings except removing the first character of each string. The
length of the strings must be 1 and above.
Test Data: Str1 = Python
Str2 = Tutorial
Sample Output:
ythonutorial
import java.lang.*;
public class Exercise71 {
public static void main(String[] args)
String str1 = "Python";
String str2 = "Tutorial";
System.out.println(str1.substring(1) + str2.substring(1));
}
72. Write a Java program to create a string taking the first three
characters from a given string. If the string length is less than 3
use "#" as substitute characters.
Test Data: Str1 = " "
Sample Output:
###
import java.lang.*;
public class Exercise72 {
public static void main(String[] args)
String str1 = "";
int len = str1.length();
if(len >= 3)
System.out.println( str1.substring(0, 3));
else if(len == 1)
System.out.println( (str1.charAt(0)+"##"));
else
System.out.println("###");
73. Write a Java program to create a string taking the first and
last characters from two given strings. If the length of each
string is 0 use "#" for missing characters.
Test Data: str1 = "Python"
str2 = " "
Sample Output:
P#
import java.lang.*;
public class Exercise73 {
public static void main(String[] args)
String str1 = "Python";
String str2 = "";
int length2 = str2.length();
String result = "";
result += (str1.length() >= 1) ? str1.charAt(0) : '#';
result += (length2 >= 1) ? str2.charAt(length2-1) : '#';
System.out.println(result);
}
}
74. Write a Java program to test if 10 appears as the first or last
element of an array of integers. The array length must be broader
than or equal to 2.
Sample Output:
Test Data: array = 10, -20, 0, 30, 40, 60, 10
true
import java.lang.*;
public class Exercise74 {
public static void main(String[] args)
int[] num_array = {10, -20, 0, 30, 40, 60, 10};
System.out.println((num_array[0] == 10 ||
num_array[num_array.length-1] == 10));
75. Write a Java program to test if the first and last elements of
an array of integers are the same. The array length must be
broader than or equal to 2.
Test Data: array = 50, -20, 0, 30, 40, 60, 10
Sample Output:
false
import java.lang.*;
public class Exercise75 {
public static void main(String[] args)
int[] num_array = {50, -20, 0, 30, 40, 60, 10};
System.out.println (num_array.length >= 2 && num_array[0]
== num_array[num_array.length-1]);
76. Write a Java program to test if the first and last element of
two integer arrays are the same. The array length must be
greater than or equal to 2.
Test Data: array1 = 50, -20, 0, 30, 40, 60, 12
array2 = 45, 20, 10, 20, 30, 50, 11
Sample Output:
false
public class Main {
public static void main(String[] args)
//false
int[] num_array1 = {50, -20, 0, 30, 40, 60, 12};
int[] num_array2 = {45, 20, 10, 20, 30, 50, 11};
//true
//int[] num_array1 = {50, -20, 0, 30, 40, 60, 12};
//int[] num_array2 = {45, 20, 10, 20, 30, 50, 12};
//Array lengths less than 2.
//int[] num_array1 = {50};
//int[] num_array2 = {45};
if(num_array1.length>=2 && num_array2.length>=2)
{
System.out.println(num_array1[0] == num_array2[0] ||
num_array1[num_array1.length-1] ==
num_array2[num_array2.length-1]);
else
System.out.println("Array lengths less than 2.");
77. Write a Java program to create an array of length 2 from two
integer arrays with three elements. The newly created array will
contain the first and last elements from the two arrays.
Test Data: array1 = 50, -20, 0
array2 = 5, -50, 10
Sample Output:
Array1: [50, -20, 0]
Array2: [5, -50, 10]
New Array: [50, 10]
import java.util.Arrays;
public class Exercise77 {
public static void main(String[] args)
int[] array1 = {50, -20, 0};
int[] array2 = {5, -50, 10};
System.out.println("Array1: "+Arrays.toString(array1));
System.out.println("Array2: "+Arrays.toString(array2));
int[] array_new = {array1[0], array2[2]};
System.out.println("New Array:
"+Arrays.toString(array_new));
78. Write a Java program to test that a given array of integers of
length 2 contains a 4 or a 7.
Sample Output:
Original Array: [5, 7]
true
import java.util.Arrays;
public class Exercise78 {
public static void main(String[] args)
int[] array_nums = {5, 7};
System.out.println("Original Array:
"+Arrays.toString(array_nums));
if(array_nums[0] == 4 || array_nums[0] == 7)
System.out.println("True");
else
System.out.println(array_nums[1] == 4 || array_nums[1] == 7);
79. Write a Java program to rotate an array (length 3) of integers
in the left direction.
Sample Output:
Original Array: [20, 30, 40]
Rotated Array: [30, 40, 20]
import java.util.Arrays;
public class Exercise79 {
public static void main(String[] args)
int[] array_nums = {20, 30, 40};
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int[] new_array_nums = {array_nums[1], array_nums[2],
array_nums[0]};
System.out.println("Rotated Array:
"+Arrays.toString(new_array_nums));
80. Write a Java program to get the largest value between the
first and last elements of an array (length 3) of integers.
Sample Output:
Original Array: [20, 30, 40]
Larger value between first and last element: 40
import java.util.Arrays;
public class Exercise80 {
public static void main(String[] args)
int[] array_nums = {20, 30, 40};
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int max_val = array_nums[0];
if(array_nums[2] >= max_val)
max_val = array_nums[2];
System.out.println("Larger value between first and last
element: "+max_val);
81. Write a Java program to swap the first and last elements of
an array (length must be at least 1) and create another array.
Sample Output:
Original Array: [20, 30, 40]
New array after swaping the first and last elements: [40, 30, 20]
import java.util.Arrays;
public class Exercise81 {
public static void main(String[] args)
int[] array_nums = {20, 30, 40};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int x = array_nums[0];
array_nums[0] = array_nums[array_nums.length-1];
array_nums[array_nums.length-1] = x;
System.out.println("New array after swaping the first and last elements:
"+Arrays.toString(array_nums));
82. Write a Java program to find the largest element between
the first, last, and middle values in an array of integers (even
length).
Sample Output:
Original Array: [20, 30, 40, 50, 67]
Largest element between first, last, and middle values: 67
import java.util.Arrays;
public class Exercise82 {
public static void main(String[] args)
int[] array_nums = {20, 30, 40, 50, 67};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int max_val = array_nums[0];
if(max_val <= array_nums[array_nums.length-1])
max_val = array_nums[array_nums.length-1];
if(max_val <= array_nums[array_nums.length/2])
max_val = array_nums[array_nums.length/2];
System.out.println("Largest element between first, last, and middle values: "+max_val);
83. Write a Java program to multiply the corresponding elements
of two integer arrays.
Sample Output:
Array1: [1, 3, -5, 4]
Array2: [1, 4, -5, -2]
Result: 1 12 25 -8
import java.util.*;
public class Exercise83 {
public static void main(String[] args){
String result = "";
int[] left_array = {1, 3, -5, 4};
int[] right_array = {1, 4, -5, -2};
System.out.println("\nArray1: "+Arrays.toString(left_array));
System.out.println("\nArray2: "+Arrays.toString(right_array));
for (int i = 0; i < left_array.length; i++) {
int num1 = left_array[i];
int num2 = right_array[i];
result += Integer.toString(num1 * num2) + " ";
System.out.println("\nResult: "+result);
84. Write a Java program to take the last three characters from
a given string. It will add the three characters at both the front
and back of the string. String length must be greater than three
and more.
Test data: "Python" will be "honPythonhon"
Sample Output:
honPythonhon
import java.util.*;
import java.io.*;
public class Exercise84 {
public static void main(String[] args)
String string1 = "Python";
int slength = 3;
if (slength > string1.length()) {
slength = string1.length();
String subpart = string1.substring(string1.length()-3);
System.out.println(subpart + string1 + subpart);
85. Write a Java program to check if a string starts with a
specified word.
Sample Data: string1 = "Hello how are you?"
Sample Output:
true
import java.util.*;
import java.io.*;
public class Exercise85 {
public static void main(String[] args)
{
String string1 = "Hello how are you?";
System.out.println(string1.startsWith("Hello"));
86. Write a Java program starting with an integer n, divide it by 2
if it is even, or multiply it by 3 and add 1 if it is odd. Repeat the
process until n = 1.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input the value of n: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
else {
n = (3 * n + 1) / 2;
System.out.println("\nValue of n = "+n);
in.close();
}
}
87. Write a Java program that then reads an integer and
calculates the sum of its digits and writes the number of each
digit of the sum in English.
import java.io.*;
public class Main {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
try {
int sum = 0;
String str = br.readLine();
char[] numStr = str.toCharArray();
for (int i = 0; i < numStr.length; i ++) {
sum += numStr[i] - '0';
System.out.println("Original Number: "+str);
print_number(sum);
} catch (IOException e) {
e.printStackTrace();
}
public static void print_number(int n) {
int x; int y; int z;
String[] number =
{"zero","one","two","three","four","five","six","seven","eight","nin
e"};
System.out.println("Sum of the digits of the said
number: "+n);
if (n < 10) {
System.out.println(number[n]);
else if (n < 100) {
x = n / 10;
y = n - x *10;
System.out.println("In English: "+number[x] + " " +
number[y]);
else {
x = n / 100;
y = (n - x * 100) / 10;
z = n - x * 100 - y * 10;
System.out.println("In English: "+number[x] + " " +
number[y] + " " + number[z]);
}
88. Write a Java program to get the current system environment
and system properties.
import java.lang.*;
public class Exercise88 {
public static void main(String[] args)
System.out.println("\nCurrent system environment:");
System.out.println(System.getenv());
System.out.println("\n\nCurrent system properties:");
System.out.println(System.getProperties());
}
89. Write a Java program to check whether a security manager
has already been established for the current application or not.
import java.lang.*;
public class Exercise89 {
public static void main(String[] args)
System.out.println("System security interface:");
System.out.println(System.getSecurityManager());
90. Write a Java program to get the value of environment
variables PATH, TEMP, USERNAME.
import java.lang.*;
public class Exercise90 {
public static void main(String[] args)
// gets the value of the specified environment variable
"PATH"
System.out.println("\nEnvironment variable PATH: ");
System.out.println(System.getenv("PATH"));
// gets the value of the specified environment variable "TEMP"
System.out.println("\nEnvironment variable TEMP: ");
System.out.println(System.getenv("TEMP"));
// gets the value of the specified environment variable
"USERNAME"
System.out.println("\nEnvironment variable USERNAME: ");
System.out.println(System.getenv("USERNAME"));
91. Write a Java program to measure how long code executes in
nanoseconds.
import java.lang.*;
public class Exercise91 {
public static void main(String[] args)
long startTime = System.nanoTime();
// Sample program
// Display the first 10 natural numbers.
int i;
System.out.println ("The first 10 natural numbers are:\n");
for (i=1;i<=10;i++)
System.out.println (i);
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Estimated time (in nanoseconds) to get
the first 10 natural numbers: "+estimatedTime);
92. Write a Java program to count the number of even and odd
elements in a given array of integers.
import java.util.*;
public class Exercise92 {
public static void main(String[] args)
{
int[] nums = {5, 7, 2, 4, 9};
int ctr_even = 0, ctr_odd = 0;
System.out.println("Original Array: "+Arrays.toString(nums));
for(int i = 0; i < nums.length; i++) {
if(nums[i] % 2 == 0)
ctr_even++;
else
ctr_odd++;
System.out.printf("\nNumber of even elements in the array:
%d",ctr_even);
System.out.printf("\nNumber of odd elements in the array:
%d",ctr_odd);
System.out.printf("\n");
93. Write a Java program to test if an array of integers contains
an element 10 next to 10 or an element 20 next to 20, but not
both.
import java.util.*;
public class Exercise93 {
public static void main(String[] args)
{
//int[] nums = {10, 10, 2, 4, 9};
int[] nums = {10, 10, 2, 4, 20, 20};
int ctr_even = 0, ctr_odd = 0;
System.out.println("Original Array: "+Arrays.toString(nums));
boolean found1010 = false;
boolean found2020 = false;
for(int i = 0; i < nums.length - 1; i++) {
if(nums[i] == 10 && nums[i+1] == 10)
found1010 = true;
if(nums[i] == 20 && nums[i+1] == 20)
found2020 = true;
System.out.printf( String.valueOf(found1010 != found2020));
System.out.printf("\n");
94. Write a Java program to rearrange all the elements of a given
array of integers so that all the odd numbers come before all the
even numbers.
import java.util.*;
import java.io.*;
public class Exercise94 {
public static void main(String[] args)
int[] array_nums = {1, 7, 8, 5, 7, 13, 0, 2, 4, 9};
int i = 0;
System.out.println("Original Array:
"+Arrays.toString(array_nums));
while(i < array_nums.length && array_nums[i] % 2 == 0)
i++;
for(int j = i + 1; j < array_nums.length; j++) {
if(array_nums[j] % 2 != 0) {
int temp = array_nums[i];
array_nums[i] = array_nums[j];
array_nums[j] = temp;
i++;
System.out.println("New Array:
"+Arrays.toString(array_nums));
95. Write a Java program to create an array (length # 0) of string
values. The elements will contain "0", "1", "2" … through ... n-1.
import java.util.*;
import java.io.*;
public class Exercise95 {
public static void main(String[] args)
int n= 5;
String[] arr_string = new String[n];
for(int i = 0; i < n; i++)
arr_string[i] = String.valueOf(i);
System.out.println("New Array:
"+Arrays.toString(arr_string));
}
96. Write a Java program to check if there is a 10 in an array of
integers with a 20 somewhere later on.
import java.util.*;
import java.io.*;
public class Exercise96 {
public static void main(String[] args)
int[] array_nums = {10, 70, 80, 50, 20, 13, 50};
boolean testd = false;
int result=0;
int x = 10;
int y = 20;
for(int i = 0; i < array_nums.length; i++) {
if(array_nums[i] == x)
testd = true;
if(testd && array_nums[i] == y)
System.out.printf( String.valueOf(true));
result = 1 ;
if (result==0)
System.out.printf( String.valueOf(false));
System.out.printf("\n");
97. Write a Java program to check if an array of integers
contains a specified number next to each other or two same
numbers separated by one element.
import java.util.*;
import java.io.*;
public class Exercise97 {
public static void main(String[] args)
int[] array_nums = {10, 20, 10, 50, 20, 13, 50};
//int[] array_nums = {10, 10, 50, 50, 20, 13, 50};
boolean testd = false;
int result=0;
int x = 10;
for(int i = 0; i < array_nums.length - 1; i++) {
if(array_nums[i] == x && array_nums[i+1] == x)
{
System.out.printf( String.valueOf(true));
result = 1 ;
if(i <= array_nums.length - 3 && array_nums[i] == x &&
array_nums[i+2] == x)
System.out.printf( String.valueOf(true));
result = 1 ;
if (result==0)
System.out.printf( String.valueOf(false));
System.out.printf("\n");
98. Write a Java program to check if the value 20 appears three
times and no 20's are next to each other in the array of integers.
import java.util.*;
import java.io.*;
public class Exercise98 {
public static void main(String[] args)
int[] array_nums = {10, 20, 10, 20, 40, 13, 20};
int count = 0, result =0;
if(array_nums.length >= 1 && array_nums[0] == 20)
count++;
for(int i = 1; i < array_nums.length; i++) {
if(array_nums[i - 1] == 20 && array_nums[i] == 20)
{
System.out.printf( String.valueOf(false));
result = 1;
if(array_nums[i] == 20)
count++;
if (result==0)
System.out.printf( String.valueOf(count == 3));
System.out.printf("\n");
99. Write a Java program that checks if a specified number
appears in every pair of adjacent integers of a given array of
integers.
import java.util.*;
import java.io.*;
public class Exercise99 {
public static void main(String[] args)
int[] array_nums = {10, 20, 10, 20, 40, 20, 50};
int result = 0;
int x = 20;
for(int i = 0; i < array_nums.length - 1; i++) {
if(array_nums[i] != x && array_nums[i + 1] != x)
result = 1;
if (result==0)
System.out.printf( String.valueOf(true));
else
System.out.printf( String.valueOf(false));
100. Write a Java program to count the elements that differ by 1
or less between two given arrays of integers with the same
length.
import java.util.*;
import java.io.*;
public class Exercise100 {
public static void main(String[] args)
int[] array_nums1 = {10, 11, 10, 20, 43, 20, 50};
int[] array_nums2 = {10, 13, 11, 20, 44, 30, 50};
System.out.println("Array1: "+Arrays.toString(array_nums1));
System.out.println("Array2: "+Arrays.toString(array_nums2));
int ctr = 0;
for(int i = 0; i < array_nums1.length; i++) {
if(Math.abs(array_nums1[i] - array_nums2[i]) <= 1 &&
array_nums1[i] != array_nums2[i])
ctr++;
System.out.printf("Number of elements: "+ctr);
System.out.printf("\n");
101. Write a Java program to determine whether the number 10
in a given array of integers exceeds 20.
import java.util.*;
import java.io.*;
public class Exercise101 {
public static void main(String[] args)
int[] array_nums = {10, 11, 10, 30, 45, 20, 33, 53};
int result = 0;
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int ctr1 = 0;
int ctr2 = 0;
for(int i = 0; i < array_nums.length; i++) {
if(array_nums[i] == 10)
ctr1++;
if(array_nums[i] == 20)
ctr2++;
System.out.printf(String.valueOf(ctr1 > ctr2));
System.out.printf("\n");
}
102. Write a Java program to check if a specified array of
integers contains 10 or 30.
import java.util.*;
import java.io.*;
public class Exercise102 {
public static void main(String[] args)
int[] array_nums = {11, 11, 13, 31, 45, 20, 33, 53};
int result = 1;
System.out.println("Original Array:
"+Arrays.toString(array_nums));
for(int i = 0; i < array_nums.length; i++)
{
if(array_nums[i] == 10 || array_nums[i] == 30)
result =0;
if (result==1)
System.out.printf( String.valueOf(false));
else
System.out.printf(String.valueOf(true));
103. Write a Java program to create an array from a given array
of integers. The newly created array will contain elements from
the given array after the last element value is 10.
import java.util.*;
import java.io.*;
public class Exercise103 {
public static void main(String[] args)
int[] array_nums = {11, 10, 13, 10, 45, 20, 33, 53};
int result = 0;
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int l = array_nums.length - 1;
int[] new_array;
while(array_nums[l] != 10)
l--;
new_array = new int[array_nums.length - 1 - l];
for(int i = l + 1; i < array_nums.length; i++)
new_array[i - l - 1] = array_nums[i];
System.out.println("New Array:
"+Arrays.toString(new_array));
104. Write a Java program to create an array from a given array
of integers. The newly created array will contain the elements
from the given array before the last element value of 10.
import java.util.*;
import java.io.*;
public class Exercise104 {
public static void main(String[] args)
int[] array_nums = {11, 15, 13, 10, 45, 20, 33, 53};
int result = 0;
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int l = 0;
int[] new_array;
while(array_nums[l] != 10)
l++;
new_array = new int[l];
for(int i = 0; i < l; i++)
new_array[i] = array_nums[i];
System.out.println("New Array:
"+Arrays.toString(new_array));
105. Write a Java program to check if a group of numbers (l) at
the start and end of a given array are the same.
import java.util.*;
import java.io.*;
public class Exercise105 {
public static void main(String[] args)
int[] array_nums = {11, 15, 13, 10, 45, 20, 11, 15};
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int result = 0;
int l = 2;
int start = 0;
int end = array_nums.length-l;
for(; l > 0; l--)
{
if(array_nums[start] != array_nums[end])
result = 1;
else
start++;
end++;
if (result==1)
System.out.printf(String.valueOf(false));
else
System.out.printf(String.valueOf(true));
System.out.printf("\n");
106. Write a Java program to create an array left shifted from a
given array of integers.
import java.util.*;
import java.io.*;
public class Exercise106 {
public static void main(String[] args)
int[] array_nums = {11, 15, 13, 10, 45, 20};
System.out.println("Original Array:
"+Arrays.toString(array_nums));
if(array_nums.length >1)
int first = array_nums[0];
for(int i = 1; i < array_nums.length; i++)
array_nums[i - 1] = array_nums[i];
array_nums[array_nums.length - 1] = first;
System.out.println("New Array:
"+Arrays.toString(array_nums));
107. Write a Java program to check if an array of integers
contains three increasing adjacent numbers.
import java.util.*;
import java.io.*;
public class Exercise107 {
public static void main(String[] args)
int[] array_nums = {11, 12, 13, 14, 45, 20};
System.out.println("Original Array:
"+Arrays.toString(array_nums));
int result =1;
for(int i = 0; i <= array_nums.length - 3; i++) {
if(array_nums[i] + 1 == array_nums[i+1] && array_nums[i+1]
+ 1 == array_nums[i+2])
result =0;
if (result==1)
System.out.printf(String.valueOf(false));
else
System.out.printf(String.valueOf(true));
System.out.printf("\n");
108. Write a Java program to add all the digits of a given positive
integer until the result has a single digit.
import java.util.Scanner;
public class Example108 {
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in.nextInt();
if (n>0)
System.out.print("The single digit number is: "+(n == 0 ? 0 :
(n % 9 == 0 ? 9 : n % 9)));
}
System.out.println("\n");
109. Write a Java program to form a staircase shape of n coins
where every k-th row must have exactly k coins.
import java.util.Scanner;
public class Example109 {
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in.nextInt();
if (n>0)
System.out.println("Number of rows: "+((int)((Math.sqrt(8 *
(long)n + 1) - 1) / 2)));
110. Write a Java program to check whether the given integer is
a power of 4 or not.
Given num = 64, return true. Given num = 6, return false.
import java.util.Scanner;
public class Example110 {
public static void main(String[] arg)
int test = 0;
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in.nextInt();
if (n < 1) {
System.out.print(Boolean.toString(false));
test = 1;
if ((n & (n - 1)) != 0) {
System.out.print(Boolean.toString(false));
test = 1;
if (test==0)
System.out.print(Boolean.toString((n &
0x55555555) != 0));
System.out.print("\n");
111. Write a Java program to add two numbers without
arithmetic operators.
Given x = 10 and y = 12; result = 22
import java.util.Scanner;
public class Example111 {
public static void main(String[] arg)
int x, y ;
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
x = in.nextInt();
System.out.print("Input second number: ");
y = in.nextInt();
while(y != 0){
int carry = x & y;
x = x ^ y;
y = carry << 1;
System.out.print("Sum: "+x);
System.out.print("\n");
112. Write a Java program to compute the number of trailing
zeros in a factorial.
7! = 5040, therefore the output should be 1
import java.util.Scanner;
public class Example112 {
public static void main(String[] arg)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int n = in.nextInt();
int n1 = n;
long ctr = 0;
while (n != 0)
ctr += n / 5;
n /= 5;
System.out.printf("Number of trailing zeros of the
factorial %d is %d ",n1,ctr);
System.out.printf("\n");
113. Write a Java program to merge two given sorted arrays of
integers and create another sorted array.
array1 = [1,2,3,4]
array2 = [2,5,7, 8]
result = [1,2,2,3,4,5,7,8]
import java.util.*;
public class Example113 {
public static void main(String[] arg)
// Sorted integer array array1 which has m elements,
// but size of array1 is m+n, sorted integer array array2 which
has n elements
//declaration and instantiation.
int array1[]=new int[8];
//initialization.
array1[0]=1;
array1[1]=2;
array1[2]=3;
array1[3]=4;
int[] array2 = {2,5,7,8};
System.out.println("\nArray1: "+Arrays.toString(array1));
System.out.println("\nArray2: "+Arrays.toString(array2));
int m =4, n=4;
int i = m-1, j = n-1, index = m + n - 1;
while (i >= 0 && j >= 0) {
if (array1[i] > array2[j]) {
array1[index--] = array1[i--];
} else {
array1[index--] = array2[j--];
while (i >= 0) {
array1[index--] = array1[i--];
while (j >= 0) {
array1[index--] = array2[j--];
System.out.println("\nMerged array:
"+Arrays.toString(array1));
}
}
114. Write a search Java program that rotates a string by an
offset (rotate from left to right.
import java.util.*;
import java.util.*;
public class Example114 {
public static void main(String[] arg)
String str = "abcdef";
char[] A = str.toCharArray();
int offset=3;
int len = A.length;
offset %= len;
reverse(A, 0, len - offset - 1);
reverse(A, len - offset, len - 1);
reverse(A, 0, len - 1);
System.out.println("\n"+Arrays.toString(A));
private static void reverse(char[] str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
115. Write a search Java program to check if a positive number is
a palindrome or not.
Input a positive integer: 151
Is 151 is a palindrome number?
true
import java.util.*;
public class test {
public static void main(String[] args)
int num;
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in.nextInt();
System.out.printf("Is %d is a palindrome number?\n",n);
System.out.println(is_Palindrome(n));
public static int reverse_nums(int n) {
int reverse = 0;
while (n != 0) {
reverse *= 10;
reverse += n % 10;
n /= 10;
return reverse;
public static boolean is_Palindrome(int n) {
return (n == reverse_nums(n));
116. Write a Java program that iterates integers from 1 to 100.
For multiples of three print "Fizz" instead of the number and print
"Buzz" for five. When the number is divided by three and five,
print "fizz buzz".
import java.util.*;
public class Exercise116 {
public static void main(String[] args)
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.printf("\n%d: fizz buzz",i);
} else if (i % 5 == 0) {
System.out.printf("\n%d: buzz",i);
} else if (i % 3 == 0) {
System.out.printf("\n%d: fizz",i);
System.out.printf("\n");
117. Write a Java program to compute the square root of a given
number.
Input a positive integer: 25
Square root of 25 is: 5
import java.util.*;
public class Exercise117 {
public static void main(String[] args)
int num;
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in.nextInt();
System.out.printf("Square root of %d is: ",n);
System.out.println(sqrt(n));
private static int sqrt(int num) {
if (num == 0 || num == 1) {
return num;
int a = 0;
int b = num;
while (a <= b) {
int mid = (a + b) >> 1;
if (num / mid < mid) {
b = mid - 1;
} else {
if (num / (mid + 1) <= mid) {
return mid;
}
a = mid + 1;
return a;
118. Write a search Java program to get the first occurrence
(Position starts from 0.) of a string within a given string.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s = "Python";
//String t = "Py";
String t = "yt";
// String t = "ab";
System.out.printf(String.valueOf(strStr(s, t)));
public static int strStr(String source, String target) {
if (source == null || target == null) {
return -1;
if ("".equals(target) || source.equals(target)) {
return 0;
int i = 0;
int last = source.length() - target.length() + 1;
while (i < last) {
if (source.charAt(i) == target.charAt(0)) {
boolean equal = true;
for (int j = 0; j < target.length() && equal; ++j) {
if (source.charAt(i + j) != target.charAt(j)) {
equal = false;
if (equal) {
return i;
}
++i;
return -1;
119. Write a search Java program to get the first occurrence
(Position starts from 0.) of an element of a given array.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int nums[] = {2, 4, 6, 7, 8};
int target = 7;
int lower = 0;
int upper = nums.length - 1;
int index = -1;
while (lower <= upper) {
int mid = (lower + upper) >> 1;
if (nums[mid] == target) {
index = mid;
if (nums[mid] >= target) {
upper = mid - 1;
} else {
lower = mid + 1;
System.out.print("Position of "+target +" is "+index);
120. Write a Java program that searches for a value in an m x n
matrix.
public class Main {
public static void main(String[] args) {
// int target = 5;
int target = 0;
int[][] matrix = new int[3][3];
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
matrix[row][col] = (1 + row * 3 + col);
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
System.out.print(matrix[row][col]+" ");
if (col == 2)
System.out.println();
System.out.print(Boolean.toString(searchMatrix(matrix,
target)));
public static boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) {
return false;
int m = matrix.length;
int n = matrix[0].length;
int lower = 0;
int higher = m * n - 1;
while (lower <= higher) {
int mid = (lower + higher) >> 1;
int val = matrix[mid / n][mid % n];
if (val == target) {
return true;
if (val < target) {
lower = mid + 1;
} else {
higher = mid - 1;
return false;
121. Write a Java program to reverse a linked list.
Example: For linked list 20->40->60->80, the reversed linked list
is 80->60->40->20
class LinkedList {
static Node head;
static class Node {
int data;
Node next_node;
Node(int d) {
data = d;
next_node = null;
/* Reverse the linked list */
Node reverse(Node node) {
Node prev_node = null;
Node current_node = node;
Node next_node = null;
while (current_node != null) {
next_node = current_node.next_node;
current_node.next_node = prev_node;
prev_node = current_node;
current_node = next_node;
node = prev_node;
return node;
// Prints the elements of the double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next_node;
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(20);
list.head.next_node = new Node(40);
list.head.next_node.next_node = new Node(60);
list.head.next_node.next_node.next_node = new
Node(80);
System.out.println("Original Linked list:");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed Linked list:");
list.printList(head);
122. Write a Java program to find a contiguous subarray with the
largest sum from a given array of integers.
Note: In computer science, the maximum subarray problem is the
task of finding the contiguous subarray within a one-dimensional
array of numbers which has the largest sum. For example, for the
sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous
subarray with the largest sum is 4, −1, 2, 1, with sum 6. The
subarray should contain one integer at least.
public class Main {
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.print(max_SubArray(nums));
}
public static int max_SubArray(int[] nums) {
if (nums.length < 1) {
return 0;
int max = nums[0];
int max_Begin = 0;
int max_End = 0;
int begin = 0;
int end = 0;
int sum = 0;
while (end < nums.length) {
sum += nums[end];
if (sum < 0) {
sum = 0;
begin = end + 1;
} else {
if (sum > max) {
max = sum;
max_Begin = begin;
max_End = end;
end++;
}
return max;
123. Write a search Java program to find the subarray with
smallest sum from a given array of integers.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(-2);
nums.add(1);
nums.add(-3);
nums.add(4);
System.out.print(min_SubArray(nums));
public static int min_SubArray(ArrayList<Integer> nums) {
int[] nums1 = new int[nums.size()];
nums1[0] = nums.get(0);
int min = nums1[0];
for (int i = 1; i < nums.size(); ++i) {
nums1[i] = Math.min(nums.get(i), nums.get(i) + nums1[i -
1]);
min = Math.min(min, nums1[i]);
return min;
124. Write a search Java program to find the index of a value in a
sorted array. If the value does not find return the index where it
would be if it were inserted in order.
Example:
[1, 2, 4, 5, 6] 5(target) -> 3(index)
[1, 2, 4, 5, 6] 0(target) -> 0(index)
[1, 2, 4, 5, 6] 7(target) -> 5(index)
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] nums = {1,2,4,5,6};
int target;
target = 5;
// target = 0;
// target = 7;
System.out.print(searchInsert(nums, target));
}
public static int searchInsert(int[] nums1, int target) {
if (nums1 == null || nums1.length == 0) {
return 0;
int start = 0;
int end = nums1.length - 1;
int mid = start + (end - start)/2;
while (start + 1 < end) {
mid = start + (end - start)/2;
if (nums1[mid] == target) {
return mid;
} else if (nums1[mid] > target) {
end = mid;
} else {
start = mid;
if (nums1[start] >= target) {
return start;
} else if (nums1[start] < target && target <= nums1[end]) {
return end;
} else {
return end + 1;
125. Write a Java program to get the preorder traversal of the
values of the nodes in a binary tree.
Example:
10
/ \
20 30
/ \
40 50
Expected output: 10 20 40 50 30
class Node
int key;
Node left, right;
public Node(int item)
key = item;
left = right = null;
}
class BinaryTree
// Root of Binary Tree
Node root;
BinaryTree()
root = null;
// Print the nodes of binary tree
void print_Preorder(Node node)
if (node == null)
return;
/* Print data of node */
System.out.print(node.key + " ");
print_Preorder(node.left);
print_Preorder(node.right);
void print_Preorder()
{
print_Preorder(root);
// Driver method
public static void main(String[] args)
BinaryTree tree = new BinaryTree();
tree.root = new Node(55);
tree.root.left = new Node(21);
tree.root.right = new Node(80);
tree.root.left.left = new Node(9);
tree.root.left.right = new Node(29);
tree.root.right.left = new Node(76);
tree.root.right.right = new Node(91);
System.out.println("Preorder traversal of binary tree is: ");
tree.print_Preorder();
126. Write a search Java program to get the in-order traversal of
its nodes' values in a binary tree.
10
/ \
20 30
/ \
40 50
Example:{10, 20, 30, 40, 50}
Output: 40 20 50 10 30
class Node
int key;
Node left, right;
public Node(int item)
key = item;
left = right = null;
class BinaryTree
// Root of Binary Tree
Node root;
BinaryTree()
root = null;
// Print the nodes of binary tree in inorder
void print_Inorder(Node node)
if (node == null)
return;
print_Inorder(node.left);
// Print the data of node
System.out.print(node.key + " ");
print_Inorder(node.right);
void print_Inorder()
print_Inorder(root);
public static void main(String[] args)
BinaryTree tree = new BinaryTree();
tree.root = new Node(55);
tree.root.left = new Node(21);
tree.root.right = new Node(80);
tree.root.left.left = new Node(9);
tree.root.left.right = new Node(29);
tree.root.right.left = new Node(76);
tree.root.right.right = new Node(91);
System.out.println("\nInorder traversal of binary tree is: ");
tree.print_Inorder();
}
127. Write a search Java program to get the Postorder traversal
of its nodes' values in a binary tree.
10
/ \
20 30
/ \
40 50
class Node
int key;
Node left, right;
public Node(int item)
key = item;
left = right = null;
class BinaryTree
{
// Root of Binary Tree
Node root;
BinaryTree()
root = null;
// Print the nodes of binary tree
void print_Postorder(Node node)
if (node == null)
return;
print_Postorder(node.left);
print_Postorder(node.right);
System.out.print(node.key + " ");
// Wrappers over above recursive functions
void print_Postorder()
print_Postorder(root);
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(55);
tree.root.left = new Node(21);
tree.root.right = new Node(80);
tree.root.left.left = new Node(9);
tree.root.left.right = new Node(29);
tree.root.right.left = new Node(76);
tree.root.right.right = new Node(91);
System.out.println("\nPostorder traversal of binary tree is: ");
tree.print_Postorder();
128. Write a Java program to calculate the median of a non-
sorted array of integers.
Original array: [10, 2, 38, 22, 38, 23]
Median of the said array of integers: 30
Original array: [10, 2, 38, 23, 38, 23, 21]
Median of the said array of integers: 23
import java.util.*;
public class Main {
public static void main(String[] args)
int[] nums = {10,2,38,22,38,23};
System.out.println("Original array: "+Arrays.toString(nums));
System.out.println("Median of the said array of integers:
"+getMedian(nums));
int[] nums1 = {10,2,38,23,38,23,21};
System.out.println("\nOriginal array: "+Arrays.toString(nums1));
System.out.println("Median of the said array of integers:
"+getMedian(nums1));
}
public static int getMedian(int[] array) {
if(array.length % 2 == 0) {
int mid = array.length / 2;
return (array[mid] + array[mid - 1]) / 2;
return array[array.length / 2];
129. Write a Java program to find a number that appears only
once in a given array of integers. All numbers occur twice.
Source Array : [10, 20, 10, 20, 30, 40, 40, 30, 50] 50 appears only
once
import java.util.*;
public class Main {
public static void main(String[] arg)
int nums[] = {10, 20, 10, 20, 30, 40, 40, 30, 50};
int result;
System.out.println("Source Array :
"+Arrays.toString(nums));
result = getSingleNumber(nums);
System.out.println("\n"+result+" appears only once.");
}
public static int getSingleNumber(int[] nums) {
if(nums == null || nums.length == 0) {
return -1;
int result = 0;
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];
return result;
130. Write a search Java program to find the maximum depth of a
given binary tree.
Sample Output: The Maximum depth of the binary tree is: 3
class Node
int data;
Node left, right;
public Node(int item)
data = item;
left = right = null;
}
}
public class BinaryTree
//Root of the Binary Tree
Node root;
public int maxDepth(Node root) {
if(root==null)
return 0;
int left_Depth = maxDepth(root.left);
int right_Depth = maxDepth(root.right);
int bigger = Math.max(left_Depth, right_Depth);
return bigger+1;
/* Driver program to test above functions */
public static void main(String args[])
BinaryTree tree = new BinaryTree();
tree.root = new Node(55);
tree.root.left = new Node(21);
tree.root.right = new Node(80);
tree.root.left.left = new Node(9);
tree.root.left.right = new Node(29);
tree.root.right.left = new Node(76);
tree.root.right.right = new Node(91);
System.out.println("The Maximum depth of the binary tree
is: " + tree.maxDepth(tree.root));
131. Write a search Java program to find the updated length of a
sorted array where each element appears only once (remove
duplicates).
Original array: [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7] The length of the
original array is: 11 After removing duplicates, the new length of
the array is: 7
import java.util.Arrays;
class Solution {
static int removeDuplicates(int[] nums) {
if (nums == null) {
return 0;
}
if (nums.length <= 1) {
return nums.length;
int current_pos = 0;
int moving_pos;
for (moving_pos = 1; moving_pos < nums.length;
moving_pos++) {
if (nums[current_pos] != nums[moving_pos]) {
nums[current_pos + 1] = nums[moving_pos];
current_pos++;
return current_pos + 1;
/* Driver program to test above functions */
public static void main(String[] args)
int[] nums = {1,1,2,3,3,3,4,5,6,7,7};
System.out.println("Original array: "+Arrays.toString(nums));
System.out.println("The length of the original array is: " +
nums.length);
System.out.println("After removing duplicates, the new
length of the array is: " + removeDuplicates(nums));
}
}
132. Write a Java program to find the updated length of a given
sorted array where duplicate elements appear at most twice.
Original array: [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7, 7]
The length of the original array is: 13
After removing duplicates, the new length of the array is: 10
import java.util.Arrays;
class Solution {
static int remove_Duplicates_twice(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
int index = 1;
for (int i = 2; i < nums.length; i++) {
if (nums[i] != nums[index] || (nums[i] == nums[index] &&
nums[i] != nums[index - 1])) {
index++;
nums[index] = nums[i];
return index + 1;
/* Driver program to test above functions */
public static void main(String[] args)
int[] nums = {1,1,2,3,3,3,4,5,6,7,7,7,7};
System.out.println("Original array: "+Arrays.toString(nums));
System.out.println("The length of the original array is: " +
nums.length);
System.out.println("After removing duplicates, the new
length of the array is: " + remove_Duplicates_twice(nums));
}
}
133. Write a search Java program to find a path from top left to
bottom in the right direction which minimizes the sum of all
numbers along its path.
Note: Move either down or right at any point in time.
Sample Output: Sum of all numbers along its path: 13
public class Solution {
public static int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0] == null ||
grid[0].length == 0) {
return 0;
int m = grid.length;
int n = grid[0].length;
int[][] temp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
temp[i][j] = grid[i][j];
continue;
// Compute temp
int from_up = i == 0 ? Integer.MAX_VALUE : temp[i - 1]
[j];
int from_left = j == 0 ? Integer.MAX_VALUE : temp[i][j -
1];
temp[i][j] = Math.min(from_up, from_left) + grid[i][j];
return temp[m - 1][n - 1];
/* Driver program to test above functions */
public static void main(String[] args) {
int[][] grid = new int[][] {{7,4,2},
{0,5,6},
{3,1,2}};
System.out.println("Sum of all numbers along its path:
"+minPathSum(grid));
134. Write a search Java program to find distinct ways to climb
to the top (n steps to reach the top) of stairs. Each time you
climb, you can climb 1 or 2 steps.
Example: n = 5
a) 1+1+1+1+1 = 5 b) 1+1+1+2 = 5 c) 1+2+2 = 5 d) 2+2+1 = 5 e)
2+1+1+1 = 5 f) 2+1+2 = 5 g) 1+2+1+1 = 5 h) 1+1+2+1 = 5
Sample Output: Distinct ways can you climb to the top: 8
class Solution {
public static int climbStairs(int n) {
if (n <= 1) {
return 1;
int[] s_case = new int[n + 1];
s_case[0] = 1;
s_case[1] = 1;
for (int i = 2; i <= n; i++) {
s_case[i] = s_case[i - 1] + s_case[i - 2];
return s_case[n];
/* Driver program to test above functions */
public static void main(String[] args) {
int steps = 5;
System.out.println("Distinct ways can you climb to the
top: "+climbStairs(steps));
135. Write a search Java program to remove duplicates from a
sorted linked list.
Original List with duplicate elements:
12->12->13->14->15->15->16->17->17
After removing duplicates from the said list:
12->13->14->15->16->17
class LinkedList
Node head; // head of list
/* Linked list Node*/
class Node
int data;
Node next;
Node(int d) {data = d; next = null; }
void remove_Duplicates()
{
Node current = head;
Node next_next;
if (head == null)
return;
while (current.next != null) {
if (current.data == current.next.data) {
next_next = current.next.next;
current.next = null;
current.next = next_next;
else
current = current.next;
// In front of the list insert a new Node
public void push(int new_data)
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
/* Function to print linked list */
void printList()
Node temp = head;
while (temp != null)
System.out.print(temp.data);
if (temp.next != null)
System.out.print("->");
temp = temp.next;
System.out.println();
/* Driver program to test above functions */
public static void main(String args[])
LinkedList l_list = new LinkedList();
// Insert data into LinkedList
l_list.push(17);
l_list.push(17);
l_list.push(16);
l_list.push(15);
l_list.push(15);
l_list.push(14);
l_list.push(13);
l_list.push(12);
l_list.push(12);
System.out.println("Original List with duplicate
elements:");
l_list.printList();
l_list.remove_Duplicates();
System.out.println("After removing duplicates from the
said list:");
l_list.printList();
136. Write a search Java program to find possible distinct paths
from the top-left corner to the bottom-right corner of a given grid
(m x n).
Note: You can move either down or right at any point in time.
Sample Output: Unique paths from top-left corner to bottom-right
corner of the said grid: 3
public class Solution {
/**
* @param n, m: positive integer (1 <= n ,m <= 100)
* @return an integer
*/
public static int unique_Paths(int m, int n) {
if (m <= 0 || n <= 0) {
return 0;
int[][] grid = new int[m][n];
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
grid[i][j] = get_Paths(grid, i, j);
return grid[0][0];
private static int get_Paths(int[][] grid, int i, int j) {
if (i >= grid.length - 1 || j >= grid[0].length - 1) {
return 1;
return grid[i][j + 1] + grid[i + 1][j];
public static void main(String[] args) {
int m = 3;
int n = 2;
System.out.println("Unique paths from top-left corner
to bottom-right corner of the said grid: "+unique_Paths(m, n));
}
137. Write a Java program to find possible unique paths
considering some obstacles, from top-left corner to bottom-right
corner of a given grid (m x n).
Note: You can move either down or right at any point in time and
an obstacle and empty space is marked as 1 and 0 respectively
in the grid.
Sample grid:
int[][] obstacle_Grid ={
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
};
Sample Output: Unique paths from top-left corner to bottom-right
corner of the said grid (considering some obstacles): 2
public class Solution {
public static int uniquePaths_With_obstacle_Grid(int[][]
obstacle_Grid) {
int m = obstacle_Grid.length;
if (m <= 0) {
return 0;
int n = obstacle_Grid[0].length;
if (n <= 0) {
return 0;
int[][] dp = new int[m + 1][n + 1];
dp[m][n - 1] = 1;
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
dp[i][j] = (obstacle_Grid[i][j] == 0) ? dp[i + 1][j]
+ dp[i][j + 1] : 0;
return dp[0][0];
public static void main(String[] args) {
int[][] obstacle_Grid ={
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
};
System.out.println("Unique paths from top-left corner
to bottom-right corner of the said grid (considering some
obstacles): "+uniquePaths_With_obstacle_Grid(obstacle_Grid));
public class Solution {
public static int uniquePaths_With_obstacle_Grid(int[][]
obstacle_Grid) {
int m = obstacle_Grid.length;
if (m <= 0) {
return 0;
int n = obstacle_Grid[0].length;
if (n <= 0) {
return 0;
int[][] dp = new int[m + 1][n + 1];
dp[m][n - 1] = 1;
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
dp[i][j] = (obstacle_Grid[i][j] == 0) ? dp[i + 1][j]
+ dp[i][j + 1] : 0;
return dp[0][0];
public static void main(String[] args) {
int[][] obstacle_Grid ={
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
};
System.out.println("Unique paths from top-left corner
to bottom-right corner of the said grid (considering some
obstacles): "+uniquePaths_With_obstacle_Grid(obstacle_Grid));
138. Write a search Java program to find the longest words in a
dictionary.
Example-1:
{
"cat",
"flag",
"green",
"country",
"w3resource"
}
Result: "w3resource"
Example-2:
{
"cat",
"dog",
"red",
"is",
"am"
}
Result: "cat", "dog", "red"
import java.util.*;
public class Solution {
static ArrayList<String> longestWords(String[] dictionary) {
ArrayList<String> list = new ArrayList<String>();
int longest_length = 0;
for (String str : dictionary) {
int length = str.length();
if (length > longest_length) {
longest_length = length;
list.clear();
if (length == longest_length) {
list.add(str);
}
}
return list;
public static void main(String[] args) {
//String [] dict = {"cat", "flag", "green", "country",
"w3resource"};
String [] dict = {"cat", "dog", "red", "is", "am"};
System.out.println("Original dictionary :
"+Arrays.toString(dict));
System.out.println("Longest word(s) of the above
dictionary: "+longestWords(dict));
139. Write a search Java program to get the index of the first and
the last number of a subarray where the sum of numbers is zero.
This is from a given array of integers.
Original Array : [1, 2, 3, -6, 5, 4]
Index of the subarray of the said array where the sum of numbers
is zero: [0, 3]
import java.util.*;
public class Solution {
public static List<Integer> subarraySum(int[] nums) {
List<Integer> temp = new ArrayList<>();
if (nums == null || nums.length == 0) {
return temp;
int pre_Sum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(pre_Sum, -1);
for (int i = 0; i < nums.length; i++) {
pre_Sum += nums[i];
if (map.containsKey(pre_Sum)) {
temp.add(map.get(pre_Sum) + 1);
temp.add(i);
return temp;
map.put(pre_Sum, i);
return temp;
public static void main(String[] args) {
int [] nums = {1, 2, 3, -6, 5, 4};
System.out.println("Original Array :
"+Arrays.toString(nums));
System.out.println("Index of the subarray of the said
array where the sum of numbers is zero: "+subarraySum(nums));
140. Write a Java program to merge all overlapping intervals
from a given collection of intervals.
Sample Output: 1 6
8 10
15 20
#// Source: https://bit.ly/2PjMfds
import java.util.*;
public class Solution
public static void main (String[] args) throws
java.lang.Exception
ArrayList<Interval> x = new ArrayList<>();
x.add(new Interval(1, 3));
x.add(new Interval(2, 6));
x.add(new Interval(8, 10));
x.add(new Interval(15, 18));
x.add(new Interval(17, 20));
x = merge(x);
for(Interval i : x)
System.out.println(i.getStart() + " " + i.getEnd());
}
public static ArrayList<Interval> merge(ArrayList<Interval>
intervals) {
if(intervals.size() == 0 || intervals.size() == 1)
return intervals;
Collections.sort(intervals, new IntervalComparator());
Interval first = intervals.get(0);
int start = first.getStart();
int end = first.getEnd();
ArrayList<Interval> result = new ArrayList<Interval>();
for (int i = 1; i < intervals.size(); i++) {
Interval current = intervals.get(i);
if (current.getStart() <= end) {
end = Math.max(current.getEnd(), end);
} else {
result.add(new Interval(start, end));
start = current.getStart();
end = current.getEnd();
}
result.add(new Interval(start, end));
return result;
class Interval
private int start;
private int end;
Interval() {
start = 0;
end = 0;
Interval(int s, int e)
start = s;
end = e;
public int getStart() {
return start;
}
public int getEnd() {
return end;
class IntervalComparator implements Comparator<Interval>
public int compare(Interval i1, Interval i2)
return i1.getStart() - i2.getStart();
141. Write a search Java program to check if a given string has
all distinct characters.
Sample Output: Original String : xyyz
String has all unique characters: false
import java.util.*;
public class Solution {
/**
* @param str: a string
* @return: a boolean
*/
public static boolean is_Unique_str(String str) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
for (int i = 1; i < chars.length; ++i) {
if (chars[i] == chars[i-1]) {
return false;
return true;
public static void main(String[] args) {
//String str = "xyz";
String str = "xyyz";
System.out.println("Original String : "+str);
System.out.println("String has all unique characters:
"+is_Unique_str(str));
142. Write a search Java program to check if two strings are
anagrams or not.
According to Wikipedia "An anagram is a word or phrase formed
by rearranging the letters of a different word or phrase, typically
using all the original letters exactly once. For example, the word
anagram can be rearranged into nag a ram, or the word binary
into brainy."
Sample Output: String-1 : wxyz
String-2 : zyxw
Check if two given strings are anagrams or not?: true
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public static boolean anagram_test(String str1, String str2) {
if (str1 == null || str2 == null) {
return false;
} else if (str1.length() != str2.length()) {
return false;
} else if (str1.length() == 0 && str2.length() == 0) {
return true;
int[] count = new int[256];
for (int i = 0; i < str1.length(); i++) {
count[str1.charAt(i)]++;
count[str2.charAt(i)]--;
for (int num : count) {
if (num != 0) {
return false;
return true;
public static void main(String[] args) {
String str1 = "wxyz";
String str2 = "zyxw";
System.out.println("String-1 : "+str1);
System.out.println("String-2 : "+str2);
System.out.println("Check if two given strings are
anagrams or not?: "+anagram_test(str1,str2));
}
}
143. Write a search Java program to merge the two sorted lists.
Sample Output:
Merge Two Sorted ListsT:
1 2 3 7 9 13 40
public class Solution {
public static void main(String[] args) {
ListNode list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(7);
list1.next.next.next = new ListNode(9);
list1.next.next.next.next = new ListNode(13);
ListNode list2 = new ListNode(2);
list2.next = new ListNode(40);
ListNode head = mergeTwoLists(list1, list2);
System.out.print("Merge Two Sorted ListsT:\n");
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
public static ListNode mergeTwoLists(ListNode list1, ListNode
list2) {
ListNode head = new ListNode(0);
ListNode mlist = head;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
mlist.next = new ListNode(list1.val);
mlist = mlist.next;
list1 = list1.next;
} else {
mlist.next = new ListNode(list2.val);
mlist = mlist.next;
list2 = list2.next;
while (list1 != null) {
mlist.next = new ListNode(list1.val);
mlist = mlist.next;
list1 = list1.next;
while (list2 != null) {
mlist.next = new ListNode(list2.val);
mlist = mlist.next;
list2 = list2.next;
head = head.next;
return head;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
144. Write a search Java program to remove all occurrences of a
specified value in a given array of integers. Return the updated
array length.
Sample Output:
Original array: [1, 4, 6, 7, 6, 2]
The length of the new array is: 4
import java.util.*;
public class Solution {
/**
*@param nums: A list of integers
*@param element: An integer
*@return: The new length after remove
*/
public static int removeElement(int[] nums, int elem) {
int length = nums.length;
if(length==0) return 0;
int i=0;
for(int j=0; j<length; j++)
if(nums[j]!=elem)
nums[i]=nums[j];
i++;
if(i<length) nums[i]='\0';
return i;
public static void main(String[] args) {
int x = 6;
int [] nums = {1,4,6,7,6,2};
System.out.println("Original array:
"+Arrays.toString(nums));
System.out.println("The length of the new array is: " +
removeElement(nums, x));
}
145. Write a Java program to remove the nth element from the
end of a given list.
Sample Output:
Original node:
12345
After removing 2nd element from end:
1235
import java.util.*;
public class Solution {
public static void main(String[] args) {
ListNode h = new ListNode(1);
h.next = new ListNode(2);
h.next.next = new ListNode(3);
h.next.next.next = new ListNode(4);
h.next.next.next.next = new ListNode(5);
ListNode o = h;
System.out.println("Original node:");
while (o != null) {
System.out.print(o.val + " ");
o = o.next;
System.out.println("\nAfter removing 2nd element from
end:");
ListNode head = removeNthFromEnd(h, 2);
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
public static ListNode removeNthFromEnd(ListNode head, int
n) {
ListNode p = head;
int size = 0;
while (p != null) {
size++;
p = p.next;
}
if (n == size) {
head = head.next;
} else {
int index = size - n;
ListNode t = head;
while (index > 1) {
t = t.next;
index--;
t.next = t.next.next;
return head;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
146. Write a search Java program to convert an array of sorted
items into a binary search tree. Maintain the minimal height of
the tree.
Sample Output:
2
1
4
6
5
3
public class Solution {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
TreeNode root = sortedArrayToBST(arr);
traverseTree(root);
public static TreeNode sortedArrayToBST(int[] arr) {
if (arr.length == 0) return null;
return creation(arr, 0, arr.length - 1);
private static TreeNode creation(int[] arr, int start, int end) {
TreeNode node = new TreeNode(0);
if (start == end - 1) {
node = new TreeNode(arr[start]);
node.right = new TreeNode(arr[end]);
} else if (start == end) {
return new TreeNode(arr[start]);
} else {
int mid = (start + end) / 2;
node.val = arr[mid];
node.left = creation(arr, start, mid - 1);
node.right = creation(arr, mid + 1, end);
return node;
private static void traverseTree(TreeNode root) {
if (root != null) {
traverseTree(root.left);
traverseTree(root.right);
System.out.println(root.val);
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
147. Write a search Java program to find the number of bits
required to flip to convert two given integers.
Sample Output:
2
public class Solution {
public static void main(String[] args) {
System.out.println(bitSwapRequired(27, 23));
public static int bitSwapRequired(int x, int y) {
int ctr = 0;
for (int z = x ^ y; z != 0; z = z >>> 1) {
ctr += z & 1;
return ctr;
148. Write a Java program to find the index of the first unique
character in a given string. Assume that there is at least one
unique character in the string.
Sample Output:
Original String: wresource
First unique character of the above: 0
import java.util.*;
public class Solution {
public static void main(String[] args) {
String s = "wresource";
System.out.println("Original String: "+s);
System.out.println("First unique character of the above:
"+first_Uniq_Char(s));
}
public static int first_Uniq_Char(String s) {
int[] freq = new int[256];
for (char c : s.toCharArray()) {
freq[c - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (freq[s.charAt(i) - 'a'] == 1) return i;
return -1;
149. Write a Java program to check if a given string is a
permutation of another given string.
Sample Output:
Original strings: xxyz yxzx
true
import java.util.*;
public class Solution {
public static void main(String[] args) {
String str1 = "xxyz";
String str2 = "yxzx";
System.out.println("Original strings: "+str1+" "+str2);
System.out.println(stringPermutation(str1, str2));
public static boolean stringPermutation(String str1, String
str2) {
int[] arr = new int[500];
for (int i = 0; i < str1.length(); i++) {
arr[(int) str1.charAt(i)] += 1;
for (int i = 0; i < str2.length(); i++) {
arr[(int) str2.charAt(i)] -= 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) return false;
return true;
150. Write a search Java program to test if a binary tree is a
subtree of another binary tree.
Sample Output:
Original strings: xxyz yxzx
true
public class Solution {
/**
* @param T1, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
public static boolean is_Subtree(TreeNode T1, TreeNode T2)
{
if (T2 == null) return true;
if (T1 == null) return false;
if (is_Same(T1, T2)) return true;
if (is_Subtree(T1.left, T2) || is_Subtree(T1.right, T2)) return
true;
return false;
public static boolean is_Same(TreeNode t1, TreeNode t2) {
if (t1 == null || t2 == null) {
return t1 == t2;
} else if (t1.val != t2.val) {
return false;
} else {
return is_Same(t1.left, t2.left) && is_Same(t1.right,
t2.right);
}
/* Driver program to test above functions */
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
t1.left = t2;
t1.right = t3;
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
n1.left = n2;
n1.right = n3;
System.out.println(is_Subtree(t1, n1));
class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;