Tuesday, June 25, 2019

Java finally blocks usees or limitations.

Java finally blocks usees or limitations. 


YouTube Video >> 


  • Java finally block is a block that is used to execute important codes such as closing connection, stream, etc.
  • Java finally block is always executed whether an exception is handled or not.
  • Java finally blocks follows try or catch block.
java finally


Rule: For each try block there can be zero or more catch blocks, but only one finally block. 


=====================================================================

Limitations:-


Note: The final block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). 


check Code:

package interviewQuestion;

public class FinallyBlockUseAndLimitation {

public static void main(String[] args) {

System.out.println("Before Exit");
// program exits by calling System.exit()

System.exit(0);


try {
int data = 25 / 0;
System.out.println(data);
}
catch (NullPointerException e) {
System.out.println(e);
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");

System.out.println("Without Exit");
}

}

Monday, June 10, 2019

How to find Palindrome string??

Q. How to find the Palindrome string??



In this program, we need to check whether a given string is a palindrome or not.
  1. Kayak  

What is Palindrome ?? 

A string is said to be palindrome if it reads the same backward as forward. For e.g. above string is a palindrome because if we try to read it from backward, it is same as forward. One of the approach to check this is iterate through the string till middle of string and compare a character from back and forth.

Algorithm

  1. Define a string.
  2. Define a variable flag and set it to true.
  3. Convert the string to lowercase to make the comparison case-insensitive.
  4. Now, iterate through the string forward and backward, compare one character at a time till middle of the string is reached.
  5. If any of the character doesn't match, set the flag to false and break the loop. 
  6. At the end of the loop, if flag is true, it signifies string is a palindrome.
  7. If flag is false, then string is not a palindrome.

JAVA code:



  1. public class Palindrome {
    public static void main(String[] args) {
    String string = "Kayaka";
    boolean flag = true;
    string = string.toLowerCase();

    for (int i = 0; i < string.length() / 2; i++) {
    if (string.charAt(i) != string.charAt(string.length() - i - 1)) {
    flag = false;
    break;
    }
    }
    if (flag)
    System.out.println("Given string is palindrome");
    else
    System.out.println("Given string is not a palindrome");
    }

    }

Thursday, June 6, 2019

Extract All Numbers from a String

Extract All Numbers from a String

package com.testingexcellence.tutorials;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExamples {
    public static void main(String[]args) {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher("string1234more567string890");
        while(m.find()) {
            System.out.println(m.group());
        }
    }
}
Output:

1234
567
890

Wednesday, June 5, 2019

Regular Expression

Java Regex

The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.


USE:
It is widely used to define the constraint on strings such as password and email validation. After learning the Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.


The java.util.regex package provides the following classes and interfaces for regular expressions.
  1. MatchResult interface
  2. Matcher class
  3. Pattern class
  4. PatternSyntaxException class


The regular expression metacharacters work as shortcodes.



RegexDescription
.Any character (may or may not match terminator)
\dAny digits, short of [0-9]
\DAny non-digit, short for [^0-9]
\sAny whitespace character, short for [\t\n\x0B\f\r]
\SAny non-whitespace character, short for [^\s]
\wAny word character, short for [a-zA-Z_0-9]
\WAny non-word character, short for [^\w]
\bA word boundary
\BA non word boundary




Q. How to Extract AllNumbers from a String ??


  1. package Java_String;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;

  4. public class ExtractAllNumbersfromString {
  5. static int finalsum=0;
  6. static String str = "ram101shyam320mohan420modi108rahul99";

  7.     public static void main(String[]args) {
  8.        
  9. //     static Pattern compile(String regex) compiles the given regex and returns the instance of the Pattern.

  10.     Pattern p = Pattern.compile("\\d+");   // ''\\d+'' regex matchcharacter Any digits, short of [0-9]

  11.        
  12. //     Matcher matcher(CharSequence input) creates a matcher that matches the given input with the pattern.
  13.     Matcher m = p.matcher(str); 
  14.        
  15.        
  16.         while(m.find()) {
  17.        
  18. //         String group() returns the matched subsequence.
  19. //             System.out.println(m.group());  // this will give number in String
  20.            
  21.             int add = Integer.parseInt(m.group()); // this will give number in Integer
  22.            
  23.             System.out.println(add);
  24.            
  25.             finalsum += add;  // this will add all group of integer number.
  26.            
  27.         }
  28.         System.out.println("Sum of all above number is  "+finalsum );
  29.     }
  30. }




Monday, June 3, 2019

Reverse words in a given String in Java

Q. To Reverse words in a given String in Java


Input : "Welcome to geeksforgeeks"
Output : "geeksforgeeks to Welcome"

Input : "I love Java Programming"
Output :"Programming Java love I"


===========================================

YouTube video:-



Our code :
  • Example No.1
  1. import java.util.regex.Pattern;
  2. public class ReverseOfWordPart2 {
  3. static String rev = "";
  4.    public static void main(String[] args) {
  5.       String str = "the sky is blue in india";
  6.   
  7.       System.out.println("The original string is: " + str);
  8.       
  9.       Pattern p = Pattern.compile("\\s");
  10.       
  11.       String[] temp = p.split(str);
  12.       
  13.       
  14.       for (int i = 0; i < temp.length; i++) {
  15.         
  16.             rev = " " + temp[i] + rev;
  17.       }
  18.       System.out.println("The reversed string is: " + rev);
  19.    }
  20. }
O/P
The original string is: the sky is blue in india
The reversed string is:  india in blue is sky the
=============================================================================
  • Example No.2
  1. // Java Program to reverse a String // without using inbuilt String function 
  1. import java.util.regex.Pattern; 
  2. public class ReverseOfWord { 
  3. // Method to reverse words of a String 
  4. static String reverseWords(String str) 
  5. { 
  6. // Specifying the pattern to be searched 
  7. Pattern pattern = Pattern.compile("\\s"); 
  8. // splitting String str with a pattern 
  9. // (i.e )splitting the string whenever their 
  10. // is whitespace and store in temp array. 
  11. String[] temp = pattern.split(str); 
  12. String result = ""; 
  13. // Iterate over the temp array and store 
  14. // the string in reverse order. 
  15. for (int i = 0; i < temp.length; i++) { 
  16. if (i == temp.length - 1) 
  17. result = temp[i] + result; 
  18. else
  19. result = " " + temp[i] + result; 
  20. } 
  21. return result; 
  22. } 
  23. // Driver methods to test above method 
  24. public static void main(String[] args) 
  25. { 
  26. String s1 = "Welcome to geeksforgeeks"; 
  27. System.out.println(reverseWords(s1)); 
  28. String s2 = "I love Java Programming"; 
  29. System.out.println(reverseWords(s2)); 
  30. } 
  31. } 






Sunday, June 2, 2019

Java String equals()

 

Introduction:-

The Java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

 

Example:

public class EqualsExample{
public static void main(String args[]){
String s1="automationworld";
String s2="automationworld";
String s3="AUTOMATIONWORLD";
String s4="manualworld";
System.out.println(s1.equals(s2));      //true because content and case is same
System.out.println(s1.equals(s3));     //false because case is not same
System.out.println(s1.equals(s4));    //false because content is not same
}}

 

  • The equals() method compares two strings and can be used in the if-else control structure.
  • public class EqualsExample {
        public static void main(String[] args) {
            String s1 = "automation"
            String s2 = "automation"
            String s3 = "Automation";
            System.out.println(s1.equals(s2)); // True because content is same  
            if (s1.equals(s3)) {
                System.out.println("both strings are equal");
            }else System.out.println("both strings are unequal");  
        }

     

 

 

 Test the equality of string present in the list.

import java.util.ArrayList;
public class EqualsExample3 {
    public static void main(String[] args) {
        String str1 = "Mukesh";
        ArrayList<String> list = new ArrayList<>();
        list.add("Ravi");
        list.add("Mukesh");
        list.add("Ramesh");
        list.add("Ajay");
        for (String str : list) {
            if (str.equals(str1)) {
                System.out.println("Mukesh is present");
            }
        }
    }
}


o/p
Mukesh is present
 
 
  • Difference between == and .equals() method in Java

     
 public class equalMethod {
 public static void main(String[] args) {
  
  
  String s = "Hello";
  String s1 = "Hello";
  String s2 = "hello";
   System.out.println(s==s1);    //true : literal String are equals
   System.out.println(s.equals(s1));       //true
   System.out.println(s1.equals(s2));   //false
   System.out.println(s1.equalsIgnoreCase(s2));  //true
   System.out.println(s.equalsIgnoreCase(s2));  //true
   
   
   String s3 = new String("Hello");
   String s4 = new String("Hello");
   
   System.out.println(s3==s4);    //false  // String with new keyword are not equals
   System.out.println(s3.equals(s4));   //true 
   
   
         System.out.println('a' == 97.0);   //true it will compare unicode value of 'a' that is 97 
   
         System.out.println('a' == 'a');
         System.out.println('a' == 'A');