java strings - coderz.py https://coderzpy.com Keep Coding Keep Cheering! Fri, 17 Jun 2022 22:08:48 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://coderzpy.com/wp-content/uploads/2022/08/cropped-image1-1-32x32.jpg java strings - coderz.py https://coderzpy.com 32 32 Strings in Java https://coderzpy.com/strings-in-java/ https://coderzpy.com/strings-in-java/#respond Sat, 11 Jun 2022 15:04:14 +0000 http://coderzpy.com/?p=1588 Strings are Objects in Java that are internally backed by a char array. They are immutable because arrays are immutable ...

The post Strings in Java first appeared on coderz.py.

]]>
Strings are Objects in Java that are internally backed by a char array. They are immutable because arrays are immutable (they can’t grow). Every time you make a change to a String, a new String is created.

An array of characters functions similarly to a Java string. Consider the following scenario:

char[] ch={'c','o','d','e','r','z','p','y'};  
String s=new String(ch);  

is the same as:

String s="coderzpy";  

The Serializable, Comparable, and CharSequence interfaces are implemented by the Java String class, as shown in the diagram below.

String in Java
Interface for CharSequences:


To represent a sequence of characters, the CharSequence interface is used. It is implemented by the String, StringBuffer, and StringBuilder classes. This means that these three classes can be used to create strings in Java.

Memory allotment of String

A String Object will be created in the string constant pool whenever it is created as a literal. This allows JVM to optimize String literal initialization.

The string can also be dynamically allocated by using the new operator. Strings that are dynamically allocated are given a new memory location in the heap. The string constant pool will not include this string.

For instance:

String str = new String("Coderzy");
Example to declare String :
// Java code to illustrate String
import java.io.*;
import java.lang.*;

class Test {
	public static void main(String[] args)
	{
		// Declare String without using new operator
		String s = "student at";

		// Prints the String.
		System.out.println("String s = " + s);

		// Declare String using new operator
		String s1 = new String("Coderzpy");

		// Prints the String.
		System.out.println("String s1 = " + s1);
	}
}
Output:
String s = student at
String s1 = Coderzpy

Note: also read about the Interface vs Abstract class

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

The post Strings in Java first appeared on coderz.py.

]]>
https://coderzpy.com/strings-in-java/feed/ 0
String class methods in Java https://coderzpy.com/string-class-methods-in-java/ https://coderzpy.com/string-class-methods-in-java/#respond Sat, 11 Jun 2022 15:17:48 +0000 http://coderzpy.com/?p=1590 Many useful methods for performing operations on a sequence of char values are available in the java.lang.String class. No. Method ...

The post String class methods in Java first appeared on coderz.py.

]]>
Many useful methods for performing operations on a sequence of char values are available in the java.lang.String class.

No.MethodDescription
1char charAt(int index)It returns the char value for the given index.
2int length()It returns the string length.
3static String format(String format, Object… args)It returns a formatted string.
4static String format(Locale l, String format, Object… args)It returns a formatted string in the locale specified.
5String substring(int beginIndex)For a given begin index, it returns a substring.
6String substring(int beginIndex, int endIndex)It returns substring for the given begin index and end index.
7boolean contains(CharSequence s)After matching the sequence of char values, it returns true or false.
8static String join(CharSequence delimiter, CharSequence… elements)It returns a joined string.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)It returns a joined string.
10boolean equals(Object another)It compares the string to the given object to see if they are equal.
11boolean isEmpty()It determines if the string is empty.
12String concat(String str)The specified string is concatenated.
13String replace(char old, char new)All occurrences of the specified char value are replaced.
14String replace(CharSequence old, CharSequence new)It replaces all occurrences of the specified CharSequence.
15static String equalsIgnoreCase(String another)It makes a comparison with another string. It does not perform a case check.
16String[] split(String regex)It returns a split string that matches the regex pattern.
17String[] split(String regex, int limit)It returns a split string matching regex and limit.
18String intern()It returns an interned string.
19int indexOf(int ch)It returns the specified char value index.
20int indexOf(int ch, int fromIndex)It starts with the given index and returns the specified char value index.
21int indexOf(String substring)It returns the specified substring index.
22int indexOf(String substring, int fromIndex)It returns the specified substring index starting with the given index.
23String toLowerCase()It returns a string in lowercase.
24String toLowerCase(Locale l)It returns a string in lowercase using a specified locale.
25String toUpperCase()It returns a string in uppercase.
26String toUpperCase(Locale l)It returns an uppercase string in the specified locale.
27String trim()It removes the beginning and ending spaces of this string.
28static String valueOf(int value)It converts the specified type to a string. It’s a method that’s been overworked.

Also read about the Strings in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

The post String class methods in Java first appeared on coderz.py.

]]>
https://coderzpy.com/string-class-methods-in-java/feed/ 0
Some examples of string class methods https://coderzpy.com/some-examples-of-string-class-methods/ https://coderzpy.com/some-examples-of-string-class-methods/#respond Tue, 14 Jun 2022 20:24:05 +0000 http://coderzpy.com/?p=1595 The methods listed below are some of the most frequently used String class methods in Java. charAt() method: The charAt() ...

The post Some examples of string class methods first appeared on coderz.py.

]]>
The methods listed below are some of the most frequently used String class methods in Java.

charAt() method:

The charAt() function in a string returns the character at the specified index.

class HelloWorld {
    public static void main(String[] args) {
        String myStr = "Hello";
        char result = myStr.charAt(0);
        System.out.println(result);
    }
}
Output:
H
equalsIgnoreCase() method:

equalsIgnoreCase() checks for equality between two Strings while ignoring their case.

        class HelloWorld {
    public static void main(String[] args) {
        String myStr = "Hello",str="Coder";
        boolean result = myStr.equalsIgnoreCase(str);
        System.out.println(result);
    }
}
Output:
false
indexOf() method:

  The index of the first occurrence of a substring or a character is returned by the indexOf() method.

 class HelloWorld {
    public static void main(String[] args) {
       String myStr = "Hello planet earth, you are a great planet.";
    System.out.println(myStr.indexOf("e", 5));
    }
}
Output:
10
length() method:

The length() function of a String returns the number of characters in it.

 class HelloWorld {
    public static void main(String[] args) {
       String myStr = "Hello planet earth, you are a great planet.";
    System.out.println(myStr.length());
    }
}
Output:
43
replace() method:

The replace() method in a string replaces all occurrences of a character with a new character.

public class Demo {
    public static void main(String[] args) {   
        String str = "coderzpy";
        System.out.println(str.replace('c','C'));
    }
}
Output:
Coderzpy
substring() method:

The substring() method returns a part of the string.

public class Demo {
    public static void main(String[] args) {
        String str = "ABCDEFGHIJKLMNO";
        System.out.println(str.substring(4));
        System.out.println(str.substring(4,7));        
    }
}
Output:
EFGHIJKLMNO
EFG
valueOf() method:

String class uses an overloaded version of valueOf() method for all primitive data types and for type Object.

public class Demo {
    public static void main(String[] args) {
         int num = 115;
         String s1 = String.valueOf(num);    //converting int to String
         s1+= "hello";
         System.out.println(s1);
         System.out.println("type of num : "+s1.getClass().getName());   
    }
}
Output:
115hello
type of num : java.lang.String
trim() method:

This method returns a string that has been stripped of any leading and trailing whitespaces.

public class Demo {
    public static void main(String[] args) {
        String str = "   hello coderzpy  ";
        System.out.println(str.trim());   
    }
}
Output:
hello coderzpy
endsWith() method:

the endsWith() method is used to determine whether the string ends with the specified suffix. If the suffix matches the string, it returns true; otherwise, it returns false.

public class Demo {
    public static void main(String[] args) {
        String a="Hello welcome to Coderzpy.com";  
        System.out.println(a.endsWith("m"));  
        System.out.println(a.endsWith("com"));       
    }
}
    
Output:
true
true

Note: also read about the String class methods in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

The post Some examples of string class methods first appeared on coderz.py.

]]>
https://coderzpy.com/some-examples-of-string-class-methods/feed/ 0
Java StringBuffer class https://coderzpy.com/java-stringbuffer-class/ https://coderzpy.com/java-stringbuffer-class/#respond Thu, 16 Jun 2022 07:49:30 +0000 http://coderzpy.com/?p=1598 StringBuffer is a String peer class that provides a lot of the same functionality as strings. StringBuffer represents growable and ...

The post Java StringBuffer class first appeared on coderz.py.

]]>
StringBuffer is a String peer class that provides a lot of the same functionality as strings. StringBuffer represents growable and writable character sequences, whereas a string represents fixed-length, immutable character sequences. Characters and substrings can be inserted in the middle or appended to the end of a StringBuffer.

Constructors of StringBuffer class :

1. StringBuffer(): It saves 16 characters by not reallocating space.

StringBuffer s = new StringBuffer();

2. StringBuffer( int size): It accepts an integer argument that specifies the buffer’s size.

StringBuffer s = new StringBuffer(20);

3. StringBuffer(String str): It takes a string argument that sets the initial contents of the StringBuffer object and frees up space for 16 more characters without reallocating space.

StringBuffer s = new StringBuffer("studentscoding");
Important methods of StringBuffer class:
Modifier and TypeMethodDescription
public synchronized StringBufferappend(String s)It is used to append the specified string with this string. Like append(char), append(boolean), append(int), append(float), append(double), etc., the append() function has many overloads.
public synchronized StringBufferinsert(int offset, String s)It is used to insert the specified string with this string at the specified position. There are several other overloaded versions of the insert() method, including insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double), etc.
public synchronized StringBufferreplace(int startIndex, int endIndex, String str)It replaces the string from specified startIndex and endIndex.
public synchronized StringBufferdelete(int startIndex, int endIndex)It deletes the string from specified startIndex and endIndex.
public synchronized StringBufferreverse()it reverses the string.
public intcapacity()It returns the current capacity.
public voidensureCapacity(int minimumCapacity)It ensures the capacity is at least equal to the given minimum.
public charcharAt(int index)It returns the character at the specified position.
public intlength()It returns the length of the string i.e. total number of characters.
public Stringsubstring(int beginIndex)It returns the substring from the specified beginIndex.
public Stringsubstring(int beginIndex, int endIndex)It returns the substring from the specified beginIndex and endIndex.
Example: length(),capacity(),append(), reverse(), replace(), ensurecapacity()

import java.io.*;

// Main class
class Demo {

	// main driver method
	public static void main(String[] args)
	{

		// Creating adn storing string by creating object of
		// StringBuffer
		StringBuffer s = new StringBuffer("Coderzpy");

		// Getting the length of the string
		int p = s.length();

		// Getting the capacity of the string
		int q = s.capacity();
			System.out.println("Length of string "+s+"="
						+ p);
		System.out.println(
			"Capacity of string "+s+"=" + q);
		s.append(".com");

		
		System.out.println("Length of string "+s+"="
						+ s.length());
		System.out.println(
			"Capacity of string "+s+"=" + s.capacity());
			System.out.println("reverse = "+s.reverse());
			
			
        s.deleteCharAt(7);
        // Returns string after deletion
        System.out.println("deleted "+s);
        
         s.replace(5, 8, "are");
 
       
        System.out.println("replaced with are"+s);

        s.ensureCapacity(40);
         	System.out.println(
			"Capacity of string "+s+"=" + s.capacity());
        
	}
}
Output:
Length of string Coderzpy=8
Capacity of string Coderzpy=24
Length of string Coderzpy.com=12
Capacity of string Coderzpy.com=24
reverse = moc.ypzredoC
deleted moc.ypzedoC
replaced with aremoc.yaredoC
Capacity of string moc.yaredoC=50

Note: also read about the Some examples of string class methods

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

The post Java StringBuffer class first appeared on coderz.py.

]]>
https://coderzpy.com/java-stringbuffer-class/feed/ 0
StringBuilder class in Java https://coderzpy.com/stringbuilder-class-in-java/ https://coderzpy.com/stringbuilder-class-in-java/#respond Fri, 17 Jun 2022 11:26:19 +0000 http://coderzpy.com/?p=1602 The Java class StringBuilder represents a mutable string of characters. The StringBuilder class offers a substitute for the String Class ...

The post StringBuilder class in Java first appeared on coderz.py.

]]>
  • The Java class StringBuilder represents a mutable string of characters.
  • The StringBuilder class offers a substitute for the String Class in Java since it constructs a mutable sequence of characters instead of an immutable one as the String Class does.
  • The functions of the StringBuilder and StringBuffer classes are extremely similar because both create changeable sequences of characters as an alternative to the String Class.
  • Except for being non-synchronized, the Java StringBuilder class is identical to the StringBuffer class.
  • Constructors of StringBuilder class:
    • StringBuilder(): It generates a blank String Builder with a 16-character initial capacity.
    • StringBuilder(String str): The provided string is used to generate a String Builder.
    • StringBuilder(int length): It generates a new String Builder that is empty and has the given capacity and length.
    A simple example illustrates the use of a constructor:
    // Java Code to illustrate StringBuilder
    
    import java.util.*;
    import java.util.concurrent.LinkedBlockingQueue;
    
    public class Demo {
    	public static void main(String[] argv) throws Exception
    	{
    		// Create a StringBuilder object
    		// using StringBuilder() constructor
    		StringBuilder str = new StringBuilder();
    
    		str.append("Coderzpy");
    
    		// print string
    		System.out.println("String = " + str.toString());
    
    		// create a StringBuilder object
    		// using StringBuilder(CharSequence) constructor
    		StringBuilder str1
    			= new StringBuilder("AAAABBBCCCC");
    
    		// print string
    		System.out.println("String1 = " + str1.toString());
    
    	}
    }
    
    Output:
    String = Coderzpy
    String1 = AAAABBBCCCC
    Methods of StringBuilder class:
    • public StringBuilder append(String s): This string is utilized to append to the provided string. Like append(char), append(boolean), append(int), append(float), append(double), etc., the append() function has many overloads.
    • public StringBuilder insert(int offset, String s): It is used to insert the specified string with this string at the specified position. There are several other overloaded versions of the insert() method, including insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double), etc.
    • public StringBuilder replace(int startIndex, int endIndex, String str): The string from the startIndex and endIndex values are replaced using this method.
    • public StringBuilder delete(int startIndex, int endIndex): It is used to remove the string from startIndex and endIndex that are supplied.
    • public StringBuilder reverse(): It is used to reverse the string.
    • public int capacity(): The current capacity is returned using it.
    • public void ensureCapacity(int minimumCapacity):To make sure the capacity is at least equal to the required minimum, it is used.
    • public char charAt(int index): The character at the requested place is returned using it.
    • public int length(): The length of the string, or the total number of characters, is returned using this method.
    • public String substring(int beginIndex): The substring starting at the supplied beginIndex is returned using it.
    • public String substring(int beginIndex, int endIndex): It is used to retrieve the substring starting at the beginIndex and endIndex values supplied.
    Simple code to illustrate the use of StringBuilder class methods:
    // Java code to illustrate
    // methods of StringBuilder
    
    import java.util.*;
    import java.util.concurrent.LinkedBlockingQueue;
    
    public class Demo1 {
    	public static void main(String[] argv)
    		throws Exception
    	{
    
    		// create a StringBuilder object
    		// with a String pass as parameter
    		StringBuilder str
    			= new StringBuilder("Coderzpy.com");
    
    		// print string
    		System.out.println("String = "
    						+ str.toString());
    
    		// reverse the string
    		StringBuilder reverseStr = str.reverse();
    
    		// print string
    		System.out.println("Reverse String = "
    						+ reverseStr.toString());
    
    		// Append ', '(44) to the String
    		str.appendCodePoint(44);
    
    		// Print the modified String
    		System.out.println("Modified StringBuilder = "
    						+ str);
    
    		// get capacity
    		int capacity = str.capacity();
    
    		// print the result
    		System.out.println("StringBuilder = " + str);
    		System.out.println("Capacity of StringBuilder = "
    						+ capacity);
    	}
    }
    
    Output:
    String = Coderzpy.com
    Reverse String = moc.ypzredoC
    Modified StringBuilder = moc.ypzredoC,
    StringBuilder = moc.ypzredoC,
    Capacity of StringBuilder = 28
    

    Note: also read about the Java StringBuffer class

    Follow Me

    If you like my post, please follow me to read my latest post on programming and technology.

    https://www.instagram.com/coderz.py/

    https://www.facebook.com/coderz.py

    The post StringBuilder class in Java first appeared on coderz.py.

    ]]>
    https://coderzpy.com/stringbuilder-class-in-java/feed/ 0
    StringTokenizer in Java https://coderzpy.com/stringtokenizer-in-java/ https://coderzpy.com/stringtokenizer-in-java/#respond Fri, 17 Jun 2022 22:08:46 +0000 http://coderzpy.com/?p=1604 A string can be divided into tokens using Java’s StringTokenizer class.  Internally, a StringTokenizer object keeps track of where it is in the string that has to be tokenized.  Some procedures move this place ahead of the currently processed characters.  By extracting a substring from the string that was used to generate the StringTokenizer object, a token is returned.  It offers the initial stage of the parsing procedure, often known as the lexer or scanner.  The String Tokenizer class enables applications to tokenize strings. The Enumeration interface is implemented by it.  Data parsing is done using this class.  We must specify an input string and a string with delimiters  to use the String Tokenizer class  The characters that divide tokens are known as delimiters. The delimiter string’s characters are all accepted as delimiters. Whitespaces, new ...

    The post StringTokenizer in Java first appeared on coderz.py.

    ]]>
  • A string can be divided into tokens using Java’s StringTokenizer class.
  •  Internally, a StringTokenizer object keeps track of where it is in the string that has to be tokenized. 
  • Some procedures move this place ahead of the currently processed characters.
  •  By extracting a substring from the string that was used to generate the StringTokenizer object, a token is returned.
  •  It offers the initial stage of the parsing procedure, often known as the lexer or scanner. 
  • The String Tokenizer class enables applications to tokenize strings. The Enumeration interface is implemented by it. 
  • Data parsing is done using this class. 
  • We must specify an input string and a string with delimiters  to use the String Tokenizer class 
  • The characters that divide tokens are known as delimiters.
  • The delimiter string’s characters are all accepted as delimiters. Whitespaces, new lines, spaces, and tabs are the default delimiters.
  • Constructors of StringToken: 

    Let us consider ‘str’ as the string to be tokenized

    1. StringTokenizer(String str): Delimiters that are typically used include newline, space, tab, carriage return, and form feed.
    2. StringTokenizer(String str, String delim):  To tokenize the supplied string, a collection of delimiters called delim is used.
    3. StringTokenizer(String str, String delim, boolean flag):The meaning of the first two parameters is the same, and the flag has the following function.

    3.1: If the flag is false, delimiter characters serve to separate tokens

    Example:

    Input : if string --> "hello coderz" and Delimiter is " ", then 
    Output:  tokens are "hello" and "coderz".

    3.2: If the flag is true, delimiter characters are considered to be tokens.

    Example:

    Input : String --> is "hello coderz"and Delimiter is " ", then 
    Output: Tokens --> "hello", " " and "coderz".
    Methods of the StringTokenizer Class:
    MethodsDescription
    boolean hasMoreTokens()It determines if more tokens are accessible.
    String nextToken()It returns the next token from the StringTokenizer object.
    String nextToken(String delim)Based on the delimiter, it returns the subsequent token.
    boolean hasMoreElements()It is the same as hasMoreTokens() method.
    Object nextElement()It is the same as nextToken() but its return type is Object.
    int countTokens()It returns the total number of tokens.
    Example to illustrate the use of StringTokenizer class:
    // Java Program to Illustrate StringTokenizer Class
    
    // Importing required classes
    import java.util.*;
    
    // Main class
    public class GFG {
    
    	// Main driver method
    	public static void main(String args[])
    	{
    
    		// Constructor 1
    		System.out.println("Using Constructor 1 - ");
    
    		// Creating object of class inside main() method
    		StringTokenizer st1 = new StringTokenizer(
    			"Hello Coderz, keep coding - keep cheering", " ");
    
    		// Condition holds true till there is single token
    		// remaining using hasMoreTokens() method
    		while (st1.hasMoreTokens())
    
    			// Getting next tokens
    			System.out.println(st1.nextToken());
    
    		// Constructor 2
    		System.out.println("Using Constructor 2 - ");
    
    		// Again creating object of class inside main()
    		// method
    		StringTokenizer st2 = new StringTokenizer(
    			"JAVA : Code : String", " :");
    
    		// If tokens are present
    		while (st2.hasMoreTokens())
    
    			// Print all tokens
    			System.out.println(st2.nextToken());
    
    		// Constructor 3
    		System.out.println("Using Constructor 3 - ");
    
    		// Again creating object of class inside main()
    		// method
    		StringTokenizer st3 = new StringTokenizer(
    			"JAVA : Code : String", " :", true);
    
    		while (st3.hasMoreTokens())
    			System.out.println(st3.nextToken());
    	}
    }
    
    Output:
    Using Constructor 1 - 
    Hello
    Coderz,
    keep
    coding
    -
    keep
    cheering
    Using Constructor 2 - 
    JAVA
    Code
    String
    Using Constructor 3 - 
    JAVA:
     
    Code
     :
     
    String

    Note: also read about the StringBuilder class in Java

    Follow Me

    If you like my post, please follow me to read my latest post on programming and technology.

    https://www.instagram.com/coderz.py/

    https://www.facebook.com/coderz.py

    The post StringTokenizer in Java first appeared on coderz.py.

    ]]>
    https://coderzpy.com/stringtokenizer-in-java/feed/ 0