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 Print numbers for 1 to 100 without using for Loop

This is very common interview question asked in java interviews .It can be asked in other way also as an example of recursion .

For the solution of this program we will use recursion mechanism in which a method calls itself again and again till the condition satisfies.





package com.javainhouse;


public class JavaInHousePrintNumber
{
  
  public static void main(String[] args)
  {
    printNumber(100);
    
  }



public static void printNumber(int number)
{
  if(number>0)
  {
    
    
    System.out.print(" "+number);
    number--;
    printNumber(number);
  }
  
}

}

     



Output:

Print Numbers Java

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