Friday 30 November 2012

EXCEPTION HANDLING CONT3.....

RETHROWING THE SAME EXCEPTION:
        Just as you can toss a new exemption from a capture agreement you can also toss the same exemption you just captured here's capture stipulation that does this.

   catch(IOException e) {
   // do factor then if you choose you can't manage it
   toss e;
   }

      All other capture conditions associated with the same try are ignored if a lastly prevent leaves it operates and the exemption is tossed returning to the contacting technique (the next technique down the contact stack). If you toss a examined exemption from a capture stipulation you must also announce that exemption in other terms you must manage ad announce in contrast to deal with or announce the following example is illegal:
     community gap dostuff() {
     try {
     // dangerous IO things
     } catch(IOException ex) {
     // can't manage it
     toss ex; // can't toss it unless you announce it
    }
     }

  In the previous value the doStuff() technique is clearly able to toss a examined exemption in this situation an IOException so the compiler says "well that's just wonderful that you have a try/catch in there but it's not excellent enough. If you might rethrow the IOExcepion you capture then you must announce it

CREATING AN EXCEPTION:
         In this work out we create an effort to create a customized exemption we won't put in any new technique (It will have only those got from exception) and because expands exemption the compiler consider it a examined exemption the objective of the system is to figure out whether a control range discussion comprising a particular meals (as a string) is regarded bad or OK.

    Let's first create our exemption we will contact it BadFoodException this exemption will be tossed when a bad meals is experienced.
    create an linking category known as MyException and a min() technique which will stay vacant for now.

RETHROWING THE SAME EXCEPTION:
    Build a technique known as checkFood(). It requires a sequence justifications and punches our exemption if it doesn't like the meals it was given. Otherwise it informs us it prefers the meals you can add meals you aren't particularly attached to to the record.
    Now in the main() technique you'll get command-line discussion out of the sequence range and then finish that sequence on to the CheckFood() technique. Because it's examined exemption the checkFood() technique must announce it and the main() technique must manage it (using a try/catch). Do not have main() announce the exemption because if main() geese the exemption who else is returning there to capture it?
    As awesome as exemption managing creates dealing with is it's still up to designer to create appropriate use of it. Exception managing creates planning our value and signaling issue simple but the exemption owner still have to be published. you'll discover that even the most complicated circumstances can be managed and your value will be recyclable understandable and maintainable.

THROW KEYWORD

THROW KEYWORD:-
       Sometimes we can make Exception to this rule item clearly and we can handover that exception things to the JVM clearly by throw keyword and key phrase. The objective of throw keyword and key phrase is to handover our make exception item object clearly to the JVM.

EXAMPLE1:
 category Test{
                  community fixed gap primary (string[] args){
                      program.out.println(10/0);
                }
                 }

                  In this situation arithmeticException item designed unquestioningly and handover to the JVM instantly by the primary method

EXAMPLE 2:-
   category Test{
                    community fixed gap main(string[] args) {
                       throw new arithmeticexception("/by Zero");
                         }
                   }

                    In this situation development of an item and handover to the JVM clearly by the programmer

NOTE:-
      (i) After throw announcement we are not allow to placed any declaration straight breach leaded to gather time mistake saying remote declaration.
(ii)It is possible to tossed any throwable kind such as error
(iii) we can use throw keyword and key phrase only for throwable things otherwise we will get gather time mistake saying unique type

EXCEPTION HANDLING CONT2........

 EXCEPTION HANDLING CONT2........
EXCEPTION MATCHING:
     If you have different framework consisting of a super class exception and a variety of subtypes and you've enthusiastic about managing one of the subtype in unique way but want to deal with all the relax together you need create only two capture conditions. When different is tossed coffee will try to discover (by looking at the available capture conditions from the top down) a capture stipulation for the exception kind if it doesn't discover one it will look for for a owner for a super type of the exception then the exception is spread down the contact collection. This procedure is known as exception related. Let's look at example:

    transfer coffee.io.*;
    community category readData {
    community fixed gap main(String args[]) {
    try {
    RandomAccessFile raf =
    new RandomAccessFile("myfile.txt","r");
    byte b[] = new byte[1000];
    rar.readfully(b, 0, 1000);
    }
    catch(FileNotFoundException e) {
    System.err.println("File not found");
    system.err.println(e.getmessage());
    e.printStackTrace();
    }
    catch(IOException e) {
    system.err.println("IO Error");
    system.err.println(e.tostring());
    e.printstacktrace();
    }
    }
    }


    This brief program efforts to start a information file and to study some information from it starting and studying information files can produce many exception most of which are some kind of IOException suppose in this software we're enthusiastic about understanding only whether the actual exception is a filenotfoundException. Otherwise we don't care exactly what the issue is

       FileNotFoundException is a subclass of IOException. Therefore we could manage it in the capture stipulation that conditions that grabs all subtypes of IOException but we would have to check the exception to figure out whetherit was a FileNotFoundException. Instead we known as a unique exception owner for the FileNotFoundException and a individual exception owner for all other
IOException subtypes.
       If this value produces a FileNotFoundException it will be managed by the capture stipulation that starts at range 10 if it produces another IOException-perhaps EOFException which is a subclass of IOException-it will be managed by the capture stipulation that starts at line15. If some other exception is produced such as a playback exception will be spread down the contact collection.

      Observe that the capture stipulation for the File Not Found Exception was placed above the owner for the IOException. This is really necessary if we do it the other way this method will not gather. The handlers for the most particular exclusions must always be placed will not gather the handlers for the most unique exclusions must always be placed above those for more common exclusions. The following will not compile:

       try {
       // do dangerous IO things
      } capture (IOException e) {
      // manage common IOException
      } capture (FileNotFoundException ex) {
      // manage just FileNotFoundException
      }


YOU'LL GET A COMPILER ERROR SOMETHING LIKE THIS:
TestEx.java:15
: exception coffee.io.FileNotFoundException has already been caught
} capture (FileNotFoundException ex) {

      If you think returning to the individuals with football safety gloves (in the area "propagating Uncaught Exception") suppose the most common safety gloves are the biggest and can thus capture many different types paint balls. An Ioexception glove is huge enough and versatile enough to capture any kind of IOException so if the individual on the fifth ground (say, Fred) has a big 'ol IOException glove he can't help but capture a File Not Found Exception football with it,

    And if the guy (say,jimmy) on the second ground is having a File Not Found Exception glove that   File Not Found Exception football will never get to him since it will always be ceased by Sam on the fifth ground status there with his big-enough-for-any-IOException glove so what do you do with exception that are friends in the other then the transaction in which the capture stipulation re placed doesn't issue.

Thursday 29 November 2012

EXCEPTION HANDLING CONT1.........

THE FOLLOWING LEGAL CODE DEMONSTRATES A TRY WITH A FINALLY BUT NO CATCH:
  try{
  // do stuff
  } finally {
  //clean up
  }
  the following legal code demonstrates a try catch and finally;
  try {
  // do stuff
  }catch (SomeException ex) {
  // do exception handling
  } finally {
  // clean up
  }
  the following ILLEGAL code demonstrates a try without  a catch or finally:
  try {
  // do stuff
  }
  // need a catch or finally here
  system.out.println("out of try block");
  the following ILLEGAL code demonstrates a misplaced catch block::
  try {
  }
  // do stuff
  }
  // can't have code between try/catch
  system.out.println("out of try block");
  catch (Exception ex) {}
It is illegal to use a try condition without either a catch condition or a finally condition A try condition by itself will result in a compiler error any catch circumstances must immediately comply with the try avoid any finally condition must straight away comply with the last catch condition ( or it must quickly comply with the try avoid if there is no catch ). It is legal to take out either the catch condition or the finally circumstances but not both

EXCEPTION HANDLING CONT..........

Using finally:
     A lastly prevents clos value that is always executed at some point after the try prevent climate an exemption was tossed or not. Even if there is a come back declaration in the try prevent the lastly prevent finishes right after the come back declaration is experienced and before the come back executes

    This is the right place to shut your information launch your system electrical sockets and execute any other clean-up your value needs. If the try prevents finishes with no different the lastly prevent is implemented soon after the try prevent finishes if there was an exemption tossed the lastly prevent finishes soon after the appropriate capture prevent finishes the main objective of lastly prevents is to sustain the clean-up code

     Let's look at another pseudocode example:

       try{
    // This is the first range of the "guarded region"
    }
    capture (MyFirstException) {
    // put value here that manages this exemption.
    }
    capture  (My First Exception) {
    // put value here to launch any source we
    }
    lastly {
    // put value here to launch any source we
    // assigned in the try clause
    }
    // More value here


As before performance  begins at the first range of the try prevent range 2 If there are no exclusions tossed in the try prevent performance exchange to range 11 the first range of the lastly prevent. on the other hand if a My Second Exception id thrown while the value in the try prevent is executing performance exchanges to the first range of that exemption owner range 8 in the capture stipulation. After all the value in the capture stipulation is implemented the system goes to range 11 the first range of the lastly clause

    do it again after me : lastly always runs! OK we'll have to improve that a little but for now begins losing in the concept lastly always operates if an finishes is tossed lastly operates if an exemption is not tossed lastly operates if the omission is captured lastly operates if the exemption is not captured lastly operates later we'll look at the few circumstances in which lastly might not run or finish.

      Keep in mind lastly conditions are not needed if you don't create one your value will gather and run excellent in fact if you have no source to fresh up after your tr prevent finishes you probably don't need a lastly stipulation. Also because the compiler doesn't even need capture situations sometimes you'll run across value that has a try prevent instantly followed by a lastly prevent such value is useful when the exemption is going to be approved back to the contacting  technique as described in the next area. Using a lastly prevent allows the clean-up value to finishes even when there isn't a capture stipulation 

EXCEPTION HANDLING.....CONT

 CATCHING AN EXCEPTION USING TRY AND CATCH:
      Before we start, let's provide some language  The phrase "exception" indicates "exception condition" and is an incident that change the regular system circulation. A lot of factor can cause to exclusions. such as components failing source fatigue and excellent old insects. When an remarkable occasion happens in coffee an exception is said to be "thrown" the value that's accountable for doing something about the exception is known as an "exception handler" and it "catches" the tossed exception.

     The try is used to described a prevent of value in which exclusions may happen. This prevent of value is known as a included area ( which really indicates "risky value goes here") one or more capture sessions go with a certain exception (or list of exceptions-more on that later) to a prevent of value that manages. It the primary objective of capture the exception from try prevent. Here's how it looks in pseudocode.


    try
    // this is the first range of the "guarded region"
    // that is controlled by the keyword and key phrase.
    // put value here that might cause some type of exception.
    // we may have many value collections here or just one.
    }
    capture (MyFirstException)  {
    // put value here that manages this exception.
    // this is the next range of the exception owner.
    // this is the last range of the exception owner
    }
    catch(MySecondException) {
    // put value here that  manages this exception
    }
    
    // some other unguarded (normal, non-risky) value begins here

  In this pseudocode example collections 2 through 5 represent the covered area that is controlled by the stipulation . Line 7 is an exception owner for an exception of type My Second Exception. Observe that capture prevent instantly adhere to the try prevent. This is a need if you have one or more capture prevent they must instantly adhere to the try prevent. Furthermore the capture prevents they must all adhere to each other without any other declaration or prevents in between. Also the transaction in which the record prevents appear issues as we'll see a little later.

      Exemption of the covered area begins at range 2. If the system exception all the way previous range 5 with no exclusions being tossed performance will transform to range 15 and proceed downwards. However if whenever they want in collections 2 through 5 ( the try prevents ) an completes is tossed of type My First Exception performance will instantly  exchange to range 7 collections 8 through 10 will then be implemented so that the whole capture prevent operates and then exertion will exchange to range 15 and proceed. Observe that that if an exception happened on say line3 of the try prevent the relax of the collections in the try avoid (4 and 5) would never be implemented once management leaps to the capture prevent it never profits to finished the stability of the try prevent

Tuesday 27 November 2012

EXCEPTION HANDLING

 What is the difference between and Error?
    Omission is a program we are able to provide the solution programmatically.
    Error is a program we cannot provide the solution programmatically.


If any exemption is raised in your program if we are not moving that Omission it is always infrequent cancellations to provide smooth cancellations for the program we should handle the Omission effectively.
Exception Passing is nothing but we are providing an alternative way to continue the rest of the program efficiently.

IMPORTANT IN INTERVIEW:-

Explain Conventional Omission Passing Process in java?

If different raised the strategy in which it's raised is responsible for the growth of Omission product by such as the following details.

     Name of the Exception
     Information of the Exception
     Selection Trace

     After creating Omission product the strategy handover it to the JVM
     JVM tests for Omission Passing value in that strategy.
     If the strategy doesn't contain any exemption Passing value then JVM finishes the strategy uncommonly and removes the corresponding accessibility from the gathering.
    JVM identify the contact strategy and tests for Omission Passing value in that strategy. If the contact doesn't contain any exemption moving value then JVM finishes that strategy uncommonly and removes the corresponding accessibility from the gathering.
    The process will be continue until main() strategy
    If the main() strategy also doesn't contain exemption moving value the JVM finishes that main() strategy and removes the corresponding accessibility from the gathering  
    The process will be continue until main() strategy.
    If the main() strategy also doesn't contain exemption moving value the JVM finishes that main() strategy and removes the corresponding accessibility from the gathering.
    Just before finishes the program uncommonly JVM handover the responsibility of exemption  handling to the Conventional Omission Proprietor which is the aspect of JVM
    Standard Omission Proprietor just make exemption details to the program in-the following framework.

Name of Exception: Description
Stack Monitor (location of the Omission )

       classification TestEx {
       group set gap main (String [] args) {
       doStaff();
       }
       Fixed gap dostuff() {
        doMoreStuff();
       }
        set gap doMoreStuff() {
        int = 5/0; // can't divided by zero!
        // ArithmrticException is thrown here
        }
         }

WHICH PRINTS OUT A STACK TRACE SOMETHING LIKE,
C:/>java TestEx
Exception in range "main" java.lang.ArithmeticException : /
by zero
at TestEx.doMoreStuff(TestEx.java:10)
at TestEx.doStuff(TestEx.java:7)
at TestEx.main(TestEx.java:3)

STRING TOKENIZER CLASS

* the processing to text often comprises of parsing a formatted input string.
* Parsing is the division of text into a set of discrete parts or tokens which in a certain sequence can convey a semantic meaning.
* The string tokenizer class provides the facility of parsing the text. It is often called lexer(lexical analyxer) or scanner the String tokenizer class is present in java.util package
* String tokenizer we can specify an input string and a string that contains delimiters.
* To use string tokenizer we can specify an input string and a string that contains delimiter.
* Delimiter are Character that separate tokens. Each character in the delimiter string is considered a valid delimiter.
* The default set of delimiter consist of white space character such as space tab newline etc.
* In genaral space is used the default delimiter.
* The following are the constructor in string tokenizer

     string tokenizer(string str)
     string tokenizer (string str, string delimiter)
     string tokenizer(string str, string delimiter delimiters, Boolean delim as token)

* In all the tree constructor mentioned above str is the string that be tokenized.
* in the first constructor the default delimiter (space) is used.
* In the second and third constructor delimiter is a string that specifies the delimiters.
* In the third constructor if delim a stoken is true then the delimiters are also returned as token when the string is parsed. Otherwise the delimiter are not returned. Delimiter are not went back as tokens by the first two forms.

*The following are the methods defined in string tokenizer.
      int countTokens()
      Boolean hasMoreElements()
      Boolean hasMoreTokens()
      object nextElement()
      String nextToken()
      String nextToken(String delimiters)


*The following program demonstrates a StringTokenizer
    import java,util.StringTokenizer;
    Class STDemo
     {
        stastic string str:"this-is-my-core-java-notes";
        public static void main(String args[])
        String Tokenizer st= new StringTokenizer(str,"-")
        While (st.hasMoreTokens();
        System.out.println(s1);
      }
}

OUTPUT:
   This is my core java notes (printed vertically)

PROGRAMS ON ARRAY2

NOTE:-
       we cant use {} to announce arrays where ever we want i.e if we declare an variety at one place and initialize it at another place then we cant use {} for initialization. In this scenario we have to use the 'new' proprietor.

consider the following example
       classification Ademo5
         {
             Series s1 ] = {"abc","xyz"};
             int i1 [];
             group set gap main (String args [])
               {
                     Ademo5 a1 = new Ademo ();
                    // a1.i1={1,2,3}; // this is disallowed associate notice above
                    a1.i1=new int [6]; // this is permitted
                    int j[] = new int [0];// this is disallowed because sizing is not // defined
                  /* Any non-negative integer can be described as the size*/
                  int j[] = new int [0]; //An variety with zero elements
                   System.oy.println (j); // cope with of variety product j will be printed
                   System.ot.println (j.length); // 0 printed
                   // System.out.println (j [0]); // error because variety has no // elements
                   Series S1[] = new Series [0];
                   Series S1 [] = {};
               }
         }


NOTE:

     When JVM telephone cellphone calls the main strategy it finishes main strategy as a range when we get in touch with the main strategy JVM finishes it as a function

    whether JVM telephone cellphone calls the main strategy or we get in touch with the main strategy the corresponding discussion have to be the main strategy.
    now the question is when JVM telephone cellphone calls the main strategy. What is that conversation ?

HINT: Definitely the conversation is not zero. Then what is it ?

NOTE:
       We can get in touch with main strategy of one classification pc computer file from the main strategy of another classification pc computer file by going zero as conversation . But JVM cannot get in touch with main strategy of a classification pc computer file by going zero as an conversation.

HERE COMES THE CONCEPT OF COMMAND LINE ARGUMENTS.
  The command range discussion the conversation which are accepted along with the java command on the command prompt.

class ArgDemo
 {
    group sdtatic gap main (staring args [])
     /* ( we can offer any name which is not a key phrase. It is the physical work out to use args, but not necessary.)*/
     {
         System.out.println (args.length);
         if (args.length>0)
           {
               System.out.println (args[args.length-1]);
            }
        }
}


C:/> javac ArgDemo.java
java ArgDemo 10 a "bbb" 20.5f "nit"

OUTPUT:-
5
nit

PROGRAM ON ARRAYS

NOTE:-
   As soon as JVM activities {} it makes an things with the provides in {} and designates the deal with of the item to a varying.
      In this way we can make range item of all basic information types
      In a identical way we can determine arrays of things of classes
      The following system illustrates this concept
class Ademo3
 {
     community fixed gap primary (String args [])
      {
          A a1 [] = new A[3];
          Program.out.println(a1 [0]' // a1 [0] = null
          a1 [0] =new A ();
          Program.ou.println(a1 [0]); // deal with is printed
          a1 [0].i=10
          a1 [0].j=20;
          a1 [0]. operate A();
          A1[1]=a1[0];
         Program.out.println(a1[1].i);// 10 is printed
         a1[2] = new A ();
     }
}


NOTE:-
int i [] =....is same as int [] I =....
               // Another example program
               category Ademo4
                {
                   community fixed gap primary (string args [])
                     {
                          sequence s1 []; // zero is printed
                          s1 [0] = "java";
                          Program.out.println(s1 [0]; // coffee is printed
                          s1 [1] = "abc";
                          s2 [2] ="xyz";
                         Program.out.println (s1); // make deal with of range objectof kind String
                         Program.out.println (s1 [2]); // xyz is printed
                   }
            }
           // Another example program
           Training Ademos
           {
                 int i=0;
                 community fixed gap primary (string args [])
                   {
                       sequence s1 ]={"abc","xyz",MSD","SSA"};
                       Ademos a1[]={ new Ademo(), new Ademos(), new Ademo()
                    };
                   Program.out.println (s1.lenght); // 4 is printed
                   Sustem.out.println (s1 [3]); // SSA is printed
                   a1[0].i = 11;
                   Program.out.println (a1[1].i); // 0 is printed
                   }

          }

ARRAYS

 In coffee arrays are handled as things while using arrays e make things for arrays whose classification in non-existent (which we have not done so far).
   DEF:-An range is listed selection of set no of homogeneous data values. once we designed an range we cannot modified its dimension i.e range dimension is set.
    int x[];//array declaration
    int x[][];
    int x[][][];
    simultaneously of announcement the dimension is prohibited.
    int x[]=new int[4];//array construction
    int x[][]=new int[3][3];
    at enough duration of range development the dimension is compulsory.
    x[0]=10;
    x[1]=20;  //array initialization
    x[2]=30;
    x[3]=40


ARRAY DECLARATION, CONSTRUCTION, INITIALIZATION WITH IN A SINGLE LINE:-
int x[]={10,20,30,40};
int x[]={{10,20,30},{40,50}};

EX:

        category Ademo2
         {
             community fixed gap primary (String args [])
               {
                             int i [] = { 10,9,8,7};
                             char ch [] = {'a','b','c','9','4'};
                             program.out.println(ch [1]); // ch [1] =b
                             Program.out.println (i[1]);  // i[1] =9
                  }
            }

 What is the distinction between length varying length() technique ?
the timeframe varying can be used to discover out the range dimension. Where the duration ) technique is existing is Sequence category and it is used to discover out the Sequence dimension.

STRING AND STRING BUFFER CONT.........

STRING CONCATENATION:
appending a string to another string is known as string concatenation.
the '+' icon functions as the concatenation owner.

NOTE:-
 + owner performs as an mathematics owner if and only if the two operands provided to the + owner are mathematics number
  + owner performs as a concatenation owner if at least one operand provided to the + owner is a Sequence object
concatenation owner always results a new string category item with the material of LHS and RHS of the + owner.
       EX:
              Program.out.println (s1);  //  it printing abcxyz.
              Sequence s2="msd"; Program.out,println(s2); // MSD is printed
              S2=s2 + "SA"; Program.out.println (s2); // MS D S S A is printed

We said that Sequence are immutable (i.e material of the item of Sequence category cannot be changed) but how are the above claims possible?

  Actually the material of the item by S2 id not personalized. Actually a new item is designed and some new the whole material is appended to the current material and this is saved is in the item and deal with of the item is allocated to the varying. That's all in the above example the material "MSD" is not at all customized some new material "SSA" is included to it and then the whole material is saved in a new item.

   Using concatenation owner we can signify all the basic information kinds by means of their comparative Sequence category things.

         int x=10;
         Sequence s4="";
         s4=s4+10;
         Program.ut.println(s4); // 10 is printed
         int x =10;
         Sequence s3="MSD"+10
         Program.out.println(s3); // MSD 10is printed
         Sequence s5 = "xyz"+x+10;

         Program.out.println(s5); // xyz1010 is printed
         Sequence s6=x+10+ "abc";
         Program.out.println (s6) ; // 20abc is printed
         string s7 = "abc" +x+3;
*operator has more concern (procedure) over + operator
          Program.out.printeln (s7); // abc 30 is printed
          Sequence s7 = x* "abc" +3;  // It gives error

because * owner performs only on mathematics numbers

STRING BUFFER CLASS:
    We said that Sequence are immutable. But we have another category by name String Buffer category the materials of whose things are mutable i.e we can change the material of the item which is designed upon the String Buffer class

EX:
              StringBuffer SBI=new StringBuffer ("abc");
Some of the technique available in the string barrier category are add (); eliminate (); substitute (); e.t.c by using these techniques we can change the material of the item of Pattern barrier category.

           StringBuffer sb2 = new Sequence ("xyz");
           Sequence s3 = new StringBuffer ("abc");   // gives a collection error

Both the above claims are not valid claims : the purpose us we are trying to determine item of one category to testimonials of another category which is against the concept that an item of a category should be allocated to the referrals varying of the kind same category.

STRING AND STRINGBUFFER CLASSES

A sequence is a list of individuality. String sessions are used to symbolizes these list of personality.
We can even make an item an item of a sequence category without using new owner instead of the Stringclass with the materials provides in "" and for each and every people personality within "" it designates a exclusive catalog value beginning from zero
       EX: String s= "abcde";
Address of the item is allocated to the varying s
     This item has near regards with  arrays. once a sequence item is designed the details within the item cannot be customized. This is the purpose why we say that post are immutable

DIFFERENT WAYS OF CREATING STRING OBJECTS ARE SHOWN BELOW.
         String S1=new String (); 
         String S2=new String ("abc")
         String S3="MSDASS"


Consider the following two statements
         (i) A a1 = new A (),(ii) String S1="abcde";
now when we say System.out.println (a1); it create the deal with of the item where as for System.out.println (s1); it printing abcde (i.e the material of the object) why?
For the first declaration internal item category toString () is implemented and which makes the deal with of the object
But for the second declaration internal sequence category toString () is implemented and it can created the meaningfull
representation
NOTE:-
  In String,Stringbuffer,Thread, Exemption, wrapper sessions and all the selection sessions already  the toString() is overridden in a meaningfull representation

QUESTION:
What is the distinction between allowing the pattern item using new owner and allowing the sequence item using dual quotes?
       Using new owner we can make many objects of the same sequence class
For example
                String s1=new String("xyz");
                String S2="xyz";


    Here though the material are same two different item are make and the details are allocated to different varying.

      But when we make objects of String category using dual quotations we can highest make only one item into the whole program of we try to make more objects the same deal with of already  designed objects.
EX:
        String S1="MSO";
        String S2="MSD";
  The above describe distinction is caved the following program
         category Sdemo1
           {
                     community fixed gap primary (String args[])
                        {
                               String s1="abc";
                               String S2= new String ("xyz");
                               String s3 = new String ("xyz");
                               if (s2==s3)
                                         system.out.println("s2 & s3 are equal");
                               else
                                          System.out.println("s2 &s3 are not equal"); // this  //statement is executed
                               String s4="abc";
                                if (s1==s4)
                                           System.out.println("s1 & s4 are equal");  //  this declaration is // executed
                                else
                                           system.out.println("s1 & s4 are not equal");
                            }
             }

The following program is another which indicales that using dual quotations we can make only one String category comprising a list of figures not only in the functionality but in the whole program
           category Sdemo2
               {
                   String s1="abc";
                   gap operate ()
                     {
                          String s1="abc";
                           if (s1 == this . s1)
                           System.out.println("s1 & this. s1 are equal");
                           else
                           System.out.println("s1 & this. s1 are not equal");
                            System.out.println("end of function");
                      }
                     Public fixed gap primary (string args [])
                      {
                            Sdemo2 d=new Sdemo2 ();
                            d.function ();
                            String s3="abc";
                             if (s3 == d.s1)
                             System.out.println("s3 & d.s1 are equal");
                             else
                             System.out.println("s1 & d.s1 are not equal");
                     }
            }

WRAPPER CLASSES...CONT

i)XXXVALUE ():
      We can use these means for modifying  wrapper item to basic value. Every variety kind wrapper category (byte, brief, integer, lengthy, flow, double) the following xxxvalue technique (xxxvalue ()) for transforming wrapper item basic kind.

           Community byte bytevalue ();
           Community brief shortvalue ();
           public in intvalue ();
           Community lengthy longvalue ();
           Community flow floatvalue ();
           Community dual double ();

          Integer I = new Integer (130);
          Program.out.println(I.bytevalue()); // -126
          Program.out.println(I.shortvalue()); // 130
          Program.out.println(I.intvalue()); // 130
          Program.out.println(I.longvalue()); // 130
          Program.out.println(I.floatvalue()); // 130
          Program.out.println(I.doublevalue()); // 130.0


CHARVALUE ():-
       Personality category contains char value means for transforming  character item to char basic.

                      Community char charvalue ();
                      Personality ch = new character ('a');
                      char ch1 = ch . charvalue ();

BOOLEANVALUE():
        Boolean category contain booleanValue() to discover boolean basic for the given boolean wrappr item.

                 Community Boolean Booleanvlaue ();
                 //Blooean b = new Boolean("naresh");
                 Boolean b = Boolean.valueof ("NARESH");
                 Program.out.println(b.Booleanvalue());  // false

NOTE:
      In complete 38 (=6*6+1+1) xxx value techniques as possible
PAREXXX():
     These means for transforming sequence purpose to corresponding basic .

FORM-I:
      Every wrapper category anticipate personality category contains the following fixed bag xxx() public fixed basic parse xxx (string str)

EX:
          Int I=Integer.parseInt("10");
          Double d=double.parsedouble("10.5");
          Boolean b = Boolean.parseBoolean("true");
Every integer kind wrapper category contains the following parseXXX().
          Community fixed anyprimitive(return type) parseXXX (string s, int radix);

EX:

           Int i = integer.parseInt("1010"2);
           Program.out.println(8);// "1.5"

FORM -II:
     Every wrapper category contains a sequence to sequence means for modifying basic value to pattern by public fixed sequence to sequence (primitive p).
        EX:
                String s = Boolean.toString(true)
FORM - III:
              Integer and lengthy sessions contains the following toString() for transforming int or lengthy value into specification

         Community fixed Strin to String (primitive p, int radix 2 to 36)
         String s1 =Integer. toString (10/);
         Program.out.println(s1); // "1010"
         String s1 = lengthy.toString (101,16);
         Program.out.println(s); //"a"

FORM IV:
        Integer & Long sessions contains the following toXXXstring() methods

    public fixed sequence toBinaryString (primitive p)
    Community fixed String toOctalString(primitive p)
    public fixed String toHexaString (primitive p

                            String s1 = Integer.toBinaryString(12);
                            Program.out.println(s1)//100
                            String s2 = Long.oHexaString(100l);
                            Ystem.out.println (s2);//64


PARTIAL HIERARCHY OF JAVA. LANG PACKAGE
String
String barrier String builder
math
number ->byte, Short,Integer, lons, Float, Double
Character
Boolean
Void

     Some periods gap is also handled as wrapper class
He wrapper sessions which are not kid sessions of number/ character/ Boolean
In the lang program, the following sessions are final
         1) String, sequence designer, all wrapper sessions
In including to sequence all wrap sessions are immutable i.e once we designed an item we are prohibited to modify its material.

Monday 26 November 2012

WRAPPER CLASSES...CONT

Flow category contains three constructor one can take float as the discussion the second can take pattern as the discussion 8 the other dual as discussion.
       Flow f= new Flow (10.5 f);
       Flow f+ new float ("10.5f);
       Flow f= new float (10.5D);


    Personality category contains only one constructor which can take corresponding char as discussion there is no character which can take sequence discussion.

       character ch = new character ('a');
       character ch = new character ("a");

  Boolean category also contains two constructors one can take Boolean basic as the discussion & other can take sequence discussion.

   If we are moving Boolean basic the permitted any factor as the discussion also is not essential material is also not essential if the material as us insensitive of real the it is handled as other sensible it is handled as incorrect.

WHICH OF THE FOLLOWING BOOLEAN DECLARATION ARE VALID

    Boolean b1 = new Boolean (true);
    Boolean b2 = new Boolean (true);
    Boolean b3 = new Boolean ("true");
    Boolean b4 = new Boolean ("false");
    Boolean b5 = new Boolean ("hai ramesh");  // False
    Boolean b6 = new Boolean ("true 123");   //False


CONSIDER THE FOLLOWING DECLARATION:

    Boolean b1 = new Boolean ("YES");
    Boolean b2 = new Boolean ("NO");

      Program.out.println(b1);//false
      Program.out.println(b2);//false
      Program.out.println(b1.equals (b2));//true
      Program.out.println(b1==b2);//false


UTILITY METHODS:

    valueof()
    xxxvalue ()
    parseXXX()
    toString ()


VALUEOF()
      We can use value of () means for the development of wrapper item as substitute to constructor
FORM I:
     Every wrapper category except character category contain a fixed value of means for transforming sequence to corresponding wrapper item.
       community fixed any wrapper class(return kind ) valueof (String s)
EX:
           Integer i = Integer.valueOf("10");
           Boolean B = Boolean.valueOf("true");
           Personality ch = character.valueOf ("a");

FROM II:
     Every wrapper category such as character category contain a fixed value of technique altering basic to corresponding wrapper object
       community fixed any wrapper class(return type) value of (primitive p)
Ex:
       Integer i= Integer.valueOf(10);
       Personality ch = character.valueof('a');
       Boolean B = Boolean.valueOf(true);

FROM III:
         Every integer kind wrapper category [byte , brief, integer, long] contains the following value of technique.

  Public fixed anywrapperclass(return type) valueof(string s, int radix)
  The permitted principles for the radix are 1-36
       Integer i=integer value of (1010,2);

Sunday 25 November 2012

WRAPPER CLASSES.

There are many conditions where we need to signify the basic information kinds by means of things.
Some sessions have been described to signify the basic information kinds by means of things.
 These sessions are known as wrapper sessions. There sessions cover the idea of item on the basic information kinds.

USES OF WRAPPER CLASSES:
(i) To symbolizes basic datatypes by means of their comparative things.
(ii) Wrapper sessions have some operate which are useful in comprising the material of a sequence category item of a basic data kind in its unique kind (primitive information type)
 EX:    int x = 10;
          String s1 = x1" ";
           s1 = s1.trim();
           Program.out.println (s1): // 10 is printed

      Now this sequence category item can be converted returning into its comparative basic information kind by using the features of wrapper sessions.
NOTE:
  Since we have eight basic information kinds, obviously, we have eight wrapper periods, as proven below
      byte,Short,Integer,Long,Float,Double,Character,Boolean.
the wrapper sessions are existing in the coffee lang program.

EVERY WRAPPER CLASS HAS TWO CONSTRUCTORS:
The primary goals of wrapper sessions are
i) to cover primitives into things kind so that we can manage primitives also just like object
ii) To described several application operate for the primitives

PRIMITIVE TYPES                          WRAPPER CLASSES
      byte                                                    Byte
      brief                                                   Short
      int                                                       integer
      lengthy                                                    Long
     flow                                                     Float
     dual                                                 Double
     char                                                     Character
     boolean                                               Boolean

CONSTRUCTOR OF WRAPPER CLASSES
      Almost of all wrapper sessions contains two specialist one can take the corresponding primitives as discussion the other can take corresponding sequence as discussion.

           Integer i =new integer (10);
           Integer i =new integer ("10");

If sequence is incapable to turn to the corresponding variety kinds we will get run time exemption saying number Format Exception.

WRAPPER CLASS                                       CONSTRUCTOR ARGUMENTS
Byte                                                                   byte or string
Short                                                                  brief or string
Integer                                                                int or string
Long                                                                   lengthy or string
Float                                                                   flow or sequence or deniable
double                                                                dual or string
Character                                                            char(*)
Boolean                                                               Boolean or sequence 

PROGRAMS ON JAVA PACKAGES

 FOR EXAMPLE:
    Community fixed last int a = 10;

    Secured int d;
    int x; [we are not using any accessibility specifier  it is handled as standard accessibility modifier]
    Personal int e;

  
NOTE:
1.Private accessibility specifier is also known as local accessibility specifier
2.Default accessibility specifier is also known as system accessibility specifier.
3.protected  accessibility specifier is also known as monetary gift accessibility specifier.
4.Public accessibility specifier is also known as worldwide accessibility specifier.

WRITE A JAVA PROGRAM WHICH ILLUSTRATES THE CONCEPT OF ACCESS RULES?
ANS:
      //Sbc.java
     // javac -d . sbc.java
 
     system sp
     public category Sbc
       {
             private int N_PRI=10;
             int N_DEF=20;
             protected int N_PRO=30;
             public int N_PUB=40;
             public Sbc()
              {
                 Program.out.println ("VALUE OF N_PRIVATE = "+N_pri);
                 Program.out.println ("VALUE OF N_DEFAULT ="+N_DEF);
                 Program.out.println ("VALUE OF N_PROTECTED ="+N_PRO);
                 Program.out.println ("VALUE OF N_PUBLIC ="+N_PUB);
              }
};

//Sic.java
// javac -d . sicjava

package sp;
public category Sic
{
     Sbc so=new Sbc();  //(has-a regards & within only)
     public Sic()
       {
           //System.out.println ("VALUE OF N_PRIVATE = "so.N_PRI);
          Program.out.println ("VALUE OF N_DEFAULT = "so.N_DEF);
          Program.out.println ("VALUE OF N_PROTECTED = "so.N_PRO);
          Program.out.println ("VALUE OF N_PUBLIC = "so.N_PUB);
       }
};

//Odc.java
//javac -d Odc.java

package op;
public category Odc expands sp.Sbc // (is relatoin & across)
{
     public odc()
      {
           //syatem.out.println ("VALUE OF N_PRIVATE = "+N_PRI);
             //System.out.println ("VALUE OF N_DEFAULT ="+N_DEF);
              Program.out.println ("VALUE OF N_PROTECTED ="+N_PRO);
              Program.out.println ("VALUE OF N_PUBLIC ="+N_PUB);
      }
};


//Oic.java
//javac -d Oic.java

packages op;
public category Oic
{
     sp.Sbc so = new sp.Sbc (); // (has-a regards & across)
     public Oic()
       {
            //System.out.println ("VALUE OF N_PRIVATE = "so.N_PRI);
           // Program.out.println ("VALUE OF N_DEFAULT = "so.N_DEF);
           //System.out.println ("VALUE OF N_PROTECTED = "so.N_PRO);
           Program.out.println ("VALUE OF N_PUBLIC = "so.N_PUB);
      }
};
//ASDemo.java
// java ASDemo.java

import sp.Sbc;
import sp.Sbc;
import sp.Sic;
class ASDemo
{
      public fixed gap primary (string [] args)
       {
           //import approach
           Program.out.println ("WHIT RESPECT TO SAME PACKAGE BASE CLASS");
           Sbc so1=new Sbc();
            Program.out.println ("WHIT RESPECT TO SAME PACKAGE DERIVED CLASS");
           Sbc so2=new Sbc();
           Program.out.println ("WHIT RESPECT TO SAME PACKAGE INDEPENDENT CLASS");
           Sic so3 = NEW Sic();
           //fully certified name approach
           Syatem.out.println ("WHIT RESPECT TO SAME PACKAGE DERIVED CLASS");
           op.Odc.oo1=new op.Odc();
           Program.out.println ("WHIT RESPECT TO SAME PACKAGE INDEPENDENT CLASS");
           op.Oic oo2=new op.Oic();
         }
};


NAMELESS OBJECT APPROACH:
       Sometimes there is no requirement for the JAVA developer to make a product with some name. In such scenario we can use the concept of unidentified object.

FOR EXAMPLE:
          //named object approach
          Check t1= new Check ();
          t1.display ();
  To turn the above claims into unidentified object strategy adhere to the following claims.

FOR EXAMPLE:
     //nameless object strategy
     new Check ().display ();