Posts

Showing posts from April, 2021

Java Basics:String Methods-4

  Java String matches() The Java String matches() method checks whether the string matches the given regular expression or not. The syntax of the string  matches()  method is: string.matches(String regex) Here,  string  is an object of the  String  class. matches() Parameters The  matches()  method takes a single parameter. regex  - a regular expression matches() Return Value returns true  if the regex matches the string returns false  if the regex doesn't match the string Example 1: Java matches() class Main { public static void main (String[] args) { // a regex pattern for // five letter string that starts with 'a' and end with 's' String regex = "^a...s$" ; System.out.println( "abs" .matches(regex)); // false System.out.println( "alias" .matches(regex)); // true System.out.println( "an abacus" .matches(regex)); // false System.out.println( "abyss" .matches(regex)); // tru

Java Basics:String methods-3

  Java String charAt() The Java String charAt() method returns the character at the specified index. The syntax of the string  charAt()  method is: string.charAt( int index) Here,  string  is an object of the  String  class. charAt() Parameters index  - the index of the character (an  int  value) charAt() Return Value returns the character at the specified  index Note:  If the index passed to  chartAt()  is negative or out of bounds, it throws an exception. Example: Java String charAt() class Main { public static void main (String[] args) { String str1 = "Learn Java" ; String str2 = "Learn\nJava" ; // first character System.out.println(str1.charAt( 0 )); // 'L' // seventh character System.out.println(str1.charAt( 6 )); // 'J' // sixth character System.out.println(str2.charAt( 5 )); // '\n' } } In Java, the index of Strings starts from 0, not 1. That's why  chartAt(0)  returns the first c