Array Basics
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
(Optional) Variable-Length Argument Lists
The Arrays Class
Two-Dimensional Arrays
(Optional) Multidimensional Arrays
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Arrays in Java” will talk about one of the pillars of Java fundamentals i.e Arrays. It will also take you through the various types of arrays in Java and how they are used to achieve various functionalities. Through this tutorial, you will learn the following topics:
1. Arrays in Java
2. Types of Arrays
3. Working with Arrays
4. Sorting in Arrays
5. Searching in Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Array Basics
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
(Optional) Variable-Length Argument Lists
The Arrays Class
Two-Dimensional Arrays
(Optional) Multidimensional Arrays
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Arrays in Java” will talk about one of the pillars of Java fundamentals i.e Arrays. It will also take you through the various types of arrays in Java and how they are used to achieve various functionalities. Through this tutorial, you will learn the following topics:
1. Arrays in Java
2. Types of Arrays
3. Working with Arrays
4. Sorting in Arrays
5. Searching in Arrays
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
An Introduction to Programming in Java: ArraysMartin Chapman
An Introduction to Programming in Java: Arrays. Last delivered in 2012. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Sequential collection of elements of the same type
used to store a collection of data
consist of contiguous memory locations
lowest address corresponds to the first element and the highest address to the last element.
What is an Array?
Array are the homogeneous(similar) collection of data types.
Array Size remains same once created.
Simple Declaration format for creating an array
type [ ] identifier = new type [integral value];
,,,,,,jhbhhhhhvggvvcccccccfghhhhhhhhhhhhhgggggggggyyyyy hhbbhhhhgggyhhsyddhdhhddhsiejdhajshdhdhdhdhdhdudufjdhyeyeg hhdhdhdhdhdhdhdhdh d bhsuhabuesjjsoeijshshdhsjajsijehfdhhdhdhdhdhhdxbbxxhxhhdja hi in najajajhwhr7fhhhhhhhhhhhhhhhhhuhhuwbshdhhddh8rhedi8fnf
An Introduction to Programming in Java: ArraysMartin Chapman
An Introduction to Programming in Java: Arrays. Last delivered in 2012. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Sequential collection of elements of the same type
used to store a collection of data
consist of contiguous memory locations
lowest address corresponds to the first element and the highest address to the last element.
What is an Array?
Array are the homogeneous(similar) collection of data types.
Array Size remains same once created.
Simple Declaration format for creating an array
type [ ] identifier = new type [integral value];
,,,,,,jhbhhhhhvggvvcccccccfghhhhhhhhhhhhhgggggggggyyyyy hhbbhhhhgggyhhsyddhdhhddhsiejdhajshdhdhdhdhdhdudufjdhyeyeg hhdhdhdhdhdhdhdhdh d bhsuhabuesjjsoeijshshdhsjajsijehfdhhdhdhdhdhhdxbbxxhxhhdja hi in najajajhwhr7fhhhhhhhhhhhhhhhhhuhhuwbshdhhddh8rhedi8fnf
An array is a group of data items of same data type that share a common name. Ordinary variables are capable of holding only one value at a time. If we want to store more than one value at a time in a single variable, we use arrays.
An array is a collective name given to a group of similar variables. Each member in the group is referred to by its position in the group.
Arrays are alloted the memory in a strictly contiguous fashion. The simplest array is a one-dimensional array which is a list of variables of same data type. An array of one-dimensional arrays is called a two-dimensional array.
This is a presentation on Arrays, one of the most important topics on Data Structures and algorithms. Anyone who is new to DSA or wants to have a theoretical understanding of the same can refer to it :D
Using various data structures: Using Arrays (One Dimensional, Two Dimensional,
Jagged), Array.
ArrayList classes
Using Collections: Collection, HashTable, List, Stack, Queue, HashSet classes.
Similar to Class notes(week 4) on arrays and strings (20)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Kuntal Bhowmick
A Hash table is a data structure used for storing and retrieving data very quickly. Insertion of data in the hash table is based on the key value. Hence every entry in the hash table is associated with some key.
HASHING AND HASH FUNCTIONS, HASH TABLE REPRESENTATION, HASH FUNCTION, TYPES OF HASH FUNCTIONS, COLLISION, COLLISION RESOLUTION, CHAINING, OPEN ADDRESSING – LINEAR PROBING, QUADRATIC PROBING, DOUBLE HASHING
introduction to E-commerce, Electronic commerce, EDI, CS802E,
e-commerce ,edi ,electronic data interchange ,traditional commerce ,buyer and seller ,origin of e-commerce ,business process ,impact of e-commerce ,value chain analysis ,company value chain ,case studies on e-commerce ,advantages of e-commerce ,disadvantages of e-commerce
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
Class notes(week 4) on arrays and strings
1. Page 1 of 19
Class Notes on Arrays and Strings (Week - 4)
Contents:-1 D Array,Creating an Array, Initialization, Array Length, 2-D Array, Variable Size Arrays, Strings, String Arrays,
String Methods, StringBuffer Class, Manipulation of Strings, basic string handling concepts, -String (char(), compare(),
equals(), equalsIgnorecase(), indexOf(), length(), substring(), toCharArray(),toLowercCase(),tostring(), methods), concept
of mutable and immutable string.
Arrays
An array is a very common type of data structure where in all elements must be of the same data type. Once
defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element
of an array starts with zero.
An array is a container object that holds a fixed number of values of a single type. The length of an array is
established when the array is created. After creation, its length is fixed.
Characteristics of an Array:-
An array is a group of contiguous or related data items that share a common name.
Used when programs have to handle large amount of data.
Each value is stored at a specific position.
Position is called a index or superscript. Base index = 0.
The ability to use a single name to represent a collection of items and refer to an item by specifying the
item number enables us to develop concise and efficient programs. For example, a loop with index as
the control variable can be used to read the entire array, perform calculations, and print out the
results.
An array of ten elements
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in
the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed
at index 8.
Using and array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initializing your Array
2. Page 2 of 19
Syntax for Declaring Array Variables is
Form 1:
Type arrayname[];
Form 2:
Type[] arrayname;
Examples:
int[] students;
int students[];
Note: we don’t specify the size of arrays in the declaration.
Constructing an Array
After declaring arrays, we need to allocate memory for storage array items.In Java, this is carried out by using
“new” operator, as follows:
Arrayname = new type[size];
Examples:
students = new int[7];
Initialisation of Arrays
Once arrays are created, they need to be initialised with some values before access their content. A general
form of initialisation is:
Arrayname [index/subscript] = value;
Example:
students[0] = 50;
students[1] = 40;
Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified.Unlike
C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will
generate an error message.
Arrays – Length
Arrays are fixed length. Length is specified at create time. In java, all arrays store the allocated size in a
variable named “length”. We can access the length of arrays as arrayName.length:
e.g. int x = students.length; // x = 7
The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to
standard output.
3. Page 3 of 19
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// etc.
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: "
+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}
The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
4. Page 4 of 19
In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate
through each element of the array, rather than write each line individually as shown above. However, this
example clearly illustrates the array syntax.
Arrays – Another Example
// StudentArray.java: store integers in arrays and access
class StudentArray{
public static void main(String[] args) {
int[] students;
students = new int[7];
System.out.println("Array Length = " + students.length);
for ( int i=0; i < students.length; i++)
students[i] = 2*i;
System.out.println("Values Stored in Array:");
for ( int i=0; i < students.length; i++)
System.out.println(students[i]);
}
}
Arrays – Initializing at Declaration
Arrays can also be initialised like standard variables at the time of their declaration.
Type arrayname[] = {list of values};
Example:
int[] students = {55, 69, 70, 30, 80};
Creates and initializes the array of integers of length 5.
In this case it is not necessary to use the new operator.
Example of Arrays using initialization at declaration
// StudentArray.java: store integers in arrays and access
class StudentArray{
public static void main(String[] args) {
int[] students = {55, 69, 70, 30, 80};
System.out.println("Array Length = " + students.length);
System.out.println("Values Stored in Array:");
for ( int i=0; i < students.length; i++)
System.out.println(students[i]);
}
}
5. Page 5 of 19
Two-Dimensional Arrays
An array keeps track of multiple pieces of information in linear order, a one-dimensional list. However, the
data associated with certain systems (a digital image, a board game, etc.) lives in two dimensions. To visualize
this data, we need a multi-dimensional data structure, that is, a multi-dimensional array.
A two-dimensional array is really nothing more than an array of arrays (a three-dimensional array is an array of
arrays of arrays). Think of your dinner. You could have a one-dimensional list of everything you eat:
(lettuce, tomatoes, salad dressing, steak, mashed potatoes, string beans, cake, ice cream, coffee)
Or you could have a two-dimensional list of three courses, each containing three things you eat:
(lettuce, tomatoes, salad dressing) and (steak, mashed potatoes, string beans) and (cake, ice cream, coffee)
In the case of an array, our old-fashioned one-dimensional array looks like this:
int[] myArray = {0,1,2,3};
And a two-dimensional array looks like this:
int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} };
For our purposes, it is better to think of the two-dimensional array as a matrix. A matrix can be thought of as a
grid of numbers, arranged in rows and columns, kind of like a bingo board. We might write the two-
dimensional array out as follows to illustrate this point:
int[][] myArray = { {0, 1, 2, 3},
{3, 2, 1, 0},
{3, 5, 6, 1},
{3, 8, 3, 4} };
We can use this type of data structure to encode information about an image. For example, the following
grayscale image could be represented by the following array:
int[][] myArray = { {236, 189, 189, 0},
{236, 80, 189, 189},
{236, 0, 189, 80},
{236, 189, 189, 80} };
6. Page 6 of 19
2D arrays manipulations
Declaration:
int myArray [][];
Creation:
myArray = new int[4][3]; // OR
int myArray [][] = new int[4][3];
Initialisation:
Single Value:
myArray[0][0] = 10;
Multiple values:
int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};
int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
Variable Size Arrays
Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows:
Arrays of Objects
Arrays can be used to store objects
Circle[] circleArray;
circleArray = new Circle[25];
The above statement creates an array that can store references to 25 Circle objects. Circle objects are not
created.
Create the Circle objects and stores them in the array.
//declare an array for Circle
Circle circleArray[] = new Circle[25];
int r = 0;
// create circle objects and store in array
for (r=0; r <25; r++)
circleArray[r] = new Circle(r);
7. Page 7 of 19
Strings in Java
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this
case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String
class has eleven constructors that allow you to provide the initial value of the string using different sources,
such as an array of characters:
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce following result:
Hello.
Following are some useful classes that Java provides for String operations.
String Class
StringBuffer Class
StringTokenizer Class
Although character arrays have the advantage of being able to query their length, they themselves are too
primitive and don’t support a range of common string operations. For example, copying a string, searching for
specific pattern etc.
Recognising the importance and common usage of String manipulation in large software projects, Java
supports String as one of the fundamental data type at the language level. Strings related book keeping
operations (e.g., end of string) are handled automatically.
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a
necessity to make a lot of modifications to Strings of characters then you should use String Buffer Classes.
8. Page 8 of 19
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method
that you can use with strings is the length() method, which returns the number of characters contained in the
string object.
After the following two lines of code have been executed, len equals 17:
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This would produce following result:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals, as in:
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in:
"Hello," + " world" + "!"
which results in:
"Hello, world!"
Let us look at the following example:
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
9. Page 9 of 19
This would produce following result:
Dot saw I was Tod
Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class has an
equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to
a one-time print statement. For example, instead of:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
you can write:
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Array In Java
In this section, you will learn how to use string array in Java. Here, you will see how to declare a string array
and the syntax for using in the program. This section provides you a simple java program which illustrates
about the string array in very efficient manner.
Program Description:
Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar",
"santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrieving
from the specified string array named names. In this program all the string values are stored in the names
string array at the declaration time.
Here is the code of this program:
class StringCharacter
{
static String[] names={"chanan","tapan","Amar","santosh","deepak"};
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println(names[i]);
}
}
}
10. Page 10 of 19
Output of program:
C:>javac StringCharacter.java
C:>java StringCharacter
chanan
tapan
Amar
santosh
deepak
C:>
You can also initialize Strings Arrays by using new operator as shown below
String city[] = new String[5];
city[0] = new String(“Melbourne”);
city[1] = new String(“Sydney”);
String class – Constructors
The String class supports several constructors. To create an empty String, you call the default constructor. For
example,
String s = new String();
will create an instance of String with no characters in it. Frequently, you will want to create strings that have
initial values. The String class provides a variety of constructors to handle this. To create a String initialized by
an array of characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string "abc".
You can specify a subrange of a character array as an initializer using the following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of
characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
11. Page 11 of 19
This initializes s with the characters cde.
You can construct a String object that contains the same character sequence as another String object using
this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings
on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings
are common, the String class provides constructors that initialize a string when given a byte array. Their forms
are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of
these constructors, the byte-to-character conversion is done by using the default character encoding of the
platform. The following program illustrates these constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
12. Page 12 of 19
This program generates the following output:
ABCDEF
CDE
Extended versions of the byte-to-string constructors are also defined in which you can specify the character
encoding that determines how bytes are converted to characters. However, most of the time, you will want to
use the default encoding provided by the platform.
Note: The contents of the array are copied whenever you create a String object from an array. If you modify
the contents of the array after you have created the string, theString will be unchanged.
String Methods:
Here is the list methods supported by String class (go to link for details):
SN Methods with Description
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
3 int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str)
Concatenates the specified string to the end of this string.
6 boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
7 boolean equals(Object anObject)
Compares this string to the specified object.
8 boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
9 byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte
array.
10 byte[] getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
11 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
12 int hashCode()
Returns a hash code for this string.
13 int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
14 int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the
specified index.
15 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
16 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
13. Page 13 of 19
17 String intern()
Returns a canonical representation for the string object.
18 int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
19 int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at
the specified index.
20 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
21 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at
the specified index.
22 int length()
Returns the length of this string.
23 boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
24 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
25 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
26 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
27 String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
28 String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
29 String[] split(String regex)
Splits this string around matches of the given regular expression.
30 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
31 boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
32 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
33 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
34 String substring(int beginIndex)
Returns a new string that is a substring of this string.
35 String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
36 char[] toCharArray()
Converts this string to a new character array.
37 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
38 String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
39 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
40 String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
41 String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
14. Page 14 of 19
toString() Method
toString() method is a special method that can be defined in any class. This method should return a String
argument. When an object is used in a String concatenation operation or when specified in print statement,
this method gets invoked automatically.
toString() Method –Example
class Circle {
double x,y,r;
public Circle(double centreX, double centreY, double radius ) {
x = centreX ; y = centreY; r = radius;
}
public String toString()
{
String s = “I am a Circle with centre [“ + x + “,” + y + “] and
radius [“+ r + “]”;
return s;
}
}
class CircleTest {
Circle c = new Circle(10,20, 30);
System.out.println( c );
// I am a circle with centre [10.0,20.0] and radius [30.0]
}
StringBufferClass
Unlike the String class, StringBuffer class is mutable (changeable).Use StringBufferClass class in operations
where the string has to be modified.
15. Page 15 of 19
StringBuffer class – Constructors
public StringBuffer() Constructs a StringBuffer with an empty string.
public StringBuffer(String str) Constructs a StringBuffer with initial value of str.
StringBuffer class – Some operations
public int length() Returns the length of the buffer
public void setCharAt(int index, char ch) Replaces the character at the specified position
s1.setLength(int n)
Truncates or extends the buffer.
If(n<s1.length(), s1 is truncated; else zeros are added to s1.
public StringBuffer append(String str) Appends the string to this string buffer.
public StringBuffer append(int i)
Append of other data items (float, char, etc.)
is supported.
Appends the string representation of the int argument to this
string buffer.
Java StringBuffer Examples
StringBuffer is a mutable sequence of characters. It is like a String but the contents of the StringBuffer can be
modified after creation.
StringBuffer Capacity
Every StringBuffer object has a capacity associated with it. The capacity of the StringBuffer is the number of
characters it can hold. It increases automatically as more contents added to it.
StringBuffer’s current capacity can be obtained using following method.
int capacity()
This method returns the current capacity of the StringBuffer object.
For example,
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.capacity());
16. Page 16 of 19
This will print 27 (11 + 16) on console when executed.
The actual number of characters in StringBuffer can be obtained by following method.
int length()
Returns the actual number of characters contained in the StringBuffer object.
For example,
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.length());
System.out.println(stringBuffer.capacity());
This will print,
11
27
on console when run.
Specifying initial capacity of StringBuffer
Initial capacity of the StringBuffer object can be specified using following method.
void ensureCapacity(int initialCapacity)
Ensures that the StringBuffer’s initial capacity would be grater than or equal to the specified initial capacity.
The new capacity of the StringBuffer is the maximum of,
1) The initialCapacity argument passed and
2) ( Old capacity * 2 ) + 2
StringBuffer Constructors
StringBuffer object can be created using following StringBuffer constructors.
1) StringBuffer()
Creates empty StringBuffer object having initial capacity of 16.
For example,
StringBuffer stringBuffer = new StringBuffer();
Here, capacity of stringBuffer object would be 16.
17. Page 17 of 19
2) StringBuffer(int capacity)
Creates empty StringBuffer object having initial capacity specified.
For example,
StringBuffer stringBuffer = new StringBuffer(50);
Here, capacity of stringBuffer object would be 50.
This constructor may throw NegativeArraySizeException if the passed argument is less than 0.
3) StringBuffer(String content)
Creates new StringBuffer object having contents same as the argument string object. The initial capacity of the
newly created StringBuffer object will be the length of the argument string object + 16.
For example,
String str = “Hello”;
StringBuffer stringBuffer = new StringBuffer(str);
Here, capacity of stringBuffer object would be 5 + 16 = 21.
String concatenation and StringBuffer
In Java, String concatenation operator (+) is internally implemented using StringBuffer.
For Example,
String str = “Hello” + “World”;
Would be executed as,
String str = new
StringBuffer().append(“Hello”).append(“World”).toString();
First an empty StringBuffer will be created and then operands of the + operator would be appended using
append method of the StringBuffer. Finally toString() method of the StringBuffer would be called to convert it
to string object and the same will be returned.
String concatenation using this approach is very expensive in nature, because it involves creation of temporary
StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer
would be converted back to String using toString() method.
When to use String and when StringBuffer?
If there is a need to change the contents frequently, StringBuffer should be used instead of String because
StringBuffer concatenation is significantly faster than String concatenation.
18. Page 18 of 19
Inserting a String in Middle of Existing StringBuffer
StringBuffer str = new StringBuffer(“Object Language”);
String aString = new String(str.toString());
Int pos = aString.indexOf(“ Language”);
str.insert(pos, “ Oriented “);
What will output of at this point?
System.out.println(“Modified String:”+str);
What will be string after executing (modifying character)?
str.setChar(6,’-’);
For more example on StringBuffer visit:
http://www.java-examples.com/java-stringbuffer-examples
StringTokenizer
Breaks string into parts, using delimiters.
The sequence of broken parts are the tokens of the string.
More than one delimiter can be specified.
The tokens can be extracted with or without the delimiters.
StringTokenizer – Functionality
Consider the following String
CREATE_USER:1234567;John;Smith
Separate the tokens(Here Delimiters are: “:;”)
CREATE_USER
1234567
John
Smith
StringTokenizer – Constructors
public StringTokenizer(String str, String delim,
boolean returnTokens)
Creates a SringTokenizer with the specified delimiter. If
returnTokens is true the delimiters are also returned.
public StringTokenizer(String str, String delim) Delimiters are not returned
public StringTokenizer(String str) Delimiters are (“ tnrf”)
public boolen hasMoreTokens() Returns true if more tokens are found.
19. Page 19 of 19
public String nextToken() Returns the next token of the String.
public String nextToken(String delim) Switches the delimiter set to characters in delim and returns
the next token.
public int countTokens() Returns the count of remaining tokens.
StringTokenizer – example
import java.util.StringTokenizer;
class TokenizerExample {
public static void main(string[] args)
{
String str = “CREATE_USER:123456;John;Smith”;
StringTokenizer tokens = new StringTokenizer(str, “:;”);
while ( tokens.hasMoreTokens() )
System.out.println(tokens.nextToken());
}
}
Output of the program
CREATE_USER
123456
John
Smith