Programming in JAVA Unit-II BY N.RUBA ASST.PROF/DEPT. OF CA, BON SECOURS COLLEGE FOR WOMEN, THANJAVUR. 1
UNIT-II Chapter 3 Java language fundamentals  Building blocks of Java  Java as a programming language, follows a set of rules  Predfefined conventions that specify how syntactically legal constructs can be formed using the language elements.  A semantic definition specifies the meaning of syntactically legal constructs. 2
LEXICAL TOKENS low level language elements are known as lexical elements. 3 OPERATORS SEPARATORS LITERALS WHITE SPACE IDENTIFIER KEY WORD JAVA TOKENS
Identifiers  Identifiers are the names of variables, methods, classes, packages and interfaces. Unlike literals they are not the things themselves, just ways of referring to them. In the HelloWorld program, HelloWorld, String, args, main and println are identifiers.  Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.  4
literals  Literals in Java – Integral, Floating-Point, Char, String, Boolean  Literals are number, text, or anything that represent a value. In other words, Literals in Java are the constant values assigned to the variable. It is also called a constant.  For example,  int x = 100; 5
Literals integral Floating point Char string boolean 6
1. Integral literal  Hexa-Decimal (Base 16)  Digits 0-9 are allowed and also characters from a-f are allowed in this form. Furthermore, both uppercase and lowercase characters can be used, Java provides an exception here.e.g A34,76F  Decimal-(base 10)0-9e.g 598  Octal (base -8)0-7 e.g 675 7
2.Floating-Point Literals in Java  Here, datatypes can only be specified in decimal forms and not in octal or hexadecimal form.  Decimal (Base 10)  E.g 5.78 8
3. Char Literals in Java These are the four types of char-  Single Quote Java Literal can be specified to a char data type as a single character within a single quote. char ch = 'a';  Char as Integral A char literal in Java can specify as integral literal which also represents the Unicode value of a character. Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is 0-65535. char ch = 062;  Unicode Representation Char literals can specify in Unicode representation ‘uxxxx’. Here XXXX represents 4 hexadecimal numbers. char ch = 'u0061';// Here /u0061 represent a.  Escape Sequence Escape sequences can also specify as char literal. E.g-char ch = 'n'; 9
 4. String Literals  Java String literals are any sequence of characters with a double quote.  String s = "Hello";  5. Boolean Literals  They allow only two values i.e. true and false.  boolean b = true; 10
Variable declaration in Java  Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold.  Variable is a memory location name of the data. The Java variables have mainly three types :  Local,  Instance and  Static.  variable in a program can perform 2 steps  Variable Declaration  Variable Initialization 11
Variable Declaration:  To declare a variable, must specify the data type & give the variable a unique name.  Examples of other Valid Declarations are int a,b,c; float pi; double d; char a; 12
Variable initialization  To initialize a variable, you must assign it a valid value.  Example of other Valid Initializations are pi =3.14f; do =20.22d; a=’v’; You can combine variable declaration and initialization.  Example : int a=2,b=4,c=6; float pi=3.14f; double do=20.22d; char a=’v’; 13
Types of variables In Java, there are three types of variables:  Local Variables  Instance Variables  Static Variables 1) Local Variables Local Variables are a variable that are declared inside the body of a method. 2) Instance Variables Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are Object specific and are known as instance variables. 3) Static Variables Static variables are initialized only once, at the start of the program execution. These variables should be initialized first, before the initialization of any instance variables. Example: Types of Variables in Java class sum { static int a = 1; //static variable int data = 99; //instance variable void method() { int b = 90; //local variable } } 14
Wrapper classes in Java  Each primitive data type in java has a corresponding wrapper class.  The wrapper class in Java used to represent a primitive data type as an object. It is used to convert primitive into object and object into primitive.  Wrapper class belong to the java.lang.package  Wrapper classes for integers and floating-point numbers are sub-classes of the number class in the java.lang package. 15
Wrapper classes for primitive datatype Primitive data type Wrapper classes int Integer byte Byte short Short long Long float Float double Double 16
Operators in Java An operator takes one or more arguments and produces new value.  Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc. Types of operators in Java which are given below:  Unary Operator,  Arithmetic Operator,(or)mathematical  Shift Operator,  Relational Operator,  Bitwise Operator,  Logical Operator,  Ternary if-else Operator  Comma operator  Assignment Operator  String operator +  Operator precedence  Casting operators 17
 Ternary if-else operator  Boolean-exp?value():value1  Comma operator  Used in for loops  E.g for (i=1,j=10;i<10;i++,j--)  String operator +  used to concatenate two strings  Casting operator  Used to make type conversions 18
Control structures Control structures Selection statements Iterative statements Jump statements 19
Selection or branching  if statement to test a condition and decide the execution of a block of statements based on that condition result. The if statement checks, the given condition then decides the execution of a block of statements. If the condition is True, then the block of statements is executed and if it is False, then the block of statements is ignored. 20
If-else 21
Nested if statement in java  Writing an if statement inside another if-statement is called nested if statement. Syntax if(condition_1){ if(condition_2){ inner if-block of statements; ... } ... } 22
if-else if statement in java  Writing an if-statement inside else of an if statement is called if-else-if statement. Syntax if(condition_1){ condition_1 true-block; ... } else if(condition_2){ condition_2 true-block; condition_1 false-block too; ... } 23
switch statement in java  Using the switch statement, one can select only one option from more number of options very easily.  In the switch statement, we provide a value that is to be compared with a value associated with each option.  Whenever the given value matches the value associated with an option, the execution starts from that option.  In the switch statement, every option is defined as a case. 24
25
loop  while loop -used to repeat a given statement over and over. -entry controlled syntax: while(boolean-expression) { statements } 26
loop (or) iteration ->do-while statement in java - is used to execute a single statement or block of statements repeatedly as long as given the condition is TRUE. The do-while statement is also known as the Exit control looping statement. 27
for statement The for statement is used to execute a single statement or a block of statements repeatedly as long as the given condition is TRUE. 28
JUMP STATEMENTS IN JAVA  The java programming language supports jump statements that used to transfer execution control from one line to another line. The java programming language provides the following jump statements.  break statement  continue statement  labelled break and continue statements  return statement  break statement in java  The break statement in java is used to terminate a switch or looping statement. That means the break statement is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each. 29
30
continue statement in java  The continue statement is used to move the execution control to the beginning of the looping statement.  When the continue statement is encountered in a looping statement, the execution control skips the rest of the statements in the looping block and directly jumps to the beginning of the loop.  The continue statement can be used with looping statements like while, do-while, for, and for-each.  When we use continue statement with while and do-while statements, the execution control directly jumps to the condition  When we use continue statement with for statement the execution control directly jumps to the modification portion (increment/decrement/any modification) of the for loop. 31
32
Empty statement  Consists simply of a semicolon(;) if(x<0) { x=-x; }; legal –presence of the semicolon the compiler considers it to be an empty statement, not part of the if statement. 33
Arrays  Arrays are data structures that hold data of the same type in contiguous memory.  A group of memory cells that are contiguous have same name and store the same data type.  Two types  One dimensional  Multidimensional 34
Declaring Array Variables  To use an array in a program, must declare a variable to reference the array, and must specify the type of array the variable can reference Syntax Int age[ ]; double score[ ]; 35
Creating Arrays Allocation of memory and initialization create an array by using the new operator with the following syntax − Syntax arrayRefVar = new dataType[arraySize]; age= new int[ 10]; The above statement does two things −  It creates an array using new dataType[arraySize].  It assigns the reference of the newly created array to the variable arrayRefVar. 36
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − dataType[] arrayRefVar = new dataType[arraySize];  Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, ..., valuek}; The array elements are accessed through the index. Array indices are 0- based; that is, they start from 0 to arrayRefVar.length-1. 37
Representation of one dimensional array  38
Multidimensional array  Can be used to represent tables of data  It has rows and columns and two subscripts are needed to access the array elements.  (m-rows & n-column ie. m x n array) Syntax  int arrayofnum[ i] [j ];  arrayname[ i] [j ]=value;  int[ ] [ ] arrayofnum={{12,12,3},{45,8,90}}; data_type[dimension 1][dimension 2][]…[dimension n] = new data_type[size 1][size 2]…[size n]  example int[][] array1 = new int[2][2];//Two dimensional Integer Array with 2 rows and 2 columns Three Dimensional Array’s Declaration int[][][] array2 = new int[12][24][36]; //Three dimensional Array 39
Strings  Represents group of characters  Strings written in java program are all String class objects.  String class objects are immutable  Java defines the String class , which is part of java.lang.package 40
Constructor of string class String (char array[]);  String (char array[], int start, int count);  String (String object);  Constructor of String class with byte array  String(byte a[]);  String (byte a[], int start, int count); Special type of constructor  String(StringBuffer a[]); 41
Methods of String class  Char charAt(int index)  Void getChars()  Byte[] getBytes()  boolean equals(String str)  boolean equalsIgnoreCase(String str)  int compareTo(String str)  int compare ToIgnoreCase (String str)  Boolean startsWith(String str)  Boolean startsWith(String str, int index)  Boolean endsWith(String str)  Boolean endsWith(String str, int index)  int indexOf(int ch)  int indexOf(int ch, int index) 42
 Int lastIndexOf(int ch)  Int lastIndexOf(int ch, int index)  String subString(int index)  String subString(int index1,int index2)  String concat(String str)  String replace(char oldcharacter,char newcharacter)  String trim()  String toLowerCase()  String toUpperCase()  Int length() 43
 valueOf() method  The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.  equals() method  The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. The String equals() method overrides the equals() method of Object class.  44
StringBuffer class  Java provides a class called StringBuffer.  StringBuffer is a mutable string, which can be changed during the execution of a program.  Changeable of set of character StringBuffer(); StringBuffer(int size): StringBuffer(String str); 45
Constructor Description StringBuffer() creates an empty string buffer with the initial capacity of 16. StringBuffer(String str) creates a string buffer with the specified string. StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length. 46
 StringBuffer append(int value)  StringBuffer append(char[] str, int start,int length)  Int capacity()  StringBuffer delete()  StringBuffer insert()  StringBuffer reverse()  Void setCharAt(int index,char ch)  Void setLength(int size) 47
 1) StringBuffer append() method  The append() method concatenates the given argument with this string. class StringBufferExample{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.appen d("Java");//now original string is changed System.out.println(sb);//prints Hello Java } } 48
 StringBuffer insert() method  The insert() method inserts the given string with this string at the given position. class StringBufferExample2 { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } } 49
 3) StringBuffer replace() method  The replace() method replaces the given string from the specified beginIndex and endIndex.  class StringBufferExample3{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.replace(1,3,"Java");  System.out.println(sb);//prints HJavalo  }  } 50
 4) StringBuffer delete() method  The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.  class StringBufferExample4{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.delete(1,3);  System.out.println(sb);//prints Hlo  }  } 51
 5) StringBuffer reverse() method  The reverse() method of StringBuilder class reverses the current string.  class StringBufferExample5{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.reverse();  System.out.println(sb);//prints olleH  }  } 52
 6) StringBuffer capacity() method  The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.  class StringBufferExample6{  public static void main(String args[]){ StringBuffer sb=new StringBuffer(); System.out.printl n(sb.capacity());//default 16  sb.append("Hello");  System.out.println(sb.capacity());//now 16  sb.append("java is my favourite language");  System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  }  } 53
Method Description char charAt(int index) returns char value for the particular index int length() returns string length static String format(String format, Object... args) returns a formatted string. static String format(Locale l, String format, Object... args) returns formatted string with given locale. String substring(int beginIndex) returns substring for given begin index. String substring(int beginIndex, int endIndex) returns substring for given begin index and end index. boolean contains(CharSequence s) returns true or false after matching the sequence of char value. static String join(CharSequence delimiter, CharSequence... elements) returns a joined string. 54
static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string. boolean equals(Object another) checks the equality of string with the given object. boolean isEmpty() checks if string is empty. String concat(String str) concatenates the specified string. String replace(char old, char new) replaces all occurrences of the specified char value. String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence. static String equalsIgnoreCase(String another) compares another string. It doesn't check case. String[] split(String regex) returns a split string matching regex. 55
String[] split(String regex, int limit) returns a split string matching regex and limit. String intern() returns an interned string. int indexOf(int ch) returns the specified char value index. int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index. int indexOf(String substring) returns the specified substring index. int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index. String toLowerCase() returns a string in lowercase. String toLowerCase(Locale l) returns a string in lowercase using specified locale. String toUpperCase() returns a string in uppercase. String toUpperCase(Locale l) returns a string in uppercase using specified locale. String trim() removes beginning and ending 56
THANK YOU 57

Java Programming

  • 1.
    Programming in JAVA Unit-II BY N.RUBA ASST.PROF/DEPT.OF CA, BON SECOURS COLLEGE FOR WOMEN, THANJAVUR. 1
  • 2.
    UNIT-II Chapter 3 Javalanguage fundamentals  Building blocks of Java  Java as a programming language, follows a set of rules  Predfefined conventions that specify how syntactically legal constructs can be formed using the language elements.  A semantic definition specifies the meaning of syntactically legal constructs. 2
  • 3.
    LEXICAL TOKENS low levellanguage elements are known as lexical elements. 3 OPERATORS SEPARATORS LITERALS WHITE SPACE IDENTIFIER KEY WORD JAVA TOKENS
  • 4.
    Identifiers  Identifiers arethe names of variables, methods, classes, packages and interfaces. Unlike literals they are not the things themselves, just ways of referring to them. In the HelloWorld program, HelloWorld, String, args, main and println are identifiers.  Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.  4
  • 5.
    literals  Literals inJava – Integral, Floating-Point, Char, String, Boolean  Literals are number, text, or anything that represent a value. In other words, Literals in Java are the constant values assigned to the variable. It is also called a constant.  For example,  int x = 100; 5
  • 6.
  • 7.
    1. Integral literal Hexa-Decimal (Base 16)  Digits 0-9 are allowed and also characters from a-f are allowed in this form. Furthermore, both uppercase and lowercase characters can be used, Java provides an exception here.e.g A34,76F  Decimal-(base 10)0-9e.g 598  Octal (base -8)0-7 e.g 675 7
  • 8.
    2.Floating-Point Literals inJava  Here, datatypes can only be specified in decimal forms and not in octal or hexadecimal form.  Decimal (Base 10)  E.g 5.78 8
  • 9.
    3. Char Literals inJava These are the four types of char-  Single Quote Java Literal can be specified to a char data type as a single character within a single quote. char ch = 'a';  Char as Integral A char literal in Java can specify as integral literal which also represents the Unicode value of a character. Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is 0-65535. char ch = 062;  Unicode Representation Char literals can specify in Unicode representation ‘uxxxx’. Here XXXX represents 4 hexadecimal numbers. char ch = 'u0061';// Here /u0061 represent a.  Escape Sequence Escape sequences can also specify as char literal. E.g-char ch = 'n'; 9
  • 10.
     4. StringLiterals  Java String literals are any sequence of characters with a double quote.  String s = "Hello";  5. Boolean Literals  They allow only two values i.e. true and false.  boolean b = true; 10
  • 11.
    Variable declaration inJava  Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold.  Variable is a memory location name of the data. The Java variables have mainly three types :  Local,  Instance and  Static.  variable in a program can perform 2 steps  Variable Declaration  Variable Initialization 11
  • 12.
    Variable Declaration:  Todeclare a variable, must specify the data type & give the variable a unique name.  Examples of other Valid Declarations are int a,b,c; float pi; double d; char a; 12
  • 13.
    Variable initialization  Toinitialize a variable, you must assign it a valid value.  Example of other Valid Initializations are pi =3.14f; do =20.22d; a=’v’; You can combine variable declaration and initialization.  Example : int a=2,b=4,c=6; float pi=3.14f; double do=20.22d; char a=’v’; 13
  • 14.
    Types of variables InJava, there are three types of variables:  Local Variables  Instance Variables  Static Variables 1) Local Variables Local Variables are a variable that are declared inside the body of a method. 2) Instance Variables Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are Object specific and are known as instance variables. 3) Static Variables Static variables are initialized only once, at the start of the program execution. These variables should be initialized first, before the initialization of any instance variables. Example: Types of Variables in Java class sum { static int a = 1; //static variable int data = 99; //instance variable void method() { int b = 90; //local variable } } 14
  • 15.
    Wrapper classes inJava  Each primitive data type in java has a corresponding wrapper class.  The wrapper class in Java used to represent a primitive data type as an object. It is used to convert primitive into object and object into primitive.  Wrapper class belong to the java.lang.package  Wrapper classes for integers and floating-point numbers are sub-classes of the number class in the java.lang package. 15
  • 16.
    Wrapper classes forprimitive datatype Primitive data type Wrapper classes int Integer byte Byte short Short long Long float Float double Double 16
  • 17.
    Operators in Java Anoperator takes one or more arguments and produces new value.  Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc. Types of operators in Java which are given below:  Unary Operator,  Arithmetic Operator,(or)mathematical  Shift Operator,  Relational Operator,  Bitwise Operator,  Logical Operator,  Ternary if-else Operator  Comma operator  Assignment Operator  String operator +  Operator precedence  Casting operators 17
  • 18.
     Ternary if-elseoperator  Boolean-exp?value():value1  Comma operator  Used in for loops  E.g for (i=1,j=10;i<10;i++,j--)  String operator +  used to concatenate two strings  Casting operator  Used to make type conversions 18
  • 19.
  • 20.
    Selection or branching if statement to test a condition and decide the execution of a block of statements based on that condition result. The if statement checks, the given condition then decides the execution of a block of statements. If the condition is True, then the block of statements is executed and if it is False, then the block of statements is ignored. 20
  • 21.
  • 22.
    Nested if statementin java  Writing an if statement inside another if-statement is called nested if statement. Syntax if(condition_1){ if(condition_2){ inner if-block of statements; ... } ... } 22
  • 23.
    if-else if statementin java  Writing an if-statement inside else of an if statement is called if-else-if statement. Syntax if(condition_1){ condition_1 true-block; ... } else if(condition_2){ condition_2 true-block; condition_1 false-block too; ... } 23
  • 24.
    switch statement injava  Using the switch statement, one can select only one option from more number of options very easily.  In the switch statement, we provide a value that is to be compared with a value associated with each option.  Whenever the given value matches the value associated with an option, the execution starts from that option.  In the switch statement, every option is defined as a case. 24
  • 25.
  • 26.
    loop  while loop -usedto repeat a given statement over and over. -entry controlled syntax: while(boolean-expression) { statements } 26
  • 27.
    loop (or) iteration->do-while statement in java - is used to execute a single statement or block of statements repeatedly as long as given the condition is TRUE. The do-while statement is also known as the Exit control looping statement. 27
  • 28.
    for statement The forstatement is used to execute a single statement or a block of statements repeatedly as long as the given condition is TRUE. 28
  • 29.
    JUMP STATEMENTS INJAVA  The java programming language supports jump statements that used to transfer execution control from one line to another line. The java programming language provides the following jump statements.  break statement  continue statement  labelled break and continue statements  return statement  break statement in java  The break statement in java is used to terminate a switch or looping statement. That means the break statement is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each. 29
  • 30.
  • 31.
    continue statement injava  The continue statement is used to move the execution control to the beginning of the looping statement.  When the continue statement is encountered in a looping statement, the execution control skips the rest of the statements in the looping block and directly jumps to the beginning of the loop.  The continue statement can be used with looping statements like while, do-while, for, and for-each.  When we use continue statement with while and do-while statements, the execution control directly jumps to the condition  When we use continue statement with for statement the execution control directly jumps to the modification portion (increment/decrement/any modification) of the for loop. 31
  • 32.
  • 33.
    Empty statement  Consistssimply of a semicolon(;) if(x<0) { x=-x; }; legal –presence of the semicolon the compiler considers it to be an empty statement, not part of the if statement. 33
  • 34.
    Arrays  Arrays aredata structures that hold data of the same type in contiguous memory.  A group of memory cells that are contiguous have same name and store the same data type.  Two types  One dimensional  Multidimensional 34
  • 35.
    Declaring Array Variables To use an array in a program, must declare a variable to reference the array, and must specify the type of array the variable can reference Syntax Int age[ ]; double score[ ]; 35
  • 36.
    Creating Arrays Allocation ofmemory and initialization create an array by using the new operator with the following syntax − Syntax arrayRefVar = new dataType[arraySize]; age= new int[ 10]; The above statement does two things −  It creates an array using new dataType[arraySize].  It assigns the reference of the newly created array to the variable arrayRefVar. 36
  • 37.
    Declaring an arrayvariable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − dataType[] arrayRefVar = new dataType[arraySize];  Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, ..., valuek}; The array elements are accessed through the index. Array indices are 0- based; that is, they start from 0 to arrayRefVar.length-1. 37
  • 38.
  • 39.
    Multidimensional array  Canbe used to represent tables of data  It has rows and columns and two subscripts are needed to access the array elements.  (m-rows & n-column ie. m x n array) Syntax  int arrayofnum[ i] [j ];  arrayname[ i] [j ]=value;  int[ ] [ ] arrayofnum={{12,12,3},{45,8,90}}; data_type[dimension 1][dimension 2][]…[dimension n] = new data_type[size 1][size 2]…[size n]  example int[][] array1 = new int[2][2];//Two dimensional Integer Array with 2 rows and 2 columns Three Dimensional Array’s Declaration int[][][] array2 = new int[12][24][36]; //Three dimensional Array 39
  • 40.
    Strings  Represents groupof characters  Strings written in java program are all String class objects.  String class objects are immutable  Java defines the String class , which is part of java.lang.package 40
  • 41.
    Constructor of stringclass String (char array[]);  String (char array[], int start, int count);  String (String object);  Constructor of String class with byte array  String(byte a[]);  String (byte a[], int start, int count); Special type of constructor  String(StringBuffer a[]); 41
  • 42.
    Methods of Stringclass  Char charAt(int index)  Void getChars()  Byte[] getBytes()  boolean equals(String str)  boolean equalsIgnoreCase(String str)  int compareTo(String str)  int compare ToIgnoreCase (String str)  Boolean startsWith(String str)  Boolean startsWith(String str, int index)  Boolean endsWith(String str)  Boolean endsWith(String str, int index)  int indexOf(int ch)  int indexOf(int ch, int index) 42
  • 43.
     Int lastIndexOf(intch)  Int lastIndexOf(int ch, int index)  String subString(int index)  String subString(int index1,int index2)  String concat(String str)  String replace(char oldcharacter,char newcharacter)  String trim()  String toLowerCase()  String toUpperCase()  Int length() 43
  • 44.
     valueOf() method The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.  equals() method  The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. The String equals() method overrides the equals() method of Object class.  44
  • 45.
    StringBuffer class  Javaprovides a class called StringBuffer.  StringBuffer is a mutable string, which can be changed during the execution of a program.  Changeable of set of character StringBuffer(); StringBuffer(int size): StringBuffer(String str); 45
  • 46.
    Constructor Description StringBuffer() createsan empty string buffer with the initial capacity of 16. StringBuffer(String str) creates a string buffer with the specified string. StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length. 46
  • 47.
     StringBuffer append(intvalue)  StringBuffer append(char[] str, int start,int length)  Int capacity()  StringBuffer delete()  StringBuffer insert()  StringBuffer reverse()  Void setCharAt(int index,char ch)  Void setLength(int size) 47
  • 48.
     1) StringBufferappend() method  The append() method concatenates the given argument with this string. class StringBufferExample{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.appen d("Java");//now original string is changed System.out.println(sb);//prints Hello Java } } 48
  • 49.
     StringBuffer insert()method  The insert() method inserts the given string with this string at the given position. class StringBufferExample2 { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } } 49
  • 50.
     3) StringBufferreplace() method  The replace() method replaces the given string from the specified beginIndex and endIndex.  class StringBufferExample3{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.replace(1,3,"Java");  System.out.println(sb);//prints HJavalo  }  } 50
  • 51.
     4) StringBufferdelete() method  The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.  class StringBufferExample4{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.delete(1,3);  System.out.println(sb);//prints Hlo  }  } 51
  • 52.
     5) StringBufferreverse() method  The reverse() method of StringBuilder class reverses the current string.  class StringBufferExample5{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.reverse();  System.out.println(sb);//prints olleH  }  } 52
  • 53.
     6) StringBuffercapacity() method  The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.  class StringBufferExample6{  public static void main(String args[]){ StringBuffer sb=new StringBuffer(); System.out.printl n(sb.capacity());//default 16  sb.append("Hello");  System.out.println(sb.capacity());//now 16  sb.append("java is my favourite language");  System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  }  } 53
  • 54.
    Method Description char charAt(intindex) returns char value for the particular index int length() returns string length static String format(String format, Object... args) returns a formatted string. static String format(Locale l, String format, Object... args) returns formatted string with given locale. String substring(int beginIndex) returns substring for given begin index. String substring(int beginIndex, int endIndex) returns substring for given begin index and end index. boolean contains(CharSequence s) returns true or false after matching the sequence of char value. static String join(CharSequence delimiter, CharSequence... elements) returns a joined string. 54
  • 55.
    static String join(CharSequence delimiter,Iterable<? extends CharSequence> elements) returns a joined string. boolean equals(Object another) checks the equality of string with the given object. boolean isEmpty() checks if string is empty. String concat(String str) concatenates the specified string. String replace(char old, char new) replaces all occurrences of the specified char value. String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence. static String equalsIgnoreCase(String another) compares another string. It doesn't check case. String[] split(String regex) returns a split string matching regex. 55
  • 56.
    String[] split(String regex, intlimit) returns a split string matching regex and limit. String intern() returns an interned string. int indexOf(int ch) returns the specified char value index. int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index. int indexOf(String substring) returns the specified substring index. int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index. String toLowerCase() returns a string in lowercase. String toLowerCase(Locale l) returns a string in lowercase using specified locale. String toUpperCase() returns a string in uppercase. String toUpperCase(Locale l) returns a string in uppercase using specified locale. String trim() removes beginning and ending 56
  • 57.