0% found this document useful (0 votes)
195 views

Java Notes by Pradeep Goud

Arrays allow storing multiple variables of the same type. There are three steps to using arrays: 1. Declare an array variable specifying the type in square brackets 2. Construct the array object by using new along with the type and size 3. Initialize the array by assigning values to indexes Multidimensional arrays are arrays of arrays, where each additional dimension is specified with another set of square brackets. Strings are objects that store character sequences. Strings are immutable but their reference variables are not, so new strings are created when modifying existing strings.

Uploaded by

PradeepGoud
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
195 views

Java Notes by Pradeep Goud

Arrays allow storing multiple variables of the same type. There are three steps to using arrays: 1. Declare an array variable specifying the type in square brackets 2. Construct the array object by using new along with the type and size 3. Initialize the array by assigning values to indexes Multidimensional arrays are arrays of arrays, where each additional dimension is specified with another set of square brackets. Strings are objects that store character sequences. Strings are immutable but their reference variables are not, so new strings are created when modifying existing strings.

Uploaded by

PradeepGoud
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Arrays

Arrays are objects in Java that store multiple


variables of the same type.
Arrays can hold either primitives or object references
For this arrays, you need to know three things:
How to make an array reference variable (declare)
How to make an array object (construct)
How to populate the array with elements (initialize)

Declaring an Array
Arrays are declared by stating the type of element the array will
hold followed by square brackets to the left or right of the
identifier.
Example:
int[] key; // brackets before name (recommended)
int key []; // brackets after name (legal but less readable)
// spaces between the name and [] legal, but bad
It is never legal to include the size of the array in your declaration.
int[5] scores;
Remember, the JVM doesn't allocate space until you actually
instantiate the array object.

Constructing an Array

Constructing an array means creating the array object on the


heap.
To create an array object, Java must know how much space to
allocate on the heap, so you must specify the size of the array
at creation time.
The size of the array is the number of elements the array will
hold.
The most straightforward way to construct an array is to use
the keyword new followed by the array type, with a bracket
specifying how many elements of that type the array will hold.
int[] testScores; // Declares the array of ints
testScores = new int[4];

int[] testScores;
testScores = new int[4];

----values-------

0
1

The Heap

You can also declare and construct an array in one


statement as follows:
int[] testScores = new int[4];
int[] carList = new int[];// Compilation Fails

Initializing an Array
Initializing an array means putting elements into it.
Note
if an array has three elements, trying to access the [3] element
will raise an ArrayIndexOutOfBoundsException, because in
an array of three elements, the legal index values are 0, 1, and
2.
int[] x = new int[5];
x[4] = 2; // OK, the last element is at index 4
x[5] = 3;

int[] z = new int[2];


int y = -3;
z[y] = 4;
Declaring, Constructing, and Initializing on One Line
int[] dots = {6,9,8};

Constructing and Initializing an Anonymous Array


The second shortcut is called "anonymous array creation" and
can be used to construct and initialize an array, and then assign
the array to a previously declared array reference variable:
int[] testScores;
testScores = new int[] {4,7,2};

Remember that you do not specify a size when using


anonymous array creation syntax.

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.
To declare a multidimensional array variable, specify each
additional index using another set of square brackets.
For example, the following declares a two dimensional array
variable called twoD.
int twoD[][] = new int[4][5];

Multidimensional Arrays

Strings

Group of characters are called strings


In java, a string is an object of String class
In Java, each character in a string is a 16-bit Unicode
character
String class is declared as final, which means that String class
not subclassed

Creation of Strings
1)We can create a string just by assigning a group of characters to
a string type variable
String s;// declare a string type variable
S=Hello;//assign a group of characters to it
Note: String s=Hello;
2) We can create an object to String class by allocating memory
using new operator
String s=new String(Hello);
3)Creating string by converting character array into strings
char[] arr={H,e,l,l,o};
String s=new String(arr);
String s=new String(arr,1,3); //ell

String s=abc;
String s1=new String(abc);

Strings Are Immutable Objects


Once a String object is created, it can never be changed it's
immutable
The good news is that while the String object is immutable, its
reference variable is not.
String s=abcdef; //create a new String object, with value "abcdef",
refer s to it

String s2 = s; // create a 2nd reference variable referring to the same


String

s = s.concat(" more stuff"); //create a new String object, with value


"abcdef more stuff", refer s to it.

String objects and their reference variables

String s=abc;

s
abc

String s2=s;

abc
s2

s = s.concat (def);

abc
s2
s
abcdef
s

String x = "Java";
x.concat(" Rules!");
System.out.println("x = " + x);

String x = "Java";
x = x.concat(" Rules!");
System.out.println("x = " + x);

String s1 = "spring ";


String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
Answer: spring winter spring summer.
There are two reference variables, s1 and s2. There were
a total of eight String objects created as follows: "spring",
"summer " (lost), "spring summer", "fall" (lost), "spring
fall" (lost), "spring summer spring" (lost), "winter" (lost),
"spring winter" (at this point "spring" is lost). Only two
of the eight String objects are not lost in this process.

String class methods


Character Extraction
charAt()
getChars()
getBytes()
toCharArray()
charAt()
To extract a single character from a Sting
public char charAt(int index)
Example:
String x = "airplane";
System.out.println( x.charAt(2) ); // output is 'r

getChars()
To extract more than one character at a time
public void getChars(int start, int end,char target[], int targetStart)

Example:
String s=This is a demo of the getChars method;
int start=10;
int end=14;
char[] buf=new char[end-start];
s.getChars(start,end,buf,0);
System.out.println(buf); //demo

getBytes()
public byte[] getBytes()
toCharArray()
Convert all the characters in a string object into a
character array
public char[] toCharArray()

String Comparison

equals()
equalsIgnoreCase()
regionMatches()
startsWith()
endsWith()
compareTo()

equals()
1) To compare two strings for equality, use equals()
2) It returns true if the strings contains same characters in the
same order, and false otherwise
3) The comparison is case-sensitive
public boolean equals(Object str)
String s1=exit;
String s2=exit;
Strrong s3=Exit;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));

equalsIgnoreCase(String s)
This method returns a boolean value (true or false) depending
on whether the value of the String in the argument is the same
as the value of the String used to invoke the method.
This method will return true even when characters in the
String objects being compared have differing cases
public boolean equalsIgnoreCase(String s)
String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); // is "true"
System.out.println( x.equalsIgnoreCase("tixe")); // is "false"

regionMatches()
This method compares a specific region inside a string with
another specific region in other string
boolean regionMatches(int startindex, String s2, int s2Startindex,
int numChars)
String s1="helloworld";
String s2="world";
System.out.println(s1.regionMatches(5,s2,0,3));
boolean regionMatches(boolean ignoreCase,int startindex, String
s2, int s2Startindex, int numChars)

startsWith()
This method determines whether a given string begins with a
specified string
public boolean startsWith(String str)
String s1=hello world;
System.out.println(s1.startsWith(hello);

public boolean startsWith(String str, int startindex)


System.out.println(s1.startsWith("world",6));

endsWith()
This method determines the string ends with a specified string
public boolean endsWith(String str)

String s1="hello world";


System.out.println(s1.endsWith("rld"));

compareTo()
This method is useful to compare two strings and to know which
string is bigger or smaller
This should be used as s1.compareTo(s2)
If s1 and s2 strings are equal, then this method gives 0
If s1 is greater than s2, then this method a +ve number
If s1 is less than s2, then it returns a ve number
When we arrange the strings in dictionary order, which ever
string comes first is lesser than the string that comes next.
Example: Box is lesser than Boy
This method case sensitive. It means BOX and box are not
same for this method
public int compareTo(String s)
public int compareToIgnoreCase(String s)

Modifying a Strings
1) substring()
2) concat()
3) replace()
4) trim()

substring()
This method is useful to extract sub string from a main string
public String substring(int x)
It return a new string consisting all characters starting from the
position x until the end of the string
Example:
String x = "0123456789";
System.out.println( x.substring(5) ); // 56789
public String substring(int stratindex, int endindex)
The string returned contains all the characters from the beginning
index, up to, but not including the ending index
System.out.println( x.substring(5, 8));

String concat()
This method concatenates or joins two strings (s1 and s2) and
return a third string (s3) as result.
public String concat(String s)
Example:
String x = "taxi";
System.out.println( x.concat(" cab") );

String replace(char old, char new)


public String replace(char old, char new)
This method replaces all the occurrences of character by a new
character ;
String x = "oxoxoxox
System.out.println( x.replace('x', 'X') ); // output is
"oXoXoXoX

String trim()
public String trim()
This method removes spaces from the beginning and ending of a
string
String x = Rishvad Mohan ";

System.out.println( x.trim() );

Searching String
indexOf()
This method is called in the form s1.indexOf(s2), and it
returns an integer value.
If s1 contains s2 as sub string, then the first occurrence of s2 in
the string s1 will be returned by this method
public int indexOf(String s)
String s1=This is a book
String s2=is
int n=s1.indexOf(s2);

lastIndexOf(String s)
This method returns the last occurrence of the sub string s in the
main string. If s is not found, then it returns negative value
public int lastIndexOf(String s)
String s1=This is a book
String s2=is
int n=s1.lastIndexOf(s2);

length()
public int length()
This method returns the length of the String used to invoke the
method
String x = "01234567";
System.out.println( x.length() ); // returns "8"

public String toLowerCase()


This method returns a String whose value is the String used to
invoke the method, but with any uppercase characters
converted to lowercase
String x = "A New Moon";
System.out.println( x.toLowerCase() );
public String toUpperCase()
This method returns a String whose value is the String used to
invoke the method, but with any lowercase characters
converted to uppercase
String x = "A New Moon";
System.out.println( x.toUpperCase() );

StringBuffer
StringBuffer is a class which represents strings in
such a way that their data can be modified
It means StringBuffer class objects are mutable

Creating StringBuffer class objects


StringBuffer sb=new StringBuffer(Hello);
StringBuffer sb=new StringBuffer();
Here, we are creating a StringBuffer object as an empty object.
In this case, a StringBuffer object will be created a default capacity of 16
characters
StringBuffer sb=new StringBuffer(50);
In this case, a StringBuffer object will be created a default capacity of 50
characters
Even if we declare the capacity as 50, it is possible to store more than 50
characters into this StringBuffer.
The reason is StringBuffer is mutable and can expand dynamically in
memory

Methods of StringBuffer class


public StringBuffer append(x)
x may be boolean, byte, int, long, float, double, char, character
array,String or other StringBuffer
It will be append to the StringBuffer object
Example:
StringBuffer sb=new StringBuffer(uni);
sb.append(versity);
System.out.println(sb);

public StringBuffer insert(int i , x)


It will be inserted into StringBuffer at the position represented by
i
Example:
StringBuffer sb=new StringBuffer(intelligent person);
sb.insert(11,young);
System.out.println(sb);

public StringBuffer delete(int I, int j)


This method removes characters from ith position till j-1th
position in the StringBuffer
sb.delete(0,3);
public StringBuffer reverse()
This method reverse the characters in the StringBuffer
StringBuffer sb=new StringBuffer(abc);
sb.reverse();
System.out.println(sb);

public int length()


public int indexOf(String str)
public int lastIndexOf(String str)
public StringBuffer replace(int I, int j,String str)
This replace characters from I to j-1, by the string str in the
StringBuffer object
StringBuffer sb=new StringBuffer(High Cost);
sb.replace(0,4,low);
System.out.println(sb);

You might also like