Programming Exercises with Solutions

You will find a collection of programming problems and their solutions in these pages.

Most of the problems are taken from HackerRank.

Note: All answers are coded in Java.

If you have any questions or comments feel free to email me at vishnu2929@gmail.com

Happy Coding!

Basic Java Exercises

Click on the icon to view the problem description

Hello World!

public class Solution {

    public static void main(String[] args) {
        //print hello world to the console.
        System.out.println("Hello, World.");
    }
}

Input and Output 1

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        //Scanner is a class that allows the user to parse different user inputs such as words and numbers
        Scanner scan = new Scanner(System.in);

        //the nextInt() method gets the next integer from input. the loop does this 3 times.
        for (int i = 0; i < 3; i++) {
            int a = scan.nextInt();
            //this line prints out the integer we just read from the input
            System.out.println(a);
        }
    }
}

Int to String

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //The Integer class contains a method toString() which converts integer to a string
        String s = Integer.toString(sc.nextInt());
        System.out.println(s);
    }
}

Output Formatting

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("================================");
        for (int i = 0; i < 3; i++) {
            String s1 = sc.next();
            int x = sc.nextInt();
            //the % symbol allows a variable to be substituted which can be formatted in various ways.
            //-15s formats a string to have left padding of 15 characters
            //03d specifies a integer that has 3 digits, if it's less than 3 then it will be filled with 0's
            System.out.printf("%-15s%03d\n", s1, x);
        }
        System.out.println("================================");

    }
}

Loops I

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        //the for loop allows the repetition of statments
        //we declare the starting value for i, what i cant go past, and its increment
        //the i will be 0 at first iteration, and then 1 and so on, until it becomes 9
        for (int i = 0; i < 10; i++){
            //we print out a multiplication table using the values of i
            System.out.println(N + " x " + (i+1) + " = " + N*(i+1));
        }
    }
}

Loops II

import java.util.*;

class Solution{
    public static void main(String []argh){
        Scanner sc = new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++){
            int a = sc.nextInt();
            int b = sc.nextInt();
            int n = sc.nextInt();
            for (int j = 0; j < n; j++){
                int sum = 0;
                //a nested loop
                for (int k = 0; k < j+1; k++){
                   sum += (b * Math.pow(2, k));
                }
                System.out.print(a + sum + " ");
            }
            System.out.println();               
        }
        sc.close();
    }
}

End of file

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i = 0;
        //the while loop will terminate when there is no more input
        while(sc.hasNext()){
            i++;
            System.out.println(i + " " +sc.nextLine());
        }
    }
}

If-Else

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String ans = "";
        /**
         * % is known as a mod function, it gives the remainder when two numbers
         * are divided if a number is modded with 2, there are only two possible
         * remainders: 1 and 0 if n is even. Ex: n = 2, then 2/2 is 1 with a
         * remainder of 0. If n is odd Ex:n=3, 3/2 is 1 with a remainder of 1.
         * so if n mod 2 equals 0, it is even, if it equals 1 it is odd.
         */
        if (n % 2 == 1) {
            ans = "Weird";
        } //if n is greater than or equal to 2 AND n is less than or equal to 5
        else {
            if (n >= 2 && n <= 5) {
                ans = "Not Weird";
            } //if n is greater than or equal to 6 AND n is less than or equal to 20
            else if (n >= 6 && n <= 20) {
                ans = "Weird";
            } //if n is greater than 20
            else if (n > 20) {
                ans = "Not Weird";
            }
        }
        System.out.println(ans);
    }
}

Data Types

import java.util.*;

class Solution {

    public static void main(String[] argh) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        for (int i = 0; i < t; i++) {
            try {
                //check all the various ranges of the given input
                long x = sc.nextLong();
                System.out.println(x + " can be fitted in:");
                if (x >= -128 && x <= 127) {
                    System.out.println("* byte");
                }
                if (x >= -32768 && x <= 32767) {
                    System.out.println("* short");
                }
                if (x >= -2147483648 && x <= 2147483647) {
                    System.out.println("* int");
                }
                if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) {
                    System.out.println("* long");
                }
            } catch (Exception e) {
                System.out.println(sc.next() + " can't be fitted anywhere.");
            }
        }
    }
}

Input and Output 2

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //the int type stores whole numbers. Upper bound: (2^31 - 1), lower bound: (-2^31)
        int i = scan.nextInt();
        //the double type allows the storage of floating point numbers or decimals
        double d = scan.nextDouble();
        //the string type is generally used for letters/words, but can also hold numbers/symbols in sentence format.
        String s = scan.nextLine();
        s = scan.nextLine();

        //the + operator is used to concatenate/fuse different types together into a single string
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

Static Block

import java.util.*;

public class Solution {

    private static int B;
    private static int H;
    private static boolean flag;

    static {
        Scanner sc = new Scanner(System.in);
        B = sc.nextInt();
        H = sc.nextInt();
        flag = true;
        if ((B <= 0) || (H <= 0)) {
            flag = false;
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        }
    }

    public static void main(String[] args) {
        if (flag) {
            int area = B * H;
            System.out.print(area);
        }
    }
}

Date and Time

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String month = in.next();
        String day = in.next();
        String year = in.next();
        //create a calendar object with the current time
        Calendar c = Calendar.getInstance();
        //set the calendar object to the input
        c.set(Integer.valueOf(year), Integer.valueOf(month) - 1, Integer.valueOf(day));
        String[] weekday = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
        //output the day of week for the date provided
        System.out.println(weekday[c.get(Calendar.DAY_OF_WEEK) - 1]);
    }
}

Currency Formatter

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

public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();
        //numberformat is a class that allows different locales to be set
        NumberFormat usnf = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat indianf = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
        NumberFormat chinanf = NumberFormat.getCurrencyInstance(Locale.CHINA);
        NumberFormat francenf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
        
        //format the string to the different locales
        String us = usnf.format(payment);
        String india = indianf.format(payment);
        String china = chinanf.format(payment);
        String france = francenf.format(payment);
        
        System.out.println("US: " + us);
        System.out.println("India: " + india);
        System.out.println("China: " + china);
        System.out.println("France: " + france);
    }
}

String exercises solved with Java

Click on the icon to view the problem description

Substrings

Substring Comparisons

String Reverse

Anagrams

Syntax Checker

Regex I

Regex Username Validation

Regex II Duplicate Words

Lexicographical Order

String tokens

Tag Content Extractor

Java Data Structures

Java Object Oriented

Java Advanced