Java Basics

988 views
829 views

Published on

Java Basics

Published in: Technology, Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
988
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
56
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Java Basics

  1. 1. A Preview
  2. 2. Primitive Data Types in JavaPrimitive data typesBoolean type Numeric typesIntegral types Floating-point typesCharacter type Integer typesintboolean shortbytechar long float double
  3. 3. DataTypesName Size Rangeboolean 1 true or falsechar 16 0 to 65535byte 8 -128 to 127short 16 -32768 to 32767int 32 -2147483648 to 2147483647long 64 -9223372036854775808 to 9223372036854775807float 32 +/- 1.4023x10-45 to 3.4028x10+38double 64 +/- 4.9406x10-324 to 1.7977x10308
  4. 4. Variables A variable stores a value of a particular type. A variable hasa name, a type, and a value associated with it. Variables that store reference values of objects are calledreference variables. If no initialization is provided for static or instancevariables either in the declaration or in an initializer block,it is initialized with the default value of its type when theclass is loaded or instantiated respectively. Local variables declared in methods, constructors, andblocks are not initialized when they are created at methodinvocation or execution of a method. Instance variables, created for each object of the class, existas long as the object they belong to is in use at runtime. Static variables which not created for any specific object,created when the class is loaded at runtime, and exist aslong as the class is available at runtime.
  5. 5. Class Declarations Class Declaration Syntax <class modifiers> class <class name><formal type parameterlist> <extends clause> <implements clause> // Class header { // Class body <field declarations> <method declarations> <nested class declarations> <nested interface declarations> <nested enum declarations> <constructor declarations> <initializer blocks> }
  6. 6. Method Declarations <method modifiers> <formal type parameter list><return type> <method name> (<formal parameter list>) <throws clause> // Methodheader { // Method body <local variable declarations> <nested local class declarations> <statements> }
  7. 7. Methods Overloading Each method has a signature, which comprises thename of the method, and the types and order of theparameters in the formal parameter list. Several method implementations may have the samename, but different method signatures, which is calledmethod overloading. The overloaded methods have the same name, buttheir parameter lists must be different.
  8. 8. Method Overriding A subclass can override instance methods inherited from asuperclass providing its own implementation of the method. When the method is invoked on an object of the subclass,the overridden method in the subclass is executed. If the return type of overridden method is a subtype of thereturn type of base class method, then such methods arecalled covariant return. An instance method in a subclass cannot override a staticmethod in the superclass. A subclass cannot override fields and static methods of thesuperclass, but it can hide them. Method overriding always requires the same methodsignature (name and parameter types) and same orcovariant return types.
  9. 9. Constructor Declarations <accessibility modifier> <class name> (<formalparameter list>) <throws clause> // Constructor header { // Constructor body <local variable declarations> <nested local class declarations> <statements> }
  10. 10. Constructors A default constructor is a constructor without anyparameters. If a class does not specify any constructors, then an implicitdefault constructor is generated for the class by thecompiler. <class name>() { super(); } All instance variables in the object are set to default valueof their type, barring those that are initialized by aninitialization expression in their declaration. If a class defines any explicit constructors, it can no longerrely on the implicit default constructor to set the state of itsobjects. Constructors can be overloaded as methods with theirdifferentiating signatures being their parameter lists.
  11. 11. Parameter Passing All parameters in Java are passed by value, that is, an actualparameter is evaluated and its value is assigned to thecorresponding formal parameter. In case of primitive data types, the data value of the actualparameter is passed. If the actual parameter is a reference to an object, thereference value is passed and not the object itself. If the actual parameter is an array element of a primitivedata type, its data value is passed, and if the array elementis a reference to an object, then its reference value ispassed. The order of evaluation in the actual parameter list isalways from left to right.
  12. 12. Parameter Passing continued An actual parameter is an expression that is evaluated first andthe resulting value is then assigned to the corresponding formalparameter at method invocation The primitive formal parameters are local to the method, henceany changes made to the primitive formal parameters will not bereflected in actual parameter after the call completes. In case of primitive values, type conversions between actualparameters and formal parameters such as widening primitiveconversion and unboxing conversion are allowed. In case of reference values, the actual parameter and the formalparameter are aliases to the object denoted by the reference valueduring method invocation and changes made to such object viathe formal parameter will be apparent after the call returns.
  13. 13. Interfaces An interface is not a class but a set of requirements forclasses that want to conform to the interface. All methods of an interface are automatically public. However, when implementing the interface in a class, themethod must be declared as public. An interface variable must refer to an object of a class thatimplements the interface. The instanceof is used to check whether an object is of aspecific class or implements an interface. Fields in an interface are always public static final. A tagging interface has no methods; its only purpose is toallow the use of instanceof in a type inquiry.
  14. 14. Interface Syntax <accessibility modifier> interface <interface name> <extends interface clause> // Interface header { // Interface body <constant declarations> <abstract method declarations> <nested class declarations> <nested interface declarations> }
  15. 15. Interfaces and Callbacks The callback pattern needs to specify the action thatshould occur whenever a particular event occurs. In java an object of some class e.g. ActionListener ispassed to the event generating class e.g. Timer whichthen calls one of the methods e.g. ActionPerformed onthat object. Example: ActionListener listener = new TimePrinter(); Timer t = new Timer(10000, listener);
  16. 16. Proxies Used to construct an object of a class that implements one or more interfaceswhose exact nature you may not be known at compile time. The proxy class can create brand-new classes at runtime. The proxy class implements the interfaces specified. The proxy class has all methods required by specified interfaces and methodsdefined in the Object class. It cannot define new code for these methods at runtime but needs aninvocation handler. An invocation handler is an object of any class that implements theInvocationHandler interface with a single method invoke(Object pxy, Methodmethod, Object[] ags). Whenever a method is called on the proxy object, the invoke method of theinvocation handler gets called, with Method object and parameters of originalcall. The invocation handler must then figure out how to handle the call. The proxy object is created using the newProxyInstance method of Proxy class. All proxy classes extend the class Proxy. A proxy class has only one instance field—the invocation handler, which isdefined in the Proxy superclass. The names of proxy classes are not defined and proxy classes are always publicand final. There is only one proxy class for a particular class loader and ordered set ofinterfaces. To test whether a particular Class object is a proxy class call methodisProxyClass.
  17. 17. The main() method The java command executes a method called main inthe class specified on the command line. The main() method must have public accessibility sothat the interpreter can call this method. It is a static method belonging to the class, so that noobject of the class is required to start the execution. It does not return any value, and is declared void.
  18. 18. Class Scope for Members Class scope concerns accessing members (includinginherited ones) from code within a class. Static code can only access other static members bytheir simple names. Static members are always accessible in a non-staticcontext.
  19. 19. Block Scope for Local Variables Declarations and statements can be grouped into a block using braces,{}. Blocks can be nested, and scope rules apply to local variabledeclarations in such blocks. A variable declared in a block is in scope inside the block in which it isdeclared, but it is not accessible outside of this block. It is not possible to redeclare a variable if a local variable of the samename is already declared in the current scope. Local variables of a method include the formal parameters of themethod and variables declared in the method body. The local variables in a method are created each time the method isinvoked, and are distinct from local variables in other invocations ofthe same method that might be executing. A local variable already declared in an enclosing block cannot beredeclared in the nested block but can be declared if the blocks aredisjoint.
  20. 20. Some Modifiers for Members synchronized Methods: Only one thread at a time can executesuch methods of the object and their execution is mutuallyexclusive among all threads. native Methods: These are the methods whose implementationis not defined in Java but in another programming language suchas C, C++ etc. Serialization transforms objects into an output format that isconducive for storing objects and can later be retrieved in thesame state as when they were serialized. transient Fields: The value of a transient field in an objectshould not be saved when the objects of the class are written topersistent storage using serialization. volatile Fields: During execution, compiled code might cachethe values of fields for efficiency reasons. The volatile modifierinforms the compiler that it should not attempt to performoptimizations on the field, which could cause unpredictableresults when the field is accessed by multiple threads.
  21. 21. Type Conversions Widening primitive conversions are usually done implicitly,whereas narrowing primitive conversions usually require a cast. Narrowing reference conversions, which require a runtime checkand can throw a ClassCastException if the conversion is notlegal. A boxing conversion converts the value of a primitive typeto a corresponding value of its wrapper type. A unboxing conversion converts the value of a wrapper type to avalue of its corresponding primitive type. String conversions allow a value of any other type to be convertedto a String type using the string concatenation operator + Type Conversions can occur in assignments, method invocation,and casting for reference values. The instanceof operator is used check if a reference value can bea subtype of the <destination type>. It always returns false if theleft-hand operand is null. If the instanceof operator returns true,the corresponding type cast expression will always be valid.
  22. 22. Initialization When a class is loaded, it is initialized, i.e., its static fields areinitialized with the values of the initializer expressions. After the class is initialized it can be instantiated, an instanceinitializer expression can always refer to any static member of aclass. Static initializer blocks can be defined in a class (not inmethods) and used for initializing static fields. They areexecuted only once, when the class is initialized. Instance initializer blocks are used to initialize fields duringobject creation and serve same purpose as constructors. A typical usage of an instance initializer block is in anonymousclasses which cannot declare constructors. Instance initializers are executed in the order they are specifiedin the class declaration The execution of an instance initializer block can result in anuncaught checked exception, provided the exception is declaredin the throws clause of every constructor in the class.
  23. 23. Initialization continued Class initialization takes place before any instance ofthe class can be created or a static method of the classcan be invoked. A superclass is initialized before its subclasses areinitialized. Initializing a class involves initialization of the staticfields by executing their static initializer expressionsand any static initializer blocks. Initialization of an interface only involves execution ofany static initializer expressions for the static fieldsdeclared in the interface
  24. 24. Packages Java allows you to group classes in a collection called a package. All standard Java packages are inside the java and javax packagehierarchies. It guarantees the uniqueness of class names. A class can use all classes from its own package and all publicclasses from other packages. To access the class in a package add the full package name infront of every class name or import a specific class or the wholepackage. The * notation imports only a single package. Import statement is enhanced to permit the importing of staticmethods and fields, along with the classes. Identifiers in a class can shadow static members that areimported.
  25. 25. Break statement The break statement is used to exit a switch block or tobreak out of a loop e.g. while, for etc. A labeled break statement allows to break out ofmultiple nested loops. E.g: break label;
  26. 26. Arrays An array is a data structure that stores a collection of values ofthe same type. Each individual value is accessed through an integer index. An array variable is declared by specifying the array typefollowed by [] and array variable name.<element type>[] <array name>; OR<element type> <array name>[]; Array are initialized using the new operator.<array name> = new <element type> [<array size>]; array.length gives the number of elements of an array. Array can be initialized as follows:<element type>[] <array name> = { <array initialize list> }; Anonymous array, allows array creation and initializer block tobe combined, to create and initialize an array object without anyname:new <element type>[] { <array initialize list> }
  27. 27. Arrays continued Array initializers: int[] smallPrimes = { 2, 3, 5, 7, 11, 13 }; Anonymous Arrays: new int[] { 17, 19, 23, 29, 31, 37 }; The copyTo() method in Arrays class copies all values ofone array into a new array. The sort(type[] a) method sorts the array using a tunedQuickSort algorithm. The binarySearch(type[] a, type v) method uses thebinary search algorithm to search for the value v. The fill(type[] a, type v) method sets all elements of thearray to v. Multidimensional arrays defined as,double[][] balances = new double[NYEARS][NRATES];
  28. 28. Exception Handling An exception object is always an instance of a class derived fromThrowable. All exceptions descend from Throwable, and then splits into twohierarchies: Error and Exception. The Error hierarchy describes internal errors and resourceexhaustion inside the Java runtime system. Error object should not be thrown by the programmer. The Exception hierarchy also splits into two branches:exceptions that derive from RuntimeException and those that do not. A RuntimeException happens due to programming error. Other Non-RuntimeExceptions occurs because of problems,such I/O errror etc. Any exception that derives from the class Error or the classRuntimeException an unchecked exception. All otherexceptions are called checked exceptions.
  29. 29. Exception Handling continued A method must declare all the checked exceptions that it mightthrow or the compiler will issue an error message. Either declare the exception in method or catch it. If the superclass method throws no checked exception at all,neither can the subclass. The checked exceptions declared by thesubclass method cannot be more general than those of thesuperclass method. When a method in a class declares that it throws an exceptionthat is an instance of a particular class, then it may throw anexception of that class or of any of its subclasses. A method without a throws specifier may not throw any checkedexception at all. The syntax to throw an exception in java is as follows: throw new Exception(); Only the objects of subclasses of Throwable can be thrown.
  30. 30. Catching Exceptions If an exception occurs that is not caught anywhere, it goes to javadefault exception handler which terminates the program andprints a message and the stack trace to the console. To catch an exception, you set up a try/catch block. If any of the code inside the try block throws an exception of theclass specified in catch clause, then the program skips theremainder of the code in the try block and executes the handlercode inside the catch block. If there is no exception, then the program skips the catch clause. If you call a method that throws a checked exception, you musteither handle it or pass it on. No more throws specifiers can be added to a subclass methodthan those which are present in the superclass method.
  31. 31. Catching Exceptions Multiple exception types can be caught in a try blockand each type handled differently. An exception can be thrown in a catch clause. To retrieve the original exception when the exceptionis caught we use the following statement before throw: Throwable e = se.getCause(); The wrapping technique is also useful if a checkedexception occurs in a method that is not allowed tothrow a checked exception. The checked exception iscaught and wrap it into a runtime exception.
  32. 32. Finally When there is an exception, it stops processing theremaining code in the method and exits, withoutcleaning some acquired local resource if any. The finally block is executed irrespective of theoccurrence of an exception. The finally clause could exist without a catch clause. A finally clause can yield unexpected results when itcontains return statements.
  33. 33. Stack Trace A stack trace is a listing of all pending method calls at aparticular point in the execution of a program. The getStackTrace() method gets an array ofStackTraceElement objects that can be analyzed in theprogram. The StackTraceElement class has methods to obtain the filename and line number, as well as the class and methodname, of the executing line of code. The toString methodyields a formatted string containing all of this information. The static Thread.getAllStackTraces method yields thestack traces of all threads.
  34. 34. Tips on Exception Handling Exception handling is not supposed to replace a simpletest or validations. Do not micromanage exceptions with complex nesting. Make good use of the exception hierarchy and throw/catch exceptions of appropriate subclasses. Do not squelch exceptions and silently ignoreexceptions. When you detect an error throw exceptions instead ofreturning some dummy values. Propagating exceptions is better sometimes rather thancatching them.
  35. 35. Assertions They are used to document and validate assumptions madeabout the state of the program at designated locations inthe code. The assertion contains a boolean expression which isexpected to be true and when it is false, the JVM throws aspecial error of AssertionError class. Two forms in which assertions are specified: assert <boolean expression> ; // the simple form assert <boolean expression> : <message expression> ; If assertions are enabled, then the <boolean expression> isevaluated. If its value is true, execution continues normallyafterwards or if it is false, an AssertionError is thrown andpropagated.
  36. 36. Assertions continued The java.lang.AssertionError class is a subclass of java.lang.Errorand are unchecked. They can be explicitly caught and handled using the try-catchconstruct but are seldom caught. By default, assertions are disabled and not executed. Assertions need to be enabled to execute at runtime. -ea and –da : Applies to all non-system classes. -ea:<package name>... and -da:<package name>...: Applies tothe named package and its subpackages. -ea:... and -da:...: Applies to the unnamed package in thecurrent working directory. -ea:<class name> and -da:<class name>: Applies to namedclass. -enablesystemassertions or –esa: Enable assertions in allsystem classes. -disablesystemassertions or –dsa: Disable assertions in allsystem classes.
  37. 37. Inner Classes An inner class is a class that is defined inside anotherclass. Inner class methods can access the data from the scopein which they are defined including the data thatwould otherwise be private. Inner classes can be hidden from other classes in thesame package. Anonymous inner classes are handy to define callbackswithout writing a lot of code.
  38. 38. Inner Classes continued An inner class method gets to access both its own data fields andthose of the outer object creating it. An object of an inner class always gets an implicit reference tothe object that created it. Such reference is invisible in thedefinition of the inner class. The compiler modifies all inner class constructors, by adding aparameter for the outer class reference. The syntax for the outer class reference is, OuterClass.this. The inner object constructor has the syntax outerObject.newInnerClass(construction parameters). It is also possible to set the outer class reference to another objectof outer class by explicitly naming it. An inner class is referred as OuterClass.InnerClass when itoccurs outside the scope of the outer class. Inner classes are translated by the compiler, and not the virtualmachine.
  39. 39. Static member classes, enum typesand interfaces A static class can be instantiated like any ordinary top-levelclass, using its full name. No enclosing instance is required to instantiate a staticmember class. A static member class must be declared explicitly withkeyword static, as a static member of an enclosing type Nested interfaces and enum types are considered implicitlystatic. Static member classes, enum types and interfaces can onlybe declared in top-level type declarations, or within othernested static members. Static member classes & interfaces can directly access othermembers that are declared static within the same class.
  40. 40. Non Static Member Classes Non-static member classes are defined as instance members of otherclasses. An instance of a non-static member class always has an enclosinginstance associated with it. Code in a non-static member class can directly refer to any member(including nested) of any enclosing class or interface, including privatemembers. Non-static member class being a class member can have anyaccessibility i.e. public, private etc. A special form of the new operator is used to instantiate a non-staticmember class:<enclosing object reference>.new <non-static member class constructorcall> An implicit reference to the enclosing object is always available in everymethod and constructor of a non-static member class. The expression <enclosing class name>.this evaluates to a referencethat denotes the enclosing object (of the class <enclosing class name>)of the current instance of a non-static member class.
  41. 41. Local Inner Classes Local classes are defined in the context of a block as in a methodbody or a local block were a this reference is available. Local classes are never declared with an access modifier (that is,public or private). Their scope is always restricted to the block in which they aredeclared. Local inner classes are completely hidden from the outsideworld. Local inner classes can access the fields of their outer classes,and also its local variables. The local variables of outer class mustbe declared final to access them. Local classes cannot have static members as they cannot provideclass-specific services. A local class can be instantiated in the block in which it isdefined.
  42. 42. Anonymous Inner Classes Anonymous classes combine the process of definition and instantiationinto a single step using the new operator. An anonymous inner class is used to create only a single object of theclass, without giving the class a name. Instantiated by extending a class or implementing an interface: new <superclass name> (<optional argument list>){ <member declarations> } ORnew <interface name>() { <member declarations> } An anonymous inner class cannot have constructors because the classhas no name. Only non-static members and final static fields can be declared in theclass body. The construction parameters are given to the superclass constructor,were incase of interfaces it cannot have any construction parameters. An anonymous class provides only a single interface implementation. While implementing an interface it implicitly extends the Object class.
  43. 43. Static Inner Class When the inner class simply hides one class insideanother, but doesn’t have a reference to the outer classobject, then such inner class is a static inner class. Only inner classes can be declared static. A static inner class object does not have a reference tothe outer class object that generated it. Inner classes that are declared inside an interface areautomatically static and public.
  44. 44. Object class The Object class is the ultimate ancestor and every class in Java extendsObject. In java all except the primitive types (numbers, characters, and booleanvalues) are not objects. All array types including the arrays of objects and primitive types, areclass types extending Object class. The equals method in the Object class tests whether one object isconsidered equal to another. A hash code is an integer that is derived from an object and is returnedusing the hashcode() method. If equals method is redefined, redefine the hashCode() method mustalso be redefined. The toString() method returns a string representing the value of theobject. It is automatically invoked by java when an object isconcatenated with a string by the “+” operator. The clone() method creates a clone of the object. The Java runtimesystem allocates memory for the new instance and copies the memoryallocated for the current object.
  45. 45. Object Cloning The clone method is used to make a copy of an objectto be a new object which is identical to original butwhose state can diverge over time. The clone method is a protected method of Object,hence only a particular class can clone its objects. The default cloning operation is “shallow” i.e. itdoesn’t clone objects that are referenced inside otherobjects which works fine if subobjects are immutable. When the subobjects are mutable, the clone methodmust be redefined to make a deep copy that clones thesubobjects too.
  46. 46. Wrappers Classes All primitive types have Wrapper class counterparts. All wrapper classes are immutable (cannot change thewrapped value after been constructed) and final. The Void class is considered a wrapper class, but it doesnot wrap any primitive value and is not instantiable. Except the Character class, all other wrapper classes havetwo public one-argument constructors: one taking aprimitive value and the other taking a String. Each wrapper class (except Character) defines the staticmethod valueOf(String str) that returns the wrapperobject corresponding to the primitive value represented bythe String object passed as argument.
  47. 47. Wrapper Classes continued The integer wrapper classes define an overloaded staticvalueOf() method taking an argument the base or radix. Each wrapper class overrides the toString() method from theObject class. Each wrapper class defines a typeValue() method which returnsthe primitive value in the wrapper object. Each wrapper class also implements the Comparable<Type>interface which defines compareTo(Type) method. The compareTo () method returns a value which is less than,equal to, or greater than zero, depending on whether theprimitive value in the current wrapper Type object is less than,equal to, or greater than value in the wrapper Type objectdenoted by the argument.
  48. 48. Numeric Wrapper Classes The numeric wrapper classes Byte, Short, Integer, Long,Float, and Double are all subclasses of the abstract classNumber. Each numeric wrapper class defines a set of typeValue()methods for converting the primitive value in the wrapperobject to a value of any numeric primitive type. They are: byte byteValue() short shortValue() int intValue() long longValue() float floatValue() double doubleValue()
  49. 49. Numeric Wrapper Classes Each numeric wrapper class defines a static methodparseType(String str), which returns the primitivenumeric value represented by the String object passedas argument else throws a NumberFormatException ifthe String parameter is not a valid argument. The wrapper classes Integer and Long provide staticmethods for converting integers to stringrepresentation in decimal, binary, octal, andhexadecimal notation.
  50. 50. Autoboxing Array list of integers is represented using the Integerwrapper class as below: ArrayList<Integer> list = new ArrayList<Integer>(); The elements added and retrieved from array using: list.add(3); which is automatically translated to list.add(new Integer(3)); Such conversion is called autoboxing. Automatic boxing and unboxing even works witharithmetic expressions. The boxing and unboxing is a courtesy of the compiler, notthe virtual machine.
  51. 51. Java.lang.String The String class implements immutable characterstrings, which are read-only once the string has beencreated and initialized. Hence its threadsafe. A java.lang.String class is final which implies noclass can extend it. Strings are said to be interned, meaning that they sharea unique String object if they have the same content. String objects can be used with the += and + operatorsfor concatenation. String, StringBuilder and StringBuffer, all implementCharSequence interface to facilitate interoperability.It defines charAt(int index), length() and toString()methods.
  52. 52. String Class Methods compareTo(String anotherString): Compares two strings lexicographically. charAt(int index): Returns the character at the specified index. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies characters from this string intothe destination character array. length(): Returns the length of this string. equals(Object anObject): Compares this string to the specified object. equalsIgnoreCase(String anotherString): Compares this String to another String, ignoring caseconsiderations. toUpperCase(): Converts all of the characters in this String to upper case using the rules of the defaultlocale. Similarly toLowerCase(). concat(String str): Concatenates the specified string to the end of this string. indexOf(int ch): Returns the index within this string of the first occurrence of the specified character.Similarly lastIndexOf(int ch). indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of thespecified character, starting the search at the specified index. lly lastIndexOf(int ch, int fromIndex) indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.Similarly lastIndexOf(String str). indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of thespecified substring, starting at the specified index. Similarly lastIndexOf(String str, int fromIndex). substring(int beginIndex): Returns a new string that is a substring of this string. substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string. replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences ofoldChar in this string with newChar. trim(): Returns a copy of the string, with leading and trailing whitespace omitted. split(String regexStr, int limit): It creates an array by splitting the string according to a regular expressionpattern.
  53. 53. StringBuilder The StringBuilder class implements dynamic character strings and ismutable. The capacity of the string builder can also be changed dynamically. It efficiently concatenates strings, without constructing a new Stringobject every time and wasting memory. StringBuilder is used to store character strings that are updatedfrequently and automatically expands as needed. Appending, inserting, and deleting characters automatically results inadjustment of the string builder’s capacity, if necessary. StringBuilder class does not override the equals() method and thehashcode() method from the Object class. It is identical in all respects to StringBuffer except that it is notsynchronized, hence multiple threads accessing it at the same timewould create problems. In single-threaded programs avoiding the overhead of synchronizationmakes the StringBuilder slightly faster. The compiler uses string builders to implement the stringconcatenation.
  54. 54. StringBuffer It is a mutable class unlike the String class in terms ofcapacity and character string. The StringBuffer class is a thread-safe version of theStringBuilder class. StringBuffer can be changed dynamically as StringBuilder. String buffers are preferred when heavy modification ofcharacter strings is involved. A String can be obtained from string buffer. Since the StringBuffer class does not override the equals()method from the Object class as StringBuilder, hence thecontents of string buffers should be converted to Stringobjects for string comparison.
  55. 55. StringBuffer Methods capacity(): Returns the current capacity of the String buffer. length(): Returns the length (character count) of this string buffer. charAt(int index): The specified character of the sequence currentlyrepresented by the string buffer, as indicated by the index argument, isreturned. setCharAt(int index, char ch): The character at the specified index of thisstring buffer is set to ch toString(): Converts to a string representing the data in this string buffer insert(int offset, char c): Inserts the string representation of the char argumentinto this string buffer.delete(int start, int end): Removes the characters in a substring of thisStringBuffer replace(int start, int end, String str): Replaces the characters in a substring ofthis StringBuffer with characters in the specified String. reverse(): The character sequence contained in this string buffer is replaced bythe reverse of the sequence. append(String str): Appends the string to this string buffer.setLength(int newLength): Sets the length of this String buffer. Note that the StringBuffer class has got many overloaded ‘insert’ and‘append’ methods which can be used based on the application need.
  56. 56. Enumerated Types An enumerated type has a finite number of namedvalues, for example: enum Size { SMALL, MEDIUM, LARGE }; Variables can be declared for such type as: Size s = Size.MEDIUM; A variable of such type e.g Size can hold only one ofthe values listed in the type declaration or the specialvalue null that indicates that the variable is not set toany value at all.
  57. 57. Enumeration Classes Similar to enumerated types there are enumerated classes. public enum Size { SMALL, MEDIUM, LARGE }; Constructors, methods, and fields can be added to anenumerated type. The constructors are only invoked when the enumeratedconstants are constructed. Example: enum Size{ SMALL("S"), MEDIUM("M"), LARGE("L");private Size(String abbreviation) { this.abbr = abbr; } } All enumerated types are subclasses of the class Enum. Each enumerated type has a static values method that returnsan array of all values of the enumeration. The ordinal method yields the position of an enumeratedconstant in the enum declaration, counting from zero.
  58. 58. File Handling The java.io package provides an extensive library ofclasses for I/O. Java provides streams as a general mechanism fordealing with data I/O. Streams implement sequential access of data. There are two kinds of streams: byte streams andcharacter streams. An input stream is an object that an application canuse to read a sequence of data, and an output streamis an object that an application can use to write asequence of data.
  59. 59. File Class A File object represents the pathname of a file ordirectory in the host file system. A File object can also be used to query the file systemfor information about a file or directory. The File class can be used to create, rename or deletefiles and directories. A File object created using a pathname can be used tocheck if File or Directory actually exists in the system.
  60. 60. ByteStreams Abstract classes InputStream and OutputStream are baseclasses for handling reading and writing of bytes. Subclasses override their methods to customize read/write. The InputStream class:int read() throws IOExceptionint read(byte[] b) throws IOExceptionint read(byte[] b, int off, int len) throws IOException The OutputStream class:void write(int b) throws IOExceptionvoid write(byte[] b) throws IOExceptionvoid write(byte[] b, int off, int len) throws IOException
  61. 61. InputStreamByteArrayInputStream FileInputStreamFilterInputStreamObjectInputStream PipedInputStreamSequenceInputStreamBufferedInputStream DataInputStream PushbackInputStreamZipInputStream ZipInputStream is defined in: java.util.zipInputStream Classes
  62. 62. OutputStreamByteArrayOutputStream FileOutputStreamFilterOutputStreamObjectOutputStreamPipedOutputStreamBufferedOutputStreamDataOutputStream PrintStreamZipOutputStream ZipOutputStream is defined in: java.util.zipOutputStream Classes
  63. 63. Some InputStream Classes FileInputStream: Data is read as bytes from a file. The fileacting as the input stream can be specified by a File object,a FileDescriptor or a String file name. FilterInputStream: Superclass of all input stream filters.An input filter must be chained to an underlying inputstream. DataInputStream: A filter that allows the binaryrepresentation of Java primitive values to be read from anunderlying input stream. The underlying input streammust be specified. ObjectInputStream: Allows binary representations ofJava objects and Java primitive values to be read from aspecified input stream.
  64. 64. Some OutputStream Classes FileOutputStream: Data is written as bytes to a file. Thefile acting as the output stream can be specified by a Fileobject, a FileDescriptor or a String file name. FilterOutputStream: Superclass of all output streamfilters. An output filter must be chained to an underlyingoutput stream. DataOutputStream: A filter that allows the binaryrepresentation of Java primitive values to be written to anunderlying output stream. The underlying output streammust be specified. ObjectOutputStream: Allows the binary representationof Java objects and Java primitive values to be written to aspecified underlying output stream.
  65. 65. Filter Streams A filter is a high-level stream that provides additionalfunctionality to an underlying stream to which it ischained. The data from the underlying stream is manipulated insome way by the filter. The FilterInputStream and FilterOutputStream classes,together with their subclasses, define input and outputfilter streams. The subclasses BufferedInputStream andBufferedOutputStream implement filters that bufferinput from and output to the underlying stream. The subclasses DataInputStream andDataOutputStream implement filters that allow binaryrepresentation of Java primitive values to be read andwritten, respectively, to and from an underlying stream
  66. 66. DataInput and DataOutput The java.io package contains the two interfaces DataInputand DataOutput, that streams implement to allow readingand writing of binary representations of Java primitivevalues (boolean, char, byte, short, int, long, float, double). The methods for reading and writing binaryrepresentations of Java primitive values are named readXand writeX respectively, where X is any Java primitive datatype. To write binary values create a FileOutputStream, thenchain it to created DataOutputStream and use writeX()methods to write respective data types.
  67. 67. Character Streams: Readers and Writers The abstract classes Reader and Writer are the roots ofthe inheritance hierarchies for streams that read andwrite Unicode characters using a specific characterencoding. A reader is an input character stream that reads asequence of Unicode characters, and a writer is anoutput character stream that writes a sequence ofUnicode characters.
  68. 68. Some Reader Classes BufferedReader: A reader that buffers the characters readfrom an underlying reader. The underlying reader must bespecified and an optional buffer size can be given. InputStreamReader: Characters are read from a byteinput stream which must be specified. The defaultcharacter encoding is used if no character encoding isexplicitly specified. FileReader: Reads characters from a file, using the defaultcharacter encoding. The file can be specified by a Fileobject, a FileDescriptor, or a String file name. Itautomatically creates a FileInputStream that is associatedwith the file.
  69. 69. Some Writer Classes BufferedWriter: A writer that buffers the characters beforewriting them to an underlying writer. The underlying writermust be specified, and an optional buffer size can be specified. OutputStreamWriter: Characters are written to a byte outputstream which must be specified. The default character encodingis used if no explicit character encoding is specified. FileWriter: Writes characters to a file, using the defaultcharacter encoding. The file can be specified by a File object, aFileDescriptor, or a String file name. It automatically creates aFileOutputStream that is associated with the file. PrintWriter: A filter that allows text representation of Javaobjects and Java primitive values to be written to an underlyingoutput stream or writer. The underlying output stream or writermust be specified.
  70. 70. Console Class A console is a unique character-based device associatedwith a JVM. The Console class has methods as follows: Read a line of character-based response:console.readLine(String format, Object... args) Read passwords without echoing characters on consoleconsole.readPassword(String format, Object... args) Print formatted strings to the console:Console format(String format, Object... args)Console printf(String format, Object... args) The flush() method flushes the console and forces anybuffered output to be written immediately.
  71. 71. Object Serialization It allows an object to be transformed into a sequence of bytesthat can later be re-created (deserialized) into the original object. The object retains its state after deserialization, to one it hadwhen it was serialized. The ObjectInput and ObjectOutput interfaces, allow suchreading and writing of objects from and to streams and extendthe DataInput and DataOutput interfaces. The ObjectOutputStream and ObjectInputStream classesprovide implementation to write and read binary representationof objects as well as Java primitive values to any stream that is asubclass of the OutputStream and InputStream respectively. The class of the object must implement the Serializableinterface if we want the object to be serialized. If this object is acompound object, then all its constituent objects must also beserializable.

×