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


Difference between error and exception in java

  • Exception and Error both are sub classes of java.lang.Throwable class.
  • We can handle Exceptions at runtime but Errors we can not handle.

  • Exceptions are the objects representing the logical errors that occur at run time and makes JVM enters into the state of  "ambiguity".
  • The objects which are automatically created by the JVM for representing these run time errors are known as Exceptions.
  • An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
  • An error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Examples of errors include OutOfMemoryError, StackOverflowError, and NoClassDefFoundError. An exception, on the other hand, is a subclass of Throwable that indicates conditions that a reasonable application might want to catch. Examples of exceptions include IOException, SQLException, and NullPointerException.
  • Exceptions are used to indicate that a problem occurred that the application can handle, while errors indicate that a more serious problem has occurred that the application cannot handle.
  • Exceptions are events that are triggered by the code you write, such as a null pointer reference or a file that cannot be found. When an exception occurs, the program will stop executing and the control will be transferred to an exception handler. You can catch exceptions using try-catch blocks and handle them appropriately.
  • Errors, on the other hand, are typically caused by external factors such as the JVM running out of memory, or the system running out of resources. These types of errors are not typically recoverable by your application and are not meant to be handled by you.
  • It is generally recommended to handle exceptions, as they are often the result of programming mistakes and can be corrected in the code. Errors, on the other hand, should be logged and reported to the user, but the program should not try to recover from them.
  • In summary, Errors are serious problems that are not usually handled by the application and are thrown by the JVM when it encounters a problem that it can't handle, like running out of memory, stack overflow, etc. While exceptions are events that are triggered by the code you write or external libraries, and can be handled by the application using try-catch blocks, to handle the exceptional events in an appropriate way.
difference between error and exception handling

  Difference Between Exceptions and Errors

  • If exception occurs we can handle it by using try and catch block. If Error occurs we can noyt handle it , program execution will be terminated.
  • In Exception we have two types
    1. Checked Exception
    2.Unchecked Exceptions
  • Error are by default unchecked exceptions.
  • Exceptions are related to application where ad Error are related to environment in which application is running.

  • Exception are of type java.lang.Exception
  • Errors are of type java.lang.Error
  • Error will run at run time.
  • In Exceptions Checked Exceptions will known to compiler so we need to handle these exceptions at compile time itself otherwise compile time Error will come.
  • Unchecked Exception will come at run time need to handle by using try and catch blocks.

Read More About Exceptions here:
  1. Exception Handling Introduction
  2. try catch finally in Java
  3. User Defined Exceptions in Java
  4. Throw vs throws 
  5. Final vs finally vs finalize()


Select Menu