Java – AppDividend https://appdividend.com Latest Code Tutorials Fri, 18 Oct 2019 11:01:10 -0400 en-US hourly 1 https://wordpress.org/?v=5.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Java – AppDividend https://appdividend.com 32 32 Java String replace Example | String replace() Function In Java https://appdividend.com/2019/10/18/java-string-replace-example-string-replace-function-in-java/ https://appdividend.com/2019/10/18/java-string-replace-example-string-replace-function-in-java/#respond Fri, 18 Oct 2019 10:41:03 +0000 http://localhost/wordpress/?p=12019 Java String replace Example | String replace() Function In Java

Java string replace method returns the string replacing all the old char or CharSequence to a new char or CharSequence. At times, it is required to replace some characters in a String with a new character. It might also be required to change an entire sequence of characters with a new sequence of characters, i.e., […]

The post Java String replace Example | String replace() Function In Java appeared first on AppDividend.

]]>
Java String replace Example | String replace() Function In Java

Java string replace method returns the string replacing all the old char or CharSequence to a new char or CharSequence. At times, it is required to replace some characters in a String with a new character. It might also be required to change an entire sequence of characters with a new sequence of characters, i.e., replacing an old CharSequence with a new CharSequence. The java.lang.String.replace() method is a built-in method of the String class designed just for this purpose.

Java String replace

Java string replace() method returns the new string resulting from replacing all occurrences of old characters in the string with new characters.

See the following figure.

 

Java String replace Example

Syntax

public String replace(char old, char new),

Where old is the character to be replaced and new is the character to be inserted in its place.

It returns a string by replacing every occurrence of old with new.

Internal Implementation

public String replace(char oldChar, char newChar) {
    if (oldChar != newChar) {
      int len = value.length;
      int i = -1;
      char[] val = value; /* avoid getfield opcode */

      while (++i < len) {
        if (val[i] == oldChar) {
          break;
        }
      }
      if (i < len) {
        char buf[] = new char[len];
        for (int j = 0; j < i; j++) {
          buf[j] = val[j];
        }
        while (i < len) {
          char c = val[i];
          buf[i] = (c == oldChar) ? newChar : c;
          i++;
        }
        return new String(buf, true);
      }
    }
    return this;
  }

Example1.java:

The following example demonstrates how the replace() method is used to change all occurrences of an old character with a new character.

public class Example1 {
  public static void main(String[] args) {
    System.out.println("This program will replace all occurences of 's' with 'z'");
    String s = new String("This is a demo string. This is s.");

    System.out.println(s);
    String s_new = new String();
    s_new = s.replace('s', 'z');

    System.out.println(s_new);

  }
}

Output

This program will replace all occurrences of ‘s’ with ‘z’
This is a demo string. This is s.
Thiz iz a demo ztring. Thiz iz z.

Here, java replace() method is used to replace all occurrences of the old character ‘s,’ replaced with the new character ‘z’.

Example2.java

Since JDK 1.5, Java also allows replacing an entire CharSequence with a new one. The following example demonstrates such a case:

public class Example2 {
  public static void main(String[] args) {
    String s = new String("He decided to go to New York.");
    System.out.println(s);

    String s2 = new String();
    s2 = s.replace("New York", "Moscow");
    System.out.println(s2);
  }
}

Output

He decided to go to New York.
He decided to go to Moscow.

Here, the sequence “New York” gets replaced with “Moscow”. Multiple occurrences of a sequence can be replaced in the same way. The same is demonstrated in the next example.

Example3.java

public class Example3 {
  public static void main(String[] args) {
    String s = new String("I had a bike. But I sold the bike to get a new bike.");
    System.out.println(s);

    String s2 = new String();
    s2 = s.replace("bike", "car");
    System.out.println(s2);
  }
}

See the output.

I had a bike. But I sold the bike to get a new bike.
I had a car. But I sold the car to get a new car.

Here, all occurrences of “bike” are replaced with “car” by using the replace() method.

In conclusion, the java.lang.String.replace() method is used to replace all the occurrences of a character/sequence of characters with a new character/sequence of characters.

Finally, String replace() Function In Java Tutorial is over.

Recommended Posts

Java String replaceAll function

Java String getBytes() Example

How To Convert String Characters To Lowercase

Java String toCharArray() Example

Java String indexOf() Example

The post Java String replace Example | String replace() Function In Java appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/18/java-string-replace-example-string-replace-function-in-java/feed/ 0
Java String replaceAll Example | replaceAll() Function In Java https://appdividend.com/2019/10/18/java-string-replaceall-example-replaceall-function-in-java/ https://appdividend.com/2019/10/18/java-string-replaceall-example-replaceall-function-in-java/#respond Fri, 18 Oct 2019 09:36:53 +0000 http://localhost/wordpress/?p=12007 Java String replaceAll Example

The Java String replaceAll function returns the string after it replaces each substring of that matches a given regular expression with a given replacement. Sometimes, it is required to replace more than just one character or one character sequence in a given String, and instead do the replacement on a larger part of the String. Java […]

The post Java String replaceAll Example | replaceAll() Function In Java appeared first on AppDividend.

]]>
Java String replaceAll Example

The Java String replaceAll function returns the string after it replaces each substring of that matches a given regular expression with a given replacement. Sometimes, it is required to replace more than just one character or one character sequence in a given String, and instead do the replacement on a larger part of the String.

Java String replaceAll

Java String has three types of Replace method

  1. replace
  2. replaceAll
  3. replaceFirst.

We will see replaceAll() function. 

The Java.lang.String.replaceAll() method takes in a regular expression (regex) and a replacement String as parameters and returns a string by replacing each substring of the initial string that matches the given regex with the replacement String. See the following method.

 

Java String replaceAll

See the following syntax.

public String replaceAll(String regex, String replacement)

Parameters: 

String regex – The String is matched to this regex.

String replacement – The matched regex is replaced with this replacement.

Returns:

The String after replacing each substring that matches the regex with the replacement.

Internal Implementation:

public String replaceAll(String regex, String replacement){
	return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

Examples: The starting examples demonstrate the similarities of the replaceAll() method with that of replace() method. The examples that follow describe the unique applicabilities of the replaceAll() method.

See the following method.

The following example demonstrates how the replaceAll() method can be used to change all occurrences of an old character with a new character, similar to that done by the replace() method.

public class Example1 {
	public static void main(String[] args) {
		String s1 = new String("aaa");
		System.out.println(s1);

		String s2 = new String();
		s2 = s1.replaceAll("a", "z");

		System.out.println(s2);
	}
}

Output

aaa
zzz

Example2.java:

The following example demonstrates how the replaceAll() method can be used to replace all occurrences of an old character sequence with a new one, similar to that done by the replace() method.

public class Example2 {
	public static void main(String[] args) {
		String s1 = new String("You don't know who I am. You clearly don't know who I am.");
		System.out.println(s1);

		String s2 = new String();
		s2 = s1.replaceAll("I am", "Heisenberg is");

		System.out.println(s2);
	}
}

Output

You don’t know who I am. You clearly don’t know who I am.
You don’t know who Heisenberg is. You clearly don’t know who Heisenberg is.

Example3.java

The following examples describes the use of the replaceAll() method in manipulating Strings using regex in different possible ways.

public class Example3 {
	public static void main(String[] args) {
		String s1 = new String("War of the worlds.");
		System.out.println(s1);

		String s2 = new String();
		s2 = s1.replaceAll("(.*)the", "Hello,");
		System.out.println(s2);
	}
}

Output

War of the worlds.
Hello, worlds.

Example4.java

public class Example4 {
	public static void main(String[] args) {
		String s1 = new String("A new world order.");
		System.out.println(s1);

		String s2 = new String();
		s2 = s1.replaceAll("world(.*)", "border.");
		System.out.println(s2);
	}
}

Output

A new world order.
A new border.

Example5.java

public class Example5 {
	public static void main(String[] args) {
		String s1 = new String("I am an old old man.");
		System.out.println(s1);
		String s2 = new String();
		s2 = s1.replaceAll("old(.*)", "new man.");
		System.out.println(s2);
	}
}

Output

I am an old old man.
I am a new man.

Example6.java

public class Example6 {
	public static void main(String[] args) {
		String s1 = new String("I am a old old man.");
		System.out.println(s1);

		String s2 = new String();
		s2 = s1.replaceAll("(.*)old", "new man.");
		System.out.println(s2);
	}
}

Output

I am an old old man.
new man. man.

These are the various ways in which the replaceAll() method can be used to manipulate Strings and take in a regular expression (regex) and a replacement String as parameters and return the String by replacing each substring of the initial string that matches the given regex with the replacement String.

throws PatternSyntaxException

Watch out that replaceAll() throws PatternSyntaxException if the regular expression’s syntax is invalid. In the given an example, “[” is an invalid regular expression.

public class Example7 {
	public static void main(String[] args) {
		String newStr = "krunal lathiya".replaceAll("[", "");
	}
}

Output

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0
[
^
    at java.util.regex.Pattern.error(Pattern.java:1955)
    at java.util.regex.Pattern.clazz(Pattern.java:2548)
    at java.util.regex.Pattern.sequence(Pattern.java:2063)
    at java.util.regex.Pattern.expr(Pattern.java:1996)
    at java.util.regex.Pattern.compile(Pattern.java:1696)
    at java.util.regex.Pattern.<init>(Pattern.java:1351)
    at java.util.regex.Pattern.compile(Pattern.java:1028)
    at java.lang.String.replaceAll(String.java:2210)
    at com.StringExample.main(StringExample.java:9)

Finally, Java String replaceAll Example | replaceAll() Function In Java Tutorial is over.

Recommended Posts

Java String Format Example

Java String getBytes() Example

How To Convert String Characters To Lowercase

Java String toCharArray() Example

Java String indexOf() Example

The post Java String replaceAll Example | replaceAll() Function In Java appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/18/java-string-replaceall-example-replaceall-function-in-java/feed/ 0
Java String Format Example | String Format In Java https://appdividend.com/2019/10/13/java-string-format-example-string-format-in-java/ https://appdividend.com/2019/10/13/java-string-format-example-string-format-in-java/#respond Sun, 13 Oct 2019 17:45:18 +0000 http://localhost/wordpress/?p=11999 Java String Format Example | String Format In Java

Java String Format Example | String Format In Java is today’s topic. The Java String format() method is used to return formatted strings using given locale, format, and arguments. If you don’t specify the locale in the String format() method, by default, it uses the Locale.getDefault() method. Using this method, we can concatenate the strings, […]

The post Java String Format Example | String Format In Java appeared first on AppDividend.

]]>
Java String Format Example | String Format In Java

Java String Format Example | String Format In Java is today’s topic. The Java String format() method is used to return formatted strings using given locale, format, and arguments. If you don’t specify the locale in the String format() method, by default, it uses the Locale.getDefault() method. Using this method, we can concatenate the strings, and at the same time, we can format the output concatenated strings.

Java String Format

The Java String format() method returns the formatted string by given locale, format, and arguments.

If you don’t specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.

The format() method of java language is like sprintf() function in c language and printf() method of java language.

See the following syntax.

public static String format(Locale loc, String form, Object... args)

Here on the above in syntax, the loc refers to the locale value to be applied on the format() method, form refers to the format of the output string, args refers to the number of arguments for the format string. It may be zero or more.

The method returns the formatted string.

Exception: This method has two types of exception; they are:

  1. NullPointerException -If the string format is null.
  2. IllegalFormatException – If the format specified is illegal or there are insufficient arguments in the method.

See the following code.

class JavaStrFormat {
    public static void main(String args[]) {
        String s = "Appdividend";
        // Concatenating the strings using format
        String s1 = String.format("Welcome to %s", s);
        System.out.println(s1);
        // Left Padding using format()
        int x = 15;
        String str2 = String.format("%05d", x);
        System.out.println(str2);
        // Float value using String format
        String str3 = String.format("%f", 16.10);
        System.out.println(str3);
        // Hexadecimal value using String format
        String str4 = String.format("%x", 189);
        System.out.println(str4);
        // Char value using String format
        String str5 = String.format("%c", 'P');
        System.out.println(str5);
        // Octal value using String format()
        String str6 = String.format("%o", 189);
        System.out.println(str6);
    }
}

See the output.

String Format In Java

 

Format Specifiers

Here is a quick reference to all the conversion specifiers supported:

SPECIFIER APPLIES TO OUTPUT
%a floating-point (except BigDecimal) Hex output of the floating-point number
%b Any type Returns “true” if non-null returns “false” if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Returns decimal Integer
%e floating point Returns decimal number in scientific notation
%f floating point Returns decimal number
%g floating point Returns decimal number, possibly in scientific notation depending on the precision and value.
%h any type Returns the Hex String of value from the hashCode() method.
 %n none Returns the Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Returns the Octal number
%s any type Returns String value
%t Date/Time (incl. long, Calendar, Date, and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint) Returns the Hex string.

 

Finally, String Format In Java Tutorial is over.

Recommended Posts

Java String getBytes() Example

How To Convert String Characters To Lowercase

Java String toCharArray() Example

Java String indexOf() Example

Java String compareTo Example

The post Java String Format Example | String Format In Java appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/13/java-string-format-example-string-format-in-java/feed/ 0
Java String getBytes() Example | Java getBytes() Function https://appdividend.com/2019/10/13/java-string-getbytes-example-java-getbytes-function/ https://appdividend.com/2019/10/13/java-string-getbytes-example-java-getbytes-function/#respond Sun, 13 Oct 2019 16:16:02 +0000 http://localhost/wordpress/?p=11988 Java String getBytes() Example | Java getBytes() Function

Java String getBytes() Example | Java getBytes() Function is today’s topic. Java String getByte() method helps us to encode a given string into a sequence of byte code and returns an array of bytes. It encodes the String into a sequence of bytes using the specified charset and returns the array of those bytes. It […]

The post Java String getBytes() Example | Java getBytes() Function appeared first on AppDividend.

]]>
Java String getBytes() Example | Java getBytes() Function

Java String getBytes() Example | Java getBytes() Function is today’s topic. Java String getByte() method helps us to encode a given string into a sequence of byte code and returns an array of bytes. It encodes the String into a sequence of bytes using the specified charset and returns the array of those bytes. It throws UnsupportedEncodingException – If the specified charset is not supported.

Java String getBytes()

The Java String getBytes Method encodes the string into the sequence of bytes using the user-specified charset, and it will store the result in the byte array.

The getBytes() function can be implemented in two ways:

public byte[] getBytes(String charsetName)

The method encodes a string into a sequence of bytes using some specified charset and returns the array of those bytes. If the specified charset is not supported, then it throws an exception called UnsupportedEncodingException.

See the following program of String getBytes().

import java.io.*;

class GetBytes {
    public static void main(String args[]) {

        String str = "Welcome to Appdividend";
        System.out.println("The String before conversion is : ");
        System.out.println(str);
        // converting the string into byte
        // using getBytes ( converts into ASCII values )
        byte[] arr = str.getBytes();

        // Displaying converted string after conversion
        System.out.println("The String after conversion is : ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]);
        }
        System.out.println("\n");
    }
}

See the following output.

 

Java String getBytes()

public byte[] getBytes()

It encodes the string using the default charset method. There is some default charset defined in Java, some of them are:

  1. US-ASCII: Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
  2. ISO-8859-1: ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
  3. UTF-8: Eight-bit UCS Transformation Format
  4. UTF-16BE: Sixteen-bit UCS Transformation Format, big-endian byte order
  5. UTF-16LE: Sixteen-bit UCS Transformation Format, little-endian byte order
  6. UTF-16: Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark.

See the following programing example of getBytes() function.

import java.io.*;

class GetBytes {
   public static void main(String args[]) {
      String str = new String("Welcome to Appdividend");
      byte[] array1 = str.getBytes();

      // Printing default charset encoding
      System.out.print("Default Charset encoding:");
      for (byte b : array1) {
         System.out.print(b);
      }
      // printing UTF-16 Charset encoding
      System.out.print("\nUTF-16 Charset encoding:");
      try {
         byte[] array2 = str.getBytes("UTF-16");
         for (byte b1 : array2) {
            System.out.print(b1);
         }
         // converting UTF-16BE encoding
         byte[] array3 = str.getBytes("UTF-16BE");
         System.out.print("\nUTF-16BE Charset encoding:");
         for (byte b2 : array3) {
            System.out.print(b2);
         }
         System.out.println("\n");
         // throwing exception
      } catch (UnsupportedEncodingException ex) {
         System.out.println("Unsupported character set" + ex);
      }
   }
}

See the output.

getBytes2

 

Finally, Java String getBytes() Example | Java getBytes() Function Tutorial is over.

Recommended Posts

How To Convert String Characters To Lowercase

Java String toCharArray() Example

Java String indexOf() Example

Java String compareTo Example

How to find string length In Java

The post Java String getBytes() Example | Java getBytes() Function appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/13/java-string-getbytes-example-java-getbytes-function/feed/ 0
Java String toLowerCase() | Convert String Characters To Lowercase https://appdividend.com/2019/10/12/java-string-tolowercase-convert-string-characters-to-lowercase/ https://appdividend.com/2019/10/12/java-string-tolowercase-convert-string-characters-to-lowercase/#respond Sat, 12 Oct 2019 11:34:20 +0000 http://localhost/wordpress/?p=11980 Java String toLowerCase() | Convert String Characters To Lowercase

In this example, How To Convert String Characters To Lowercase is today’s topic. Suppose you want to convert any string to all lower characters, then you have to use Java String toLowerCase() method. This method helps us to convert a string into all lowercase characters. Java String toLowerCase() The java string toLowerCase() method returns the string […]

The post Java String toLowerCase() | Convert String Characters To Lowercase appeared first on AppDividend.

]]>
Java String toLowerCase() | Convert String Characters To Lowercase

In this example, How To Convert String Characters To Lowercase is today’s topic. Suppose you want to convert any string to all lower characters, then you have to use Java String toLowerCase() method. This method helps us to convert a string into all lowercase characters.

Java String toLowerCase()

The java string toLowerCase() method returns the string in the lowercase letter. In other words, it converts all characters of the string into a lower case letter.

The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally uses the default locale.

Variants of Function

String toLowerCase():

The toLowerCase() method gets the current value of the default locale using toLowerCase (Locale.getDefault()) method for the instance of the Java Virtual Machine.

This Java Virtual Machine sets default locale during the start of the host environment. However, it can be changed using the setDefault() method.

Syntax

public String toLowerCase()

See the following program.

class LowerCase {
	public static void main(String args[]) {
		// initializing the string
		String s = "Welcome to APPDIVIDEND";
		// converting string s to lowercase letter
		String str = s.toLowerCase();
		System.out.println(str);
	}
}

See the output.

 

Java String toLowerCase()

String toLowerCase(Locale locale)

The toLowerCase(Locale locale) method converts the string into LowerCase using the rules defined by some specified Locale.

Syntax

public String toLowerCase(Locale loc)

Here loc converts all characters into lowercase value using the rules defined in Locale.

See the following program.

import java.util.Locale;

class LowerCase {
	public static void main(String args[]) {
		// initializing the string
		String s = "Welcome to APPDIVIDEND.";
		// converting string s to lowercase letter using Locale method
		String eng = s.toLowerCase(Locale.ENGLISH);
		System.out.println(eng);
		String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i without dot
		System.out.println(turkish);
	}
}

See the output.

 

Convert String Characters To Lowercase

Finally, How To Convert String Characters To Lowercase Tutorial With Example is over.

Recommended Posts

Java String toUpperCase() Example

How To Find String Length In Python

Java String toCharArray() Example

Java String compareTo Example

How to find string length In Java

The post Java String toLowerCase() | Convert String Characters To Lowercase appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/12/java-string-tolowercase-convert-string-characters-to-lowercase/feed/ 0
Java String toCharArray() Example | Java toCharArray() Function https://appdividend.com/2019/10/12/java-string-tochararray-example-java-tochararray-function/ https://appdividend.com/2019/10/12/java-string-tochararray-example-java-tochararray-function/#respond Sat, 12 Oct 2019 10:48:46 +0000 http://localhost/wordpress/?p=11973 Java toCharArray() Function Example

Java String toCharArray() Example | Java toCharArray() Function is today’s topic. The method is used to return a sequence of into an array of characters. The length of the array is equal to the length of the string. The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is […]

The post Java String toCharArray() Example | Java toCharArray() Function appeared first on AppDividend.

]]>
Java toCharArray() Function Example

Java String toCharArray() Example | Java toCharArray() Function is today’s topic. The method is used to return a sequence of into an array of characters. The length of the array is equal to the length of the string. The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string.

Java String toCharArray()

The method returns an Array of chars after converting a String into a sequence of characters. The returned array length is equal to the length of the String, and the sequence of chars in Array matches the sequence of characters in the String.

Syntax

public char[] toCharArray()

See the following code example.

class Chararr {
	public static void main(String args[]) {
		// initializing the string
		String str = "Appdividend";
		// converting the string into character array
		char[] ch = str.toCharArray();
		// printing array values
		for (int i = 0; i < ch.length; i++) {
			System.out.print(ch[i] + " ");
		}
		System.out.println("\n");
	}
}

See the output.

Java toCharArray() Function

Convert String to char in Java

The string class has three methods related to char. Let’s look at them before we look at a java program to convert string to char array.

char[] toCharArray()

The method converts string to a character array. The char array size is the same as the length of the string.

char charAt(int index)

This method returns character at a specific index of string. This method throws StringIndexOutOfBoundsException if the index argument value is negative or greater than the length of the string.

getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

This is a beneficial method when you want to convert part of the string to a character array. First, two parameters define the start and end index of the string; the last character to be copied is at index srcEnd-1.  The characters are copied into the char array starting at index dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.

See the following program.

class Chararr {
	public static void main(String[] args) {
		String str = "Jesse Pinkman";
		
		//string to char array
		char[] chars = str.toCharArray();
		System.out.println(chars.length);
		
		//char at specific index
		char c = str.charAt(2);
		System.out.println(c);
		
		//Copy string characters to char array
		char[] chars1 = new char[7];
		str.getChars(0, 7, chars1, 0);
		System.out.println(chars1);
		
	}
}

See the output.

➜  java javac Chararr.java
➜  java java Chararr
13
s
Jesse P
➜  java

Finally, Java String toCharArray() Example | Java toCharArray() Function is over.

Recommended Posts

Java String indexOf() Example

Java String compareTo Example

Java String valueOf() Example

How to find string length In Java

Java Trim String Example

The post Java String toCharArray() Example | Java toCharArray() Function appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/12/java-string-tochararray-example-java-tochararray-function/feed/ 0
Java String indexOf() Example | Java indexOf() Function https://appdividend.com/2019/10/12/java-string-indexof-example-java-indexof-function/ https://appdividend.com/2019/10/12/java-string-indexof-example-java-indexof-function/#respond Sat, 12 Oct 2019 10:11:25 +0000 http://localhost/wordpress/?p=11961 Java String indexOf() Example | Java indexOf() Function

Java String indexOf() Example | Java indexOf() Function is today’s topic. The java string indexOf() method returns the index of given character value or substring. If it is not found, then it returns -1. The index counter starts from zero. The indexOf method is used to get the integer value of a particular index of […]

The post Java String indexOf() Example | Java indexOf() Function appeared first on AppDividend.

]]>
Java String indexOf() Example | Java indexOf() Function

Java String indexOf() Example | Java indexOf() Function is today’s topic. The java string indexOf() method returns the index of given character value or substring. If it is not found, then it returns -1. The index counter starts from zero. The indexOf method is used to get the integer value of a particular index of String type object, based on criteria specified in the parameters of the IndexOf method.

Java String indexOf()

A common scenario can be when a system admin wants to find the index of the ‘@’ character of the email Id of a client and then wants to get the remaining substring. In that situation, the IndexOf method can be used.

Types of indexOf method

String indexOf( char ch):

The indexOf(char ch) method returns the index of the first occurrence of the given character, if it is not present there, it returns -1.

Syntax

stringName.indexOf(character)

Here stringName is the string from which you want to find the index of the character, and character means that character whose index you want to find.

See the following program.

class IndexOfStr {
	public static void main(String args[]) {
		String str = "Welcome to Appdividend";
		System.out.print("First occurence of 'd' in the string is: ");
		// we are finding the index of 'd'
		// it will return the index of first
		// occurence of 'd'
		System.out.println(str.indexOf('d'));

	}
}

See the output.

 

Java indexOf() Function

String indexOf(char ch, int x)

The indexOf() method returns an index of the given character present in a string, but it starts searching its position at index x. If it cannot find the index of the character, it returns -1.

Syntax

int indexOf(int ch, int start)

Here ch is the character whose position we want to find, and start is the index starting from where we want to find the index of ch.

See the following code.

class IndexOfStr {
	public static void main(String args[]) {
		String str = "Welcome to Appdividend";
		System.out.print("First occurence of 'd' after index 15 is: ");
		// we are finding the index of 'd'
		// it will return the index of d
		// after index position 15
		System.out.println(str.indexOf('d', 15));

	}
}

See the output.

 

Java String indexOf() Example

String indexOf(String str)

The indexOf(String str) method returns an index of the first occurrence of the substring from a given string.

Syntax

int indexOf(String str)

Here str is the substring whose index we want to find from the given string.

class IndexOfStr {
	public static void main(String args[]) {
		String str = "I like Apple. What do you like?";
		System.out.print("First occurence of 'like' in the string is: ");
		// Initialising search string
		String substr = new String("like");
		// we are finding the index of 'like'
		// it will return the index of first
		// occurence of 'like'
		System.out.println(str.indexOf(substr));

	}
}

See the output.

 

indexof3

String indexOf(String str, int x)

The indexOf() method returns the index of the given substring but starting from the given index x. This means after index position x, and it will return the first occurrence of the given substring.

Syntax

int indexOf(String str, int x)

Here str is the character whose position we want to find, and x is the index starting from where we want to find the index of str.

See the program.

class IndexOfStr {
	public static void main(String args[]) {
		String str = "I like Apple. What do you like?";
		System.out.print("First occurence of 'like' after index 7 is: ");
		// Initialising search string
		String substr = new String("like");
		// we are finding the index of 'like'
		// it will return the index of first
		// occurence of 'like'
		System.out.println(str.indexOf(substr, 7));

	}
}

See the output.

 

indexof4

Finally, Java String indexOf() Example | Java indexOf() Function is over.

Recommended Posts

Java String compareTo Example

How to find string length In Java

Java String toUpperCase() Example

Java Trim String Example

Java String valueOf() Example

The post Java String indexOf() Example | Java indexOf() Function appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/12/java-string-indexof-example-java-indexof-function/feed/ 0
Java String compareTo Example | String compareTo() Function https://appdividend.com/2019/10/12/java-string-compareto-example-string-compareto-function/ https://appdividend.com/2019/10/12/java-string-compareto-example-string-compareto-function/#respond Sat, 12 Oct 2019 09:04:16 +0000 http://localhost/wordpress/?p=11947 Java String compareTo Example | String compareTo() Function

Java String compareTo Example | String compareTo() Function is today’s topic. Java String compareTo() method is used to compare two strings lexicographically where each character of both the strings are converted into a Unicode value. The Java String compareTo() method is used for comparing the two strings lexicographically. Each character of both the strings is converted […]

The post Java String compareTo Example | String compareTo() Function appeared first on AppDividend.

]]>
Java String compareTo Example | String compareTo() Function

Java String compareTo Example | String compareTo() Function is today’s topic. Java String compareTo() method is used to compare two strings lexicographically where each character of both the strings are converted into a Unicode value. The Java String compareTo() method is used for comparing the two strings lexicographically.

Each character of both the strings is converted into the Unicode value for comparison. If both strings are equal, then this method returns 0; otherwise, it returns the positive or negative value.

Java String compareTo

The compareTo() method returns three types of value, if both the string is equal, then it returns 0, if the first string is lexicographically greater than the second string then it returns a positive value, if the second string is lexicographically greater than the first one, then it returns a negative value.

Variants of Function

There are three variants of this method; they are:

int compareTo(Object obj):

The compareTo() method compares one string with another string object.

Syntax

int compareTo(Object obj)

Here obj is the string object to be compared.

Here the comparison is between the string and the object.

For example, string1.compareTo(“Just a String object”) where string1 is the literal and its values are compared with the string specified in the method argument.

See the following program.

class CompareToStr {
	public static void main(String args[]) {
		// Initializing the string
		String str = "Appdividend";
		// Declaring string object
		String str1 = new String("Appdividend"); // str1 is the object
		String str2 = new String("appdividend"); // str2 is the object
		System.out.print("Difference between Appdividend and str1 is: ");
		System.out.println(str.compareTo(str1));

		System.out.print("Difference between Appdividend and str2 is: ");
		System.out.println(str.compareTo(str2));
	}
}

See the output.

Java String compareTo

int compareTo(String anotherString)

The method works like the same of the above method, but the difference is it compares with another string lexicographically.

Syntax

int compareTo(String anotherString)

Here anotherString indicates another string with which the first string to be compared.

class CompareToStr {
	public static void main(String args[]) {
		// Initializing the string
		String str = "Appdividend";
		// Declaring another string
		String str1 = "Appdividend"; // str1 is the string
		String str2 = "appdividend"; // str2 is the string
		System.out.print("Difference between Appdividend and str1 is: ");
		System.out.println(str.compareTo(str1));

		System.out.print("Difference between Appdividend and str2 is: ");
		System.out.println(str.compareTo(str2));
	}
}

See the output.

 

compare2

int compareToIgnoreCase(String str)

The method is used to compare two strings but ignoring case differences. This means it ignores the uppercase and lowercase of a string.

Syntax

int compareToIgnoreCase(String str)

Here str is the string with which we have to compare.

See the following program.

class CompareToStr {
	public static void main(String args[]) {
		// Initializing the string
		String str = "Appdividend";
		// Declaring another string
		String str1 = "Appdividend"; // str1 is the string
		String str2 = "appdividend"; // str2 is the string
		System.out.print("Difference between Appdividend and str1 is: ");
		// it will print 0
		System.out.println(str.compareToIgnoreCase(str1));

		System.out.print("Difference between Appdividend and str2 is: ");
		// it will print 0
		System.out.println(str.compareToIgnoreCase(str2));
	}
}

See the output.

 

compare3

How to find length of string using String compareTo() method

Here we will see an interesting example of how to use the compareTo() method to find the length of the string.

If we compare the string with the empty string using the compareTo() method, then a method would return the length of the non-empty string.

class CompareToStr {
	public static void main(String args[]) {
		// Initializing the string
		String str1 = "Aaron Paul";
		String str2 = ""; // empty string

		// it would return the length of str1 in positive number
		System.out.println(str1.compareTo(str2));

		// it would return the length of str1 in negative number
		System.out.println(str2.compareTo(str1));
	}
}

See the output.

➜  java java CompareToStr
10
-10
➜  java

In the above code example, the second compareTo() statement returned the length in a negative number because we have compared an empty string with str1 while in the first compareTo() statement, we have compared str1 with an empty string.

Is Java String compareTo() method case sensitive

In this example, we compare the two strings using the compareTo() method. Both the strings are the same; however, one of the string is in uppercase, and the other string is in lowercase.

class CompareToStr {
	public static void main(String args[]) {
		//uppercase
		String str1 = "BREAKING BAD";
		//lowercase
		String str2 = "breaking bad";

		System.out.println(str1.compareTo(str2));
	}
}

See the output.

➜  java javac CompareToStr.java
➜  java java CompareToStr
-32
➜  java

As you can see that the output is not zero, which means that the compareTo() method is case sensitive. However, we do have the case insensitive compare method in the String class.

Finally, Java String compareTo Example | String compareTo() Function is over.

Recommended Posts

How to find string length In Java

Java String toUpperCase() Example

Java Trim String Example

Java String valueOf() Example

Java String getchars() Method

The post Java String compareTo Example | String compareTo() Function appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/12/java-string-compareto-example-string-compareto-function/feed/ 0
Java String length() | How To Find String Length In Java https://appdividend.com/2019/10/12/java-string-length-how-to-find-string-length-in-java/ https://appdividend.com/2019/10/12/java-string-length-how-to-find-string-length-in-java/#respond Sat, 12 Oct 2019 07:25:30 +0000 http://localhost/wordpress/?p=11932 Java String length() | How To Find String Length In Java

In this example, we will see how to find string length In Java. Often, it is required to find out the length of a String, and for such scenarios, Java provides the in-built java.lang.String.length() method. Length of the String is essentially the number of 16-bit Unicode characters it contains. In the case of an empty […]

The post Java String length() | How To Find String Length In Java appeared first on AppDividend.

]]>
Java String length() | How To Find String Length In Java

In this example, we will see how to find string length In Java. Often, it is required to find out the length of a String, and for such scenarios, Java provides the in-built java.lang.String.length() method. Length of the String is essentially the number of 16-bit Unicode characters it contains. In the case of an empty String, it contains zero characters. However, in the case of a null string, this method will throw NullPointerException.

 

Java String length()

Java String length()

The function is used to get the length of a Java String.

The string length method returns the number of characters written in the String.

The method returns the length of any string, which is equal to the number of 16-bit Unicode characters in the string.

See the following syntax of Java String length().

Syntax

public int length()

Returns: Number of characters in the String.

The following examples show the use of the length() method.

public class StrLen {
	public static void main(String[] args) {
		String str1 = "Millie Bobby Brown";

		System.out.println(str1.length());
	}
}

See the output.

➜  java javac StrLen.java
➜  java java StrLen
18
➜  java

NullPointerException

Let’s find the length of the null value of the string.

public class StrLen {
	public static void main(String[] args) {
		String str1 = null;

		System.out.println(str1.length());
	}
}

See the output.

➜  java javac StrLen.java
➜  java java StrLen
Exception in thread "main" java.lang.NullPointerException
	at StrLen.main(StrLen.java:5)
➜  java
When calling length() method for a null String straight away throws a NullPointerException.

Demonstrates the use of length() method for an empty String

See the following program of finding a length of the empty string in Java.

public class StrLen {
	public static void main(String[] args) {
		String str1 = "";

		System.out.println(str1.length());
	}
}

See the output.

➜  java javac StrLen.java
➜  java java StrLen
0
➜  java

Demonstrates the use of length() method while iterating in a loop

See the following code.

public class StrLen {
	public static void main(String[] args) {
		String str1 = "El Camino";

		for (int i = 0; i < str1.length(); i++) {
			System.out.println(str1.charAt(i));
		}
	}
}

See the output.

➜  java javac StrLen.java
➜  java java StrLen
E
l

C
a
m
i
n
o
➜  java

In the above example, the length() method has been used to determine how many times the loop should run to print all the characters of the String turn by turn. Here, the charAt(int i) method returns the character at index i.

This is how the length() method can be used in various programming constructs to obtain desirable outcomes.

What is the complexity of length() function in String class of Java

It is 0(1) as the length is already known to String instance.

From JDK 1.6, it is visible.

public int length() {
    return count;
}

It is essential to understand why they can cache the value of count and keep using the same value for the count. The reason lies in the great decision they took when designing String, its Immutability.

Finally, How To Find String Length In Java Tutorial Example is over.

Recommended Posts

Java String toUpperCase() Example

Java Trim String Example

Java String valueOf() Example

Java String getchars() Method

Hashing In Java Example

The post Java String length() | How To Find String Length In Java appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/12/java-string-length-how-to-find-string-length-in-java/feed/ 0
Java String toUpperCase() Example Tutorial https://appdividend.com/2019/10/11/java-string-touppercase-example-tutorial/ https://appdividend.com/2019/10/11/java-string-touppercase-example-tutorial/#respond Fri, 11 Oct 2019 12:05:01 +0000 http://localhost/wordpress/?p=11924 Java String toUpperCase() Example Tutorial

Java String toUpperCase() Example Tutorial is today’s topic. Suppose you want to convert any string to all lower characters, then you have to use Java String toUpperCase() method. This method helps us to convert a string into all lowercase characters. The java string toUpperCase() method returns the string in the uppercase letter. In other words, it […]

The post Java String toUpperCase() Example Tutorial appeared first on AppDividend.

]]>
Java String toUpperCase() Example Tutorial

Java String toUpperCase() Example Tutorial is today’s topic. Suppose you want to convert any string to all lower characters, then you have to use Java String toUpperCase() method. This method helps us to convert a string into all lowercase characters. The java string toUpperCase() method returns the string in the uppercase letter. In other words, it converts all characters of the string into an upper case letter.

Java String toUpperCase()

The toUpperCase() method has two variants.

The first variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.getDefault()).

Variants

This method has two variants they are:

String toUpperCase():

This method gets the current value of the default locale using toUpperCase (Locale.getDefault()) method for the instance of the Java Virtual Machine. This Java Virtual Machine sets default locale during the start of the host environment. However, it can be changed using the setDefault() method.

Syntax: 
public String toUpperCase()

See the following program.

class Upper {
	public static void main(String args[]) {
		// initializing the string
		String s = "Welcome to APPDIVIDEND";
		// converting string s to uppercase letter
		String str = s.toUpperCase();
		System.out.println(str);
	}
}

See the output.

 

Java String toUpperCase()

String toUpperCase(Locale locale)

The method converts a string into UpperCase using the rules defined by some specified Locale.

Syntax: 

public String toUpperCase(Locale loc)

Here loc converts all characters into uppercase value using the rules defined in Locale.

See the following program.

import java.util.Locale;

class Upper {
    public static void main(String args[]) {
        // initializing the string
        String s = "Welcome to appdividenD.";
        // converting string s to uppercase letter using Locale method
        String eng = s.toUpperCase(Locale.ENGLISH);
        System.out.println(eng);
        String turkish = s.toUpperCase(Locale.forLanguageTag("tr")); // It shows i without dot
        System.out.println(turkish);
    }
}

See the output.

 

Java String toUpperCase() Example

toUpperCase(Locale locale) Method

See the following code example.

import java.util.Locale;

public class StringUpper {
    public static void main(String[] args) {
        String s = "Breaking Bad";
        String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
        String english = s.toUpperCase(Locale.forLanguageTag("en"));
        System.out.println(turkish);// will print I with dot on upper side
        System.out.println(english);
    }
}

See the output.

➜  java javac StringUpper.java
➜  java java StringUpper
BREAKİNG BAD
BREAKING BAD
➜  java

Finally, Java String toUpperCase() Example Tutorial is over.

Recommended Posts

Java Trim String Example

The valueOf() Function In Java

Java String Contains Example

Java String getchars() Method

Concat() In Java Example

The post Java String toUpperCase() Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/10/11/java-string-touppercase-example-tutorial/feed/ 0