Showing posts with label string in java. Show all posts
Showing posts with label string in java. Show all posts

Friday, March 1, 2024

STRING IN JAVA

 Strings in Java 

  • WHAT IS STRING
  • WAYS OF CREATING A STRING
  • INTERFACES AND CLASSES IN STRINGS IN JAVA 
  • JAVA STRING CLASS METHODS 
  • STRING TOKENIZER
  • IMMUTABLE STRING IN JAVA 
  • MEMORY ALLOTMENT IN STRING 

In this example, object creation is restricted to a single instance. It will first create a new string object because the "Welcome" object isn't already in the JVM's collection of string constants. Then, instead of creating a new object, it finds the collection whose string value is "Welcome" and returns a reference to the instance that already exists. This article covers the capabilities of strings in the Java language.

What are strings in Java?

Java's "string" object type may store character values; each character should be represented by 16 bits, according to the Unicode Technical Report (UTF). Similar to any other string in Java.

String s =” India”;

The Java String class contains countless methods for interacting with strings, such as compare, concat, equals, split, length, replace, compareTo, intern, and substring. This project is for Java. lang.

The String class implements the methods Serializable, Comparable, and CharSequence.

Example of using a string












Example

    Java strings are immutable, meaning they cannot be changed. Every time a string is changed, a new instance is created. You may use strings that can be changed with the StringBuilder and String Buffer classes.

    We shall discuss immutable strings later. We'll start by going over the fundamentals of strings and how to create a string object in Java.

    Ways of creating a string

    There are two ways of creating a string

    1)      by string literal

    2)      by new keyword

    By string literal

    For the sake of Java's memory efficiency (because the set string constant stops duplicate objects from being created).

    Ex: string demo string = “India”;

    By using keyword

    for example: String s=new String("Welcome");

    Here, the Java Virtual Machine (JVM) creates a new String object in traditional (non-pooled) heap memory and appends the literal "Welcome" to the String constant. The variables designate items that are on the heap (and those that are not).

    For example:




















Interfaces and classes in Strings in Java

The Char Buffer class is an example of an interface that is implemented by other classes. You may utilize character buffers instead of Char-Sequences with this class. To see this in action, go no further than the java. util.regex package, which contains regular expressions.

A string is presented here. Once created, string objects in Java cannot be edited; this is known as immutability.

Char-Sequence Interface

The Char-Sequence interface is used to represent strings in Java.

The following classes meet the requirements of the Char-Sequence interface. You may take use of their many helpful characteristics, such as substring, last occurrence, first occurrence, chaining, vertical, horizontal, and many more.

  • String
  • StringBuffer
  • StringBuilder

 

1)      String

The string class is said to as immutable as it is a constant that cannot be changed once it is formed. Every update necessitates the creation of a new object, and even its own operations—like to upper and to lower—return new objects that are identical to the original. It is by default thread-safe.

Syntax:

    String str= "LMS";

           or
String str= new String("LMS")

 

2)      String buffer

StringBuffer is an analog class for Strings that provides a large portion of Strings' functionality. Instead of using a string, which has a fixed length and cannot be altered, you may use the ThreadSafe class StringBuffer if you need to use a shared string buffer object while working in a multithreaded environment. Due to its overhead, which comes from being thread-safe, its primary use is in multi-threaded systems.

Syntax

                  StringBuffer demoString = new StringBuffer("LMS");
 

       3) String builder

Java's StringBuilder class represents a changing string. The StringBuilder class is a suitable substitute for Java's String class, which creates an immutable string. Although it is thread-specific rather than thread-safe, overload is avoided. For the above-mentioned reasons, it is mostly used in programs that do not support threads.

Syntax:

StringBuilder demoString = new StringBuilder();
 

demoString.append("LMS"); 

Java string class methods
The java.lang.String class provides many useful methods for performing operations on an array of character values..



























 











String tokenizer

The String-Tokenizer object internally maintains track of the string's current position. Some techniques move the pointer past the characters after they have been processed. The token may be acquired by extracting a substring from the string that was used to create the String-Tokenizer object. To create strings with optional prefixes and suffixes at the beginning and end, separated by a delimiter, one handy Java class is StringJoiner. Instead of writing a ton of code to do the same task as appending a delimiter to each string using the StringBuilder class, String-Joiner provides an easy-to-use solution.

Syntax: public StringJoiner (CharSequence delimiter)

Here, the JVM checks the string against the standard store. If there's not already a string in the pool, a new string instance is created and added. If there isn't already a string instance in the pool, one is created and added. If the string already exists, the constructor won't be called. Instead, it goes back to using the same instance as before. The cache that contains all of these strings is sometimes referred to as the "String Pool" or "String Constant pool." Up until JDK 6, the String collection in previous versions of Java was in PermGen (permanent generation) mode. It was instead moved to the main heap due to a change in JDK 7.

Immutable string in Java

In Java, string objects cannot be changed. Immaculate, to put it simply, means unchanged. A new string object must be generated since an existing string object cannot have its contents or status changed.

Let us understand with a program:














Here, Sachin is still Sachin in this instance, but "Sachin Tendulkar" is added to an already-existing object. For this reason, the string is called immutable.

As can be seen in the attached image, even though two objects are formed, "Sachin" rather than "Sachin Tendulkar" is used in the reference variable. On the other hand, when we explicitly add the object "Sachin Tendulkar" to the reference variable, it gets referred.











Memory allotment on string

When a string object is created literally, it is added to a collection of string constants. As a result, the JVM could optimize how string literals are initialized.

Syntax: string demostring = “LMS”

Another technique to define strings is to use the new operator to dynamically allocate them. When dynamic allocation is done, a string is given a new heap position. This string is not obtained via the string constant set.

Syntax: string demo string = new string(“LMS”)

For example:















Why did the String pool move from Perm-Gen to the normal heap area?

PermGen has a 64 MB default size, which limits its storage capacity. The issue was brought on by the creation and storage of an excessive number of string objects in PermGen space. As a result, the String pool was moved to a larger stack area. Using the concept of a string literal, Java memory management is made more effective.

Whether or whether the exact same object already exists in the string pool, the Java Virtual Machine will create a new string object on the usual stack region when you use the "new" keyword.

Example: String demoString = new String("Bhubaneswar");















Few more examples



ARRAYS IN JAVA

 Arrays in Java


  • SUMMARY
  • ADVANTAGES AND DISADVANTAGES 
  • TYPES OF ARRAYS 
  • INSTANTIATING AN ARRAY IN JAVA 
  • PASSING AN ARRAY IN JAVA 
  • CLASS OBJECT FOR ARRAYS 
  • ARRAY TYOES AND THIER ALLOWED DATA TYPES IN JAVA 
  • CLONING OF SINGLE AND MULTIDIMENSIONAL ARAAY IN JAVA 

An array is commonly defined as a collection of nearby memory regions that hold identical components.

In Java, arrays are groups of objects that hold similar objects. Moreover, the array items are stored in a contiguous memory region. Similar items are remembered by this database. The number of elements that can be in a Java array is limited.

In a Java array, the first element is stored at index 0; the second component is stored at index 1, and so on. An array index is the name given to this indexing technique.

The length member of an array may be used to get the array's length, unlike C and C++. The (size-of) operator is necessary in C and C++.

In Java, a class object that is created dynamically is called an array. Because Java arrays derive from the Object class, they may be serialized and cloned. We may store objects or basic data in a Java array. Java lets us create arrays with one or more dimensions, much like C and C++ do.

Unlike C/C++, Java has an anonymous array function as well.

Advantages and disadvantages of arrays in Java: -

Advantage

·       Code optimization: optimizes the code, so we can search or sort data efficiently.

·       Random access: we can get any data located at the index location.

Disadvantages

·       Size limitation: we can only store fixed-size array elements. This size does not increase while driving. To solve this problem, Java uses a collection framework that grows automatically.

Types of arrays in java: -

1)      Single dimensional array

2)      Multi-dimensional array

Single dimensional array

An array definition consists of two parts: a type and a name. In an array, "type" indicates the kind of element. Every table element's data type is determined by its element type. It is also possible to construct user-defined data types (class objects) and a variety of other more fundamental data types, such as arrays of integers, char, float, double, etc. The element type of an array can be used to determine what sort of data it contains.









 












Instantiating an array in Java
 An array is nothing more than a reference created upon declaration. It takes the following actions to build an array and allocate memory to it: A novel generic form for one-dimensional arrays is:
var name = new type[size];
Here, type designates the kind of array, size denotes the quantity of items, and var-name corresponds to the variable name inside the array. 
Before using it, you must specify to new what sort of array to allocate and how many elements to allocate.
To be explicit, reference types are initialized to null, logical types to false, and freshly allocated array components of numeric types to zero. Examine Java's default array values. 
Getting an array requires a two-step process. Initially, you must create a variable representing the type of the array. 
Second, you need to use new to allocate memory to store an array before you can assign it to a variable. This implies that every array allocation in Java occurs dynamically.








 




For each loop for the Java array
 To output a Java array, a for-each loop can also be employed. 
Java's for-each loop outputs an array's items one after the other.
 This executes the primary function of the loop after initializing a variable to hold the array element. 
The whole list of loop syntax is shown below:



















Passing an array to a method in Java
Java allows us to provide arrays to methods so that we may reuse logic across arrays.
Here's a simple illustration of a technique to get an array's minimal value.













 








Anonymous array in Java

Java offers the ability to submit an array to a method without requiring its declaration.
 
















 Returning Array from method in Java

 If we want then we can also return an array in Java using a method:















 








Multi-dimensional array

An array is considered multidimensional when each element of the array refers another array. 
An alternative term for them is dental matrices. 
A multidimensional array's dimensions are denoted by their own set of square brackets ([ ]). 
Java Multidimensional Array Syntax 
 Java multidimensional arrays can be declared in two ways
 
--datatype [][]arrayrefvariable;
-- datatype arrayrefvariable[][];

For example: -

















Multidimensional array declaration

Syntax:

1. **2D Array (Matrix)**:

```java

int[][] matrix = new int[3][3];

```

This creates a 2D array (3x3 matrix) where each element is an integer.

 

2. **3D Array**:

```java

int[][][] 3-D Array = new int[3][3][3];

```

This creates a 3D array where each element is an integer, with dimensions 3x3x3.

 

3. **Jagged Array** (Array of Arrays with varying lengths):

```java

int[][] jaggedArray = 

{

    {1, 2, 3},

    {4, 5},

    {6, 7, 8, 9}

};

```

This creates a jagged array where each sub-array can have a different length.

 

4. **Array of Matrices**:

```java

int[][][] array of matrices = new int[3][3][3];

```

This creates an array of 3 matrices, each with dimensions 3x3.

 

5. **Array of 2D Arrays**:

```java

int[][][] arrayOf2DArrays = 

{

    {{1, 2, 3}, {4, 5, 6}},

    {{7, 8, 9}, {10, 11, 12}}

};

```

This creates an array of 2D arrays, where each element is a 2D array of integers.

 

Remember to adjust the array dimensions and data types according to your specific requirements.

let us better understand a Java program











 


 




Passing an array to methods

Arrays are passable to methods in the same way that variables are.  The sum function on an array may be used in the following code to determine the total number of elements in the array.


Let's try to understand the program better











 






Returning array from methods
An
array can also be returned by a method, as is customary. For example, the
program below returns an array of method m1.














Class object for arrays

 

Every array of a certain sort shares a common class object for every component type.

 

Let us try a program for a better understanding 










 








Explanation for the above program
The runtime signature of an object of the class "array with component type int" is the text "[I]".
The only direct descendent of the array type is object, which is found in the java.lang package.
The runtime signature of the object is "[B]." The signature is an array of bytes, and the object's class is object.
The string "[S]" represents the runtime signature of the class object "array whose component type is short".
The runtime signature of the "array of class component" type is String "[L"". Put the seal on the document.". followed by the class name.

Java's array types and the data types that are permitted.

 






Cloning of single-dimensional array into Java

Cloning a one-dimensional array, like Object [], creates a new array known as a "deep copy" that is made up of copies of the original array rather than pointers.


Let's attempt a program to gain a better understanding:















Java multidimensional array Cloning

A "shallow copy" of an object[][] or other multidimensional array creates a single new array that has the subsets split but contains objects referenced from the original array.

Let us better understand with a program



Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular