Full Transcript

MANESH PATEL PRESIDENT INSTITUTE OF COMPUTER APPLICAION COLLEGE, SHAYONA CAMPUS, KADI BCA SEM: 3 JAVA - Unit – 3 JAVA Wrapper class in Java  Wrapper class in java provides the mechanism to conv...

MANESH PATEL PRESIDENT INSTITUTE OF COMPUTER APPLICAION COLLEGE, SHAYONA CAMPUS, KADI BCA SEM: 3 JAVA - Unit – 3 JAVA Wrapper class in Java  Wrapper class in java provides the mechanism to convert primitive into object and object into primitive.  Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive automatically.  The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing. PREPARED BY: PATEL MANESH - M.Sc(CA & IT) Contact: 90165 17796 1 PATEL MANESH The eight classes of java.lang package are known as wrapper classes in java. PRIMITIVE WRAPPER s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 2 PATEL MANESH Java Wrapper classes Example public class Demo{ public static void main(String args[]){ byte b=10; short s=20; int i=30; long l=40; float f=50.0f; double d=60.0d; char c='a'; boolean b2=true; //Autoboxing: Converting primitives into objects Byte byteobj=b; Short shortobj=s; Integer intobj=i; Long longobj=l; Float floatobj=f; Double doubleobj=d; Character charobj=c; Boolean boolobj=b2; //Printing objects System.out.println("---Printing object values---"); System.out.println("Byte object: "+byteobj); System.out.println("Short object: "+shortobj); System.out.println("Integer object: "+intobj); System.out.println("Long object: "+longobj); System.out.println("Float object: "+floatobj); System.out.println("Double object: "+doubleobj); System.out.println("Character object: "+charobj); System.out.println("Boolean object: "+boolobj); s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 3 PATEL MANESH //Unboxing: Converting Objects to Primitives byte bytevalue=byteobj; short shortvalue=shortobj; int intvalue=intobj; long longvalue=longobj; float floatvalue=floatobj; double doublevalue=doubleobj; char charvalue=charobj; boolean boolvalue=boolobj; //Printing primitives System.out.println("---Printing primitive values---"); System.out.println("byte value: "+bytevalue); System.out.println("short value: "+shortvalue); System.out.println("int value: "+intvalue); System.out.println("long value: "+longvalue); System.out.println("float value: "+floatvalue); System.out.println("double value: "+doublevalue); System.out.println("char value: "+charvalue); System.out.println("boolean value: "+boolvalue); } Output: } ---Printing object values--- Byte object: 10 Short object: 20 Integer object: 30 Long object: 40 Float object: 50.0 Double object: 60.0 Character object: a Boolean object: true ---Printing primitive values--- byte value: 10 short value: 20 int value: 30 long value: 40 float value: 50.0 double value: 60.0 char value: a boolean value: true s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 4 PATEL MANESH Java - String Class  Strings, which are widely used in Java programming, are a sequence of characters.  In Java programming language, Strings are treated as objects.  The Java platform provides the String class to create and manipulate strings. Creating Strings  The most direct way to create a string is to write − String greeting = "Hello world!";  Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.  As with any other object, you can create String objects by using the new keyword and a constructor.  The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters. Example public class StringDemo { public static void main(String args[]) { char helloArray[] = { 'H', 'e', 'l', 'l', 'o', '.' }; String helloString = new String (helloArray); System.out.println (helloString); } } Output Hello. s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 5 PATEL MANESH String Length  The length() method which returns the number of characters contained in the string object. Example public class StringDemo { public static void main(String args[]) { String name = "I am in BCA"; int len = name.length(); System.out.println ("String Length is: " + len ); } } Output String Length is: 11 Concatenating Strings The String class includes a method for concatenating two strings − string1.concat (string2);  This returns a new string that is string1 with string2 added to it at the end.  You can also use the concat() method with string literals, as in − "My name is ".concat("Manish"); Strings are more commonly concatenated with the + operator, as in − "Hello," + " world" + "!" Which results in − "Hello, world!" s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 6 PATEL MANESH String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. String toString() This object (which is already a string!) is itself returned. String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. int length() Returns the length of this string. int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. char charAt(int index) Returns the character at the specified index. boolean endsWith(String suffix) Tests if this string ends with the specified suffix. boolean startsWith(String prefix) Tests if this string starts with the specified prefix. s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 7 PATEL MANESH class Test { public static void main(String M[]) { String s = "I am in BCA"; s = s.concat (" Shayona Campus"); System.out.println(s); String Str = new String ("This is really not immutable"); boolean retVal; retVal = Str.endsWith ( "immutable" ); System.out.println ("Returned Value = " + retVal); retVal = Str.endsWith( "immu" ); System.out.println ("Returned Value = " + retVal); String Str2 = new String ("Welcome to Shayona BCA College"); System.out.print ("Found Index:"); System.out.println (Str2.indexOf ( 'o')); String Str3 = new String (“Patel Manesh kumar"); String Str4 = new String ("Manesh is a Teacher"); System.out.print ("String Length :"); System.out.println (Str3.length()); System.out.print ("String Length :"); System.out.println(Str4.length()); String Str5 = new String ("Welcome to MissionClasses.com"); System.out.print ("Return Value:"); System.out.println (Str5.replace ('o', 'M')); String s6 = "Patel Manesh kumar"; char result = s6.charAt(8); System.out.println (result); System.out.println (s6.startsWith ("Patel")); System.out.println (s6.toLowerCase ()); System.out.println (s6.toUpperCase ()); } } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 8 PATEL MANESH StringBuffer class  StringBuffer class is used to create a mutable or changeable string object i.e its state can be changed after it is created.  It represents grow able and writable character sequence.  As we know that String objects are immutable, so if we do a lot of changes with String objects, we will end up with a lot of memory leak.  So StringBuffer class is used when we have to make lot of modifications to our string.  StringBuffer defines 4 constructors. They are 1. StringBuffer ( ) 2. StringBuffer ( int size ) 3. StringBuffer ( String str ) 4. StringBuffer ( charSequence [ ]ch )  StringBuffer() creates an empty string buffer and reserves space for 16 characters.  stringBuffer(int size) creates an empty string and takes an integer argument to set capacity of the buffer. Example showing difference between String and StringBuffer class Test { public static void main(String M[]) { String str1 = "study"; str1.concat ("tonight"); System.out.println (str1); // Output: study StringBuffer str2 = new StringBuffer ("study"); str2.append ("tonight"); System.out.println (str2); // Output: studytonight } } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 9 PATEL MANESH Important methods of StringBuffer class append()  This method will concatenate the string representation of any type of data to the end of the invoking StringBuffer object. StringBuffer str = new StringBuffer ("Manesh"); str.append (Patel); System.out.println (str); OUTPUT = ManeshPatel insert()  This method inserts one string into another.  Here are few forms of insert() method. StringBuffer insert (int index, String str) StringBuffer insert (int index, int num) StringBuffer insert (int index, Object obj) Example StringBuffer str = new StringBuffer ("Manesh"); str.insert (6, “ Patel”); System.out.println (str); OUTPUT = Manesh Patel s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 10 PATEL MANESH reverse()  This method reverses the characters within a StringBuffer object. StringBuffer str = new StringBuffer ("12345"); str.reverse(); System.out.println (str); OUTPUT = 54321 replace()  This method replaces the string from specified start index to the end index. StringBuffer str = new StringBuffer ("Hello World"); str.replace (6, 11, "java"); System.out.println (str); OUTPUT = Hello java capacity()  This method returns the current capacity of StringBuffer object. StringBuffer str = new StringBuffer (); System.out.println (str.capacity()); OUTPUT = 16 s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 11 PATEL MANESH setLength() import java.lang.*; public class Demo { public static void main (String args[]) { StringBuffer buff = new StringBuffer ("ManeshPatel"); System.out.println ("buffer1 = " + buff); // length of stringbuffer System.out.println("length = " + buff.length()); // set the length of stringbuffer to 6 buff.setLength(6); // print new stringbuffer value after changing length System.out.println("buffer2 = " + buff); // length of stringbuffer after changing length System.out.println("length = " + buff.length()); } } Output buffer1 = ManeshPatel length = 11 buffer2 = Manesh length = 6 s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 12 PATEL MANESH charAt()  The java.lang.StringBuffer.charAt() method returns the char value in this sequence at the specified index. Example import java.lang.*; public class Demo { public static void main(String[] args) { StringBuffer br = new StringBuffer ("Patel Manesh"); System.out.println ("Answer is = " + br); // returns the char at index 6 System.out.println ("character = " + br.charAt(6)); } } OUTPUT= Answer is = Patel Manesh character = M s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 13 PATEL MANESH setCharAt()  The java.lang.StringBuffer.setCharAt() method sets the character at the specified index to ch.  This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index. import java.lang.*; public class StringBufferDemo { public static void main (String M[]) { StringBuffer buff = new StringBuffer ("MANESH"); System.out.println ("Buffer = " + buff); // character at index 3 System.out.println ("Character at index 3 = " + buff.charAt (3)); // set character at index 3 buff.setCharAt (3, 'i'); System.out.println ("After Set, buffer = " + buff); // character at index 3 System.out.println ("Character at index 3 = " + buff.charAt (3)); } } Buffer = MANESH Character at index 3 = E After Set, buffer = MANiSH Character at index 3 = i s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 14 PATEL MANESH Excepting Handing  The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that normal flow of the application can be maintained.  In this topic, we will learn about Java exceptions,  Its types and the difference between checked and unchecked exceptions. What is Exception in Java  In Java, an exception is an event that disrupts the normal flow of the program.  It is an object which is thrown at runtime. What is Exception Handling  Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. Hierarchy of Java Exception classes  The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.  A hierarchy of Java Exception classes are given below: s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 15 PATEL MANESH Types of Java Exceptions  There are mainly two types of exceptions: 1. Checked Exception 2. Unchecked Exception 1) Checked Exception  The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g.  IOException, SQLException etc. Checked exceptions are checked at compile-time. 2) Unchecked Exception  The classes which inherit RuntimeException are known as unchecked exceptions  e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.  Unchecked exceptions are checked at runtime. s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 16 PATEL MANESH Java Exception Keywords There are 5 keywords which are used in handling exceptions in Java. Keyword try The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. Exception Handling Example class Exce { public static void main(String args[]) { 1. try 2. { 3. int data=100/0; 4. } 5. catch(ArithmeticException e) 6. { System.out.println (e); 7. } } } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 17 PATEL MANESH Java Exceptions 1) A scenario where ArithmeticException occurs  If we divide any number by zero, there occurs an ArithmeticException. int a=50/0; //ArithmeticException 2) A scenario where NullPointerException occurs  If we have a null value in any variable, performing any operation on the variable throws a NullPointerException. String s=null; System.out.println (s.length()); //NullPointerException 3) A scenario where NumberFormatException occurs  If the formatting of any variable or number is mismatched, it may result into NumberFormatException.  Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException. String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 4) A scenario where ArrayIndexOutOfBoundsException occurs  When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.  There may be other reasons to occur ArrayIndexOutOfBoundsException. a=50; //ArrayIndexOutOfBoundsException s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 18 PATEL MANESH Java catch multiple exceptions Java Multi-catch block  A try block can be followed by one or more catch blocks.  Each catch block must contain a different exception handler.  So, if you have to perform different tasks at the occurrence of different exceptions, use java multi- catch block.  At a time only one exception occurs and at a time only one catch block is executed. class MultiCatch { public static void main(String[] args) { try{ int a[]=new int; a=30/0; // Error occur } catch (ArithmeticException e) { System.out.println ("Arithmetic Exception occurs"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch (Exception e) { System.out.println ("Parent Exception occurs"); } System.out.println ("Bye Bye…."); } } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 19 PATEL MANESH Java finally block  Java finally block is a block that is used to execute important code such as closing connection, stream, message etc.  Java finally block is always executed whether exception is handled or not.  Java finally block follows try or catch block. class MultiCatch { public static void main(String[] args) { try{ int a[]=new int; a=30/0; // Error occur } catch (ArithmeticException e) { System.out.println ("Arithmetic Exception occurs"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch (Exception e) { System.out.println ("Parent Exception occurs"); } 1. finally // finally block 2. { System.out.println ("finally block is always executed"); 3. } System.out.println ("Bye Bye…."); } } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 20 PATEL MANESH Difference between final, finally and finalize Key final finally finalize Definition final is the keyword finally is the block finalize is the and access modifier in Java Exception method in Java which is used to Handling to which is used to apply restrictions execute the perform clean up on a class, method important code processing just or variable. whether the before object is exception occurs or garbage collected. not. Applicable to Final keyword is Finally block is finalize() method is used with the always related to used with the classes, methods the try and catch objects. and variables. block in exception handling. Functionality (1) Once declared, (1) finally block finalize method final variable runs the important performs the becomes constant code even if cleaning activities and cannot be exception occurs or with respect to the modified. not. object before its (2) final method (2) finally block destruction. cannot be cleans up all the overridden by sub resources used in class. try block (3) final class cannot be inherited. Execution Final method is Finally block is finalize method is executed only when executed as soon as executed just before we call it. the try-catch block the object is is executed. destroyed. It's execution is not dependant on the exception. s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 21 PATEL MANESH Difference between Checked and Unchecked Exception No Checked Exception Unchecked Exception 1. These exceptions are checked and These exceptions are checked and handled at compile time. handled at run time. 2. These exceptions are direct They are the direct subclasses of the subclasses of exception but not RuntimeException class. extended from RuntimeException class. 3. The code gives a compilation The code compiles without any error in the case when a method error. These exceptions are the throws a checked exception. results of user-created errors in programming logic. 4. These exceptions mostly occur These exceptions occur mostly due when the probability of failure is to programming mistakes. too high. 5. Common checked exceptions Common unchecked exceptions include IOException, include ArithmeticException, DataAccessException, InvalidClassException, InterruptedException, etc. NullPointerException, etc. 6. These exceptions are using the These are automatically. throws keyword. 7. It is required to provide the try- In the case of unchecked exception catch and try-finally block to it is not mandatory. handle the checked exception. s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 22 PATEL MANESH The advantages of Exception Handling 1. It is used to Complete Program Execution 2. Easy Identification of Program Code and Error-Handling Code 3. Propagation of Errors 4. Meaningful Error Reporting 5. Identifying Error Types s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 23 PATEL MANESH Difference between throw and throws throw throws 1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. 2) Checked exception cannot be Checked exception can be propagated propagated using throw with throws 3) Throw is followed by an instance. Throws is followed by class. 4) Throw is used within the method. Throws is used with the method signature. 5) You cannot throw multiple exceptions. You can declare multiple exceptions Java throw and throws Example class Demo { static void get() throws ArithmeticException //static method { System.out.println ("Inside the method()"); throw new ArithmeticException("throwing ArithmeticException"); } public static void main(String args[]) { try { get(); //static method calling } catch(ArithmeticException e) { System.out.println ("caught in main() method"); } Inside the method() } caught in main() method } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 24 PATEL MANESH s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 25 PATEL MANESH Java Custom Exception  In Java, we can create our own exceptions that are derived classes of the Exception class.  Creating our own Exception is known as custom exception or user-defined exception. Why use custom exceptions?  Java exceptions cover almost all the general type of exceptions that may occur in the programming.  However, we sometimes need to create custom exceptions. Following are few of the reasons to use custom exceptions: 1. To catch and provide specific treatment to a subset of existing Java exceptions. 2. Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem. class OwnException extends Exception { OwnException (String str) { super(str); // Call super exception class constructor } } class MyClass { public static void main (String[] args) { try { OwnException obj = new OwnException ("Creating UDF exception"); throw obj; } catch (OwnException ex) { System.out.println ("Caught a user defined exception"); System.out.println (ex.getMessage()); } } } s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 26 PATEL MANESH s PREPARED BY: PATEL MANESH - M.Sc(CA & IT), B.ED Contact: 90165 17796 27

Use Quizgecko on...
Browser
Browser