easy to learn- java

Upload: choprahridyesh

Post on 03-Jun-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Easy to Learn- Java

    1/119

  • 8/12/2019 Easy to Learn- Java

    2/119

  • 8/12/2019 Easy to Learn- Java

    3/119

  • 8/12/2019 Easy to Learn- Java

    4/119

  • 8/12/2019 Easy to Learn- Java

    5/119

  • 8/12/2019 Easy to Learn- Java

    6/119

  • 8/12/2019 Easy to Learn- Java

    7/119

  • 8/12/2019 Easy to Learn- Java

    8/119

  • 8/12/2019 Easy to Learn- Java

    9/119

  • 8/12/2019 Easy to Learn- Java

    10/119

  • 8/12/2019 Easy to Learn- Java

    11/119

  • 8/12/2019 Easy to Learn- Java

    12/119

  • 8/12/2019 Easy to Learn- Java

    13/119

  • 8/12/2019 Easy to Learn- Java

    14/119

  • 8/12/2019 Easy to Learn- Java

    15/119

  • 8/12/2019 Easy to Learn- Java

    16/119

  • 8/12/2019 Easy to Learn- Java

    17/119

  • 8/12/2019 Easy to Learn- Java

    18/119

  • 8/12/2019 Easy to Learn- Java

    19/119

  • 8/12/2019 Easy to Learn- Java

    20/119

  • 8/12/2019 Easy to Learn- Java

    21/119

  • 8/12/2019 Easy to Learn- Java

    22/119

  • 8/12/2019 Easy to Learn- Java

    23/119

  • 8/12/2019 Easy to Learn- Java

    24/119

  • 8/12/2019 Easy to Learn- Java

    25/119

  • 8/12/2019 Easy to Learn- Java

    26/119

  • 8/12/2019 Easy to Learn- Java

    27/119

  • 8/12/2019 Easy to Learn- Java

    28/119

  • 8/12/2019 Easy to Learn- Java

    29/119

  • 8/12/2019 Easy to Learn- Java

    30/119

  • 8/12/2019 Easy to Learn- Java

    31/119

  • 8/12/2019 Easy to Learn- Java

    32/119

  • 8/12/2019 Easy to Learn- Java

    33/119

  • 8/12/2019 Easy to Learn- Java

    34/119

  • 8/12/2019 Easy to Learn- Java

    35/119

  • 8/12/2019 Easy to Learn- Java

    36/119

  • 8/12/2019 Easy to Learn- Java

    37/119

  • 8/12/2019 Easy to Learn- Java

    38/119

  • 8/12/2019 Easy to Learn- Java

    39/119

  • 8/12/2019 Easy to Learn- Java

    40/119

  • 8/12/2019 Easy to Learn- Java

    41/119

  • 8/12/2019 Easy to Learn- Java

    42/119

  • 8/12/2019 Easy to Learn- Java

    43/119

  • 8/12/2019 Easy to Learn- Java

    44/119

  • 8/12/2019 Easy to Learn- Java

    45/119

  • 8/12/2019 Easy to Learn- Java

    46/119

  • 8/12/2019 Easy to Learn- Java

    47/119

  • 8/12/2019 Easy to Learn- Java

    48/119

  • 8/12/2019 Easy to Learn- Java

    49/119

  • 8/12/2019 Easy to Learn- Java

    50/119

  • 8/12/2019 Easy to Learn- Java

    51/119

  • 8/12/2019 Easy to Learn- Java

    52/119

  • 8/12/2019 Easy to Learn- Java

    53/119

  • 8/12/2019 Easy to Learn- Java

    54/119

  • 8/12/2019 Easy to Learn- Java

    55/119

  • 8/12/2019 Easy to Learn- Java

    56/119

  • 8/12/2019 Easy to Learn- Java

    57/119

  • 8/12/2019 Easy to Learn- Java

    58/119

  • 8/12/2019 Easy to Learn- Java

    59/119

  • 8/12/2019 Easy to Learn- Java

    60/119

  • 8/12/2019 Easy to Learn- Java

    61/119

  • 8/12/2019 Easy to Learn- Java

    62/119

  • 8/12/2019 Easy to Learn- Java

    63/119

  • 8/12/2019 Easy to Learn- Java

    64/119

  • 8/12/2019 Easy to Learn- Java

    65/119

  • 8/12/2019 Easy to Learn- Java

    66/119

  • 8/12/2019 Easy to Learn- Java

    67/119

  • 8/12/2019 Easy to Learn- Java

    68/119

  • 8/12/2019 Easy to Learn- Java

    69/119

  • 8/12/2019 Easy to Learn- Java

    70/119

  • 8/12/2019 Easy to Learn- Java

    71/119

  • 8/12/2019 Easy to Learn- Java

    72/119

  • 8/12/2019 Easy to Learn- Java

    73/119

  • 8/12/2019 Easy to Learn- Java

    74/119

  • 8/12/2019 Easy to Learn- Java

    75/119

  • 8/12/2019 Easy to Learn- Java

    76/119

  • 8/12/2019 Easy to Learn- Java

    77/119

  • 8/12/2019 Easy to Learn- Java

    78/119

  • 8/12/2019 Easy to Learn- Java

    79/119

  • 8/12/2019 Easy to Learn- Java

    80/119

  • 8/12/2019 Easy to Learn- Java

    81/119

  • 8/12/2019 Easy to Learn- Java

    82/119

  • 8/12/2019 Easy to Learn- Java

    83/119

  • 8/12/2019 Easy to Learn- Java

    84/119

  • 8/12/2019 Easy to Learn- Java

    85/119

  • 8/12/2019 Easy to Learn- Java

    86/119

  • 8/12/2019 Easy to Learn- Java

    87/119

  • 8/12/2019 Easy to Learn- Java

    88/119

  • 8/12/2019 Easy to Learn- Java

    89/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Enumeration elements( ) Returns an enumeration of the valuescontained in the hash table.

    Object get(Object key)Returns the object that contains the valueassociated with key. If key is not in thehash table, a null object is returned.

    Boolean isEmpty( ) Returns true if the hash table is empty;Returns false if it contains at least one key.

    Enumeration keys( ) Returns an enumeration of the keyscontained in the hash table.

    Object put(Object key Object value) Inserts a key and a value into the hashtable.

    Object remove(Object key)Removes key and its value. Returns thevalue associated with key. If key is not inthe hash table, a null object is returned.

    Int size( ) Returns the number of entries in the hashtable.

    String toString( ) Returns the string equivalent of a hash

    table.

    Prog. No.:- 67

    import java.util.*;

    public class hash1{

    public static void main(String args[]){

    Hashtable marks = new Hashtable(); Enumeration names; Enumeration emarks; String str; int nm;

    // Checks wheather the hashtable is empty System.out.println("Is Hashtable empty " + marks.isEmpty()); marks.put("Ankit", 58); marks.put("Amit", 88); marks.put("Shewta", 69); marks.put("Kriti", 99); marks.put("Joyti", 54);

    System.out.println("Is Hashtable empty " + marks.isEmpty()); // Creates enumeration of keys names = marks.keys(); while(names.hasMoreElements()){

    str = (String) names.nextElement(); System.out.println(str + ": " + marks.get(str));

    } /* nm = (Integer) marks.get("Janki"); marks.put("Janki", nm+15); System.out.println("Janki's new marks: " + marks.get("Janki"));

    // Creates enumeration of values

  • 8/12/2019 Easy to Learn- Java

    90/119

    INTERNET TECHNOLOGY (CORE JAVA)

    emarks = marks.elements(); while(emarks.hasMoreElements()){

    nm = (Integer) emarks.nextElement(); System.out.println(nm);

    }

    // Number of entries in a hashtable System.out.println("The number of entries in a table are " + marks.size());

    // Checking wheather the element available

    System.out.println("The element is their " + marks.containsValue(88)); */ // Removing an element from hashtable

    System.out.println("========"); marks.remove("Bharat"); names = marks.keys(); while(names.hasMoreElements()){

    str = (String) names.nextElement(); System.out.println(str + ": " + marks.get(str)); } // Returning an String equivalent of the Hashtable

    System.out.println("String " + marks.toString()); // Emptying hashtable

    marks.clear(); System.out.println("Is Hashtable empty " + marks.isEmpty());

    } }

    Output :C:\java> javac Hash1 .javaC:\java> java Hash1

    Amit: 88Jyoti: 54

    Ankit: 58String {Kriti=99, Amit=88, Jyoti=54, Ankit=58}Is Hashtable empty true

    WRAPPER CLASS IN JAVA

    Wrapper Class: Java uses primitive types, such as int, char, double to hold the basic data types supported by the

    language. Sometimes it is required to create an object representation of these primitive types. These are collection classes that deal only with such objects. One needs to wrap the primitive type

    in a class. To satisfy this need, java provides classes that correspond to each of the primitive types. Basically,

    these classes encapsulate, or wrap, the primitive types within a class. Thus, they are commonly referred to as type wrapper. Type wrappers are classes that encapsulate a

    primitive type within an object. The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float.

  • 8/12/2019 Easy to Learn- Java

    91/119

    INTERNET TECHNOLOGY (CORE JAVA)

    These classes offer a wide array of methods that allow to fully integrate the primitive types into Javasobject hierarchy.

    Wrapper classes for converting simple types

    Converting primitive numbers to Object numbers using constructor methods

    NOTE : I, f, d and l are primitive data values denoting int, float, double and long data types. They may beconstants or variables.

    Converting Object numbers to Primitive numbers using typeValue() method

    Converting Numbers to Strings using toString() method

    Converting String Object in to Numeric Object using static method ValueOf()

    Converting Numeric Strings to Primitive numbers using Parsing method

    NOTE : parseInt() and parseLong() methods throw a NumberFormatException if the value of the str doesnot represent an integer.

    Byte class example in java:The Byte class encapsulates a byte value. It defines the constants MAX_VALUE

    and MIN_VALUE and provides these constructors:

    Byte(byte b)

    Byte(String str)

    Here, b is a byte value and str is the string equivalent of a byte value.

    Prog. No.:- 68

    import java.util.*; public class Byte_Test {

    public static void main(String args[]) {

    Byte_Test b1 = new Byte_Test ((byte)120); for(int i = 125; i

  • 8/12/2019 Easy to Learn- Java

    92/119

    INTERNET TECHNOLOGY (CORE JAVA)

    greater than 1*/ }

    } Output :

    C:\java> javac Byte_Test.javaC:\java> java Byte_Test

    b2 = 125 b2 = 126

    b2 = 127 b2 = -128 b2 = -127 b2 = -126 b2 = -125 b2 = -124 b2 = -123 b2 = -122 b2 = -121 b1 Object = 120 Minimum Value of Byte = -128 Maximum Value of Byte = 127 b1* 2 = 240 b1* 2 = 240 b3 Object = 120

    (b1==b3)? true(b1.compareTo(b3)? 0

    Short :

    The Short class encapsulates a short value. It defines the constants MAX_VALUE and MIN_VALUE and provides the following constructors:

    Short(short s)

    Short(String str)

    Prog. No.:- 69

    import java.util.*; public class Short_Test {

    public static void main(String args[]) {

    Short_Test s1 = new Short_Test ((short)2345);

    for(int i = 32765; i

  • 8/12/2019 Easy to Learn- Java

    93/119

  • 8/12/2019 Easy to Learn- Java

    94/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Output :C:\java> javac Integer_Test.java

    C:\java> java Integer_TestI1 = 12Binary Equivalent = 1100Hexadecimal Equivalent = c

    Minimum Value of Integer = -2147483648 Maximum Value of Integer = 2147483647

    Byte Value of Integer = 12Double Value of Integer = 12.0i1==i2 truei1.compareTo(i2) = 0i3 = 17

    Long :

    The Long class encapsulates a long value. It defines the constants MAX_VALUE andMIN_VALUE and provides the following constructors:

    Long(long l)

    Long(String str)

    Prog. No.:- 71

    import java.util.*;

    public class Long_Test {

    public static void main(String args[]) { Long_Test L1 = new Long_Test (68764);

    Long_Test L2 = new Long_Test ("686748"); System.out.println("Object L1 = " + L1); System.out.println("Object L2 = " + L2); System.out.println("Minimum Value of Long = " + Long.MIN_VALUE); System.out.println("Maximum Value of Long = " + Long.MAX_VALUE); System.out.println("L1 * 2 = " + L1 * 2); System.out.println("L1.longValue() * 2 = " + L1.longValue() * 2); System.out.println("L1.compareTo(l2) = " + L1.compareTo(L2)); System.out.println("L1==L2 ? = " + L1.equals(L2)); Long_Test L3 = Long.valueOf("10", 16); System.out.println("Object L3 = " + L3); System.out.println("Byte value of Long = " + L1.byteValue()); System.out.println("int value of Long = " + L1.intValue()); System.out.println("Double value of Long = " + L1.doubleValue()); int i = 12; System.out.println("Binary equivalent of decimal " + i + "=" +

    Long.toBinaryString(i)); System.out.println("Hexadecimal equivalent of decimal " + i + "=" +

    Long.toHexString(i)); }

    }

    Output :C:\java> javac Long_Test.javaC:\java> java Long_TestObject L1 = 68764

  • 8/12/2019 Easy to Learn- Java

    95/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Object L2 = 686748 Minimum Value of Long = -9223372036854775808 Maximum Value of Long = 9223372036854775807

    L1 * 2 = 137528L1.longValue() * 2 = 137528L1.compareTo(l2) = -1L1==L2 ? = falseObject L3 = 16Byte value of Long = -100int value of Long = 68764Double value of Long = 68764.0Binary equivalent of decimal 12=1100Hexadecimal equivalent of decimal 12=c

    Double class:

    The Double class encapsulates a double value. It defines several constants. The largest and smallest valuesare saved in MAX_VALUE and MIN_VALUE. The constant NaN (Not a Number) indicates that a value

    is not a number. If you divide a double number by zero, the result is NaN.This class defines these constructors :Double(double d)Double(String str)Here, d is a double value to be encapsulated in a Double object. In the last form, str is the stringrepresentation of a double value.

    Prog. No.:- 72

    import java.util.*; class Double_Test {

    public static void main(String args[]) {

    Double_Test d1 = new Double_Test (687642365.4563); Double_Test d2 = new Double_Test ("686748"); System.out.println("Object d1 = " + d1); System.out.println("Object d2 = " + d2); System.out.println("Minimum Value of Double = " + Double.MIN_VALUE); System.out.println("Maximum Value of Double = " + Double.MAX_VALUE); System.out.println("Byte value of Double = " + d1.byteValue()); System.out.println("int value of Double = " + d1.intValue()); System.out.println("Float value of Double = " + d1.floatValue()); Double_Test d3 = Double.parseDouble("765.89"); System.out.println("Double value from the string \"765.89\"="+d3);

    } } Output :C:\java> javac Double_Test.java

    C:\java> java Double_TestObject d1 = 6.876423654563E8Object d2 = 686748.0

    Minimum Value of Double = 4.9E-324 Maximum Value of Double = 1.7976931348623157E308

    Byte value of Double = -3

  • 8/12/2019 Easy to Learn- Java

    96/119

    INTERNET TECHNOLOGY (CORE JAVA)

    int value of Double = 687642365Float value of Double = 6.8764237E8Double value from the string "765.89"=765.89

    Float class:

    The float class encapsulates a float value. It defines several constants the largest and smallest values arestored in MAX_VALUE and MIN_VALUE. The constant NaN indicates that a value is not a number. Ifyou divide a floating point number by zero, the result is NaN.This class defines these constructors:

    Float(float f)Float(double d)Float(String str)

    Here, f and d are float and double types to be encapsulated in a Float object. str is the string representationof a float value.

    Prog. No.:- 73

    import java.util.*;

    public class Float_Test {

    public static void main(String args[]) {

    Float_Test f1 = new Float_Test (123.5626); Float_Test f2 = new Float_Test (854.32f); Float_Test i = new Float_Test (10); System.out.println("Object f1 = " + f1); System.out.println("Object f2 = " + f2); System.out.println("Minimum Value of Float = " + Float.MIN_VALUE); System.out.println("Maximum Value of Float = " + Float.MAX_VALUE); System.out.println("Byte value of Float = " + f1.byteValue()); System.out.println("Short value of Float = " + f1.shortValue()); System.out.println("Integer value of Float = " + f1.intValue()); System.out.println("Double value of Float = " + f1.doubleValue()); System.out.println("(f1==f2) ?= " + f1.equals(f2)); System.out.println("f1.compareTo(f2) = " + f1.compareTo(f2)); System.out.println("f1 is not a number = " + i.isNaN());

    } } Output :

    C:\java> javac Float_Test.javaC:\java> java Float_Test Object f1 = 123.5626Object f2 = 854.32

    Minimum Value of Float = 1.4E-45 Maximum Value of Float = 3.4028235E38

    Byte value of Float = 123Short value of Float = 123Integer value of Float = 123Double value of Float = 123.5625991821289(f1==f2) ?= falsef1.compareTo(f2) = -1f1 is not a number = false

  • 8/12/2019 Easy to Learn- Java

    97/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Character class:

    The Character class encapsulates a char value. This class provides the followingconstructor.

    Character(char ch)Here, c is a char value. charValue() method returns the char value that is encapsulated by a Characterobject and has the following form:

    char charValue().

    Prog. No.:- 74

    import java.util.*;

    public class Char_Test {

    public static void main(String args[]) {

    Character_Test c1 = new Character_Test ('m'); char c2 = 'O'; System.out.println("Object C1 = " + c1); System.out.println("char value of Character Object = " + c1.charValue()); System.out.println(c2 + " is defined character set ? " +

    Character.isDefined(c2)); System.out.println("c2 is digit = " + Character.isDigit(c2)); System.out.println("c2 is lowercase character = " +

    Character.isLowerCase(c2)); System.out.println("c2 is uppercase character = " +

    Character.isUpperCase(c2));

    } }

    Output :C:\java> javac Char_Test.java

    C:\java> java Char_TestObject C1 = mchar value of Character Object = mO is defined character set ? truec2 is digit = falsec2 is lowercase character = falsec2 is uppercase character = true

    Boolean class:

    The Boolean class encapsulates a Boolean value. It defines FALSE and TRUE constants.This class provides following constructors:Boolean(Boolean b)Boolean(String str)Here, b is a Boolean value and str is the string equivalent of a Boolean value.The methods associated with Boolean Class are as follows:1. Boolean booleanValue()2. Boolean equals(Boolean b)

    3. String toString(Boolean b)

  • 8/12/2019 Easy to Learn- Java

    98/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Prog. No.:- 75

    import java.util.*;

    public class Boolean_Test {

    public static void main(String args[]) {

    Boolean_Test b1 = new Boolean_Test (true); Boolean_Test b2 = new Boolean_Test (false); System.out.println("Object B1 = " + b1); System.out.println("Object B2 = " + b2); Boolean_Test b3 = new Boolean_Test ("true"); Boolean_Test b4 = new Boolean_Test ("false"); System.out.println("Object B3 = " + b3); System.out.println("Object B4 = " + b4); System.out.println("Boolean Value = " + b1.booleanValue());System.out.println("(b1==b2)? " + b1.equals(b2));String S1 = b1.toString(); System.out.println("String S1 " + S1);

    } } Output :

    C:\java> javac Boolean_Test.javaC:\java> java Boolean_TestObject B1 = trueObject B2 = falseObject B3 = trueObject B4 = falseBoolean Value = true(b1==b2)? falseString S1 true

    STRING &STRING BUFFER IN JAVA

    String Handling:-In Java, a string is defined as a sequence of characters. But, unlike many other

    languages that implement strings as character arrays, java implements strings as objects of type String.Java handles String by two classes StringBuffer and String. The String and StringBuffer classes aredefined in java.lang. Thus, they are available to all programs automatically.

    String Concatenation (+)

    Prog. No.:- 76

    import java.util.*; class STest {

  • 8/12/2019 Easy to Learn- Java

    99/119

    INTERNET TECHNOLOGY (CORE JAVA)

    public static void main(String args[]) {

    STest s1 = new STest ("Java"); STest s2 = "2all"; STest s3 = s1+s2; System.out.println("S1 = " + s1); System.out.println("S2 = " + s2); System.out.println("Concatenation Operator = " + s1+s2); System.out.println("S3 = " + s3);

    byte num [] = {65,66,67,68}; STest s4 = new STest (num); System.out.println("S4 = " + s4);

    } } Output :C:\java> javac STest.javaC:\java> java STestS1 = JavaS2 = 2allConcatenation Operator = Java2allS3 = Java2allS4 = ABCD

    Character Extraction :

    The String class provides ways in which characters can be extracted from a String object.

    String Comparison : The String class provides several methods that compare strings or substrings within strings.

    equals( ) used to compare two stringsGeneral form:Boolean equals(Object str)

    Here, str is a String object.It returns true if the strings contain the same character otherwise it returns false.The comparison is case-sensitive.

    equalsIgnoreCase( ) Same as equals but this ignores case.General form:

    Boolean equalsIgnoreCase(String str)Here, str is the String object.It returns true if the strings contain the same character otherwise it returns false.

    This is case in sensitive.regionMatches( )

    This method compares a specific region inside a string with another specific region in another string.There is an overloaded form that allows you to ignore case in such comparisons.General form:

    Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int numChars)Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int

    numChars)startsWith( ) and endsWith()The startsWith( ) method determines whether a given String begins with a specified string.endsWith( ) determines whether the String ends with a specified string.

    General Form

  • 8/12/2019 Easy to Learn- Java

    100/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Boolean startsWith(String str)Boolean endsWith(String str)equals( ) Versus = =

    Equals( ) method and the = = operator perform two different operations. The equals ( ) method comparesthe characters inside a String object. The = = operator compares two object references to see whether theyrefer to the same instance.

    compareTo( )

    It is not enough to know that two strings just for equal or not. For sorting applications, we need to knowwhich is less than, equal to, or greater than the other string.The String method compareTo( ) serves this purpose.General Form:

    int compareTo(String str)Modifying a string :

    If we want to modify a String, we must either copy it into a StringBufer or we canuse following String methods:

    valueOf() :

    The valueOf() method converts data from internal format into a human-readable form. Ithas several forms:String valueOf(double num)String valueOf(long num)String valueOf(Object ob)String valueOf(char chars[ ] )String valueOf(char chars[], int startIndex, int numChars)

    String Buffer class: StringBuffer is a peer class of String. String creates strings of fixed length, while

    StringBuffer creates strings of flexible length that can be modified in terms of both length and content. SoStrings that need modification are handled by StringBuffer class. We can insert characters and substrings inthe middle of a string, or append another string to the end.

    StringBufer defines these Constructors:

    StringBuffer()

    StringBuffer(int size)

    StringBuffer(String str)

    Method Call Task PerformedSb.length() Gives the current length of a StringBuffer.Sb.capacity() Gives the total allocated capacity (default 16)

    setLength(int len) Set the length of the buffer within a String Buffer

    object.charAt(int where) Gives the value of character

  • 8/12/2019 Easy to Learn- Java

    101/119

    INTERNET TECHNOLOGY (CORE JAVA)

    setCharAt(int where, char ch) Set the value of a character within a StringBuffer.S1.append(s2) Appends the string s2 to s1 at the end

    S1.insert(n,s2) Inserts the string s2 at the position n of the strings1S1.reverse() Reverse the string of s1S1.deleteCharAt(nth) Delete the nth character of string s1S1.delete(StartIndex, endIndex) Delete characters from start to end.

    Prog. No.:- 77

    import java.util.*;

    class Strbuf_Test {

    public static void main(String args[])

    { Strbuf_Test s1 = new Strbuf_Test (); Strbuf_Test s2 = new Strbuf_Test ("Anurag"); Strbuf_Test s3 = new Strbuf_Test (s2); Strbuf_Test s4 = new Strbuf_Test (100); System.out.println("s1 = " + s1); System.out.println("s2 = " + s2); System.out.println("s3 = " + s3);

    System.out.println("s1.length = " + s1.length()); System.out.println("s2.length = " + s2.length()); System.out.println("s3.length = " + s3.length()); System.out.println("s4.length = " + s4.length());

    System.out.println("s1.capacity = " + s1.capacity()); System.out.println("s2.capacity = " + s2.capacity()); System.out.println("s3.capacity = " + s3.capacity()); System.out.println("s4.capacity = " + s4.capacity());

    } } Output :C:\java> javac Strbuf_Test.java

    C:\java> java Strbuf_Test

    s1 =s2 = Anurags3 = Anurags1.length = 0s2.length = 9s3.length = 9s4.length = 0s1.capacity = 16s2.capacity = 25s3.capacity = 25s4.capacity = 100

    Prog. No.:- 78

  • 8/12/2019 Easy to Learn- Java

    102/119

    INTERNET TECHNOLOGY (CORE JAVA)

    import java.util.*; class Strbuf2_Test {

    public static void main(String args[]) {

    Strbuf2_Test s1 = new Strbuf2_Test ("Anurag Rana"); Strbuf2_Test s2 = new Strbuf2_Test ("Hello"); System.out.println("s1 = " + s1); //System.out.println("s1.charAt(6) = " + s1.charAt(6)); //s1.setCharAt(6,'z'); //System.out.println("s1 = " + s1);//System.out.println("Inserting String = " + s1.insert(6,s2)); //System.out.println("s1 = " + s1);//System.out.println("Appending String = " + s1.append(s2)); //System.out.println("s1 = " + s1);//System.out.println("Reversing String = " + s1.reverse());//System.out.println("Deleting 6th character = " + s1.deleteCharAt(6));System.out.println("Deleting 6 to 11 character = " + s1.delete(6,11));

    } }

    Output :C:\java> javac Strbuf2_Test.java

    C:\java> java Strbuf2_Tests1 = Anurag RanaDeleting 6 to 11 character = Anurag

    Prog. No.:- 79

    import java.util.*;

    public class Strbuf3_Test {

    public static void main(String[] args) {

    Strbuf3_Test s = new Strbuf3_Test ("Hello world!");

    System.out.println("s = " + s); System.out.println("s.length() = " + s.length()); System.out.println("s.length() = " + s.capacity()); // Change the length of buffer to 5 characters: s.setLength(5);

    System.out.println(s); System.out.println("s.length() = " + s.length()); System.out.println("s.length() = " + s.capacity());

    } }

    Output :C:\java> javac Strbuf3_Test.java

    C:\java> java Strbuf3_Tests = Hello world!

    s.length() = 12s.length() = 28

  • 8/12/2019 Easy to Learn- Java

    103/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Hellos.length() = 5s.length() = 28

    EXCEPTION HANDLING IN JAVA

    Exception handling:Exception is a run-time error which arises during the execution of java

    program. The term exception in java stands for an exceptional event .So Exceptions are nothing but some abnormal and typically an event or conditions that arise during theexecution which may interrupt the normal flow of program.An exception can occur for many different reasons, including the following:

    A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has runout of memory.

    If the exception object is not handled properly, the interpreter will display the error and will terminat e the program. Now if we want to continue the program with the remaining code, then we should write the part of the program which generate the error in the try{} block and catch the errors using catch() block..Exception turns the direction of normal flow of the program control and send to the related catch() blockand should display error message for taking proper action. This process is known as Exception handling . The purpose of exception handling is to detect and report an exception so that proper action can be takenand prevent the program which is automatically terminate or stop the execution because of that exception.

    Java exception handling is managed by using five keywords: try, catch, throw, throws and finally.Try:Piece of code of your program that you want to monitor for exceptions are contained within

    a try block. If an exception occurs within the try block, it is thrown.Catch:

    Catch block can catch this exception and handle it in some logical manner.Throw:

    System-generated exceptions are automatically thrown by the Java run-time system. Now ifwe want to manually throw an exception, we have to use the throw keyword.Throws:

    If a method is capable of causing an exception that it does not handle, it must specify this

    behavior so that callers of the method can guard themselves against that exception.You do this by including a throws clause in the methods declaration. Basically it is used for IOException.A throws clause lists the types of exceptions that a method might throw.This is necessary for all exceptions, except those of type Error or RuntimeException, or any of theirsubclasses.All other exceptions that a method can throw must be declared in the throws clause. If they are not, acompile-time error will result.Finally: Any code that absolutely must be executed before a method returns, is put in a finally block.General form:try {// block of code to monitor for errors

  • 8/12/2019 Easy to Learn- Java

    104/119

    INTERNET TECHNOLOGY (CORE JAVA)

    }catch ( ExceptionType1 e1 ) {// exception handler for ExceptionType1 }catch ( ExceptionType2 e2 ) {// exception handler for ExceptionType2 }

    // ...finally {// block of code to be executed before try block ends}

    Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class.

    The exception class is a subclass of the Throwable class. Other than the exception class there is anothersubclass called Error which is derived from the Throwable class.Errors :

    These are not normally trapped form the Java programs.Errors are typically ignored in your code because you can rarely do anything about an error.These conditions normally happen in case of severe failures, which are not handled by the java programs.Errors are generated to indicate errors generated by the runtime environment.For Example :(1) JVM is out of Memory. Normally programs cannot recover from errors.(2) If a stack overflow occurs then an error will arise. They are also ignored at the time of compilation.

    The Exception class has two main subclasses:(1) IOException or Checked Exceptions class and(2) RuntimeException or Unchecked Exception class

    (1) IOException or Checked Exceptions : Exceptions that must be included in a methods throws list if that method can

    generate one of these exceptions and does not handle it itself. These are called checked exceptions. Forexample, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptionscannot simply be ignored at the time of compilation.Javas Checked Exceptions Defined in java.lang

    (2) RuntimeException or Unchecked Exception :Exceptions need not be included in any methods throws list. These are

    called unchecked exceptions because the compiler does not check to see if a method handles or throwsthese exceptions. As opposed to checked exceptions, runtime exceptions are ignored at the time ofcompilation.Javas Unchecked RuntimeException Subclasses .

    Try and catch in java:

    Prog. No.:- 80

    public class TC_Test{

  • 8/12/2019 Easy to Learn- Java

    105/119

    INTERNET TECHNOLOGY (CORE JAVA)

    public static void main(String[] args){

    int a=10; int b=5,c=5; int x,y; try {

    x = a / (b-c); } catch(ArithmeticException e) {

    System.out.println("Divide by zero"); } y = a / (b+c); System.out.println("y = " + y);

    }

    } Output :C:\java> javac TC_Test.java

    C:\java> java TC_TestDivide by zeroy = 1

    Note that program did not stop at the point of exceptional condition.It catches the error condition, printsthe error message, and continues the execution, as if nothing has happened. If we run same programwithout try catch block we will not gate the y value in output. It displays the following message and stopswithout executing further statements.

    Exception in thread "main" java.lang.ArithmeticException: / by zeroat Thrw_Excp.TC_Demo.main(TC_Demo.java:10)

    Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero.

    Now how to display description of an exception ?

    The description of thrown object by using it in a println() statement bysimply passing the exception as an argument. For example;

    catch (ArithmeticException e)

    {

    system.out.pritnln(Exception: +e);

    }

    Multiple catch blocks :

    ? It is possible to have multiple catch blocks in our program.

    Prog. No.:- 81

    public class MultiCatch

  • 8/12/2019 Easy to Learn- Java

    106/119

    INTERNET TECHNOLOGY (CORE JAVA)

    { public static void main(String[] args){

    int a [] = {5,10}; int b=5; try {

    int x = a[2] / b - a[1]; } catch(ArithmeticException e) {

    System.out.println("Divide by zero"); } catch(ArrayIndexOutOfBoundsException e) {

    System.out.println("Array index error"); } catch(ArrayStoreException e) {

    System.out.println("Wrong data type"); } int y = a[1]/a[0]; System.out.println("y = " + y); }

    } Output :C:\java> javac MultiCatch.javaC:\java> java MultiCatch

    Array index errory = 2

    Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundary. Whenexception in try block is generated, the java treats the multiple catch statements like cases in switchstatement. The first statement whose parameter matches with the exception object will be executed, andthe remaining statements will be skipped. When you are using multiple catch blocks, it is important toremember that exception subclasses must come before any of their superclasses. This is because a catchstatement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, asubclass will never be reached if it comes after its superclass. And it will result into syntax error.

    // Catching super exception before sub

    Prog. No.:- 82

    class etion3 {

    public static void main(String args[]) {

    int num1 = 100; int num2 = 50; int num3 = 50; int result1;

    try {

    result1 = num1/(num2-num3); System.out.println("Result1 = " + result1);

    }

    catch (Exception e)

  • 8/12/2019 Easy to Learn- Java

    107/119

    INTERNET TECHNOLOGY (CORE JAVA)

    { System.out.println("This is mistake. ");

    } catch(ArithmeticException g) {

    System.out.println("Division by zero");

    } }

    } Output :

    If you try to compile this program, you will receive an error message because the exception has already been caught in first catch block. Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception based errors, including ArithmeticException. This means that the secondcatch statement will never execute. To fix the problem, revere the order of the catch statement.Nested try statements:

    The try statement can be nested. That is, a try statement can be inside a block of another try. Each time a try statement is entered, its corresponding catch block has to enter. Thecatch statements are operated from corresponding statement blocks defined by try.

    Prog. No.:- 83

    public class NestedTry{

    public static void main(String args[]) {

    int num1 = 100; int num2 = 50; int num3 = 50; int result1;

    try {

    result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); try {

    result1 = num1/(num2-num3); System.out.println("Result1 = " + result1);

    } catch(ArithmeticException e) {

    System.out.println("This is inner catch"); }

    } catch(ArithmeticException g) {

    System.out.println("This is outer catch"); }

    } } Output :C:\java> javac NestedTry.javaC:\java> java NestedTryThis is outer catch.

    Finally:

  • 8/12/2019 Easy to Learn- Java

    108/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Java supports another statement known as finally statement that can be used to handle an exception that isnot caught by any of the previous catch statements. We can put finally block after the try block or after thelast catch block. The finally block is executed in all circumstances. Even if a try block completes without

    problems, the finally block executes.

    Prog. No.:- 84

    public class Finally_Test{ public static void main(String args[]) {

    int num1 = 100; int num2 = 50; int num3 = 50; int result1;

    try {

    result1 = num1/(num2-num3); System.out.println("Result1 = " + result1);

    } catch(ArithmeticException g) {

    System.out.println("Division by zero");

    } finally {

    System.out.println("This is final"); }

    } } Output :C:\java> javac Finally_Test.javaC:\java> java Finally_TestDivision by zeroThis is final

    Throw:

    We saw that an exception was generated by the JVM when certain run-time problemsoccurred. It is also possible for our program to explicitly generate an exception. This can be done with athrow statement.

    Throw object;

    Inside a catch block, you can throw the same exception object that was provided as an argument.

    Syntax:

    catch(ExceptionType object)

    {

  • 8/12/2019 Easy to Learn- Java

    109/119

    INTERNET TECHNOLOGY (CORE JAVA)

    throw object;

    }

    Alternatively, you may create and throw a new exception object as follows:

    Throw new ExceptionType(args);

    Here, exceptionType is the type of the exception object and args is the optional argument list for itsconstructor. When a throw statement is encountered, a search for a matching catch block begins and iffound it is executed.

    Prog. No.:- 85

    class Throw_Test {

    public static void a() {

    try {

    System.out.println("Before b"); b();

    } catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here {

    System.out.println("J : " + j) ; }

    }

    public static void b() { int a=5,b=0;

    try {

    System.out.println("We r in b"); System.out.println("********"); int x = a/b;

    } catch(ArithmeticException e) {

    System.out.println("c : " + e); throw new ArrayIndexOutOfBoundsException("demo"); //throw from here

    }

    } public static void main(String args[]) {

    try {

    System.out.println("Before a"); a(); System.out.println("********"); System.out.println("After a");

    } catch(ArithmeticException e) {

    System.out.println("Main Program : " + e);

  • 8/12/2019 Easy to Learn- Java

    110/119

    INTERNET TECHNOLOGY (CORE JAVA)

    } }

    } Output :C:\java> javac Throw_Test.javaC:\java> java Throw_TestBefore aBefore b

    We r in b********c : java.lang.ArithmeticException: / by zeroJ : java.lang.ArrayIndexOutOfBoundsException: demo******** After a

    Throwing our own object :

    ?If we want to throw our own exception, we can do this by using the keyword throw as follow.

    throw new Throwable_subclass;

    Example : throw new ArithmaticException( );

    throw new NumberFormatException( );

    Prog. No.:- 86

    import java.lang.Exception;

    class MyException extends Exception

    { MyException(String message) {

    super(message); }

    } class TestMyException {

    public static void main(String[] args){

    int x = 5, y = 1000; try { float z = (float)x / (float)y;

    if(z < 0.01) {

    throw new MyException("Number is too small"); }

    } catch(MyException e) {

    System.out.println("Caught MyException"); System.out.println(e.getMessage());

    } finally

    { System.out.println("uiit.hpu");

  • 8/12/2019 Easy to Learn- Java

    111/119

    INTERNET TECHNOLOGY (CORE JAVA)

    } }

    } Output :C:\java> javac TestMyException.java C:\java> java TestMyException Caught MyException

    Number is too smalluiit.hpu

    Here The object e which contains the error message "Number is too small" is caught by the catch blockwhich then displays the message using getMessage( ) method.

    NOTE:

    Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class. Anobject of a class that extends Throwable can be thrown and caught.

    Throws:If a method is capable of causing an exception that it does not handle, it must specify this behavior so thatcallers of the method can guard themselves against that exception. We do this by including a throws clausein the methods declaration. Basically it is used for IOException. A throws clause lists the types ofexceptions that a method might throw. This is necessary for all exceptions, except those of type Error orRuntimeException,or any of their subclasses. All other exceptions that a method can throw must bedeclared in the throws clause. If they are not, a compile-time error will result.

    General form of a method declaration that includes a throws clause:type method-name(parameter-list) throws exception-list{// body of method}Here, exception-list is a comma-separated list of the exceptions that a method can throw. Throw is used toactually throw the exception, whereas throws is declarative statement for the method. They are notinterchangeable.

    Prog. No.:- 87

    class NewException extends Exception {

    public String toS() {

    return "You are in NewException ";}

    }

    class Customexception {

    public static void main(String args[]) {

    try {

    doWork(3); doWork(2); doWork(1);

  • 8/12/2019 Easy to Learn- Java

    112/119

    INTERNET TECHNOLOGY (CORE JAVA)

    doWork(0); } catch (NewException e) {

    System.out.println("Exception : " + e.toS()); }

    }

    static void doWork(int value) throws NewException {

    if (value == 0) {

    throw new NewException(); } else {

    System.out.println("****No Problem.****"); }

    } } Output:C:\java> javac Customexception.java C:\java> java Customexception ****No Problem.********No Problem.********No Problem.****

    MULTITHREADING IN JAVA

    Thread: A thread is a single flow of control like simple program.

    A unique property of java is multithreading only because javasupports multithreading. More than one thread (program) run simultaneously is known as multithreading(multiprogramming). In multithreading java interpreter handles the switching of control between thethreads in such a way that it looks like they are running concurrently. Multithreading is useful in a numberof ways. We can divide a long program into number of threads and executes them in parallel.

    The Main Thread:When our simple program starts one single thread begins running immediately. This is called our single mainthread. The main thread create automatically when program is started.It is very important thread because of two reasons:

    1.) From the main thread other child thread will be created.2.) Main thread is all most everytime stop running lastly because it has to remove or shutdown few resources aswell as few action.

    Now the question is how can we control our main thread?Actually by calling the method currentThread() of Thread class we can control our main thread.

  • 8/12/2019 Easy to Learn- Java

    113/119

    INTERNET TECHNOLOGY (CORE JAVA)

    Prog. No.:- 88 (Main Thread.)

    public class Main_Thread{

    public static void main(String args[]){

    Main_Thread t = Main_Thread.currentThread(); System.out.println("Current thread: " + t);

    // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try {

    for(int n = 5; n > 0; n--){

    System.out.println(n); //print number with interval of 1 sec. Thread.sleep(1000); //Thread is going to sleep for 1 sec.

    } }

    catch (InterruptedException e){ System.out.println("Main thread interrupted");

    } }

    } Output:C:\java> javac Main_Thread.java

    C:\java> java Main_ThreadCurrent thread: Thread[main,5,main]

    After name change: Thread[My Thread,5,main]54321

    Here first of all we give reference of our current main single thread to t by thread object andcurrentThread() method. The number 5 to 1 will be print at interval of 1 second due to sleep method.Thread will go to sleep for 1000 ms. due to sleep method

    Thread Life Cycle:

    Thread has many different state through out its life.1 Newborn State2 Runnable State3 Running State4 Blocked State5 Dead State

  • 8/12/2019 Easy to Learn- Java

    114/119

    INTERNET TECHNOLOGY (CORE JAVA)

    1 Newborn State:When we create a thread it will be in Newborn State. The thread is just created still

    its not running. We can move it to running mode by invoking the start() method and it can be killed byusing stop() method.

  • 8/12/2019 Easy to Learn- Java

    115/119

    INTERNET TECHNOLOGY (CORE JAVA)

    2 Runnable State:It means that thread is now ready for running and its waiting to give control. We can

    move control to another thread by yield() method.

    3 Running State:It means thread is in its execution mode becaause the control of cpu is given to that

    particular thread. It can be move in three different situation from running mode.

  • 8/12/2019 Easy to Learn- Java

    116/119

    INTERNET TECHNOLOGY (CORE JAVA)

    4 Blocked State:A thread is called in Blocked State when it is not allowed to entering in Runnable

    State or Running State. It happens when thread is in waiting mode, suspended or in sleeping mode.

    5 Dead State: When a thread is completed executing its run() method the life cycle of that particular thread is end. We can kill thread by invoking stop() method for that particular thread and send itto be in Dead State.

    Create Thread: We can create thread in java with two different ways.1. Extending the Thread Class.2. Implements runnable interface..1. Extending the Thread class:

  • 8/12/2019 Easy to Learn- Java

    117/119

    INTERNET TECHNOLOGY (CORE JAVA)

    In this method one normal class extends the inbuilt class thread andoverride its run() method with the code required by that particular thread. Here we are going to extendclass java.lang.Thread. so we can access all the methods of thread class. Create one class which extendsthe thread class. Override the run method and put lines of code inside thread method that will be perform

    by thread.Create an object of class which we created with extending the thread class and call the start() method toexecute the thread.

    Class MyThread extends Thread{

    .. ..

    }So now we have one thread named MyThread.Implementing the run() methodPublic void run(){

    // Thread code here}Starting new ThreadMyThread aTh = new MyThread(); // it instantiates a new object of class MyThreadaTh.start(); // invokes run() method

    Prog. No.:- 89( Extending the Thread class .)

    class A extends Thread {

    public void run(){ System.out.println("Thread A"); for(int i=1;i

  • 8/12/2019 Easy to Learn- Java

    118/119

    INTERNET TECHNOLOGY (CORE JAVA)

    new B().start(); //creating B class thread object and calling run method System.out.println("End of main thread");

    } } Output :C:\java> javac Thread_Class.java C:\java> java Thread_Class Thread AFrom thread A i = 1From thread A i = 2From thread A i = 3From thread A i = 4From thread A i = 5Exit from AEnd of main threadThread BFrom thread B i = 1From thread B i = 2From thread B i = 3From thread B i = 4From thread B i = 5Exit from B

    2. Implementing the Runnable interface:

    In this method we have one interface named runnable and we implements thisinterface for implement a thread. Create one class which implements runnable interface. Override the run()method and put some line of code for that particular thread. Now create an object of inbuilt thread classand create an object of class that implements runnable interface. Give the reference of object to threadobject by passing an argument (argument must be the object of class which implements therunnable interface) while creating a thread object. Call the start() method to run the thread.

    Prog. No.:- 90 ( Implementing the Runnable interface .)

    public class Thread_Interface{

    public static void main(String[] args){

    X x1 = new X(); //class object Thread xthread = new Thread(x1); //creating thread object and giving

    reference of class object to thread object xthread.start(); System.out.println("End of main Thread");

    }

    } class X implements Runnable {

    public void run(){

    System.out.println("Inside X thread"); for(int i=1;i

  • 8/12/2019 Easy to Learn- Java

    119/119

    Output :C:\java> javac Thread_Interface.java

    C:\java> java Thread_Interface End of main ThreadInside X threadFrom xthread i = 1From xthread i = 2From xthread i = 3

    From xthread i = 4From xthread i = 5From xthread i = 6From xthread i = 7From xthread i = 8From xthread i = 9From xthread i = 10Exit from X