SpringMVC is a part of Spring framework which makes possible client-server communication using Spring framework. It has many components which takes part in finding the request, delegating the request coming from client to the mapped class for request processing and many more. Below is the name of few important and very frequent used components are involved in SpringMVC architecture :



1. Dispatcher Servlet (Front Controller)
2. Handler Mapping
3. View Resolver 



Dispatcher Servlet : It is the first component which takes part in delegating the incoming request from clients to other component. It is designed using "front controller design pattern".  Every request from client to server passes through this servlet only that why it is designed using the front controller design pattern. 

Handler Mapping: It is one of the component used for finding the resource and exactly the method responsible for request processing after dispatcher servlet takes the incoming request. Dispatcher servlet takes the URL from the incoming request and delegates the URL to the handler mapping.
It search for the exact method mapped with that URL and return it to the Dispatcher servlet.

View Resolver: View is also one of the component which is used to complete the path of the resource to be displayed after complete request processing. InternalViewResolver is the default one used by the Spring framework.

Below is the image of the Layer structure of java web application :


In the above diagram you can see SpringMVC persists into controller layer and this layer is dedicated for request processing.





Spring is a framework and currently grabbed market of development. Spring is otherwise called as all in one framework just because with the help of Spring only one can develop entire web application. It has "HibernateTemplate" class which gives the functionality to interact with database without any other framework or technology like "Hibernate" or "JDBC" respectively. SpringMVC makes independent of relying on any other framework which persists on Controller layer for client and server communication. 

SpringMVC stands for Spring Model View and Controller. SpringMVC is designed using front controller design pattern. Dispacter Servlet i.e DS is acting as a front controller who is responsible for handing and delegating all the incoming requests from clients. This is only servlet stands before all the classes developed for handing and processing the incoming request. 

Requirement is to search a particular String in the Array of String value. To achieve this we need to have some set string values in a String array and secondly we need to have a String value to be searched.

Tips to Proceed...

1. Take counter
2. Iterate String and match the value on each iteration using equals() method.

Steps to do....

1. Take a counter count=0 .
2. Get the String to be searched.
3. Iterate the String Array and keep on searching from index=0 till length.
4. While looping keep on matching the string value with each index value of the Array.
5. If it get matched print "Match Found" and increment a counter.
6. If not matched then Print " No Match Found ".

Program :


public class Lab1{

    public static void main(String args[]){

 int count=0;
  
 String arr[]= new String[10];
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter the String ");

 for(int i=0;i<10;i++){    // Iterate loop to store value in Array
     System.out.print((i+1)+". ");
     arr[i]=sc.next();
 }

 System.out.println("Enter the String to be searched");
 String s=sc.next();      // Enter value to be searched
  
 for(int i=0;i<arr.length;i++){ // Loop to search the Element
     if(s.equals(arr[i])){  
  System.out.println("Match Found");
  count++;
     }
 }
        
        if(count==0)     // Checking No Such Element Present in Array
          System.out.println("No Element Found ");

 System.out.println("No of Words Found in Number:"+count);
  
 }
}










The above question means that we need to execute some line of code which perform something before the main() method execution. As we know that when we execute our program JVM will call main() at very first , so it seems that its not possible to perform something before the main() method execution but is possible with the static initialization block and calling method while initializing static variable 

Important Points :

1. Static initialized will always be executed before main() method calling by JVM.
2. Final static variable can be initialized using static initialization block.

1st Approach by static initialization block: 

Program :

public class Lab1 {

    static {                       // static initialization block
 int sum=10+20;
 System.out.println("SUM:"+sum);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}

In the above program sum=10+20 will be executed before main() method and hence output will look like ,
SUM:30
main() method

NOTE : We can also call a static method from static initialization block which too can perform some task which will always counted before main() method execution.


public class Lab1 {

    static {                 // static initialization block
 int s=Lab1.sum(10,20);
        System.out.println("SUM:"+s);
    }

    public static int sum(int a,int b ){
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}


Now in the above program static sum() method will be called first before main() method. And the output will look like ,

SUM:30
main() method

2nd Approach by Calling static method while initializing static variable :

public class Lab1 {

    static int x=Lab1.sum(10,20); 

    public static int sum(int a,int b ){
        System.out.println("SUM:"+(a+b));
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}



In the above program at the time of call loading JVM will try to initialize the static variable 'x' here and while initializing it will call static method sum(). So this method will be executed before the main() method execution. The output will look like,

SUM:30
main() method








This question might be asked in as interview to judge logic on how you are going to achieve without providing you the length() method to calculate the String length easily.

Tips to Think ....

1. As we know that in Java String doesn't end with the NULL character with in C it ends with the NULL character.
2. To get to the end of String we have nothing as a mark in Java but in C we can check for the NULL character.
3. Now have to think to get the mark to the end of the String.
4. One way of doing is to caught the Exception if JVM will throw "StringIndexOutOfBoundsException" if we try to access the extra index of the String.

Steps to do :

1.Initialize a count i.e c=0;
2. Run the while loop making it true ( goes infinite looping ).
3. Within the loop access the String using charAt() at each index.
4. After accessing it last index if it try to access the next index which is not actually present in the memory will will raise to "StringIndexOutOfBoundsException" and we need to caught the exception within try-catch block.
5. Keep Increasing the counter after each iteration.
6. Print the Counter at the catch block will give the length of the String.
7. Use the break statement to break the infinite looping with the while(true).

Program

public class Lab1 {

    public static void main(String[] args) {
  
        String s1="sushant";
 int count=0;
 int i=0;
 while(true){
        try{
    s1.charAt(i);
           i++;
    count++;
        }catch(StringIndexOutOfBoundsException e){
    System.out.println("String Length is : "+count);
    break;
       }
  }
     }
}





This is a interview question can be asked in an experienced or fresher's interview to write a program which will add up all the integer value present in a string and print the added number.

Tips to think how to do it...

1. For this kind of problem always think of first matching the number in a String .
2. How you are going to match?
3. The only simplest way is with the help of ASCII of 0-9 .

Steps to do :

1. Take a int variable c=0.
2. Run the loop from 0 to String length.
3. Get the each index value using charAt() method which will return the char value.
4. Convert that char into int by typecasting or any other way.
5. Now check that ASCII fall into the range of 48-57 for 0-9 int number.
6. If it matches then first convert that number into integer using Integer.parseInt().
7. Then add with the c and store to the same variable i.e c.
8. Repeat from 3-7 till the end of the loop.
9. At the end of loop , Print c outside the loop.

Program


public class Lab1 {

   public static void main(String[] args) {
 
 String s="s16u7ty9";
 int c=0;
 for(int i=0;i<s.length();i++){
    char ch=s.charAt(i);         // Getting each char from String
    int x=(int)ch;               
    for(int y=48;y<=57;y++){       // Loop for checking the ASCII
       if(x==y){
   int num=Integer.parseInt(""+ch); //Getting the int value
   c=c+num;
       }
    }
 }
 System.out.println("Total Sum:"+c); // Final sum 

   }

}







This is one of the important and mostly asked question in fresher and experienced interview. Singleton class means a class with only one object. It will have only one object which will be returned always when ever we try to create the object of singleton class. We can create our own singleton class. Interviewer will ask you to write your own singleton class, for that you need to remember following points to create your own singleton class :

a) Declare a static resource ( Object of the singleton class ) .
b) Create that resource in the static initialization block so that will be creating at the class loading time.
c) There must be a static method which return the resource.
d) Most importantly Constructor should be made private. 

Hello.java

class Hello{

   static Hello hello;
   
   private Hello(){}

   static {

     hello = new Hello(); 

   }

   public static Hello getHello(){

        return hello;
   
   }

}


A. java

class A{

  public static void main(String[] args){

     Hello h = Hello.getHello();  // return the object created at class loading.
     Hello h1 = Hello.getHello(); // It will also return the same object. 

  }
}




Hello class is the singleton class in which Hello is created in the static initialization block so that object will be created once which is at the time of class loading and will be returned as many times we try to create an object of Hello class. 

Why Constructor is made private ?

It is because object shouldn't be created directly using new operator.

Explanation :

As the Hello class ( Singleton class ) will be loaded the static initialization block will be executed and hence resource will be created and then whenever we call getHello() method it will always return the object created at the time of class loading. 

This is one of the common question to be asked in interview to judge your basic level of knowledge. We all know that String is immutable which means that once object created cannot be modified or if try to modify, it will create another String literal in the String pool. So this proves that String is immutable, but this is we are proving theoretically. Now if interviewer ask you to prove the same by writing programs then you will be doing like this,

class A{

  public static void main(String[] args){

     String s="java";  // Create a object in String pool.

     s = s + "java" ; // Create another object with "javajava" as 
                         String literal in the String pool

  }


Some of the Java Interview Questions for the fresher and Experienced ( Set - 3 )

1. What is package in Java? What is its advantage ?

Ans: This is the basic question might be asked in the interview. You just need to give the exact and proper definition in simple words.
" Package is the storage directory of java files. It is a way by which java classes get organized and placed in well structured directory. "

Advantages of packages:

1. It is going to organize the group of java classes in a well directory structure.
2. It reduces the naming conflict between the java classes.
3. It gives the hierarchy directory structure to store java classes.
4. It also increases the maintenance issue of java classes stored in different packages.
5. It increases the readability of java classes.

2. What is the difference between equals() method " == " operator ?

Ans: This is one of the commonly asked question in an interview.This can be answered with the following points:-

1. equals() is a method where as '==' is an operator.
2. equals() method can be used to compare the string literals where as '==' operator is used to compare the primitive types.
3. equals() is used to compare the content of the String object where as '==' is used to compare the memory location of the objects, whether that two object belong to same memory location or not.

3. What is the Garbage Collector in Java?

Ans: Garbage Collector in java is used to de-allocate the memory of the unreferenced object remain in the heap memory.

4. What do you understand by immutability in Java?

Ans: This is one of the famous and mostly asked question in an interview.  This can be explained in simple terms as " the object which cannot be modified once created is considered as immutable object in java , even if we try to modify the existing object then it will create another object rather modifying to the existing one ".

In java String is the immutable class.

5. What are Wrapper classes in Java?

Ans: In java for every primitive type there is a class which is called as the Wrapper classes. By the use of wrapper class we can represent the primitive types as an object.

6. What is Exception in Java ? How to handle the exception in Java?

Ans: Exception raised in the program will stops the normal flow of program unconditionally but it won't terminate the program that means exceptions can be handled.

There are two ways by which exception raised in the program :
1. By using the try-catch block.
2. Using the 'throws' keyword (let caller or JVM will handle )

7. What is error in Java? Tell some errors you have experienced while writing programs?

Ans: Error totally terminates the flow of execution of the program and hence control will never back to the program from where it get terminated. Error can't be handled and can't be recovered.

Interviewer may ask you about the error you have experienced while writing the codes if you going to an interview as a experienced guy. So you just need to mention some of the common errors we you have got like :
a) NoSuchDefinitionError
b) OutOfMemoryError....etc

8. What is the difference between Error and Exception in Java?

Ans: This is the common freshers interview question.
Error vs Exception:
1. Error terminates the normal flow of execution of program whereas it won't terminate the program.
2. Error can't be handled whereas Exception can be handled.

9. What is inheritance in Java? What are its types?

Ans: Inheritance is one of the important Oops features. Inheritance is the mechanism by which a new class is derived from existing class. By inheritance a relation is being developed between classes hierarchically.

According to Oops there are 5 types of inheritance :-

a) Simple Inheritance
b) Multiple Inheritance
c) Multi-level Inheritance
d) Hierarchical Inheritance
e) Hybrid Inheritance.

10. Is other overloaded main() method will be invoked by the JVM or not ?

Ans: No , other overloaded main() will not be invoked by JVM as it will only look for the main() method signature i.e public static void main(String[] arg) .
We are responsible to call all other overloaded method.

11. What do you understand by 'import' statement in Java?

Ans: 'import' is one of the keyword in java, which is used in java to import the packages. Import statement must be placed after package statement in java programs. Import statement will look alike:-

import java.lang.*; // one way ( will import all the classes within the java.lang package)
import java.lang.Object ; // another way ( importing specific class )

Note: second approach is the good practice always.

12. What is thread in Java?

Ans: This is one of the commonly and basic question to be asked in the interview. Thread is the smallest unit of process. It is the independent path of execution within a program. More than one thread can execute concurrently within a program which creates multi-threaded environment and hence enhance the performance.

13. Is constructor can be inherited in Java?

Ans: No , constructor cannot be inherited .

14. Is it possible to make main() as final?

Ans: Yes, it is very much possible to make main() as final.

15. Can you make methods inside an interface as static and why ?

Ans: No, method inside the interface can't be made static as because static method cannot be override in the sub-class.

16. What is finally block?

Ans: finally is a block in java to be executed at least once and it must be written either with try or with try-catch block. Finally block will have all the codes for releasing all the resources allocated while executing the java program.

17. What is singleton class in Java?

Ans: Singleton in java means the object for which will be created at the time of class loading and the same will be returned always, so singleton class will have only one object created and the same will be used every-time.

18. How many objects are created in below written codes?
String s="java";
String s1="java";

Ans: Only one object will be created.

19. Difference between StringBuilder and StringBuffer?
Ans: This is one of the most asked question in both fresher's and experienced interview.

StringBuilder :

a) All the methods in the StringBuilder are non-synchronized.
b) It is not a thread safe.

StringBuffer:

a) All the methods in the StringBuffer are synchronized.
b) It is thread safe.

20. What is the purpose of using toString() in Java?

Ans: toString() method in java will return the string representation of an object that is,

getClass().getName() + "@" + Integer.toHexString(hashCode());  

Like this toString() is overridden in different class and they have their own representation.


Some of the java Interview Questions for the fresher and Experienced ( Set - 2 )

1. What will happen if we try to modify the value of a final variable ?

Ans: Final variable can't be modified , if we try to do so then a compile time exception will be thrown i.e java.lang.IllegalAccessException.

2. What is Oops Concept ?

Ans: Oops is considered as Object Oriented Feature. As java is Object- Oriented language so it supports the following Oops features:-

a) Encapsulation
b) Inheritance
c) Polymorphism
d) Message Passing
e) Data Abstraction
f) Data Hiding

3. What is static variable ?where it is useful?

Ans: Static variable is a class variable which is at the class scope and not at the object scope. It is declared using the 'static' keyword with the variable name..........Click here to know more 


Memory allocation for the static are done only once at the time of class loading , so it is useful only if there is a common information which will be shared among all the object created for that class. 

4. What is instance variable ?

Ans: Instance variable are at the object level which means which is at the Object level scope. Each object can have a their own copy of instance variable. It is initialized by the constructor calling i.e while creating the object. 

5. What is polymorphism? How many types of Polymorphism is there in Java?

Ans: Polymorphism means 'many forms'. In java Polymorphism defines as the 'more than one methods having same name but perform different functions' . 

Basically there are two types of polymorphism in java :- 

a) Dynamic Polymorphism
b) Static Polymorphism

6. What is the difference between static method and instance method?

Ans: Static method :
a) It can be called with the class name.
b) It has only stack. 

Instance method :
a) It will be called with the Object only.
b) Separate stack will be created for each object calling instance method.  

7. Is it possible to access static content from non-static area? why ?

Ans: No, its not possible to access static content from non-static content. It is because non-static content can be accessible only if we are creating object and there are not guarantee for always creating the object. 

8. Difference between class level variable and local variable?

Ans: 
Class level variable :-

a) It is at the class scope or Object scope.

b) It can be static or instance. 
c) Memory will be allocated at the time of class loading if class level variable is static.
d) Memory will be allocated at the time of creating the object if the class level variable is instance.
e) It consume the space in heap memory. 

Local Variable:-

a) It is at the method scope,
b) It can't be static. 
c) Memory will be allocated only if method will be called.
d) It consumes the space in stack. 

9. Difference between dynamic and static Polymorphism ?

Ans: 
Dynamic Polymorphism:

a) It is otherwise called as overriding. 
b) Method to be called will be decided at the time of execution. 
c) It will be achieved by dynamic dispatch
d) It will have one method at the super class and another at the sub-class.

Static Polymorphism:

a) It is otherwise called as overloading.
b) Method to be called will be decided at the compile time only.
c) It will be achieved by calling respective overloaded method by passing requirement information.
d) It will have all the methods at the same class.

10. Why main() method is declared as static?

Ans: main() method is declared as static resulting there will not be any need to creating object for the JVM to call main() method. 

11. What is Dynamic Dispatch?

Ans: Dynamic dispatch means assigning sub-class object to the super-class reference variable. By this we can approach for dynamic polymorphism.

For ex: 

A--> super class
B----> Sub-class

A a = new B() ;---> Dynamic dispatch 


12. What is an Abstract class?
Ans:  A class declared with the abstract keyword is called as Abstract class. 
It has following features:-

a) An abstract class cannot be instantiated but can be subclassed. 
b) It can have both instance and static variables.
c) It can also have both abstract and non-abstract methods.
...............Click here to know more .

13. What is a marker interface and what is its usage?
Ans: Marker interface is an interface without any method declaration. Its is a empty interface like Serializable, Cloneable etc interfaces. 

It will be used just to indicate JVM that to perform for which that marker is designed.
for ex Cloneable marker interface has been designed to indicate JVM that there is a requirement of creating the clone of the object of the class implementing Cloneable interface.


14. What is the difference between Abstract and Interface?
Ans: Click here to know all the difference 

15. What is an anonymous class and its use?
Ans: An anonymous class is a class without any name and hence we can create only one object of an anonymous class.......Click here to know more about Anonymous class .

Use of Anonymous class:

a) It provide security to the application over network as we cannot create object of the anonymous explicitly. 
b) It can be used if we have to create only a single object to operate. 

16. Can we write constructor inside anonymous class and why ?
Ans: No , we cannot create/write constructor for the anonymous class as it has no name and constructor is same as the class name. 

17. What is the default package imported in Java class automatically ?
Ans: Default package which is going to be imported for every single java class is java.lang.* pakage. 

18. Name some of the methods from Object class?
Ans: Some of the common methods from Object class are:-
a) toString()
b) clone()
c) wait()
d) notify()
e) notifyAll()
e) hashCode()
f) equals()

g) finalize()
h) getClass()

19. What is hashcode?
Ans: HashCode is the integer representation of the object. Actual object get modified resulting some integer value is called as hashcode. Two different object can have same hashcode. 

20. What is cloning?
Ans: Cloning is process of creating proxy or dummy object of the actual object, which covers all the features of the actual/original object. Default cloning is done using clone() method. 






Some of the java Interview Questions for the fresher and Experienced ( Set - 1 )

1. What is Java , speak something about Java ?

Ans: Basically few points has to be remembered regarding java :

a) Java is high level language.
b) Java is Compiled and Interpreted language.
c) Java is a Object-Oriented Language but not a pure Object-Oriented.
d) Java is Platform-Independent Language which makes language as Portable.
........ Click here to see more

If interviewer ask you to speak something about java then without any hesitation ,confidently go on explaining from very basic of java till OOPS concept. Still interview won't let you stop speaking then start explaining threading feature of java. But mostly they will let you cover all the basic things of java and then they start asking their next level of question.
You should speak about following points->
i> What is Java?
ii> OOPS features of Java.
iii> Explain in brief about each Oops features.

2. Is Java Platform Independent ? If yes then justify your answer ?

Ans: Yes , java is platform independent. As we know that java is compiled + interpreted language and .class file is the result of compilation and this file is going to be interpreted by JVM so we need JVM to execute this .class file and thus JVM has to be present and designed for each operating System like Windows , Unix etc.So due to the portability to .class file from a machine to another machine makes java platform independent.


3. What are the command for compiling and executing Java program ?

Ans: javac is a command for compiling java file will result in .class file
        java is a command for executing .class file.

4. What is Classpath in Java ?

Ans: Classpath in java means setting path for the .class files. Classpath is a command in java used for setting path for the .class file. Let suppose we have a .class file in a directory and we are currently at another location, now that .class file which is at different location so can be from another location but we need to set the path for the .class file using classpath command.
like this way, set classpath='......directorylocaltion....';

5. Who is the super class of all the Java classes ?

Ans: Object class is super class all the classes.

6. How many keywords does Java have , name few which you have used in your program?

Ans: Java has 50 keywords. Some of the commonly used keywords are :-

public    private     protected    static    final    new    synchronized    class   int   float   long  
byte       double   default     abstract      interface   for   if     import   package   instanceof  
native     return   super    this   strictfp    switch   throw    throws   try   catch   void   while  
transient   volatile   void    implements    goto      finally   enum   do   continue   const  
break    assert   else   short.
null   true   false  ( These 3 words are Reserved word ).

7. What is "this" in Java and what is its use ?

Ans: Few points about this has to be remembered :

a) At very first this is a keyword in java.
b) this points to the current object.
c) Although 'this' is not a variable so it cannot hold any other reference.
...........Click here to know more

Some of the used of "this" keyword -
a) 'this' is the simplest way to use instead of current object reference.
b) As it always points to the current object , so we can perform any task using 'this' for the current object.

8. What is "super" in Java and for what purpose super is being used in Java programs ?

Ans:  Few points about this has to be remembered :

a) At first 'super' is a keyword in java.
b) 'super' refers to the inherited member from super class to its sub-class.
...........Click here to know more

9. How "this" is different from "super" ?

Ans: Point of differences :

a) 'this' refers to the current object where as 'super' refers to the inherited member of the super class.
b) this() is used for constructor chaining where as super() is used for calling super class default constructor.

10. Is Java is pure-object oriented language and why ?

Ans: No java is not a pure-Objected Oriented Language.
Basically there are two strong reason by which we can conclude and say that java is not a pure- Object Oriented Language, they are-

a) Use of static will not involve any Object creation.
b) Use of primitive type. Although respective Wrapper class is there but still primitive is being used for many purposes.

11. Is Java supporting multiple inheritance and why ?

Ans: No java is not supporting Multiple inheritance directly but approached towards performing multiple inheritance using interfaces. There would lead to some issues if java is supporting multiple inheritance directly :
a) Memory wastage problem
b) Ambiguity Problem in calling methods.

12. Is pointer supported by Java and why?

Ans: Yes Pointer are supported by java but is fully abstract from the developer. It is internally implemented by the java vendor. It is not given at the developer level as because to make java secured. As we know that pointer directly goes to the memory address so there may have chance of security threat if pointer is allowed to implement in java.

13. What is the use of  "native" keyword in Java ?

Ans: 'native' is a keyword in java and are used with the method, which says, that method is implemented using some low level language. So if we have to implement something in low level language then we can use the 'native' keyword.

14. What is Constructor ?

Ans: Constructor is like a method but with no return type. Constructor has same name as the class name. It is used to initialize the  instance variable.
..........Click here to know more

15. What is the purpose of making main() as static ? 

Ans: Purpose of main() as static:
a) So that JVM need not to create any object to call main().
.............Clicl here to know more

16. Does Constructor return any value ? 

Ans: As constructor doesn't have any return type so it cannot return any value, bt we can write 'return' in the constructor as writing 'return' simply means returning the control to the caller.

17. What if we write simply "return" statement in constructor?

Ans: Nothing will happen it will simply return the control to the caller.

18. How may types of initialization blocks in java ?

Ans: There are two types of initialization block:
1. Static initialization block
2. Instance initialization block.

19. What is the use of introducing static initializing block in java ?

Ans: Static initialization block can be used for following purposes:

a) It can be used to initialize the final static variable.
b) It can be used to execute some other method before the main() method.
...............Click here to know more

20. What is the use and purpose of instance initialization block in java ?

Ans: Static initialization block can be used for following purposes:

a) It can be used to initialize the final instance variable.












It is a public abstract interface. Many classes and interfaces are extending this abstract interface for different purposes.


SuperClass of Appendable:-

From java.lang package -

StringBuffer

StringBuilder

From java.io package -

BufferedWriter

CharArrayWriter

FileWriter

FilterWriter

OutputStreamWriter

PipedWriter

PrintStream

PrintWriter

StringWriter

Writer

From java.nio package - 

CharBuffer

From java.rmi.server package -

LogStream

All the above classes and interfaces are designed for different purposes and used all abstract method defined in the AbstractStringBuilder class for their own way of implementing the code by overriding these four methods.  


Methods of AbstractStringBuilder class


public abstract Appendable append(CharSequence cs) throws IOException;

public abstract Appendable append(CharSequence cs, int i, int j)  throws IOException;

public abstract Appendable append(char cs) throws IOException;





It is a private class or more specifically we can say its a ' private - package ' class i.e it is declared as not public and as abstract. As it was not there before the release of JDK 1.5 and was first introduced in java 5.0 as the superclass for both StringBuffer and StringBuilder.  Initially before JDK 1.5 there was only one class i.e StringBuffer ( which is thread safe ) and was extending Object class, but later with the release of JDK 1.5 AbstractStringBuilder and StringBuilder was introduced and now StringBuffer is extending AbstractStringBuilder . 

What is private - package class ?
If we declare a non-public class in a package whose scope will be within that package only , in other terms we create any instance of the class outside the package and hence can be considered as private class and called as private-package class. 


Aim behind intoducing AbstractStringBuilder ?
As we knowing that there are two identical class i.e StringBuilder and StringBuffer expects StringBuffer is thread safe and where as StringBuilder is not. Thus all the methods and their implementation are almost identical so instead of writing two times for both the classes they introduce a non-public abstract class i.e AbstractStringBuilder class which has same method with implementation and hence both are classes are using its implementation. 


Interesting facts of AbstractStringBuilder 

If we notice in AbstractStringBuilder class many method returns its own class instance only and its sub-classes i,e StringBuffer and StringBuilder both the classes override the methods of AbstractStringBuilder class and restrict the return type to their own class instance, this narrowing the return type by overiding the method in its sub-class is termed as ' co-variant return ', which is seen with the release of JDK 1.5 and with the later versions.    


Constrcutors of AbstractStringBuilder class


  AbstractStringBuilder(int i)

Instance variables of AbstractStringBuilder class

1. char[]   value;
2. int        count;
3. static final int[]    sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, 2147483647 };

Methods of AbstractStringBuilder class

  
  public int capacity()

  public void ensureCapacity(int i)

  void expandCapacity(int i)

  public void trimToSize()

  public void setLength(int i)

  public char charAt(int i)

  public int codePointAt(int i)

  public int codePointBefore(int i)

  public int codePointCount(int i, int j)

  public int offsetByCodePoints(int i, int j)

  public void getChars(int i, int j, char[] c, int k)

  public void setCharAt(int i, char c)

  public AbstractStringBuilder append(Object obj)

  public AbstractStringBuilder append(String s)

  public AbstractStringBuilder append(StringBuffer sb)

  public AbstractStringBuilder append(CharSequence cs)

  public AbstractStringBuilder append(CharSequence cs, int i, int j)
  
  public AbstractStringBuilder append(char[] ch)
  
  public AbstractStringBuilder append(char[] ch, int i, int j)

  public AbstractStringBuilder append(boolean b)

  public AbstractStringBuilder append(char c)

  public AbstractStringBuilder append(int i)

  static int stringSizeOfInt(int i)

  public AbstractStringBuilder append(long l)

  static int stringSizeOfLong(long l)

  public AbstractStringBuilder append(float f) 

  public AbstractStringBuilder append(double d)

  public AbstractStringBuilder delete(int i, int j)

  public AbstractStringBuilder appendCodePoint(int i)

  public AbstractStringBuilder deleteCharAt(int i)
  
  public AbstractStringBuilder replace(int i, int j, String s)
  
  public String substring(int i)

  public CharSequence subSequence(int i, int j)

  public String substring(int i, int j)

  public AbstractStringBuilder insert(int i, char[] c, int j, int k)
  
  public AbstractStringBuilder insert(int i, Object o)

  public AbstractStringBuilder insert(int i, String s)

  public AbstractStringBuilder insert(int i, char[] c)

  public AbstractStringBuilder insert(int i, CharSequence cs)

  public AbstractStringBuilder insert(int i, CharSequence cs, int j, int k)

  public AbstractStringBuilder insert(int i, boolean b)

  public AbstractStringBuilder insert(inti, char c)

  public AbstractStringBuilder insert(int i, int j)

  public AbstractStringBuilder insert(int i, long l)

  public AbstractStringBuilder insert(int i, float f)

  public AbstractStringBuilder insert(int i, double d)

  public int indexOf(String s)

  public int indexOf(String s, int i)

  public int lastIndexOf(String s)

  public int lastIndexOf(String s, int i)

  public AbstractStringBuilder reverse()

  public abstract String toString();

  final char[] getValue()

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic