Bubble sort algorithm in java with example

  Java Program to sort array using bubble sort

  1. package com.instaceofjava; 

  2. public class BubbleSortExample{
  3.   
  4. int[] array={4,2,5,6,9,1};
  5.  
  6. int n = array.length;
  7. int k;
  8.  
  9. for (int m = n; m>= 0; m--) {
  10.  
  11. for (int j = 0; j < n-1; j++) {
  12.  
  13.    k = j + 1;
  14.  
  15.  if (array[j] > array[k]) {
  16.  
  17.        int temp;
  18.        temp = array[j];
  19.        array[j] = array[k];
  20.        array[k] = temp;
  21.  
  22. }
  23. }
  24.            
  25. for (int x = 0; x < array.length; x++) {
  26.  
  27. System.out.print(array[x] + ", ");
  28.  
  29.  }
  30.  
  31. System.out.println();
  32. }  
  33.  
  34. }
  35.  
  36. }



Output:

  1. 2, 4, 5, 6, 1, 9, 
  2. 2, 4, 5, 1, 6, 9, 
  3. 2, 4, 1, 5, 6, 9, 
  4. 2, 1, 4, 5, 6, 9, 
  5. 1, 2, 4, 5, 6, 9, 
  6. 1, 2, 4, 5, 6, 9, 
  7. 1, 2, 4, 5, 6, 9,



AtomicInteger in Java


  • Java.util.concurrent.atomic package provides very useful classes that support lock free and thread safe programming.
  • The main use of this class is an int value that may be updated automatically.
  • AtomicInteger has some useful methods. Before that lets see the some points about this class.
  • Commonly we will use this AtomicInteger to handle the counter that is accessible by different threads simultaneously.

Java.util.concurrent.atomic.AtomicInteger:

  1. public class AtomicInteger
  2. extends Number
  3. implements Serializable

AtomicInteger Class Constructors:


  • public AtomicInteger(): Creates a new AtomicInteger object with default value 0.
  1. AtomicInteger atomicInteger = new AtomicInteger();
  • public AtomicInteger(int initialValue): Creates a new AtomicInteger object with given initial  value.
  1. AtomicInteger atomicInteger = new AtomicInteger(10);


 AtomicInteger Class Methods:


 1.public final void set(int newValue):
  •  Sets given value to the object.

  Java Program to create AtomicInteger class object and sets some value.

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.   System.out.println(atomicInteger);
  12.   atomicInteger.set(10);
  13.   System.out.println(atomicInteger);
  14.  
  15. }
  16.  
  17. }

Output:

  1. 0
  2. 10

2, public final void get():

  • Used to get current value.

Java Program to create AtomicInteger class object and sets some value and get.

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.   System.out.println(atomicInteger.get());
  12.   atomicInteger.set(10);
  13.   System.out.println(atomicInteger.get());
  14.  
  15. }
  16.  
  17. }

Output:

  1. 0
  2. 10
3.public final int getAndSet(int newValue):
  • Automatically sets the given value and returns old value.

  Java Program which explains getAndSet(int x) method of AtomicInteger class

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.    System.out.println(atomicInteger.get());
  12.  
  13.    atomicInteger.set(10);
  14.  
  15.    System.out.println(atomicInteger.get());
  16.  
  17.    System.out.println(atomicInteger.getAndSet(12));
  18.  
  19.    System.out.println(atomicInteger.get());
  20.  
  21. }
  22.  
  23. }

Output:

  1. 0
  2. 10
  3. 10
  4. 12



4.public final int incrementAndGet()
  • Automatically increments the value one and returns updated value

  Java Program which explains incrementAndGet() method of AtomicInteger class

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.    System.out.println(atomicInteger.get());
  12.  
  13.    atomicInteger.set(10);
  14.  
  15.    System.out.println(atomicInteger.get());
  16.  
  17.    System.out.println(atomicInteger.incrementAndGet());
  18.  
  19.  
  20. }
  21.  
  22. }

Output:

  1. 0
  2. 10
  3. 11


How to create immutable class in java

  • In Java String and all wrapper classes are immutable classes.
  • So how to create custom immutable class in java?
  • Lets see how to make a class object immutable.

  Immutable class:

  • Make class final so that it should not be inherited.
  • All the variables should be private so should not be accessible outside of class. 
  • Make all variables final so that value can not be changed.
  • A constructor to assign values to variables in class.
  • Do not add any setter methods.

1. Java Program to create custom immutable class object in java.

  1. package com.instaceofjava;

  2.  
  3. public final class ImmutableClass{
  4.   
  5. private final int a;
  6. private final int b;
  7.  
  8. ImmutableClass( int x, int y){
  9.  
  10.  a=x;
  11.  b=y; 

  12.  
  13. public getA(){
  14.  
  15.  return a;

  16. }
  17.  
  18. public getB(){
  19.  
  20.  return b;

  21. }
  22.  
  23. public static void main(String[] args) {
  24.  
  25. ImmutableClass obj= new ImmutableClass(10,20);
  26.  
  27. System.out.println("a="+obj.getA());
  28.  
  29. System.out.println("b="+obj.getB());
  30.  
  31. }
  32. }
Output:

  1. a=10
  2. b=20


String class in java: Immutable


  1. public final class String
  2.         implements java.io.Serializable, Comparable<String>, CharSequence
  3. {  
  4.   
  5. //String class variables

  6.   private final char value[];
  7.   private final int offset;
  8.   private final int count;
  9.   private int hash; // Default to 0
  10.   private static final ObjectStreamField[] serialPersistentFields =
  11.       new ObjectStreamField[0];
  12.   
  13. //String class constructor
  14. public String(String original) {
  15.  
  16.             int size = original.count;
  17.              char[] originalValue = original.value;
  18.              char[] v;
  19.              if (originalValue.length > size) {
  20.                 // The array representing the String is bigger than the new
  21.               // String itself.  Perhaps this constructor is being called
  22.                 // in order to trim the baggage, so make a copy of the array.
  23.                  int off = original.offset;
  24.                 v = Arrays.copyOfRange(originalValue, off, off+size);
  25.             } else {
  26.                  // The array representing the String is the same
  27.                  // size as the String, so no point in making a copy.
  28.                  v = originalValue;
  29.            }
  30.             this.offset = 0;
  31.              this.count = size;
  32.             this.value = v;
  33.         } 

  34. }



Java Program to find Sum of Digits


1. Java Program to find sum of digits without using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. int number;
  9. Scanner in = new Scanner(System.in);
  10.  
  11. System.out.println("Please Enter a number");
  12.  
  13. number=in.nextInt(); 
  14.  
  15. int sum=0 ;
  16.  
  17. while(number!=0){
  18.  
  19. sum=sum+(number%10);
  20. number=number/10;
  21. }
  22.  
  23. System.out.println("Sum of Digits ="+sum);
  24.  
  25. }
  26. }
Output:

  1. Please Enter a number
  2. 123
  3. Sum of Digits=6


2. Java Program to find sum of digits using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. int sum;

  7. public int CalRecSum(int n){
  8.  
  9. if(n==0){
  10. return sum;
  11. }
  12. else{
  13.  
  14.  sum+=n%10;
  15.  CalRecSum(n/10);
  16.  
  17.  
  18. return sum;
  19. }

  20. public static void main(String[] args) {
  21.  
  22. int number;
  23. Scanner in = new Scanner(System.in);
  24.  
  25. System.out.println("Please Enter a number");
  26.  
  27. number=in.nextInt(); 
  28.  
  29. SumOfDigits   ob= new SumOfDigits();
  30. System.out.println("Sum of Digits ="+ob.CalRecSum(number));
  31.  
  32. }
  33.  
  34. }


Output:

  1. Please Enter a number
  2. 326
  3. Sum of Digits=11

Swap two numbers without using third variable

1. Java Interview Program to Swap two numbers without using third variable in java



  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=20;
  8. int number2=30;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1+number2;
  15. number2=number1-number2;
  16. number1=number1-number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }
Output:

  1. Before Swapping
  2. Value of number1 is :20
  3. Value of number2 is :30
  4. After Swapping
  5. Value of number1 is :30
  6. Value of number2 is :20

2. Java Program to Swap two numbers by using division and multiplication.


  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=20;
  8. int number2=30;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1*number2;
  15. number2=number1/number2;
  16. number1=number1/number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }


Output:

  1. Before Swapping
  2. Value of number1 is :20
  3. Value of number2 is :30
  4. After Swapping
  5. Value of number1 is :30
  6. Value of number2 is :20


3. Java Program to Swap two integers by using bit wise operators


  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=2;
  8. int number2=4;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1^number2;
  15. number2=number1^number2;
  16. number1=number1^number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }
Output:

  1. Before Swapping
  2. Value of number1 is :2
  3. Value of number2 is :4
  4. After Swapping
  5. Value of number1 is :4
  6. Value of number2 is :2


HashSet class


Hierarchy of HashSet class:


 

 public class HashSet<E>
        extends AbstractSet<E>
           implements Set<E>, Cloneable, java.io.Serializable

Key points:

  • HashSet is sub class of AbstractSet class.
  • Underlying data structure of HashSet is HashTable.
  • HashSet implements Serializable and Cloneable interfaces
  • HashSet does not allow duplicate elements.
  • Insertion order is not preserved. No order(Based on hashcode of objects)



Constructors of HashSet:

1.HashSet( )
  • Creates an empty HashSet object with default initial capacity 16.  Fill ratio or load factor 0.75
2.HashSet(Collection obj)
  • This constructor initializes the hash set by using the elements of the collection obj.
3.HashSet(int capacity)
    • Creates an empty HashSet object with given capacity.
      4.HashSet(int capacity, float fillRatio)
      • This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments (fill ratio 0.1 to 1.0)

      Reverse words in a String

      1. Java Interview Program to Reverse words in a string


      1. package com.instaceofjava;
      2.  
      3. public class ReverseString {
      4.  
      5. public static void main(String[] args) {
      6.  
      7. String strng= "Instance of Java ";
      8.  
      9. String str[] =strng.split(" ");
      10.  
      11. String result="";
      12.  
      13. for(int i=str.length()-1;i>=0;i--){
      14.  
      15. result += str[i]+" ";
      16.  
      17. }
      18.  
      19. System.out.println(result );
      20. }
      21. }
      Output:

      1. Java of Instance



      2. Java Interview Program to Reverse words in a string


      1. package com.instaceofjava;
      2.  
      3. public class ReverseString {
      4.  
      5. public static void main(String[] args) {
      6.  
      7. String strng= "Instance of Java ";
      8.  
      9. StringBuilder sb = new StringBuilder(strng.length() + 1);
      10.  
      11.   String[] words = strng.split(" ");
      12.  
      13.   for (int i = words.length - 1; i >= 0; i--) {
      14.          sb.append(words[i]).append(' ');
      15.    }
      16.     
      17.     sb.setLength(sb.length() - 1); 
      18.  
      19.    String result= sb.toString();  
      20.  
      21.     System.out.println(result);

      22. }
      23. }
      Output:

      1. Java of Instance

      Introducton to Spring



      Spring Framework history:

      • Spring was developed in June,2003
      • Initially developed by Rod Johnson.
      • Latest version of  Spring Framework version 4.1.6 released in Mar 2015.

      What is Spring:
      • Spring is  Open Source Framework.
      • Spring is Lightweight Application Framework. 
      • Spring is  Simple framework.
      • Spring is loosely coupled. 
      • Spring is a complete and a modular framework,because spring can be used in all layers of applications means front end(Spring MVC),Database(Spring JDBC,Spring ORM).

      Why Spring:
      • Why Spring come in to picture is because of EJB fails,EJB having multiple configuration files,it is affected on performance.so spring came up.
      • Struts designed for Web Layer,like Other Frameworks also addressed specific layer,But Spring Framework provides solution to support all layers of application.
      • Spring is non invasive framework,means Spring doesn't force to implement or extend any class from predefined class from Spring API.

      Advantages of Spring:
      • Spring is open source and lightweight framework.
      • Spring is supports all layers including web layer.
      • Easy for testing.
      • Spring Supports POJO Model.
      • POJO-Plain Old Java Object. 
      • Spring works in simple Java environment,because it is non,invasive.
      • Spring can be integrated with any Application Server
      • Spring simplifies J2EE development. 



      Spring Modules:
       spring 1.x have seven modules,but in 2.x on wards we have 6 modules.
      • Spring Core
      • Spring DAO(Spring JDBC)
      • Spring AOP(Ascept Orient Programming)
      • Spring ORM(Spring Hibernate)
      • Spring MVC
      • Spring WEB
      • Spring Context(J2EE)  
      Spring 2.x Modules:
      from Spring 2.x ,Spring -WEB and Spring-MVC is combined.
      • Spring Core
      • Spring DAO(Spring JDBC)
      • Spring AOP(Ascept Orient Programming)
      • Spring ORM(Spring Hibernate)
      • Spring WEB-MVC
      • Spring Context(J2EE


      spring tutorial



      • Spring is combination of various modules Seven well defined modules,Most of them are reasonably independent.
      • Spring modules built using modular approach,you can use only required modules Each module is set of one or more JAR files
      • Spring’s core module is “Inversion of Control”(IoC) also known as “Dependency Injection”.
      • All other Spring modules are built on top of IoC.IoC is a Foundation or Container of Spring Framework.
      • Spring core module is the base module for all modules.

      Collection interface in java

      The Collection Interface in Java is the root interface(a kind of abstract class) in java.util package. It represents a group of objects, known as elements, and provides a unified way to manipulate and work with collections of data.

      Key Points About the Collection Interface

      Root Interface: The Collection interface is the root interface of all Collection objects in Java, except Map.
      Generic Interface: A generic interface, meaning it can work with any type of object (_e.g.,_ Collection<String>, Collection etc.).
      Common Methods: For example, we can use the following methods for both adding and deleting elements to an array: add(), remove (), size().
      Extends Iterable: The Collectioneuml; interface extends the Iterableinterface, and this means that all collections can be iterated over via either an iterator or the enhanced for-loop construct.



      1. public interface Collection<E>
      2. extends Iterable<E>


      Methods in Collection Interface:

       1.public Boolean add(Object obj)
      •  Used to add element in to the collection

       2.public Boolean addAll(Collection c)

      • Adds all the elements of c to the invoking collection. Returns true if the operation succeeded else returns false.

       3.public boolean isEmpty()
      • Returns true if collection is empty otherwise returns false.

       4.public boolean remove(Object obj)
      • Remove element from collection. Returns true if successful deletion.

      5.public boolean  removeAll(Collection c)
      • Removes all elements of a collection.

       6.public void clear()
      • Deletes total elements from collection

       7.public boolean contains(Object obj)
      • This method used to search an element

       8.public boolean containsAll(Collection c)
      • This method used to search an element in a collection

       9.public boolean retianAll(Collection c)
      • Used to delete all elements from a collection except specified one.

      10.public int size()
      • Returns total numbers of elements in a collection

      11.public Iterator iterator()
      • Returns iterator for the collection

      12.public boolean equals(Object obj)
      • Compares two collections

      13.public int hashCode()
      • Returns hashcode

      14.public Object[] toArray()
      • This method used to convert collection into array
      15.public Object[] toArray(Object[] obj)
      • Returns an array containing only those collection elements whose type matches that of array.

      Difference Between Collection and Collections:

      • Collection is the base interface for most of the classes.
      • Collections is the utility class.


      Java experience interview programming questions on Strings


      1.Java Basic interview Programs on Strings


       2.Reverse a String Without using String API?





       3.Sorting the String without using String API?


       4.Check String is palindrome or not? 

       5.How to split a String in java

      • #1: Java Program to split a String using String Split() method:
      • #2: Java Program to split a String using String Split() method and use for each loop to display  
      • #4: Java Program to split a String using String Split() method: Before splitting check whether deliminator is there or not
      • Check here for all questions on Splitting a string using string  method

      6.Removing Non Ascii character from a String?


       7.Java program to replace or remove a character in a string java



      8.Java Program to check two strings are anagrams or not

       9.Java program to return maximum occurring character in the input string

      10.Java program to count the number of vowels in a string.




      11.Java Program to find numbers of occurrences of given char in a string


      12.Java Program to count number of words in a String.
      13.How to reverse vowels in a string java
      14.Java program to remove vowels from string

       15.How to find count of uppercase letters in a string 

      Remove non ascii character from string

      #1: Java Program to Remove non ASCII chars from String

      1. package com.instanceofjava;
      2.  
      3. class RemoveNonASCIIString{
      4.  
      5. public static void main(String [] args){ 

      6.   String str = "Instance��of��java";
      7.   System.out.println(str);
      8.  
      9.   str = str.replaceAll("[^\\p{ASCII}]", "");
      10.  
      11.   System.out.println("After removing non ASCII chars:");
      12.  
      13.   System.out.println(str);
      14. }
      15. }
      Output:
      1. Instance��of��java
      2. After removing non ASCII chars:
      3. Instanceofjava


      #2: Java Program to Remove multiple spaces in a string

      1. package com.instanceofjava;
      2.  
      3. class RemoveNonASCIIString{
      4.  
      5. public static void main(String [] args){ 

      6.   String str = "Instance  of    java";
      7.   StringTokenizer st = new StringTokenizer(str, " ");
      8.  
      9.   StringBuffer sb = new StringBuffer();
      10.  
      11.   while(st.hasMoreElements()){
      12.          sb.append(st.nextElement()).append(" ");
      13.   }
      14.  
      15.      System.out.println(sb.toString().trim());
      16.     
      17.     }
      18. }
      19. }


      Output:
      1. Instance of java

      How to split a string in java


      #1: Java Program to split a String using String Split() method:

      1. package com.instanceofjava;
      2.  
      3. class SplitString{
      4.  
      5. public static void main(String [] args){ 

      6.   String str = "Instance-of-Java";
      7.   String strarray[]=str.split("-");
      8.  
      9.     for (int i = 0; i < strarray.length; i++) {
      10.         System.out.println(strarray[i]);
      11.     }
      12.    
      13. }
      14. }
      Output:
      1. Instance
      2. of
      3. Java

      #2: Java Program to split a String using String Split() method and use for each loop to display
      1. package com.instanceofjava;
      2.  
      3. class SplitString{
      4.  
      5. public static void main(String [] args){ 

      6.   
      7.     String str = "Instance-of-Java";
      8.     String strarray[]=str.split("-");
      9.  
      10.     for (String string : strarray) {
      11.         System.out.println(string);
      12.     }
      13.  
      14. }
      15. }


      Output:
      1. Instance
      2. of
      3. Java



      #3: Java Program to split a String using String Split() method: Before splitting check whether deliminator is there or not
      1. package com.instanceofjava;
      2.  
      3. class SplitString{
      4.  
      5. public static void main(String [] args){ 

      6.   
      7.     String str = "Instance-of-Java";
      8.    if(str.contains("-")){
      9.  
      10.     String strarray[]=str.split("-");
      11.  
      12.     for (String string : strarray) {
      13.         System.out.println(string);
      14.     }
      15.  
      16.     }
      17.     else{
      18.         System.out.println("String does not conatain specified char so splitting is not possible");
      19.     }
      20.  
      21. }
      22. }
      Output:
      1. Instance
      2. of
      3. Java

      #4: Java Program to split a String using String Split() method: Before splitting check whether deliminator is there or not
      1. package com.instanceofjava;
      2.  
      3. class SplitString{
      4.  
      5. public static void main(String [] args){ 

      6.   
      7.     String str = "Instance-of-Java";
      8.    if(str.contains(".")){
      9.  
      10.     String strarray[]=str.split("-");
      11.  
      12.     for (String string : strarray) {
      13.         System.out.println(string);
      14.     }
      15.  
      16.     }
      17.     else{
      18.         System.out.println("String does not contains specified char so splitting is not possible");
      19.     }
      20.  
      21. }
      22. }
      Output:
      1. String does not contains specified char so splitting is not possible

      Remove Character from string in java


      #1: Java Program to Remove all occurrences of a string 

      1. package com.instanceofjava;
      2.  
      3. class RemoveCharString{
      4.  
      5. public static void main(String [] args){ 

      6.   String str = "Java";
      7.     str = str.replace("a", "");
      8.     System.out.println(str);
      9. }
      10. }
      Output:
      1. Jv

      #2: Java Program to Replace First occurance of Specific index char in a String

      1. package com.instanceofjava;
      2.  
      3. class RemoveCharString{
      4.  
      5. public static void main(String [] args){ 

      6.   String str = "Java";
      7.  
      8. //String result = str.substring(0, index) + str.substring(index+1);
      9.  
      10.   String result = str.substring(0, 1) + str.substring(1+1);
      11.   System.out.println(result);
      12.  
      13. }
      14. }


      Output:
      1. Jva


      #3: Java Program to Remove all Numbers from a string.

      1. package com.instanceofjava;
      2.  
      3. class RemoveNumberString{
      4.  
      5. public static void main(String [] args){ 

      6.   String str = "Instance12ofjava143";
      7.   str = str.replaceAll("[0-9]","")
      8.   System.out.println(str);
      9.  
      10. }
      11. }
      Output:
      1. Instanceofjava

      Java Program to find Max occurred character in a string


      • How to print duplicate characters from string in java?
      • Java program to count number of repeated characters in a string.
      • Java program for printing a repetitive letters in a string
      • count occurrences of each character in string java


      1. package com.javatutorial;
      2.  
      3. public class MaxOccuranceOfChar{
      4.    
      5. public static String MaxOccuredChar(String str) {
      6.  
      7.         char[] array = str.toCharArray();
      8.         int maxCount = 1;
      9.         char maxChar = array[0];
      10.  
      11.   for(int i = 0, j = 0; i < str.length() - 1; i = j){
      12.        int count = 1;
      13.    while (++j < str.length() && array[i] == array[j]) {
      14.           count++;
      15.         }
      16.  
      17.   if (count > maxCount) {
      18.      maxCount = count;
      19.      maxChar = array[i];
      20.  }
      21.  
      22.   }
      23.  
      24.         return (maxChar + " = " + maxCount);
      25.  }

      26.  public static void main(String[] args) {
      27.   
      28.   String str1=MaxOccuredChar("instanceofjava");
      29.   System.out.println(str1);
      30.  
      31.   String str2=MaxOccuredChar("aaaabbbccc");
      32.   System.out.println(str2);
      33.  
      34.   String str3=MaxOccuredChar("ssssiiinnn");
      35.   System.out.println(str3);
      36.  
      37.   String str4=MaxOccuredChar("jaaaavvvvvvvvaaaaaaaaaa");
      38.   System.out.println(str4);
      39.  
      40. }

      41. }


      Output:

      1. i = 1
      2. a = 4
      3. s = 4
      4. a = 10
         

      Java program to check two strings are anagrams



      1. package com.javatutorial;
      2.  import java.util.Arrays;

      3. public class CheckAnagramStrings {
      4.   
      5. private static boolean isAnagram(String str1, String str2) {
      6.  
      7.         if (str1.length() != str2.length()) {
      8.             return false;
      9.         }
      10.         str1 = sortCharacters(str1);
      11.         str2 = sortCharacters(str2);
      12.         return str1.equals(str2);
      13.  }
      14.  
      15. private static String sortCharacters(String str) {
      16.         char[] charArray = str.toLowerCase().toCharArray();
      17.         Arrays.sort(charArray);
      18.         return String.valueOf(charArray);
      19.  }

      20.  public static void main(String[] args) {
      21.    
      22.  String str1 = "bemru";
      23.  String str2 = "mureb";
      24.  
      25.  if (isAnagram(str1, str2)) {
      26.           System.out.println(str2 + " is anagram of " + str1);
      27.   } else {
      28.           System.out.println("Strings are not anagrams.");
      29.   }
      30.  
      31. }

      32. }


      Output:

      1. mureb is anagram of bemru
         

      Java Program to count number of vowels in a string


      Solution #1:

      1. package com.javatutorial;
      2.  
      3. public class CountNumberofVowels {
      4.  
      5.  public static void main(String[] args) {
      6.   
      7. System.out.println("Please enter a String");
      8. Scanner in = new Scanner(System.in);                  
      9.  String input = in.nextLine();
      10.  
      11.      char[] Chararray = input.toCharArray();
      12.  
      13.  int count = 0;
      14.  
      15.  for (char ch : Chararray) {
      16.       switch (ch) {
      17.              case 'a':
      18.              case 'e':
      19.              case 'i':
      20.              case 'o':
      21.              case 'u':
      22.              case 'A':
      23.              case 'E':
      24.              case 'I':
      25.              case 'O':
      26.              case 'U':
      27.                  count++;
      28.      break;
      29.      default:
      30.             
      31.      }
      32.  }
      33.        System.out.println("Number of vowels in String "+count);
      34.  
      35. }

      36. }


      Output:

      1. Please enter a String
      2. Instance Of Java
      3. Number of vowels in String 6
         
      Solution #2:

      1. package com.javatutorial;
      2.  
      3. public class CountNumberofVowels {
      4.  
      5.  public static void main(String[] args) {
      6.  
      7.  int vowels = 0, digits = 0, blanks = 0; char ch; 

      8. System.out.println("Please enter a String");
      9. Scanner in = new Scanner(System.in);                  
      10. String testString= in.nextLine();
      11.  
      12.  
      13. for(int i = 0; i < testString.length(); i ++)
      14. {
      15.  
      16.   ch = testString.charAt(i);
      17.  
      18.   if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||   
      19.       ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
      20.           vowels ++;
      21.        else if(Character.isDigit(ch))
      22.           digits ++;
      23.      else if(Character.isWhitespace(ch))
      24.            blanks ++;
      25.   }
      26.  
      27.     System.out.println("Vowels : " + vowels);
      28.     System.out.println("Digits : " + digits);
      29.     System.out.println("Blanks : " + blanks);           
      30.    
      31.  
      32. }

      33. }
      Output:

      1. Please enter a String
      2. vowels and consonants
      3. Vowels : 6
      4. Digits : 0
      5. Blanks : 2

      Java Program to Count the number of occurrences of a char in a String?



      Solution #1:

      1. package com.javatutorial;
      2.  
      3. import java.util.Scanner;
      4.  
      5. public class CountNumberofChars {
      6.  
      7.  public static void main(String[] args) {
      8.   
      9.  String str = "";
      10.  
      11.  Scanner in= new Scanner(System.in);
      12.  System.out.println("Please enter a String");
      13.  
      14.  str=in.nextLine();
      15.  
      16.  System.out.println("Please enter a Character");
      17.  String chr=in.next();
      18.  
      19.  int charCount = str.length() - str.replaceAll("a", "").length();
      20.  
      21.  System.out.println("Number of occurances of given character:"+charCount);
      22.  
      23. }

      24. }



      Output:

      1. Please enter a String
      2. Java
      3. Please enter a Character
      4. a
      5. Number of occurances of given character:2


      Solution #2:


      1. package com.javatutorial;
      2.  
      3. import java.util.Scanner;
      4.  
      5. public class CountNumberofChars {
      6.   
      7. public static int countOccurrences(String find, String string)
      8. {
      9. int count = 0;
      10. int indexOf = 0;
      11.  
      12. while (indexOf > -1)
      13. {
      14.     indexOf = string.indexOf(find, indexOf + 1);
      15.     if (indexOf > -1)
      16.             count++;
      17.       }
      18. return count;
      19.  }

      20.  public static void main(String[] args) {
      21.   
      22.  int charCount=countOccurrences("a", "Instance of Java");
      23.  
      24.  System.out.println("Number of occurrences of given character:"+charCount);
      25.  
      26. }

      27. }

      Output:

      1. Number of occurrences of given character: 3

      Java program To Count the number of words in a String




      1. package com.javatutorial;
      2.  
      3. public class CountNumberofWords {
      4.  
      5.  public static void main(String[] args) {
      6.  
      7. String s="";
      8. int count=0;
      9.  
      10. Scanner in = new Scanner(System.in);
      11. System.out.println("Please enter a String");
      12.  s=in.nextLine();
      13.  
      14. char ch[]= new char[s.length()];    
      15.  
      16. for(int i=0;i<s.length();i++)
      17. {
      18.  
      19.     ch[i]= s.charAt(i);
      20.  
      21.     if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
      22.         count++;
      23.  
      24. }
      25. System.out.println("Number of words in given String: "+count);
      26.  
      27. }

      28. }


      Output:

      1. Please enter a String
      2. Java Tutorial
      3. Number of words in given String: 2

      Pattern Program in java Part-3


       Program #1:  java program to print pyramid of stars using for loop in below format


      *
      **
      ***
      ****
      *****
      ******
      *******
      ********
      *********
      **********




      1. package com.learnJavaOnline;
      2. public class PrintStarsFormat {
      3.  
      4. public static void main(String[] args) {
      5.   
      6. int  numberOfStars=10;
      7.  
      8. for (int row = 1; row <= 10; row++) {
      9.  
      10.     for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
      11.       System.out.print("*");
      12.     }
      13.  
      14.     System.out.println(); 
      15.  }
      16.  
      17. }
      18.  
      19. }
      Output:
      1. *
      2. **
      3. ***
      4. ****
      5. *****
      6. ******
      7. *******
      8. ********
      9. *********
      10. **********

                

      Program #2: java program to print pyramid of stars using for loop in below format



      **********
      *********
      ********
      *******
      ******
      *****
      ****
      ***
      **
      *



      1. package com.learnJavaOnline;
      2. public class PrintStarsPyramid {
      3.  
      4. public static void main(String[] args) {
      5.   
      6. int  numberOfStars=10;
      7.  
      8. for(int i=numberOfStars; i>0 ;i--){
      9.  
      10.     for(int j=0; j < i; j++){
      11.  
      12.           System.out.print("*");
      13.     }
      14.  
      15.     System.out.println("");
      16. }
      17.  
      18. }
      19.  
      20. }
      Output:
      1. **********
      2. *********
      3. ********
      4. *******
      5. ******
      6. *****
      7. ****
      8. ***
      9. **
      10. *



      Program #3 java program to print pyramid of stars using for loop in below format


      *
      **
      ***
      ****
      *****
      ******
      *******
      ********
      *********
      **********
      **********
      *********
      ********
      *******
      ******
      *****
      ****
      ***
      **
      *




      1. package com.learnJavaOnline;
      2. public class PrintStarsPyramid {
      3.  
      4. public static void main(String[] args) {
      5.   
      6. int  numberOfStars=10;
      7.  
      8.  for(int i=1; i<= numberOfStars ;i++){
      9.  
      10. for(int j=0; j < i; j++){
      11.  
      12.   System.out.print("*");
      13.  
      14. }
      15.  
      16. System.out.println("");
      17.  
      18. }
      19.  
      20. for(int i=numberOfStars; i>0 ;i--){
      21.  
      22. for(int j=0; j < i; j++){
      23.   System.out.print("*");
      24. }
      25.  
      26. System.out.println("")}
      27.  
      28. }
      29.  
      30. }
      Output:
      1. *
      2. **
      3. ***
      4. ****
      5. *****
      6. ******
      7. *******
      8. ********
      9. *********
      10. **********
      11. **********
      12. *********
      13. ********
      14. *******
      15. ******
      16. *****
      17. ****
      18. ***
      19. **
      20. *




      Print Pascals triangle using java program


      Pattern Program in java Part-2

      #4 Java Program to print Numbers in Below pattern

      1 2 3 4 5 6 7 8 9
       1 2 3 4 5 6 7 8
        1 2 3 4 5 6 7
         1 2 3 4 5 6
          1 2 3 4 5
           1 2 3 4
            1 2 3
             1 2
              1
              




      1. package com.learnJavaOnline;
      2. public class NumbersFormat {
      3. public static void main(String[] args) {
      4.  
      5. int r, c1,c2;
      6.  
      7. for (r = 1; r <= 10; r++) {
      8.  
      9. for (c1 = 1; c1 <r; c1++) {
      10.   System.out.print(" ");
      11. }
      12.  
      13. for (c2 = 1; c2 <= 10 - r; c2++) {
      14.     System.out.print(c2 + " ");
      15. }
      16.  
      17. System.out.println("");
      18. }
      19.  
      20. }
      21.  
      22. }


      Output:
      1. 1 2 3 4 5 6 7 8 9  
      2. 1 2 3 4 5 6 7 8 
      3.   1 2 3 4 5 6 7 
      4.    1 2 3 4 5 6 
      5.     1 2 3 4 5 
      6.      1 2 3 4 
      7.       1 2 3 
      8.        1 2 
      9.         1
                
      #5 Java Program to Print Numbers in Below pattern:

              1
             1 2
            1 2 3
           1 2 3 4
          1 2 3 4 5
         1 2 3 4 5 6
        1 2 3 4 5 6 7
       1 2 3 4 5 6 7 8
      1 2 3 4 5 6 7 8 9
      1 2 3 4 5 6 7 8 9 10




      1. package com.learnJavaOnline;
      2. public class NumbersFormat {
      3. public static void main(String[] args) {
      4.  
      5. int r, c1,c2;
      6.  
      7. for (r = 1; r <= 10; r++) {
      8.  
      9. for (c1 = 1; c1 <10-r; c1++) {
      10.   System.out.print(" ");
      11. }
      12.  
      13. for (c2 = 1; c2 <= r; c2++) {
      14.     System.out.print(c2 + " ");
      15. }
      16.  
      17. System.out.println("");
      18. }
      19.  
      20. }
      21.  
      22. }

      Output:
      1.         1 
      2.        1 2 
      3.       1 2 3 
      4.      1 2 3 4 
      5.     1 2 3 4 5 
      6.    1 2 3 4 5 6 
      7.   1 2 3 4 5 6 7  
      8. 1 2 3 4 5 6 7 8 
      9. 1 2 3 4 5 6 7 8 9 
      10. 1 2 3 4 5 6 7 8 9 10
                

      Print Pascals triangle using java program




      Pattern Program in java Part-1

      #1 Java Program To print Numbers in Below pattern:

                    1
                   2 3
                  4 5 6
                 7 8 9 10
               11 12 13 14 15




      1. package com.javatutorial;
      2. public class NumbersFormat {
      3.  
      4.  public static void main(String[] args) {
      5.  
      6.  int num=15;
      7.  int temp=1;
      8.      
      9.  for (int i = 1; i <= num; i++)
      10.  {
      11.  
      12.   for (int k = i; k <num; k++)
      13.    System.out.print(" ");
      14.    for (int j =1; j <= i; j++){
      15.  
      16.     System.out.print("" +temp+ " ");
      17.      temp++;
      18.  
      19.  if(temp>15){
      20.        break;
      21.  }
      22.  
      23.  }
      24.  
      25.   System.out.println();
      26.  
      27. if(temp>15){
      28.      break;
      29.   }
      30.  
      31. }
      32.  
      33. }

      34. }
      Output:

      1.               1
                     2 3
                    4 5 6
                   7 8 9 10
                  11 12 13 14 15





      # Java Program to print Numbers in Below Format:

      1
      1 2
      1 2 3
      1 2 3 4
      1 2 3 4 5
      1 2 3 4 5 6
      1 2 3 4 5 6 7
      1 2 3 4 5 6 7 8
      1 2 3 4 5 6 7 8 9
      1 2 3 4 5 6 7 8 9 10


      1. package com.learnJavaOnline;
      2. public class NumbersFormat {
      3. public static void main(String[] args) {
      4.  
      5. int r, c;
      6.  
      7. for (r = 1; r <= 10; r++) {
      8.  
      9. for (c = 1; c <= r; c++) {
      10.  
      11. System.out.print(c + " ");
      12.  
      13. }
      14.  
      15. System.out.println("");
      16. }
      17.  
      18. }
      19.  
      20. }
      Output:
      1. 1 2 
      2. 1 2 3 
      3. 1 2 3 4 
      4. 1 2 3 4 5 
      5. 1 2 3 4 5 6 
      6. 1 2 3 4 5 6 7 
      7. 1 2 3 4 5 6 7 8 
      8. 1 2 3 4 5 6 7 8 9 
      9. 1 2 3 4 5 6 7 8 9 10


      #3 Java Program to print numbers in below format

      1 2 3 4 5 6 7 8 9
      1 2 3 4 5 6 7 8
      1 2 3 4 5 6 7
      1 2 3 4 5 6
      1 2 3 4 5
      1 2 3 4
      1 2 3
      1 2
      1


      1. package com.learnJavaOnline;
      2. public class NumbersFormat {
      3. public static void main(String[] args) {
      4.  
      5. int r, c;
      6.  
      7. for (r = 1; r <= 10; r++) {
      8.  
      9. for (c = 1; c <= 10-r; c++) {
      10.  
      11. System.out.print(c + " ");
      12.  
      13. }
      14.  
      15. System.out.println("");
      16. }
      17.  
      18. }
      19.  
      20. }

      Output:
      1. 1 2 3 4 5 6 7 8 9 
      2. 1 2 3 4 5 6 7 8 
      3. 1 2 3 4 5 6 7 
      4. 1 2 3 4 5 6 
      5. 1 2 3 4 5 
      6. 1 2 3 4 
      7. 1 2 3 
      8. 1 2 
      9. 1



      Print Pascals triangle using java program

      Collection Framework Tutorial

      Limitations of Arrays:

      • Arrays are fixed in size. need to estimate the size of an array while declaration itself. once array created we can not increase the size of an array.
      • Arrays can hold only homogeneous data elements. Means we can add same type of elements in an array. While declaring an array we need to mention the data type.
      • int a[]= new int[10];
      • By using Object array we can add heterogeneous elements to the array.
      • Object o= new Object[10];
      • There is no underlying data structure for arrays.
      • Arrays are not recommended to use with respect to memory.
      • Performance wise arrays are good to use.

      Collections 

      • Java Collection framework added in J2SE 1.2 release.
      • Collections are set of classes and interfaces.
      • By using Collections we can store and manipulate objects easily.
      • Collections can hold heterogeneous data elements.
      • Collections are no fixed in size and dynamically increase in size.
      • Collection of objects. No primitives.
      • All collection classes having underlying data structure.
      • Collections are good with respect to memory. Bad with respect to performance.

      Collection interface Hierarchy:

      •  java.util package contains all collections classes and interfaces.
      • Lets see collection interface hierarchy.
      • under Collection. Set , List , Queue are the sub interfaces.

      Collection interface Hierarchy

      Collections Abstract classes and classes:

      • Let us see  all the abstract classes implementing all the above interfaces and classes which extending these abstract classes.
      • To Collect Objects in array format we choose Collection hierarchy classes.
      • Main abstract class is AbstractCollection.
      • AbstractSet
      • AbstractList
      • AbstractQueue
      • AbstractSequentialList
      • All the classes in Collection hierarchy are
      • TreeSet
      • HashSet
      • LinkedHashSet
      • LinkedList
      • ArrayList
      • Vector
      • Stack
      • PriorityQueue 
      • To collect unique elements we must choose Set implemented classes
      • To collect unique and duplicate elements in indexed order we choose List implemented classes.
      • To retrieve elements in FIFO manner we choose Queue implemented classes.

      Collection interview Questions

      Map Hierarchy:

      • In this hierarchy Hashtable and properties classes are avilable since java 1.0.
      • LinkedHashMap class is available since java 1.4
      • NavigableMap is available since java 6 and all other classes available since java 1.2.
      • SortedMap and NavigableMap are two main interfaces.
      • TreeMap
      • HashMap
      • LinkedHashMap
      • Hashtable
      • Properties are the classes. 
      • To collect objects in key, value pair format we choose Map hierarchy classes.


      Collection Map Hierarchy tutorial


      Select Menu