Category Archives: Java

Java program to check whether given number is a multiple of 3 or not

Given an integer n, check whether it is a multiple of 3 or not. If the number is divisible by 3, then return true else return false.


1 <= n <= 10000

import java.util.*;
import java.math.*;
public class CandidateCode {
  public static boolean threeByThree(int input1){
 return true;
 return false;
 public static void main(String[] args) throws IOException{
 Scanner in = new Scanner(;
 boolean output;
 int ip1 = Integer.parseInt(in.nextLine().trim());
 output = threeByThree(ip1);
 System.out.println(String.valueOf(output ? 1 : 0));

Java program to check whether it is a multiple of 7 or not

Given an integer n, check whether it is a multiple of 7 or not. If the number is divisible by 7, then return true else return false.


1 <= n <= 1000

Sample TestCase
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class MultipleOfSeven {
 public static boolean sevenBySeven(int num){
        return true;
       return false;
 public static void main(String[] args) throws IOException{
 Scanner in = new Scanner(;
 boolean output;
 int ip1 = Integer.parseInt(in.nextLine().trim());
 output = sevenBySeven(ip1);
 System.out.println(String.valueOf(output ? 1 : 0));

Java program for a given number n, finds a number p which is greater than or equal to n and is a power of 2.

Java Program for Replacing White Space Characters

Learn Android Programming – For Beginners To Pro

Java program for a given number n, finds a number p which is greater than or equal to n and is a power of 2.

Java program for a given number n, finds a number p which is greater than or equal to n and is a power of 2.


1 <= n <= 10000

Sample TestCase
import java.util.*;
import java.math.*;
public class NextPowerOfTwo {
public static int twoPowers(int num){
      return num;
static double log(int x, int base){
    return (Math.log(x) / Math.log(base));
public static void main(String[] args) throws IOException{
 Scanner in = new Scanner(;
 int output = 0;
 int input = Integer.parseInt(in.nextLine().trim());
 output = twoPowers(input);

Java Program for Replacing White Space Characters
Creating an App Icon with the Asset Studio
Numbers in JavaScript

Java Program for Replacing White Space Characters

Given a sentence with multiple spaces between words and also spaces in front and back of sentence and you need to remove these extra spaces.

Input Format

You will be taking a string as an input from stdin.


1 <= |S| <= 10^5

Output Format

You need to print the sentence by removing spaces in front and back of sentence.

Sample TestCase 1
     This is Rua    Tech
This is Rua Tech



import java.util.*;
public class WhiteSpaceRemove {
public static void main(String args[] ) throws Exception {

Scanner sc =new Scanner(;
String str=sc.nextLine();
// str=str.trim();
String result=delSpaces(str);

public static String delSpaces(String str){
StringBuilder sb = new StringBuilder(str);
ArrayList<Integer> spaceIndexes = new ArrayList<>();

for ( int i=1; i < sb.length(); i++ ){
if ( sb.charAt(i) == ‘ ‘ && sb.charAt(i-1) == ‘ ‘){

for (int i = 0; i < spaceIndexes.size(); i++){
return new String(sb.toString());

Understanding PHP Generator With Example

While and Do-While loop in Java with example

JAVA For Android Developer– Tutorial, Examples, And Programs

Android App are mostly developed in JAVA language using Android SDK (Software Development Kit). Other languages like C, C++, Kotlin etc. can also be used for developing Android App, but JAVA is most preferred and mostly used programming language for Android App Development. So if you are a beginner in Android then JAVA language and complete knowleadge of OOPS concepts is the first thing you need to learn before beginning Android Development.

Introduction To JAVA

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.JAVA is a programming language which is also used in Android App Development. It’s syntax is influenced by C++. The primary goals of JAVA is to be simple, object-oriented, robust, secure and high level.

JAVA application runs on JVM (JAVA Virtual Machine) but Android has it’s own virtual machine called Dalvik Virtual Machine (DVM) optimized for mobile devices.

Prerequisites For JAVA:

IntelliJ IDEA:

Being a JAVA programmer you will need some tools or software to code and run it. Lots of tools are available over the web but we recommend you to use IntelliJ IDEA for learning JAVA since Android Studio build based on IntelliJ IDEA. So getting habitual with IntelliJ IDEA and its shortcuts will be bonus in your Android journey. Other then IntelliJ IDEA you can also prefer Eclipse or netbeans for learning JAVA.

Other Tools: Eclipse and Netbeans

Tutorial On JAVA Topics For Android Developer:

Below are the tutorials on JAVA:

Introduction to Java

Topics (Follow the link to read tutorial) Description


Java Buzzwors

Learn about variables and how they are created for storing information in memory

The key considerations were summed up by the Java team in the following list of buzzwords:

Data Types Learn about Data Types (i.e. byte, int, char etc) which is basically a type of information we want to store in variable.
String String is nothing but a character array for example “ruatech” is a string of 7 characters as shown.
Operators|Set 1|Set 2|Set 3|Set 4 In computer programming Operator is a symbol that tells the compiler to perform specific action which can be mathematical or logical.
Keywords Keywords in JAVA are predefined list of keywords which has a specific meaning and cannot be used in the Java programming language as an identifier, such as the name of a variable, method, class, function, or label.
Class And Objects The concept of class comes into role when we see certain type of objects or things around us and the common idea or a blueprint behind this type of objects is called Class. Object is an instance of class.
Method A method is a self contained block of code that performs a specific task.
If Then Else|set1

If Then Else|set2

If then allow us to control the flow of program based on conditions, whether to execute a code or not.
For Loop In JAVA For statement is the most commonly used lopping statement which iterate over a range of numbers.
While Do While




switch statement

The While is a type of loop which evaluate the condition first. If condition evaluate to true the code inside the block{} will be executed and if it evaluate to false it will jump outside the while loop.


A switch statement tests a variable for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Arrays Array can be defined as a contiguous memory locations used to store the homogeneous data types. In simple words, it is a variable that can store multiple values of single data type.
Inheritance It is a mechanism that allows the class to use the states and behavior of another class.
Abstraction It is a process of hiding internal working and showing only necessary details.
Method Overriding Method Overriding means to re-write the previous described method again of Parent Class in Sub class with different functionality.
Method Overloading It allows multiple methods to have same name if the parameter list inside parenthesis are different.
Interface It is able to achieve 100% abstraction as it only contains those methods which has no implementation (i.e. methods without body).
Encapsulation Wrapping up of data member and member functions together into a single unit (i.e. Class) is called Encapsulation.
Polymorphism It means one name and many duties. Polymorphism refers to the ability of one thing to take many(Poly) distinct forms(Morphism).
Constructor A constructor is a special method that is called whenever an object is created using the new keyword.
Access Modifier Java provides us a many number of access modifiers to set access levels for class, variables, methods and constructor.
Composition Composition is a special case of aggregation. In other words, a restricted aggregation is called composition. When an object contains the other object and the contained object cannot exist without the other object, then it is called composition.
List It is the sequence of elements, or we can say collection of elements, on which user has precise control over where an elements are inserted.
ArrayList It is a dynamic data structure in which you can add or remove any number of elements and those elements are stored in ordered sequence.
LinkedList It stores data in the forms of nodes, which is divided into two parts, first part stores the data and second part points to the next node by storing the address of that node.
Vector It is type of data structure that implements List Interface. It is very much similar to ArrayList as it also maintains insertion order, that is elements are retrieved in same order as they are added into it.
Map It is the mapping between a key and a value i.e. it contains values based on the key. Each key value pair is often known as an entry, As Map contains only unique keys, we can also say Map interface maps unique keys to its corresponding values.
HashMap It is a type of Collection, that stores our data in a pair such that each element has a key associated with it. The pair of key and value is often known as Entry and these entries can have only unique keys.
LinkedHashMap In Addition to all the functionalities of HashMap Class, the functionality of maintaining the insertion is added into LinkedHashMap and to attain this  functionality all the entries(key and value) are linked to each other using doubly-linked list.
TreeMap It can  stores only unique elements, that is duplicate values are not allowed and it cannot store key as null but is can  store null values. It is mostly similar to HashMap and key difference is it maintains an increasing order according to the key value.
Set It is the group of elements, or we can say collection of elements, that can never contains Duplicate element.
HashSet It is a type of Java Collection that implements the Set Interface and extends AbstractSet Interface. It uses Hash table for storing the data.
LinkedHashSet It is a type of Collection, which takes all the functionalities of HashSet class, that it does not allow duplicate elements to be stored and allow null elements in it.
TreeSet In TreeSet all the values are stored in there natural order, like all integer values are stored in ascending order and strings are stored according to Dictionary values. Apart from adding this functionality of maintaining natural ordering, Tree Set do not allow null values.
Iterator Java Iterator is an Interface that belongs to the collection framework allow us to traverse the collection objects and access the elements of  that collection.
ListIterator Special type of Iterator that is only for List Interface is known as ListIterator

Find sum of series 1+2+8+26+80+…….+n

we can not define 1+2+8+26+80+………. series in a simple manner to write  program.


2,8,26,80,242……………..can be define as below

The way to discover the next term is multiply the next number by 2 and then add it on.

i.e. the next number of 2 is 3

so, 3*2=6+2=8


27*2=54+26=80…….. and so on


Far more simply multiply the number by 3 and add 2


2 * 3 + 2 = 8;

8 * 3 + 2 = 28

26 *3 + 2 = 80

80 *3 + 2 = 242. and so on


Now for finding the sum of the given series and add 1 with sum of this  series.

C language implementation


// C program to add 1+2+8+26+80+…….+n
//Author: Sani Kamal
//Date: 04-Oct-17


int main(){

int n,temp=0,i,sum=0,hold=0;
 printf("How many term");
 temp =3*hold+2;
 sum +=hold;

Java language implementation

import java.util.Scanner;

 * Java program to add 1+2+8+26+80+.......+n
 * @author Sani Kamal
public class SeriesSum {

public static void main(String[] args) {
 Scanner input = new Scanner(;
 System.out.print("How many term?");
 int n = input.nextInt();
 int temp, hold = 0, sum = 0;
 for (int i = 0; i < n - 1; i++) {
 temp = 3 * hold + 2;
 hold = temp;
 sum += hold;

 System.out.println("Sum=" + (sum+1));




Python language implementation

# Python program to add 1+2+8+26+80+.......+n
# Author: Sani Kamal
# Date: 04-Oct-17

num = int(input("How many term?"))
hold = 0
for i in range(0, num - 1):
    temp = 3 * hold + 2
    hold = temp
    sum += hold
print(sum + 1)

While and Do-While loop in Java with example

In this tutorial we will discuss while loop and do while loop.

Java while Loop

A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

The syntax of while loop is:

while (Expression) {
    // codes inside body of while loop

How while loop works?

The expression inside parenthesis is a boolean expression. If the test expression is evaluated to true,statements inside the while loop are executed. then, the test expression is evaluated again. This process goes on until the test expression is evaluated to false. If the test expression is evaluated to false, while loop is terminated.

Flowchart of while Loop


Example: while Loop

// Program to print Hello 10 times

class WhileLoop {
   public static void main(String[] args) {
      int i = 0;
      while (i < 10) {
         System.out.println("Hello " + i);

The output will be:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
Hello 6
Hello 7
Hello 8
Hello 9

Java do-while Loop

The do-while loop is similar to while loop with one key difference. The body of do-while loop is executed for once before the test expression is checked.

The major difference between While and do While is that statement will be executed at least once in do while.

The syntax of do-while loop is:

do {
   // statements
} while (expression);

How do-while loop works?

The body of do-while loop is executed once (before checking the test expression). Only then, the test expression is checked. If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to false. When the test expression is false, the do-while loop terminates.

Flowchart of do-while Loop


Example: do-while Loop:

class DoWhileLoopDemo {
    public static void main(String args[]){
         int i=5;

Example: Iterating array using do-while loop

class DoWhileArr{
    public static void main(String args[]){
         int arr[]={21,17,45,90};
         //in java array index start with 0
         int i=0;


Infinite while and do-while loop

If the test expression never evaluates to false, the body of while and do..while loop is executed infinite number of times.For example,

while (true) {
   // body of while loop

Example of infinite while and do-while loop

int i = 10;
while (i == 10) {

The infinite do-while loop works in similar way like while loop.

int i = 10;

do {


}(i == 10);


You need to press ctrl+c to exit from the program.

The Java Buzzwords

The key considerations were summed up by the Java team in the following list of buzzwords:

  1. Simple
  2. Secure
  3. Portable
  4. Object-oriented
  5. Robust
  6. Multi-threaded
  7. Architecture-neutral
  8. Interpreted
  9. High performance
  10. Distributed and
  11. Dynamic
  • simple – Java is designed to be easy for the professional programmer to learn and use.
  • object-oriented: a clean, usable, pragmatic approach to objects, not restricted by the need for compatibility with other languages.
  • Robust: restricts the programmer to find the mistakes early, performs compile-time (strong typing) and run-time (exception-handling) checks, manages memory automatically.
  • Multi-threaded: supports multi-threaded programming for writing program that perform concurrent computations.
  • Architecture-neutral: Java Virtual Machine provides a platform independent environment for the execution of Java byte code
  • Interpreted and high-performance: Java programs are compiled into an intermediate representation – byte code:
    • can be later interpreted by any JVM
    • can be also translated into the native machine code for efficiency.
  • Distributed: Java handles TCP/IP protocols, accessing a resource through its URL much like accessing a local file.
  • Dynamic: substantial amounts of run-time type information to verify and resolve access to objects at run-time.
  • Secure: programs are confined to the Java execution environment and cannot access other parts of the computer.
  • Portability: Many types of computers and operating systems are in use throughout the world—and many are connected to the Internet.

C program to convert temperature degree centigrade to fahrenheit

This C program convert temperature centigrade  to fahrenheit scale.

// C program to convert temperature centigrade to fahrenheit
//Author: Sani Kamal


int main(){
float c,f;
printf("Enter Temperature in centigrade:\n");
f=9/5.0*c+32; //formula to convert centigrade to fahrenheit
printf("Temperature in fahrenheit is:%f",f);
return 0;




Enter Temperature in centigrade:


Temperature in fahrenheit is: 57.200001


C Program to find sum of two number

Algorithm paradigm | Introduction to Divide and conquer algorithm

Divide and conquer algorithm

Divide and conquer (D&C) is an algorithm design paradigm based on multi-branched recursion. A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem. A typical Divide and Conquer algorithm solves a problem using following three steps.

  1. Divide: Break the problem into sub-problems of same type.
  2. Conquer: Recursively solve these sub-problems.
  3. Combine: Combine the solution sub-problems.


These are methods of designing algorithms that (informally) proceed as follows:

Given an instance of the problem to be solved, split this into several smaller sub-instances (of the same problem), independently solve each of the sub-instances and then combine the sub-instance solutions so as to yield a solution for the original instance.

With the divide-and-conquer method the size of the problem instance is reduced by a factor (e.g. half the input size), while with the decrease-and-conquer method the size is reduced by a constant.

Example of divide-and-conquer algorithms:

  • Merge Sort
  • Quick Sort
  • Binary Search
  • Strassen’s Matrix Multiplication
  • Closest pair (points)
  • Cooley–Tukey Fast Fourier Transform (FFT) algorithm
  • Karatsuba algorithm for fast multiplication

Examples of decrease-and-conquer algorithms:

  1.  Insertion sort
  2.  Topological sorting
  3. Binary Tree traversals: inorder, preorder and postorder (recursion)
  4.  Computing the length of the longest path in a binary tree (recursion)
  5.  Computing Fibonacci numbers (recursion)
  6.  Reversing a queue (recursion)
  7.  Warshall’s algorithm (recursion)


 Advantages of Divide and Conquer

  • The most recognizable benefit of the divide and conquer paradigm is that it allows us to solve difficult problem, such as the Tower of Hanoi, which is a mathematical game or puzzle. Being given a difficult problem can often be discouraging if there is no idea how to go about solving it. However, with the divide and conquer method, it reduces the degree of difficulty since it divides the problem into sub problems that are easily solvable, and usually runs faster than other algorithms would.
  • It also uses memory caches effectively. When the sub problems become simple enough, they can be solved within a cache, without having to access the slower main memory.

 Disadvantages of Divide and Conquer

  • One of the most common issues with this sort of algorithm is the fact that the recursion is slow, which in some cases outweighs any advantages of this divide and conquer process.
  • Sometimes it can become more complicated than a basic iterative approach, especially in cases with a large n. In other words, if someone wanted to add a large amount of numbers together, if they just create a simple loop to add them together, it would turn out to be a much simpler approach than it would be to divide the numbers up into two groups, add these groups recursively, and then add the sums of the two groups together.

Example Merge sort:

Merge Sort is a Divide and conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following algorithm for details.

mergeSort(arr[], left,  right)
If right > left
     1. Find the middle point to divide the array into two halves:  
             middle  = (left+right)/2
     2. Call mergeSort for first half:   
             Call mergeSort(arr, left, middle)
     3. Call mergeSort for second half:
             Call mergeSort(arr, middle+1, right)
     4. Merge the two halves sorted in step 2 and 3:
             Call merge(arr, left, middle, right)


Java implementation of merge sort is given below:

/* Java program for implement Merge Sort */
class MergeSort {

// Merges two subarrays of arr[].
// First subarray is arr[left to middle]
// Second subarray is arr[middle+1 to right]
void merge(int arr[], int left, int middle, int right) {
// Find sizes of two subarrays to be merged
int n1 = middle - left + 1;
int n2 = right - middle;

/* Create temp arrays */
int LEFT[] = new int[n1];
int RIGHT[] = new int[n2];

/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i) {
LEFT[i] = arr[left + i];
for (int j = 0; j < n2; ++j) {
RIGHT[j] = arr[middle + 1 + j];

/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;

// Initial index of merged subarry array
int k = left;
while (i < n1 && j < n2) {
if (LEFT[i] <= RIGHT[j]) {
arr[k] = LEFT[i];
} else {
arr[k] = RIGHT[j];

/* Copy remaining elements of LEFT[] if any */
while (i < n1) {
arr[k] = LEFT[i];

/* Copy remaining elements of RIGHT[] if any */
while (j < n2) {
arr[k] = RIGHT[j];

// Main function that sorts arr[l..r] using
// merge()
void mergeSort(int arr[], int left, int right) {
if (left < right) {
// Find the middle point
int middle = (left + right) / 2;

// Sort first and second halves
mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);

// Merge the sorted halves
merge(arr, left, middle, right);

/* A utility function to print array of size n */
void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");

// Driver method
public static void main(String args[]) {
int arr[] = {12, 19, 13, 51, 6, 7, 68};
MergeSort ob = new MergeSort();
System.out.println("Given Array");

ob.mergeSort(arr, 0, arr.length - 1);

System.out.println("\nSorted array");
/* This code is contributed by Sani Kamal */



Given Array
12 19 13 51 6 7 68

Sorted array
6 7 12 13 19 51 68
BUILD SUCCESSFUL (total time: 1 second)

Time Complexity: \Theta(nLogn)

Auxiliary Space: O(n)

Algorithmic Paradigm: Divide and Conquer

Sorting In Place: No in a typical implementation

Stable: Yes

Applications of Merge Sort

  1. Merge sort is useful for sorting linked lists in O(nLogn) time
  2. Inversion count problem
  3. Used in External Sorting