-->
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Sunday, August 20, 2017

String Buffer

java.lang.StringBuffer
StringBuffer is another class present in Java which allows us to manipulate strings.This class is just like the String class except the fact that the strings created by this class are mutable.It is also thread-safe which means multiple threads cannot operate on the string. 
The StringBuffer class implements:
i)Serializable interface
ii)Appendable interface
iii)CharSequence interface


Constructors of StringBuffer class


Constructors

Description

StringBuffer() Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq) Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity) Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str) Constructs a string buffer initialized to the contents of the specified string.


Methods of StringBuffer class


Modifiers and type

Methods

Description

public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.

Saturday, August 12, 2017

String Class

Java provides some inbuilt classes to manipulate strings.One of them is java.lang.String.This class provides a lot of methods for string manipulation. The java.lang.String implements 
i)Serializable
ii)Comparable<String>
iii)CharSequence interfaces

Creating String with String class

String name="Hello"
String name=new String("Java");


String class Methods:

Methods

Description

char charAt() returns the character at 'index'
int length() returns the length of String
int compareTo(String anotherString) Compares two strings lexicographically
int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences.
String concat(String str) Concatenates the specified string to the end of this string.
boolean contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values.
boolean contentEquals(CharSequence cs) Compares this string to the specified CharSequence
boolean equals(Object anObject) Compares this string to the specified object
boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array.
int hashCode() Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index
int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

Saturday, August 5, 2017

Immutable String

In Java, String is a class and objects of this class is used to store strings.These String objects are made immutable in Java.Immutable means unchangeable, which cannot be changed.Once an object of String class is created, its content cannot be changed or altered.Whenever the program tries to make any modification to any String class object, the value residing in it is not changed but rather a new String object is created with the desired value and the old reference variable is made to point at the newly created object.Let's see this example


class StringTutorial
 {  
  public static void main(String args[])
    {  
     String s="Robert";  
     s.concat("James");//Using concat function to Add "James" at the end of "Robert"
     System.out.println(s);//will print Robert because strings are immutable objects and original state cannot be changed!
    }  
  } 
Output:
Robert 

In the above example, we are trying to add the string "James" at the end of "Robert". After we have used concat function to add the two Strings the output is surprisingly still the same.Why did it happen?

It happened because String objects are immutable and cannot be changed and 's' represents a String object holding the value "Robert".Whatever changes we make to the content of 's' will not be reflected in it instead a new object will be created in memory containing the changes we wanted to do and the reference variable 's' will be made to point to that new object.


Here 's' was pointing to "Robert" and when we used the concat function to add "James" at the end of "Robert" the original object was not affected but a new object was created with the changes we wanted.
Did you notice that 's' is still pointing to the old object? and this is the reason why the output was still "Robert" not "RobertJames" because we forgot to make 's' point to the newly created object.If we want the concatenated output then we should do this

class StringTutorial
  {  
   public static void main(String args[])
    {  
       String s="Robert";  
       s=s.concat("James");//Using concat function to Add "James" at the end of "Robert"
       System.out.println(s);//will print RobertJames
       }  
    }  

Why Strings are Immutable in Java?
The exact reasons for making strings immutable in java can be stated only by the the creators of String class.There can be many possible answers to this question but let's see some reasonable arguments :
1)Required by String constant pool:
String pool is a special storage area in Java heap memory. Whenever a string is created and that newly created string already exists in the String constant pool, the reference of the existing string will be returned and  assigned to the reference variable associated with the new string, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap

String string1 = "Hello";
String string2 = "Hello";



If string is not immutable, changing any one string will lead to the wrong value for the other references.

2)Security:
3)To make Strings thread-safe:
4)Caching hashcode:
5)Class Loading Mechanism:
 

Friday, August 4, 2017

Labelled Loops

As you know loops are used to repeat a particular set of instructions. We can combine it with label concept and use it more effectively.In java we can give a label to a block of statement/s.A label can be any valid java variable name. To give a label to a loop, place the label name before the loop with a colon(:) at the end.

Syntax:
    labelname:  
    for(initialization;condition;incr/decr){  
    //code to be executed  
    }

Example of a labelled loop:

    public class LabeledLoop
1  {  
    public static void main(String[] args)  
   {
        outer:  
            for(int i=1;i<=3;i++)
               {  
                inner:  
                    for(int j=1;j<=3;j++)
                     {  
                        if(i==2&&j==2)
                        {   
                            break outer;  
                        }  
                        System.out.println(i+" "+j);  
                    }  
            }  
  }  
  }  
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3

Monday, July 24, 2017

Introduction to Java Strings

What are Strings?
A String simply refers to a set of characters.....isn't it simply array of characters then?Yes, it is! But in java String is basically an object that represents a sequence of characters.An array of String works just like a string object
    char[] ch={'j','a','v','a'};  
    String s=new String(ch);
is as same as

    String s="java";

Why use Strings?
One of the main objectives of a computer is to process real world data which includes name,address etc which is nothing but a sequence of characters. To handle these kinds of data and execute operations on them a Java programmer must know the inbuilt string class

String Classes
Java provides three String classes to handle Strings
i)java.lang.String  //Immutable
ii)java.lang.StringBuffer  //Mutable
iii)java.lang.StringBuilder   //Mutable

We will see the properties of this class later.Let us now see how we can create a String in java.

There are many ways by which we can create a String in java
i)By using a String Literal
ii)By using another String Object
iii)By using new operator
iv)By concatenation(using + operator)

By using a String Literal :
A String literal is simply a set of characters enclosed within " ". We can create a String by assigning a String literal to a String instance.
String str1 = "Hello";
String str2 = "World";

By using another String Object:
String str1 = "Hello";
String str2 = new String(str 

By using new operator:
String str3 = new String("Java");

By concatenation(using + operator)

String str1="Hello"
String str2="World"
String str3=str1+str2;

Monday, July 17, 2017

Jumps in loop

Jumps in Loop
In a loop many times it becomes desirable to skip a part of the loop or leave the loop immediately as soon as a certain condition occurs.For Example,you are searching for a name in a String array,as soons as you find the name you should exit the loop immediately as there is no point in continuing the search.

Jumping out of the loop
Exiting from a loop or switch can be achieved by using break statement.Whenever a break statement is encountered inside a loop,the loop is terminated and the execution of the code following the loop body is continued with.

Example:

for(int i=0;i<5;i++)
{
if(i==3)
break;
else
System.out.println(i);
}
System.out.println("Hello");
Output:
1
2
Hello

Explanation:
When the vaue of i is either 1 or 2..the else block is executed and the value of i is printed. As soon as the value of  i becomes 3 the if block executes and loop is exited immediately and the code just after the loop body is executed.

Skipping a part of the loop
Sometimes we want to simply skip a part of the loop as soon as a particular condition is fulfilled. To do this we use continue statement.
Example:


    public class ContinueExample {  
    public static void main(String[] args) {  
        for(int i=1;i<=10;i++){  
            if(i==5){  
                continue;  
            }  
            System.out.println(i);  
        }  
    }  
    }  

Output:
1
2
3
4
6
7
8
9
10

Do-While loop

Do-While loop
Do-While is an exit controlled loop. It means it will get executed at least once even if the test condition is false beacuse the test condition is checked inside the loop body.

Syntax:

initialization
do{  
//code to be executed
//update statement
}while(condition); 

Example:

    public class DoWhileLoop {  
    public static void main(String[] args) {  
        int i=1;  
        do{  
          System.out.println(i);  
        i++;  
        }while(i<=10);  
    }  
    }  

Output:
1
2
3
4
5
6
7
8
9
10