How To Count Occurrences Of Each Character In String In Java?



import java.util.HashMap;

public class CountCharInStringJavaInHouse
{
  
   public static void main(String[] args)
    {
       countCharacter("How many number each character is there in string using hashmap");
    }
    static void countCharacter(String inputString)
    {
        
        HashMap<Character, Integer> resultMap = new HashMap<Character, Integer>();
        
        char[] strArray = inputString.toCharArray();

        for (char c : strArray)
        {
          
          if(resultMap.containsKey(c) )
            {

                resultMap.put(c, resultMap.get(c)+1);
            }
            else
            {


                resultMap.put(c, 1);
            }
          
        }

        System.out.println(resultMap);
    }
   
}

OutPut:
Occurrences Of Each Character In String

How to Find duplicate numbers in given list in Java

For this program we are going to use HashSet as Set does not allow duplicate elements.

We will be using two HashSets . As he list is traversed ,all the elements will be started storing in the first hash set and if any element is traversed again the first hash set will not allow that element and that element will be stored in the second hash set and at last we ll print the second Hash set .




package com.javainhouse;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class findDuplicateElements
{

public static void main(String[] args) {
List<String> list = new LinkedList<String>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
for (int i = 2; i < 7; i++) {
list.add(String.valueOf(i));
}
final Set<String> setToReturn = new HashSet<String>();
final Set<String> set1 = new HashSet<String>();
 
for (String element : list) {
if (!set1.add(element)) {
setToReturn.add(element);
}
}
 
System.out.println("Original List : " + list);
System.out.println("Duplicate elements from list : " + setToReturn);
}
 
}
     

OutPut :

Duplicate Elements in List Program



Bubble Sort in Java

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
                                    First Pass:
                                    ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps                                                                                      since 5 > 1.
                                    ( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
                                    ( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
                                    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ),  
                                   Second Pass:
                                 ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
                                 ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
                                 ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                 ( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs onewhole pass without any swap to know it is sorted.
                                 Third Pass:
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
                                ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

package com.javainhouse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


        
public class MyBubbleSortJavainHouse {
 
    public static void main(String[] args) {
        int[] array = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
        int n = array.length;
        int k;
        for (int i = 0; i < n ; i++)
            {
            for (int j = 0; j < n -1; j++)
            {
                k = j + 1;
                if (array[j] > array[k])
                {
                 int temp;
              temp = array[j];
              array[j] = array[k];
              array[k] = temp;
                }
            }
            
            }
            
        for (int m = 0; m < array.length; m++) {
            System.out.print(array[m] + ", ");
        }
        System.out.println("\n");
   
 
    }
}

Output :
Bubble Sort Java


How to create a custom exception in Java


Why we need custom Exception ?
How to create a custom exception ?
Write code to create a Custom Exception

All these are questions usually asked in a Java interview .So my today's post on how to create a custom exception in java .

As we know There are two types of Exception :
1. Checked Exception
2. Unchecked Exception

Both these exceptions have a common parent class Exception .So ,in same order if we have to create a custom exception ,we need to extend Exception class.

Ok , let me explain the process step by step .

1. Any custom exception should extend Exception Class .

2. There should be a proper name given to the Exception ,For example if there is an exception related to Invalid age name can be given as InvalidAgeException


public class InvalidAgeException extends Exception {}


public class InvalidAgeException extends Exception {
private int age;

public InvalidAgeException ()
{
super();
}
public InvalidAgeException (String message, int age)

{
   super(message);

   this.age = age;


}

In the above way we can define two constructors of InvalidAgeException with message and without message

Usage of custom Exception:

Below is the program with usage of custom exception.

public class CustomExceptionDemo 



private static final Map<Integer, String> employee = new HashMap<>(); 

static

 {
   employee.put(100"Mahesh");
  employee.put(101"Suresh");

   employee.put(102"Bran");

   employee.put(103"Troy"); }

 public static void main(String args[])
 { 

     CustomExceptionDemo t = new CustomExceptionDemo();

    t.getAge(1000); } 

public String getAge(int age)

 { 

     if (employee.get(age) == null)


   throw new InvalidAgeException ("No such employee exists", age);

return employee.get(name);

}

}







Android Toast Example

Hello everyone ,

Our next Example in Basic Android Examples is Basic Toast Example . In this post we will create a Button on click of which you ll be able to see a notification on Mobile screen which is known as Toast .

So basically , what is a toast ?

It is actually like an alert message. android.widget.Toast class used to create toast alert message.

Uses :

1. Toast alert is a notification message that display for certain amount of time, and automtaically fades out after set time.

2. Use it to show alert message to user.

3. can use it for debugging your application.
4.to show alert from background sevice,boadcast reciever,getting data from server...etc.

Let us start with the code :

Step 1: Create a New Application

Let us first create a new Application/Project . I named it as Toast Example.
Android Example
Step 3:Activity  

Now add a new buuton either by dragging in activity_toast.xml or by writing the code . I changed the text of button as Toast Example .
Android Toast Example

Step 3: Add a New Button 
For Activity java class first we need to get the Button id using findIdbyView method and then we override the onclicklistener method onClick  with which a Toast with the String inside it and length defined will be shown on the mobile screen .



package javainhouse.com.toastexample;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ToastActivity extends AppCompatActivity {

    private Button toastExample;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toast);

        toastExample = (Button) findViewById(R.id.buttonToast);

        // Button click listner
        toastExample.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Context context = getApplicationContext();




               // Toast toast = new Toast(context);

                Toast.makeText(getApplicationContext(),
                        "Hello Toast", Toast.LENGTH_LONG)
                        .show();

            }
        });
    }

}
     




Step 4: Output 


Android Example

How to remove duplicate elements from a String in Java

Hello coders, as you can see that from the past poster writing  about only the coding example of Java program it is because we are now focusing make a proper list of Java program which will help   you're the readers to crack Java interview questions. so the next post is about most popular question  which  is asked  in the JAVA interviews , Is how to remove duplicate elements from a String  in Java.If you have not gone through the previous Java programs and also find  them here.


So in this program which is am about to write we are dealing only with the string that contains alphabets not  number .  We have a string  as ”pdbertasd”  the output should be as “pdbertas”.
While Giving interview interviewer can ask to use any third party library or third party API to code these kind of questions ,  so we have design the answer accordingly.





public class JavaInHouseRemoveDuplicate{


String toRemove="myteststring";

public static void main(String[] args) {


String finalString=JavaInHouseRemoveDuplicate(toRemove);
System.out.println("Final String is : " + finalString);

public static String JavaInHouseRemoveDuplicate(String str) {
    char[] tempStringString = str.toCharArray();
    int length = tempString.length;
    for (int i = 0; i < length; i++) {
        for (int j = i + 1; j < length; j++) {
            if (tempString[i] == tempString[j]) {
                int test = j;
                for (int k = j + 1; k < length; k++) {
                    tempString[test] = tempString[k];
                    test++;
                }
                length--;
                j--;
            }
        }
    }
    return String.copyValueOf(tempString).substring(0, length);
}

}
}


OutPut is :

Final String is :mytesring




if you have any questions or suggestions please comment below.

Program to find largest and smallest numbers among N numbers using an array

Hello all , I hope this blog is helping the readers to solve the issue facing for the code in their projects or on learning basis.
Today I am going to write a program on Printing Largest and Smallest among various numbers in Java . All those who are preparing for an interview
or want to enhance their coding skills in Java can go through the other JAVA PROGRAMS on this blog and you can also provide suggestions on
various other programs we can include in our Coding section in this blog in the comments below .

Now there are various of finding the Largest and Smallest number among various numbers in Java .One of the simplest way is to achieve this
through using Arrays . But the Limitation of using an Array for this purpose is that, we need to define a definite length of the array
and also the elements inside it. Since this is the foremost basic program that should be known to developers ,after this we'll also include
the enhanced versions of this program .


Below you can find the basic steps of the program .

1. Create an array with the definite size and elements predefined.
2. Assign first element of an array to two variables  named as largest and smallest.
3. Now using a FOR loop traverse the array .
4. If any  no. found in Array which is larger than the one assigned in variable named as largest the new no. will be assigned to variable largest.
5. If any  no. found in Array which is smaller than the one assigned in variable named as smallest the new no. will be assigned to variable smallest.
The loop will be executed  as many times as length of the array.
6. After the loop has ended ,Print both the numbers .


public class JavaInHouseLSExample{

        public static void main(String[] args) {
             
               
                int numbersArrayArray[] = new int[]{32,43,53,54,32,}; // (1)
             
               
                int smallest = numbersArray[0]; // (2)
                int largest = numbersArray[0]; // (2)
             
                for(int i=1; i< numbersArray.length; i++) //(3)
                {
                        if(numbersArray[i] > largest)
                                largest = numbersArray[i]; //(4)
                        else if (numbersArray[i] < smallest)
                                smallest = numbersArray[i]; //(5)
                     
                }
             
                System.out.println("Largest Number is : " + largest); //(6)
                System.out.println("Smallest Number is : " + smallest);//(6)
        }
}





if you have any questions or suggestions please comment below. 

How to sort and reverse an array list without using sort method






package test;

import java.util.ArrayList;
import java.util.List;

public class testing {

 public static void main(String[] args)
 {
 List<Integer> l= new ArrayList<Integer>();

 l.add(1);
 l.add(7);
 l.add(90);
 l.add(67);
 int temp;
  for (int i = 0; i < l.size(); i++)
  {
    for (int j =0 ; j < l.size(); j++)
    {

     if(l.get(i)>l.get(j))
     {
     temp = l.get(i);
     l.set(i,l.get(j));
     l.set(j,temp) ;

     }
    }

  }
  for (int i = 0; i < l.size(); i++)
  {
    System.out.println(l.get(i));
  }
 }
}

How to sort and reverse an array list without using sort method






package test;

import java.util.ArrayList;
import java.util.List;

public class testing {

 public static void main(String[] args)
 {
 List<Integer> l= new ArrayList<Integer>();

 l.add(1);
 l.add(7);
 l.add(90);
 l.add(67);
 int temp;
  for (int i = 0; i < l.size(); i++)
  {
    for (int j =0 ; j < l.size(); j++)
    {

     if(l.get(i)>l.get(j))
     {
     temp = l.get(i);
     l.set(i,l.get(j));
     l.set(j,temp) ;

     }
    }

  }
  for (int i = 0; i < l.size(); i++)
  {
    System.out.println(l.get(i));
  }
 }
}