SlideShare una empresa de Scribd logo
1 de 71
A Preview
Primitive Data Types in Java
Primitive data types
Boolean type Numeric types
Integral types Floating-point types
Character type Integer types
intboolean shortbytechar long float double
DataTypes
Name Size Range
boolean 1 true or false
char 16 0 to 65535
byte 8 -128 to 127
short 16 -32768 to 32767
int 32 -2147483648 to 2147483647
long 64 -9223372036854775808 to 9223372036854775807
float 32 +/- 1.4023x10-45 to 3.4028x10+38
double 64 +/- 4.9406x10-324 to 1.7977x10308
Variables
 A variable stores a value of a particular type. A variable has
a name, a type, and a value associated with it.
 Variables that store reference values of objects are called
reference variables.
 If no initialization is provided for static or instance
variables either in the declaration or in an initializer block,
it is initialized with the default value of its type when the
class is loaded or instantiated respectively.
 Local variables declared in methods, constructors, and
blocks are not initialized when they are created at method
invocation or execution of a method.
 Instance variables, created for each object of the class, exist
as 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 as
long as the class is available at runtime.
Class Declarations
 Class Declaration Syntax
 <class modifiers> class <class name><formal type parameter
list>
 <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>
 }
Method Declarations
 <method modifiers> <formal type parameter list>
<return type> <method name>
 (<formal parameter list>) <throws clause> // Method
header
 { // Method body
 <local variable declarations>
 <nested local class declarations>
 <statements>
 }
Methods Overloading
 Each method has a signature, which comprises the
name of the method, and the types and order of the
parameters in the formal parameter list.
 Several method implementations may have the same
name, but different method signatures, which is called
method overloading.
 The overloaded methods have the same name, but
their parameter lists must be different.
Method Overriding
 A subclass can override instance methods inherited from a
superclass 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 the
return type of base class method, then such methods are
called covariant return.
 An instance method in a subclass cannot override a static
method in the superclass.
 A subclass cannot override fields and static methods of the
superclass, but it can hide them.
 Method overriding always requires the same method
signature (name and parameter types) and same or
covariant return types.
Constructor Declarations
 <accessibility modifier> <class name> (<formal
parameter list>)
 <throws clause> // Constructor header
 { // Constructor body
 <local variable declarations>
 <nested local class declarations>
 <statements>
 }
Constructors
 A default constructor is a constructor without any
parameters.
 If a class does not specify any constructors, then an implicit
default constructor is generated for the class by the
compiler.
 <class name>() { super(); }
 All instance variables in the object are set to default value
of their type, barring those that are initialized by an
initialization expression in their declaration.
 If a class defines any explicit constructors, it can no longer
rely on the implicit default constructor to set the state of its
objects.
 Constructors can be overloaded as methods with their
differentiating signatures being their parameter lists.
Parameter Passing
 All parameters in Java are passed by value, that is, an actual
parameter is evaluated and its value is assigned to the
corresponding formal parameter.
 In case of primitive data types, the data value of the actual
parameter is passed.
 If the actual parameter is a reference to an object, the
reference value is passed and not the object itself.
 If the actual parameter is an array element of a primitive
data type, its data value is passed, and if the array element
is a reference to an object, then its reference value is
passed.
 The order of evaluation in the actual parameter list is
always from left to right.
Parameter Passing continued
 An actual parameter is an expression that is evaluated first and
the resulting value is then assigned to the corresponding formal
parameter at method invocation
 The primitive formal parameters are local to the method, hence
any changes made to the primitive formal parameters will not be
reflected in actual parameter after the call completes.
 In case of primitive values, type conversions between actual
parameters and formal parameters such as widening primitive
conversion and unboxing conversion are allowed.
 In case of reference values, the actual parameter and the formal
parameter are aliases to the object denoted by the reference value
during method invocation and changes made to such object via
the formal parameter will be apparent after the call returns.
Interfaces
 An interface is not a class but a set of requirements for
classes that want to conform to the interface.
 All methods of an interface are automatically public.
 However, when implementing the interface in a class, the
method must be declared as public.
 An interface variable must refer to an object of a class that
implements the interface.
 The instanceof is used to check whether an object is of a
specific class or implements an interface.
 Fields in an interface are always public static final.
 A tagging interface has no methods; its only purpose is to
allow the use of instanceof in a type inquiry.
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>
 }
Interfaces and Callbacks
 The callback pattern needs to specify the action that
should occur whenever a particular event occurs.
 In java an object of some class e.g. ActionListener is
passed to the event generating class e.g. Timer which
then calls one of the methods e.g. ActionPerformed on
that object.
 Example:
 ActionListener listener = new TimePrinter();
 Timer t = new Timer(10000, listener);
Proxies
 Used to construct an object of a class that implements one or more interfaces
whose 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 methods
defined in the Object class.
 It cannot define new code for these methods at runtime but needs an
invocation handler.
 An invocation handler is an object of any class that implements the
InvocationHandler interface with a single method invoke(Object pxy, Method
method, Object[] ags).
 Whenever a method is called on the proxy object, the invoke method of the
invocation handler gets called, with Method object and parameters of original
call. 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 is
defined in the Proxy superclass.
 The names of proxy classes are not defined and proxy classes are always public
and final.
 There is only one proxy class for a particular class loader and ordered set of
interfaces. To test whether a particular Class object is a proxy class call method
isProxyClass.
The main() method
 The java command executes a method called main in
the class specified on the command line.
 The main() method must have public accessibility so
that the interpreter can call this method.
 It is a static method belonging to the class, so that no
object of the class is required to start the execution.
 It does not return any value, and is declared void.
Class Scope for Members
 Class scope concerns accessing members (including
inherited ones) from code within a class.
 Static code can only access other static members by
their simple names.
 Static members are always accessible in a non-static
context.
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 variable
declarations in such blocks.
 A variable declared in a block is in scope inside the block in which it is
declared, but it is not accessible outside of this block.
 It is not possible to redeclare a variable if a local variable of the same
name is already declared in the current scope.
 Local variables of a method include the formal parameters of the
method and variables declared in the method body.
 The local variables in a method are created each time the method is
invoked, and are distinct from local variables in other invocations of
the same method that might be executing.
 A local variable already declared in an enclosing block cannot be
redeclared in the nested block but can be declared if the blocks are
disjoint.
Some Modifiers for Members
 synchronized Methods: Only one thread at a time can execute
such methods of the object and their execution is mutually
exclusive among all threads.
 native Methods: These are the methods whose implementation
is not defined in Java but in another programming language such
as C, C++ etc.
 Serialization transforms objects into an output format that is
conducive for storing objects and can later be retrieved in the
same state as when they were serialized.
 transient Fields: The value of a transient field in an object
should not be saved when the objects of the class are written to
persistent storage using serialization.
 volatile Fields: During execution, compiled code might cache
the values of fields for efficiency reasons. The volatile modifier
informs the compiler that it should not attempt to perform
optimizations on the field, which could cause unpredictable
results when the field is accessed by multiple threads.
Type Conversions
 Widening primitive conversions are usually done implicitly,
whereas narrowing primitive conversions usually require a cast.
 Narrowing reference conversions, which require a runtime check
and can throw a ClassCastException if the conversion is not
legal.
 A boxing conversion converts the value of a primitive type
to a corresponding value of its wrapper type.
 A unboxing conversion converts the value of a wrapper type to a
value of its corresponding primitive type.
 String conversions allow a value of any other type to be converted
to 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 be
a subtype of the <destination type>. It always returns false if the
left-hand operand is null. If the instanceof operator returns true,
the corresponding type cast expression will always be valid.
Initialization
 When a class is loaded, it is initialized, i.e., its static fields are
initialized with the values of the initializer expressions.
 After the class is initialized it can be instantiated, an instance
initializer expression can always refer to any static member of a
class.
 Static initializer blocks can be defined in a class (not in
methods) and used for initializing static fields. They are
executed only once, when the class is initialized.
 Instance initializer blocks are used to initialize fields during
object creation and serve same purpose as constructors.
 A typical usage of an instance initializer block is in anonymous
classes which cannot declare constructors.
 Instance initializers are executed in the order they are specified
in the class declaration
 The execution of an instance initializer block can result in an
uncaught checked exception, provided the exception is declared
in the throws clause of every constructor in the class.
Initialization continued
 Class initialization takes place before any instance of
the class can be created or a static method of the class
can be invoked.
 A superclass is initialized before its subclasses are
initialized.
 Initializing a class involves initialization of the static
fields by executing their static initializer expressions
and any static initializer blocks.
 Initialization of an interface only involves execution of
any static initializer expressions for the static fields
declared in the interface
Packages
 Java allows you to group classes in a collection called a package.
 All standard Java packages are inside the java and javax package
hierarchies.
 It guarantees the uniqueness of class names.
 A class can use all classes from its own package and all public
classes from other packages.
 To access the class in a package add the full package name in
front of every class name or import a specific class or the whole
package.
 The * notation imports only a single package.
 Import statement is enhanced to permit the importing of static
methods and fields, along with the classes.
 Identifiers in a class can shadow static members that are
imported.
Break statement
 The break statement is used to exit a switch block or to
break out of a loop e.g. while, for etc.
 A labeled break statement allows to break out of
multiple nested loops.
 E.g: break label;
Arrays
 An array is a data structure that stores a collection of values of
the same type.
 Each individual value is accessed through an integer index.
 An array variable is declared by specifying the array type
followed 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 to
be combined, to create and initialize an array object without any
name:
new <element type>[] { <array initialize list> }
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 of
one array into a new array.
 The sort(type[] a) method sorts the array using a tuned
QuickSort algorithm.
 The binarySearch(type[] a, type v) method uses the
binary search algorithm to search for the value v.
 The fill(type[] a, type v) method sets all elements of the
array to v.
 Multidimensional arrays defined as,
double[][] balances = new double[NYEARS][NRATES];
Exception Handling
 An exception object is always an instance of a class derived from
Throwable.
 All exceptions descend from Throwable, and then splits into two
hierarchies: Error and Exception.
 The Error hierarchy describes internal errors and resource
exhaustion 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 class
RuntimeException an unchecked exception. All other
exceptions are called checked exceptions.
Exception Handling continued
 A method must declare all the checked exceptions that it might
throw 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 the
subclass method cannot be more general than those of the
superclass method.
 When a method in a class declares that it throws an exception
that is an instance of a particular class, then it may throw an
exception of that class or of any of its subclasses.
 A method without a throws specifier may not throw any checked
exception 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.
Catching Exceptions
 If an exception occurs that is not caught anywhere, it goes to java
default exception handler which terminates the program and
prints 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 the
class specified in catch clause, then the program skips the
remainder of the code in the try block and executes the handler
code 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 must
either handle it or pass it on.
 No more throws specifiers can be added to a subclass method
than those which are present in the superclass method.
Catching Exceptions
 Multiple exception types can be caught in a try block
and each type handled differently.
 An exception can be thrown in a catch clause.
 To retrieve the original exception when the exception
is caught we use the following statement before throw:
 Throwable e = se.getCause();
 The wrapping technique is also useful if a checked
exception occurs in a method that is not allowed to
throw a checked exception. The checked exception is
caught and wrap it into a runtime exception.
Finally
 When there is an exception, it stops processing the
remaining code in the method and exits, without
cleaning some acquired local resource if any.
 The finally block is executed irrespective of the
occurrence of an exception.
 The finally clause could exist without a catch clause.
 A finally clause can yield unexpected results when it
contains return statements.
Stack Trace
 A stack trace is a listing of all pending method calls at a
particular point in the execution of a program.
 The getStackTrace() method gets an array of
StackTraceElement objects that can be analyzed in the
program.
 The StackTraceElement class has methods to obtain the file
name and line number, as well as the class and method
name, of the executing line of code. The toString method
yields a formatted string containing all of this information.
 The static Thread.getAllStackTraces method yields the
stack traces of all threads.
Tips on Exception Handling
 Exception handling is not supposed to replace a simple
test 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 ignore
exceptions.
 When you detect an error throw exceptions instead of
returning some dummy values.
 Propagating exceptions is better sometimes rather than
catching them.
Assertions
 They are used to document and validate assumptions made
about the state of the program at designated locations in
the code.
 The assertion contains a boolean expression which is
expected to be true and when it is false, the JVM throws a
special 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> is
evaluated. If its value is true, execution continues normally
afterwards or if it is false, an AssertionError is thrown and
propagated.
Assertions continued
 The java.lang.AssertionError class is a subclass of java.lang.Error
and are unchecked.
 They can be explicitly caught and handled using the try-catch
construct 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 to
the named package and its subpackages.
 -ea:... and -da:...: Applies to the unnamed package in the
current working directory.
 -ea:<class name> and -da:<class name>: Applies to named
class.
 -enablesystemassertions or –esa: Enable assertions in all
system classes.
 -disablesystemassertions or –dsa: Disable assertions in all
system classes.
Inner Classes
 An inner class is a class that is defined inside another
class.
 Inner class methods can access the data from the scope
in which they are defined including the data that
would otherwise be private.
 Inner classes can be hidden from other classes in the
same package.
 Anonymous inner classes are handy to define callbacks
without writing a lot of code.
Inner Classes continued
 An inner class method gets to access both its own data fields and
those of the outer object creating it.
 An object of an inner class always gets an implicit reference to
the object that created it. Such reference is invisible in the
definition of the inner class.
 The compiler modifies all inner class constructors, by adding a
parameter for the outer class reference.
 The syntax for the outer class reference is, OuterClass.this.
 The inner object constructor has the syntax outerObject.new
InnerClass(construction parameters).
 It is also possible to set the outer class reference to another object
of outer class by explicitly naming it.
 An inner class is referred as OuterClass.InnerClass when it
occurs outside the scope of the outer class.
 Inner classes are translated by the compiler, and not the virtual
machine.
Static member classes, enum types
and interfaces
 A static class can be instantiated like any ordinary top-level
class, using its full name.
 No enclosing instance is required to instantiate a static
member class.
 A static member class must be declared explicitly with
keyword static, as a static member of an enclosing type
 Nested interfaces and enum types are considered implicitly
static.
 Static member classes, enum types and interfaces can only
be declared in top-level type declarations, or within other
nested static members.
 Static member classes & interfaces can directly access other
members that are declared static within the same class.
Non Static Member Classes
 Non-static member classes are defined as instance members of other
classes.
 An instance of a non-static member class always has an enclosing
instance 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 private
members.
 Non-static member class being a class member can have any
accessibility i.e. public, private etc.
 A special form of the new operator is used to instantiate a non-static
member class:
<enclosing object reference>.new <non-static member class constructor
call>
 An implicit reference to the enclosing object is always available in every
method and constructor of a non-static member class.
 The expression <enclosing class name>.this evaluates to a reference
that denotes the enclosing object (of the class <enclosing class name>)
of the current instance of a non-static member class.
Local Inner Classes
 Local classes are defined in the context of a block as in a method
body 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 are
declared.
 Local inner classes are completely hidden from the outside
world.
 Local inner classes can access the fields of their outer classes,
and also its local variables. The local variables of outer class must
be declared final to access them.
 Local classes cannot have static members as they cannot provide
class-specific services.
 A local class can be instantiated in the block in which it is
defined.
Anonymous Inner Classes
 Anonymous classes combine the process of definition and instantiation
into a single step using the new operator.
 An anonymous inner class is used to create only a single object of the
class, without giving the class a name.
 Instantiated by extending a class or implementing an interface:
 new <superclass name> (<optional argument list>)
{ <member declarations> } OR
new <interface name>() { <member declarations> }
 An anonymous inner class cannot have constructors because the class
has no name.
 Only non-static members and final static fields can be declared in the
class 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.
Static Inner Class
 When the inner class simply hides one class inside
another, but doesn’t have a reference to the outer class
object, 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 to
the outer class object that generated it.
 Inner classes that are declared inside an interface are
automatically static and public.
Object class
 The Object class is the ultimate ancestor and every class in Java extends
Object.
 In java all except the primitive types (numbers, characters, and boolean
values) are not objects.
 All array types including the arrays of objects and primitive types, are
class types extending Object class.
 The equals method in the Object class tests whether one object is
considered equal to another.
 A hash code is an integer that is derived from an object and is returned
using the hashcode() method.
 If equals method is redefined, redefine the hashCode() method must
also be redefined.
 The toString() method returns a string representing the value of the
object. It is automatically invoked by java when an object is
concatenated with a string by the “+” operator.
 The clone() method creates a clone of the object. The Java runtime
system allocates memory for the new instance and copies the memory
allocated for the current object.
Object Cloning
 The clone method is used to make a copy of an object
to be a new object which is identical to original but
whose 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. it
doesn’t clone objects that are referenced inside other
objects which works fine if subobjects are immutable.
 When the subobjects are mutable, the clone method
must be redefined to make a deep copy that clones the
subobjects too.
Wrappers Classes
 All primitive types have Wrapper class counterparts.
 All wrapper classes are immutable (cannot change the
wrapped value after been constructed) and final.
 The Void class is considered a wrapper class, but it does
not wrap any primitive value and is not instantiable.
 Except the Character class, all other wrapper classes have
two public one-argument constructors: one taking a
primitive value and the other taking a String.
 Each wrapper class (except Character) defines the static
method valueOf(String str) that returns the wrapper
object corresponding to the primitive value represented by
the String object passed as argument.
Wrapper Classes continued
 The integer wrapper classes define an overloaded static
valueOf() method taking an argument the base or radix.
 Each wrapper class overrides the toString() method from the
Object class.
 Each wrapper class defines a typeValue() method which returns
the 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 the
primitive value in the current wrapper Type object is less than,
equal to, or greater than value in the wrapper Type object
denoted by the argument.
Numeric Wrapper Classes
 The numeric wrapper classes Byte, Short, Integer, Long,
Float, and Double are all subclasses of the abstract class
Number.
 Each numeric wrapper class defines a set of typeValue()
methods for converting the primitive value in the wrapper
object to a value of any numeric primitive type. They are:
 byte byteValue()
 short shortValue()
 int intValue()
 long longValue()
 float floatValue()
 double doubleValue()
Numeric Wrapper Classes
 Each numeric wrapper class defines a static method
parseType(String str), which returns the primitive
numeric value represented by the String object passed
as argument else throws a NumberFormatException if
the String parameter is not a valid argument.
 The wrapper classes Integer and Long provide static
methods for converting integers to string
representation in decimal, binary, octal, and
hexadecimal notation.
Autoboxing
 Array list of integers is represented using the Integer
wrapper 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 with
arithmetic expressions.
 The boxing and unboxing is a courtesy of the compiler, not
the virtual machine.
Java.lang.String
 The String class implements immutable character
strings, which are read-only once the string has been
created and initialized. Hence its threadsafe.
 A java.lang.String class is final which implies no
class can extend it.
 Strings are said to be interned, meaning that they share
a unique String object if they have the same content.
 String objects can be used with the += and + operators
for concatenation.
 String, StringBuilder and StringBuffer, all implement
CharSequence interface to facilitate interoperability.
It defines charAt(int index), length() and toString()
methods.
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 into
the 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 case
considerations.
 toUpperCase(): Converts all of the characters in this String to upper case using the rules of the default
locale. 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 the
specified 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 the
specified 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 of
oldChar 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 expression
pattern.
StringBuilder
 The StringBuilder class implements dynamic character strings and is
mutable.
 The capacity of the string builder can also be changed dynamically.
 It efficiently concatenates strings, without constructing a new String
object every time and wasting memory.
 StringBuilder is used to store character strings that are updated
frequently and automatically expands as needed.
 Appending, inserting, and deleting characters automatically results in
adjustment of the string builder’s capacity, if necessary.
 StringBuilder class does not override the equals() method and the
hashcode() method from the Object class.
 It is identical in all respects to StringBuffer except that it is not
synchronized, hence multiple threads accessing it at the same time
would create problems.
 In single-threaded programs avoiding the overhead of synchronization
makes the StringBuilder slightly faster.
 The compiler uses string builders to implement the string
concatenation.
StringBuffer
 It is a mutable class unlike the String class in terms of
capacity and character string.
 The StringBuffer class is a thread-safe version of the
StringBuilder class.
 StringBuffer can be changed dynamically as StringBuilder.
 String buffers are preferred when heavy modification of
character 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 the
contents of string buffers should be converted to String
objects for string comparison.
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 currently
represented by the string buffer, as indicated by the index argument, is
returned.
 setCharAt(int index, char ch): The character at the specified index of this
string 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 argument
into this string buffer.
delete(int start, int end): Removes the characters in a substring of this
StringBuffer
 replace(int start, int end, String str): Replaces the characters in a substring of
this StringBuffer with characters in the specified String.
 reverse(): The character sequence contained in this string buffer is replaced by
the 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.
Enumerated Types
 An enumerated type has a finite number of named
values, 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 of
the values listed in the type declaration or the special
value null that indicates that the variable is not set to
any value at all.
Enumeration Classes
 Similar to enumerated types there are enumerated classes.
 public enum Size { SMALL, MEDIUM, LARGE };
 Constructors, methods, and fields can be added to an
enumerated type.
 The constructors are only invoked when the enumerated
constants 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 returns
an array of all values of the enumeration.
 The ordinal method yields the position of an enumerated
constant in the enum declaration, counting from zero.
File Handling
 The java.io package provides an extensive library of
classes for I/O.
 Java provides streams as a general mechanism for
dealing with data I/O.
 Streams implement sequential access of data.
 There are two kinds of streams: byte streams and
character streams.
 An input stream is an object that an application can
use to read a sequence of data, and an output stream
is an object that an application can use to write a
sequence of data.
File Class
 A File object represents the pathname of a file or
directory in the host file system.
 A File object can also be used to query the file system
for information about a file or directory.
 The File class can be used to create, rename or delete
files and directories.
 A File object created using a pathname can be used to
check if File or Directory actually exists in the system.
ByteStreams
 Abstract classes InputStream and OutputStream are base
classes for handling reading and writing of bytes.
 Subclasses override their methods to customize read/write.
 The InputStream class:
int read() throws IOException
int read(byte[] b) throws IOException
int read(byte[] b, int off, int len) throws IOException
 The OutputStream class:
void write(int b) throws IOException
void write(byte[] b) throws IOException
void write(byte[] b, int off, int len) throws IOException
InputStream
ByteArrayInputStream FileInputStream
FilterInputStream
ObjectInputStream PipedInputStream
SequenceInputStrea
m
BufferedInputStream DataInputStream PushbackInputStream
ZipInputStream ZipInputStream is defined in: java.util.zip
InputStream Classes
OutputStream
ByteArrayOutputStream FileOutputStream
FilterOutputStrea
m
ObjectOutputStrea
m
PipedOutputStream
BufferedOutputStrea
m
DataOutputStream PrintStream
ZipOutputStream ZipOutputStream is defined in: java.util.zip
OutputStream Classes
Some InputStream Classes
 FileInputStream: Data is read as bytes from a file. The file
acting 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 input
stream.
 DataInputStream: A filter that allows the binary
representation of Java primitive values to be read from an
underlying input stream. The underlying input stream
must be specified.
 ObjectInputStream: Allows binary representations of
Java objects and Java primitive values to be read from a
specified input stream.
Some OutputStream Classes
 FileOutputStream: Data is written as bytes to a file. The
file acting as the output stream can be specified by a File
object, a FileDescriptor or a String file name.
 FilterOutputStream: Superclass of all output stream
filters. An output filter must be chained to an underlying
output stream.
 DataOutputStream: A filter that allows the binary
representation of Java primitive values to be written to an
underlying output stream. The underlying output stream
must be specified.
 ObjectOutputStream: Allows the binary representation
of Java objects and Java primitive values to be written to a
specified underlying output stream.
Filter Streams
 A filter is a high-level stream that provides additional
functionality to an underlying stream to which it is
chained.
 The data from the underlying stream is manipulated in
some way by the filter.
 The FilterInputStream and FilterOutputStream classes,
together with their subclasses, define input and output
filter streams.
 The subclasses BufferedInputStream and
BufferedOutputStream implement filters that buffer
input from and output to the underlying stream.
 The subclasses DataInputStream and
DataOutputStream implement filters that allow binary
representation of Java primitive values to be read and
written, respectively, to and from an underlying stream
DataInput and DataOutput
 The java.io package contains the two interfaces DataInput
and DataOutput, that streams implement to allow reading
and writing of binary representations of Java primitive
values (boolean, char, byte, short, int, long, float, double).
 The methods for reading and writing binary
representations of Java primitive values are named readX
and writeX respectively, where X is any Java primitive data
type.
 To write binary values create a FileOutputStream, then
chain it to created DataOutputStream and use writeX()
methods to write respective data types.
Character Streams: Readers and Writers
 The abstract classes Reader and Writer are the roots of
the inheritance hierarchies for streams that read and
write Unicode characters using a specific character
encoding.
 A reader is an input character stream that reads a
sequence of Unicode characters, and a writer is an
output character stream that writes a sequence of
Unicode characters.
Some Reader Classes
 BufferedReader: A reader that buffers the characters read
from an underlying reader. The underlying reader must be
specified and an optional buffer size can be given.
 InputStreamReader: Characters are read from a byte
input stream which must be specified. The default
character encoding is used if no character encoding is
explicitly specified.
 FileReader: Reads characters from a file, using the default
character encoding. The file can be specified by a File
object, a FileDescriptor, or a String file name. It
automatically creates a FileInputStream that is associated
with the file.
Some Writer Classes
 BufferedWriter: A writer that buffers the characters before
writing them to an underlying writer. The underlying writer
must be specified, and an optional buffer size can be specified.
 OutputStreamWriter: Characters are written to a byte output
stream which must be specified. The default character encoding
is used if no explicit character encoding is specified.
 FileWriter: Writes characters to a file, using the default
character encoding. The file can be specified by a File object, a
FileDescriptor, or a String file name. It automatically creates a
FileOutputStream that is associated with the file.
 PrintWriter: A filter that allows text representation of Java
objects and Java primitive values to be written to an underlying
output stream or writer. The underlying output stream or writer
must be specified.
Console Class
 A console is a unique character-based device associated
with 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 console
console.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 any
buffered output to be written immediately.
Object Serialization
 It allows an object to be transformed into a sequence of bytes
that can later be re-created (deserialized) into the original object.
 The object retains its state after deserialization, to one it had
when it was serialized.
 The ObjectInput and ObjectOutput interfaces, allow such
reading and writing of objects from and to streams and extend
the DataInput and DataOutput interfaces.
 The ObjectOutputStream and ObjectInputStream classes
provide implementation to write and read binary representation
of objects as well as Java primitive values to any stream that is a
subclass of the OutputStream and InputStream respectively.
 The class of the object must implement the Serializable
interface if we want the object to be serialized. If this object is a
compound object, then all its constituent objects must also be
serializable.

Más contenido relacionado

La actualidad más candente

Java Basics Presentation
Java Basics PresentationJava Basics Presentation
Java Basics PresentationOmid Sohrabi
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Learn Java language fundamentals with Unit nexus
Learn Java language fundamentals with Unit nexusLearn Java language fundamentals with Unit nexus
Learn Java language fundamentals with Unit nexusUnit Nexus Pvt. Ltd.
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingWei Jen Lu
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078Aravind NC
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesRavi_Kant_Sahu
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVATech_MX
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic ConceptsVicter Paul
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1bharath yelugula
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 

La actualidad más candente (20)

Java Basics Presentation
Java Basics PresentationJava Basics Presentation
Java Basics Presentation
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Learn Java language fundamentals with Unit nexus
Learn Java language fundamentals with Unit nexusLearn Java language fundamentals with Unit nexus
Learn Java language fundamentals with Unit nexus
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic Concepts
 
C#
C#C#
C#
 
Abap Objects for BW
Abap Objects for BWAbap Objects for BW
Abap Objects for BW
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 

Similar a Java Basics (20)

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Java defining classes
Java defining classes Java defining classes
Java defining classes
 
C# interview
C# interviewC# interview
C# interview
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
VB.net
VB.netVB.net
VB.net
 
LISP: Object Sytstem Lisp
LISP: Object Sytstem LispLISP: Object Sytstem Lisp
LISP: Object Sytstem Lisp
 
LISP:Object System Lisp
LISP:Object System LispLISP:Object System Lisp
LISP:Object System Lisp
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Hemajava
HemajavaHemajava
Hemajava
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
4. java intro class
4. java intro class4. java intro class
4. java intro class
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java
JavaJava
Java
 
Java basics
Java basicsJava basics
Java basics
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 

Más de Emprovise

Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Emprovise
 
Leadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessLeadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessEmprovise
 
Secure socket layer
Secure socket layerSecure socket layer
Secure socket layerEmprovise
 
Effective java
Effective javaEffective java
Effective javaEmprovise
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance FeaturesEmprovise
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEmprovise
 
RESTful WebServices
RESTful WebServicesRESTful WebServices
RESTful WebServicesEmprovise
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE PatternsEmprovise
 
Spring Web Services
Spring Web ServicesSpring Web Services
Spring Web ServicesEmprovise
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web WebflowEmprovise
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web ViewsEmprovise
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise SpringEmprovise
 
Spring Basics
Spring BasicsSpring Basics
Spring BasicsEmprovise
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 AdvanceEmprovise
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 FrameworkEmprovise
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 

Más de Emprovise (20)

Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
 
Leadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessLeadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/Business
 
Secure socket layer
Secure socket layerSecure socket layer
Secure socket layer
 
Effective java
Effective javaEffective java
Effective java
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance Features
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business Logic
 
EJB3 Basics
EJB3 BasicsEJB3 Basics
EJB3 Basics
 
RESTful WebServices
RESTful WebServicesRESTful WebServices
RESTful WebServices
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE Patterns
 
Spring JMS
Spring JMSSpring JMS
Spring JMS
 
JMS
JMSJMS
JMS
 
Spring Web Services
Spring Web ServicesSpring Web Services
Spring Web Services
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web Webflow
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Último

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

Java Basics

  • 2. Primitive Data Types in Java Primitive data types Boolean type Numeric types Integral types Floating-point types Character type Integer types intboolean shortbytechar long float double
  • 3. DataTypes Name Size Range boolean 1 true or false char 16 0 to 65535 byte 8 -128 to 127 short 16 -32768 to 32767 int 32 -2147483648 to 2147483647 long 64 -9223372036854775808 to 9223372036854775807 float 32 +/- 1.4023x10-45 to 3.4028x10+38 double 64 +/- 4.9406x10-324 to 1.7977x10308
  • 4. Variables  A variable stores a value of a particular type. A variable has a name, a type, and a value associated with it.  Variables that store reference values of objects are called reference variables.  If no initialization is provided for static or instance variables either in the declaration or in an initializer block, it is initialized with the default value of its type when the class is loaded or instantiated respectively.  Local variables declared in methods, constructors, and blocks are not initialized when they are created at method invocation or execution of a method.  Instance variables, created for each object of the class, exist as 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 as long as the class is available at runtime.
  • 5. Class Declarations  Class Declaration Syntax  <class modifiers> class <class name><formal type parameter list>  <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. Method Declarations  <method modifiers> <formal type parameter list> <return type> <method name>  (<formal parameter list>) <throws clause> // Method header  { // Method body  <local variable declarations>  <nested local class declarations>  <statements>  }
  • 7. Methods Overloading  Each method has a signature, which comprises the name of the method, and the types and order of the parameters in the formal parameter list.  Several method implementations may have the same name, but different method signatures, which is called method overloading.  The overloaded methods have the same name, but their parameter lists must be different.
  • 8. Method Overriding  A subclass can override instance methods inherited from a superclass 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 the return type of base class method, then such methods are called covariant return.  An instance method in a subclass cannot override a static method in the superclass.  A subclass cannot override fields and static methods of the superclass, but it can hide them.  Method overriding always requires the same method signature (name and parameter types) and same or covariant return types.
  • 9. Constructor Declarations  <accessibility modifier> <class name> (<formal parameter list>)  <throws clause> // Constructor header  { // Constructor body  <local variable declarations>  <nested local class declarations>  <statements>  }
  • 10. Constructors  A default constructor is a constructor without any parameters.  If a class does not specify any constructors, then an implicit default constructor is generated for the class by the compiler.  <class name>() { super(); }  All instance variables in the object are set to default value of their type, barring those that are initialized by an initialization expression in their declaration.  If a class defines any explicit constructors, it can no longer rely on the implicit default constructor to set the state of its objects.  Constructors can be overloaded as methods with their differentiating signatures being their parameter lists.
  • 11. Parameter Passing  All parameters in Java are passed by value, that is, an actual parameter is evaluated and its value is assigned to the corresponding formal parameter.  In case of primitive data types, the data value of the actual parameter is passed.  If the actual parameter is a reference to an object, the reference value is passed and not the object itself.  If the actual parameter is an array element of a primitive data type, its data value is passed, and if the array element is a reference to an object, then its reference value is passed.  The order of evaluation in the actual parameter list is always from left to right.
  • 12. Parameter Passing continued  An actual parameter is an expression that is evaluated first and the resulting value is then assigned to the corresponding formal parameter at method invocation  The primitive formal parameters are local to the method, hence any changes made to the primitive formal parameters will not be reflected in actual parameter after the call completes.  In case of primitive values, type conversions between actual parameters and formal parameters such as widening primitive conversion and unboxing conversion are allowed.  In case of reference values, the actual parameter and the formal parameter are aliases to the object denoted by the reference value during method invocation and changes made to such object via the formal parameter will be apparent after the call returns.
  • 13. Interfaces  An interface is not a class but a set of requirements for classes that want to conform to the interface.  All methods of an interface are automatically public.  However, when implementing the interface in a class, the method must be declared as public.  An interface variable must refer to an object of a class that implements the interface.  The instanceof is used to check whether an object is of a specific class or implements an interface.  Fields in an interface are always public static final.  A tagging interface has no methods; its only purpose is to allow the use of instanceof in a type inquiry.
  • 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. Interfaces and Callbacks  The callback pattern needs to specify the action that should occur whenever a particular event occurs.  In java an object of some class e.g. ActionListener is passed to the event generating class e.g. Timer which then calls one of the methods e.g. ActionPerformed on that object.  Example:  ActionListener listener = new TimePrinter();  Timer t = new Timer(10000, listener);
  • 16. Proxies  Used to construct an object of a class that implements one or more interfaces whose 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 methods defined in the Object class.  It cannot define new code for these methods at runtime but needs an invocation handler.  An invocation handler is an object of any class that implements the InvocationHandler interface with a single method invoke(Object pxy, Method method, Object[] ags).  Whenever a method is called on the proxy object, the invoke method of the invocation handler gets called, with Method object and parameters of original call. 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 is defined in the Proxy superclass.  The names of proxy classes are not defined and proxy classes are always public and final.  There is only one proxy class for a particular class loader and ordered set of interfaces. To test whether a particular Class object is a proxy class call method isProxyClass.
  • 17. The main() method  The java command executes a method called main in the class specified on the command line.  The main() method must have public accessibility so that the interpreter can call this method.  It is a static method belonging to the class, so that no object of the class is required to start the execution.  It does not return any value, and is declared void.
  • 18. Class Scope for Members  Class scope concerns accessing members (including inherited ones) from code within a class.  Static code can only access other static members by their simple names.  Static members are always accessible in a non-static context.
  • 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 variable declarations in such blocks.  A variable declared in a block is in scope inside the block in which it is declared, but it is not accessible outside of this block.  It is not possible to redeclare a variable if a local variable of the same name is already declared in the current scope.  Local variables of a method include the formal parameters of the method and variables declared in the method body.  The local variables in a method are created each time the method is invoked, and are distinct from local variables in other invocations of the same method that might be executing.  A local variable already declared in an enclosing block cannot be redeclared in the nested block but can be declared if the blocks are disjoint.
  • 20. Some Modifiers for Members  synchronized Methods: Only one thread at a time can execute such methods of the object and their execution is mutually exclusive among all threads.  native Methods: These are the methods whose implementation is not defined in Java but in another programming language such as C, C++ etc.  Serialization transforms objects into an output format that is conducive for storing objects and can later be retrieved in the same state as when they were serialized.  transient Fields: The value of a transient field in an object should not be saved when the objects of the class are written to persistent storage using serialization.  volatile Fields: During execution, compiled code might cache the values of fields for efficiency reasons. The volatile modifier informs the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads.
  • 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 check and can throw a ClassCastException if the conversion is not legal.  A boxing conversion converts the value of a primitive type to a corresponding value of its wrapper type.  A unboxing conversion converts the value of a wrapper type to a value of its corresponding primitive type.  String conversions allow a value of any other type to be converted to 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 be a subtype of the <destination type>. It always returns false if the left-hand operand is null. If the instanceof operator returns true, the corresponding type cast expression will always be valid.
  • 22. Initialization  When a class is loaded, it is initialized, i.e., its static fields are initialized with the values of the initializer expressions.  After the class is initialized it can be instantiated, an instance initializer expression can always refer to any static member of a class.  Static initializer blocks can be defined in a class (not in methods) and used for initializing static fields. They are executed only once, when the class is initialized.  Instance initializer blocks are used to initialize fields during object creation and serve same purpose as constructors.  A typical usage of an instance initializer block is in anonymous classes which cannot declare constructors.  Instance initializers are executed in the order they are specified in the class declaration  The execution of an instance initializer block can result in an uncaught checked exception, provided the exception is declared in the throws clause of every constructor in the class.
  • 23. Initialization continued  Class initialization takes place before any instance of the class can be created or a static method of the class can be invoked.  A superclass is initialized before its subclasses are initialized.  Initializing a class involves initialization of the static fields by executing their static initializer expressions and any static initializer blocks.  Initialization of an interface only involves execution of any static initializer expressions for the static fields declared in the interface
  • 24. Packages  Java allows you to group classes in a collection called a package.  All standard Java packages are inside the java and javax package hierarchies.  It guarantees the uniqueness of class names.  A class can use all classes from its own package and all public classes from other packages.  To access the class in a package add the full package name in front of every class name or import a specific class or the whole package.  The * notation imports only a single package.  Import statement is enhanced to permit the importing of static methods and fields, along with the classes.  Identifiers in a class can shadow static members that are imported.
  • 25. Break statement  The break statement is used to exit a switch block or to break out of a loop e.g. while, for etc.  A labeled break statement allows to break out of multiple nested loops.  E.g: break label;
  • 26. Arrays  An array is a data structure that stores a collection of values of the same type.  Each individual value is accessed through an integer index.  An array variable is declared by specifying the array type followed 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 to be combined, to create and initialize an array object without any name: new <element type>[] { <array initialize list> }
  • 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 of one array into a new array.  The sort(type[] a) method sorts the array using a tuned QuickSort algorithm.  The binarySearch(type[] a, type v) method uses the binary search algorithm to search for the value v.  The fill(type[] a, type v) method sets all elements of the array to v.  Multidimensional arrays defined as, double[][] balances = new double[NYEARS][NRATES];
  • 28. Exception Handling  An exception object is always an instance of a class derived from Throwable.  All exceptions descend from Throwable, and then splits into two hierarchies: Error and Exception.  The Error hierarchy describes internal errors and resource exhaustion 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 class RuntimeException an unchecked exception. All other exceptions are called checked exceptions.
  • 29. Exception Handling continued  A method must declare all the checked exceptions that it might throw 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 the subclass method cannot be more general than those of the superclass method.  When a method in a class declares that it throws an exception that is an instance of a particular class, then it may throw an exception of that class or of any of its subclasses.  A method without a throws specifier may not throw any checked exception 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. Catching Exceptions  If an exception occurs that is not caught anywhere, it goes to java default exception handler which terminates the program and prints 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 the class specified in catch clause, then the program skips the remainder of the code in the try block and executes the handler code 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 must either handle it or pass it on.  No more throws specifiers can be added to a subclass method than those which are present in the superclass method.
  • 31. Catching Exceptions  Multiple exception types can be caught in a try block and each type handled differently.  An exception can be thrown in a catch clause.  To retrieve the original exception when the exception is caught we use the following statement before throw:  Throwable e = se.getCause();  The wrapping technique is also useful if a checked exception occurs in a method that is not allowed to throw a checked exception. The checked exception is caught and wrap it into a runtime exception.
  • 32. Finally  When there is an exception, it stops processing the remaining code in the method and exits, without cleaning some acquired local resource if any.  The finally block is executed irrespective of the occurrence of an exception.  The finally clause could exist without a catch clause.  A finally clause can yield unexpected results when it contains return statements.
  • 33. Stack Trace  A stack trace is a listing of all pending method calls at a particular point in the execution of a program.  The getStackTrace() method gets an array of StackTraceElement objects that can be analyzed in the program.  The StackTraceElement class has methods to obtain the file name and line number, as well as the class and method name, of the executing line of code. The toString method yields a formatted string containing all of this information.  The static Thread.getAllStackTraces method yields the stack traces of all threads.
  • 34. Tips on Exception Handling  Exception handling is not supposed to replace a simple test 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 ignore exceptions.  When you detect an error throw exceptions instead of returning some dummy values.  Propagating exceptions is better sometimes rather than catching them.
  • 35. Assertions  They are used to document and validate assumptions made about the state of the program at designated locations in the code.  The assertion contains a boolean expression which is expected to be true and when it is false, the JVM throws a special 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> is evaluated. If its value is true, execution continues normally afterwards or if it is false, an AssertionError is thrown and propagated.
  • 36. Assertions continued  The java.lang.AssertionError class is a subclass of java.lang.Error and are unchecked.  They can be explicitly caught and handled using the try-catch construct 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 to the named package and its subpackages.  -ea:... and -da:...: Applies to the unnamed package in the current working directory.  -ea:<class name> and -da:<class name>: Applies to named class.  -enablesystemassertions or –esa: Enable assertions in all system classes.  -disablesystemassertions or –dsa: Disable assertions in all system classes.
  • 37. Inner Classes  An inner class is a class that is defined inside another class.  Inner class methods can access the data from the scope in which they are defined including the data that would otherwise be private.  Inner classes can be hidden from other classes in the same package.  Anonymous inner classes are handy to define callbacks without writing a lot of code.
  • 38. Inner Classes continued  An inner class method gets to access both its own data fields and those of the outer object creating it.  An object of an inner class always gets an implicit reference to the object that created it. Such reference is invisible in the definition of the inner class.  The compiler modifies all inner class constructors, by adding a parameter for the outer class reference.  The syntax for the outer class reference is, OuterClass.this.  The inner object constructor has the syntax outerObject.new InnerClass(construction parameters).  It is also possible to set the outer class reference to another object of outer class by explicitly naming it.  An inner class is referred as OuterClass.InnerClass when it occurs outside the scope of the outer class.  Inner classes are translated by the compiler, and not the virtual machine.
  • 39. Static member classes, enum types and interfaces  A static class can be instantiated like any ordinary top-level class, using its full name.  No enclosing instance is required to instantiate a static member class.  A static member class must be declared explicitly with keyword static, as a static member of an enclosing type  Nested interfaces and enum types are considered implicitly static.  Static member classes, enum types and interfaces can only be declared in top-level type declarations, or within other nested static members.  Static member classes & interfaces can directly access other members that are declared static within the same class.
  • 40. Non Static Member Classes  Non-static member classes are defined as instance members of other classes.  An instance of a non-static member class always has an enclosing instance 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 private members.  Non-static member class being a class member can have any accessibility i.e. public, private etc.  A special form of the new operator is used to instantiate a non-static member class: <enclosing object reference>.new <non-static member class constructor call>  An implicit reference to the enclosing object is always available in every method and constructor of a non-static member class.  The expression <enclosing class name>.this evaluates to a reference that denotes the enclosing object (of the class <enclosing class name>) of the current instance of a non-static member class.
  • 41. Local Inner Classes  Local classes are defined in the context of a block as in a method body 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 are declared.  Local inner classes are completely hidden from the outside world.  Local inner classes can access the fields of their outer classes, and also its local variables. The local variables of outer class must be declared final to access them.  Local classes cannot have static members as they cannot provide class-specific services.  A local class can be instantiated in the block in which it is defined.
  • 42. Anonymous Inner Classes  Anonymous classes combine the process of definition and instantiation into a single step using the new operator.  An anonymous inner class is used to create only a single object of the class, without giving the class a name.  Instantiated by extending a class or implementing an interface:  new <superclass name> (<optional argument list>) { <member declarations> } OR new <interface name>() { <member declarations> }  An anonymous inner class cannot have constructors because the class has no name.  Only non-static members and final static fields can be declared in the class 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. Static Inner Class  When the inner class simply hides one class inside another, but doesn’t have a reference to the outer class object, 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 to the outer class object that generated it.  Inner classes that are declared inside an interface are automatically static and public.
  • 44. Object class  The Object class is the ultimate ancestor and every class in Java extends Object.  In java all except the primitive types (numbers, characters, and boolean values) are not objects.  All array types including the arrays of objects and primitive types, are class types extending Object class.  The equals method in the Object class tests whether one object is considered equal to another.  A hash code is an integer that is derived from an object and is returned using the hashcode() method.  If equals method is redefined, redefine the hashCode() method must also be redefined.  The toString() method returns a string representing the value of the object. It is automatically invoked by java when an object is concatenated with a string by the “+” operator.  The clone() method creates a clone of the object. The Java runtime system allocates memory for the new instance and copies the memory allocated for the current object.
  • 45. Object Cloning  The clone method is used to make a copy of an object to be a new object which is identical to original but whose 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. it doesn’t clone objects that are referenced inside other objects which works fine if subobjects are immutable.  When the subobjects are mutable, the clone method must be redefined to make a deep copy that clones the subobjects too.
  • 46. Wrappers Classes  All primitive types have Wrapper class counterparts.  All wrapper classes are immutable (cannot change the wrapped value after been constructed) and final.  The Void class is considered a wrapper class, but it does not wrap any primitive value and is not instantiable.  Except the Character class, all other wrapper classes have two public one-argument constructors: one taking a primitive value and the other taking a String.  Each wrapper class (except Character) defines the static method valueOf(String str) that returns the wrapper object corresponding to the primitive value represented by the String object passed as argument.
  • 47. Wrapper Classes continued  The integer wrapper classes define an overloaded static valueOf() method taking an argument the base or radix.  Each wrapper class overrides the toString() method from the Object class.  Each wrapper class defines a typeValue() method which returns the 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 the primitive value in the current wrapper Type object is less than, equal to, or greater than value in the wrapper Type object denoted by the argument.
  • 48. Numeric Wrapper Classes  The numeric wrapper classes Byte, Short, Integer, Long, Float, and Double are all subclasses of the abstract class Number.  Each numeric wrapper class defines a set of typeValue() methods for converting the primitive value in the wrapper object to a value of any numeric primitive type. They are:  byte byteValue()  short shortValue()  int intValue()  long longValue()  float floatValue()  double doubleValue()
  • 49. Numeric Wrapper Classes  Each numeric wrapper class defines a static method parseType(String str), which returns the primitive numeric value represented by the String object passed as argument else throws a NumberFormatException if the String parameter is not a valid argument.  The wrapper classes Integer and Long provide static methods for converting integers to string representation in decimal, binary, octal, and hexadecimal notation.
  • 50. Autoboxing  Array list of integers is represented using the Integer wrapper 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 with arithmetic expressions.  The boxing and unboxing is a courtesy of the compiler, not the virtual machine.
  • 51. Java.lang.String  The String class implements immutable character strings, which are read-only once the string has been created and initialized. Hence its threadsafe.  A java.lang.String class is final which implies no class can extend it.  Strings are said to be interned, meaning that they share a unique String object if they have the same content.  String objects can be used with the += and + operators for concatenation.  String, StringBuilder and StringBuffer, all implement CharSequence interface to facilitate interoperability. It defines charAt(int index), length() and toString() methods.
  • 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 into the 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 case considerations.  toUpperCase(): Converts all of the characters in this String to upper case using the rules of the default locale. 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 the specified 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 the specified 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 of oldChar 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 expression pattern.
  • 53. StringBuilder  The StringBuilder class implements dynamic character strings and is mutable.  The capacity of the string builder can also be changed dynamically.  It efficiently concatenates strings, without constructing a new String object every time and wasting memory.  StringBuilder is used to store character strings that are updated frequently and automatically expands as needed.  Appending, inserting, and deleting characters automatically results in adjustment of the string builder’s capacity, if necessary.  StringBuilder class does not override the equals() method and the hashcode() method from the Object class.  It is identical in all respects to StringBuffer except that it is not synchronized, hence multiple threads accessing it at the same time would create problems.  In single-threaded programs avoiding the overhead of synchronization makes the StringBuilder slightly faster.  The compiler uses string builders to implement the string concatenation.
  • 54. StringBuffer  It is a mutable class unlike the String class in terms of capacity and character string.  The StringBuffer class is a thread-safe version of the StringBuilder class.  StringBuffer can be changed dynamically as StringBuilder.  String buffers are preferred when heavy modification of character 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 the contents of string buffers should be converted to String objects for string comparison.
  • 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 currently represented by the string buffer, as indicated by the index argument, is returned.  setCharAt(int index, char ch): The character at the specified index of this string 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 argument into this string buffer. delete(int start, int end): Removes the characters in a substring of this StringBuffer  replace(int start, int end, String str): Replaces the characters in a substring of this StringBuffer with characters in the specified String.  reverse(): The character sequence contained in this string buffer is replaced by the 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. Enumerated Types  An enumerated type has a finite number of named values, 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 of the values listed in the type declaration or the special value null that indicates that the variable is not set to any value at all.
  • 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 an enumerated type.  The constructors are only invoked when the enumerated constants 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 returns an array of all values of the enumeration.  The ordinal method yields the position of an enumerated constant in the enum declaration, counting from zero.
  • 58. File Handling  The java.io package provides an extensive library of classes for I/O.  Java provides streams as a general mechanism for dealing with data I/O.  Streams implement sequential access of data.  There are two kinds of streams: byte streams and character streams.  An input stream is an object that an application can use to read a sequence of data, and an output stream is an object that an application can use to write a sequence of data.
  • 59. File Class  A File object represents the pathname of a file or directory in the host file system.  A File object can also be used to query the file system for information about a file or directory.  The File class can be used to create, rename or delete files and directories.  A File object created using a pathname can be used to check if File or Directory actually exists in the system.
  • 60. ByteStreams  Abstract classes InputStream and OutputStream are base classes for handling reading and writing of bytes.  Subclasses override their methods to customize read/write.  The InputStream class: int read() throws IOException int read(byte[] b) throws IOException int read(byte[] b, int off, int len) throws IOException  The OutputStream class: void write(int b) throws IOException void write(byte[] b) throws IOException void write(byte[] b, int off, int len) throws IOException
  • 61. InputStream ByteArrayInputStream FileInputStream FilterInputStream ObjectInputStream PipedInputStream SequenceInputStrea m BufferedInputStream DataInputStream PushbackInputStream ZipInputStream ZipInputStream is defined in: java.util.zip InputStream Classes
  • 63. Some InputStream Classes  FileInputStream: Data is read as bytes from a file. The file acting 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 input stream.  DataInputStream: A filter that allows the binary representation of Java primitive values to be read from an underlying input stream. The underlying input stream must be specified.  ObjectInputStream: Allows binary representations of Java objects and Java primitive values to be read from a specified input stream.
  • 64. Some OutputStream Classes  FileOutputStream: Data is written as bytes to a file. The file acting as the output stream can be specified by a File object, a FileDescriptor or a String file name.  FilterOutputStream: Superclass of all output stream filters. An output filter must be chained to an underlying output stream.  DataOutputStream: A filter that allows the binary representation of Java primitive values to be written to an underlying output stream. The underlying output stream must be specified.  ObjectOutputStream: Allows the binary representation of Java objects and Java primitive values to be written to a specified underlying output stream.
  • 65. Filter Streams  A filter is a high-level stream that provides additional functionality to an underlying stream to which it is chained.  The data from the underlying stream is manipulated in some way by the filter.  The FilterInputStream and FilterOutputStream classes, together with their subclasses, define input and output filter streams.  The subclasses BufferedInputStream and BufferedOutputStream implement filters that buffer input from and output to the underlying stream.  The subclasses DataInputStream and DataOutputStream implement filters that allow binary representation of Java primitive values to be read and written, respectively, to and from an underlying stream
  • 66. DataInput and DataOutput  The java.io package contains the two interfaces DataInput and DataOutput, that streams implement to allow reading and writing of binary representations of Java primitive values (boolean, char, byte, short, int, long, float, double).  The methods for reading and writing binary representations of Java primitive values are named readX and writeX respectively, where X is any Java primitive data type.  To write binary values create a FileOutputStream, then chain it to created DataOutputStream and use writeX() methods to write respective data types.
  • 67. Character Streams: Readers and Writers  The abstract classes Reader and Writer are the roots of the inheritance hierarchies for streams that read and write Unicode characters using a specific character encoding.  A reader is an input character stream that reads a sequence of Unicode characters, and a writer is an output character stream that writes a sequence of Unicode characters.
  • 68. Some Reader Classes  BufferedReader: A reader that buffers the characters read from an underlying reader. The underlying reader must be specified and an optional buffer size can be given.  InputStreamReader: Characters are read from a byte input stream which must be specified. The default character encoding is used if no character encoding is explicitly specified.  FileReader: Reads characters from a file, using the default character encoding. The file can be specified by a File object, a FileDescriptor, or a String file name. It automatically creates a FileInputStream that is associated with the file.
  • 69. Some Writer Classes  BufferedWriter: A writer that buffers the characters before writing them to an underlying writer. The underlying writer must be specified, and an optional buffer size can be specified.  OutputStreamWriter: Characters are written to a byte output stream which must be specified. The default character encoding is used if no explicit character encoding is specified.  FileWriter: Writes characters to a file, using the default character encoding. The file can be specified by a File object, a FileDescriptor, or a String file name. It automatically creates a FileOutputStream that is associated with the file.  PrintWriter: A filter that allows text representation of Java objects and Java primitive values to be written to an underlying output stream or writer. The underlying output stream or writer must be specified.
  • 70. Console Class  A console is a unique character-based device associated with 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 console console.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 any buffered output to be written immediately.
  • 71. Object Serialization  It allows an object to be transformed into a sequence of bytes that can later be re-created (deserialized) into the original object.  The object retains its state after deserialization, to one it had when it was serialized.  The ObjectInput and ObjectOutput interfaces, allow such reading and writing of objects from and to streams and extend the DataInput and DataOutput interfaces.  The ObjectOutputStream and ObjectInputStream classes provide implementation to write and read binary representation of objects as well as Java primitive values to any stream that is a subclass of the OutputStream and InputStream respectively.  The class of the object must implement the Serializable interface if we want the object to be serialized. If this object is a compound object, then all its constituent objects must also be serializable.