Você está na página 1de 29

Java Notes 1

Java Notes

Interface
An interface in the Java programming language is an abstract type that is used to specify an
interface (in the generic sense of the term) that classes must implement.
Interfaces are declared using the interface keyword, and may only contain method signatures and
constant declarations (variable declarations that are declared to be both static and final). An
interface may never contain method definitions. Interfaces cannot be instantiated. A class that
implements an interface must implement all of the methods described in the interface, or be an
abstract class.

In Java language an interface can be defined as a contract between objects on how to communicate
with each other. Interfaces play a vital role when it comes to the concept of inheritance.
An interface defines the methods, a deriving class(subclass) should use. But the implementation of
the methods is totally up to the subclass.

Overview
Interfaces are used to encode similarities which classes of various types share, but do not
necessarily constitute a class relationship. For instance, a human and a parrot can both whistle;
however, it would not make sense to represent Humans and Parrots as subclasses of a Whistler
class. Rather they would most likely be subclasses of an Animal class (likely with intermediate
classes), but both would implement the Whistler interface
Usage
public interface Predator { /*Interface*/
boolean chasePrey(Prey p);
void eatPrey(Prey p);
}

The member type declarations in an interface are implicitly static and public, but otherwise they can
be any type of class or interface.

Now, Classes may implement an interface,see

public class Lion implements Predator {

public boolean chasePrey(Prey p) {


// programming to chase prey p (specifically for a lion)
}

public void eatPrey (Prey p) {


// programming to eat prey p (specifically for a lion)
}
}
Java Notes 2

If a class implements an interface and does not implement all its methods, it must be marked as
abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented
methods.

Now , Classes can implement multiple interfaces also,see

public class Frog implements Predator, Prey {

... //something

Subinterfaces

Interfaces can extend several other interfaces, using the same formula as described above. For
example
public interface VenomousPredator extends Predator, Venomous {
//interface body
}
is legal and defines a subinterface. Note how it allows multiple inheritance, unlike classes. Note
also that Predator and Venomous may possibly define or inherit methods with the same signature,
say kill(Prey prey). When a class implements VenomousPredator it will implement both methods
simultaneously

Examples Some common Java interfaces are:


• Comparable has the method compareTo, which is used to describe two objects as equal, or
to indicate one is greater than the other. Generics allow implementing classes to specify
which class instances can be compared to them.
• Serializable is a marker interface with no methods or fields - it has an empty body. It is used
to indicate that a class can be serialized.
In Short, read
The interface is Java's answer to multiple inheritance. It is a Java type that defines what should be
done, but not how to do it.

Imagine an interface with some method signatures, and a class that will implement the interface.
Interface: I have 5 method signatures.
Class: I want to implement them.
Interface. Okay. But then you have to implement all of them. You are not allowed to say that you
implement me without implementing every single one of my methods.
Class: It's a deal.
The Java interface is a development contract. It ensures that a particular object satisfies a given set
of methods. Interfaces are used throughout the Java API to specify the necessary functionality for
object interaction. It is binding between the interface and the class that implements the interface.
An interface is a totally abstract class. In an abstract class, you can define some methods that
are abstract, and some methods that are fully implemented. Any class that extends that abstract class
must implement the abstract methods, but it inherits the functionality as implemented in the abstract
class
Java Notes 3

Rules for Writing an Interface


1. Declare an interface using the keyword interface.
2. An interface may extend zero or more interfaces if it likes, but it cannot extend a class,
because then it would inherit functionality, and interfaces cannot have functionality. They
can only talk about it.
3. Interface methods cannot be static.
4. Interface methods are implicitly abstract. For that reason, you cannot mark them final (duh),
synchronized, or native because all of these modifiers tell how you're going to implement
the method, and you're voluntarily giving up that ability when you write the method in an
interface.
5. strictfp is okay on an interface. It is okay because you can evaluate compile-time constants
using strictfp rules within an interface.
6. All interface methods are implicitly abstract and public, regardless of what you write in the
interface definition! It is true. The interface method declaration void biteIt(int times), despite
its apparent access level of default, actually has public access. Try it. If you write a class in
another package beyond the visibility of default access, and include the seemingly legal
implementation of void biteIt(int times) { ; }, the compiler will tell you that you cannot
reduce the visibility of the method from public to default. They're all abstract; they're all
public.
7. An interface can define variables. But all variables defined in an interface must be declared
public, static, and final. Many Java programmers have adopted the practice of defining only
variables within an interface and putting constants in it. This works to get at shared
constants, but it is a workaround and is no longer necessary if you're using J2SE SDK 5.0. It
features a new static import facility that allows you to import constants just as you would a
class or package.
8. It should be obvious by now that an interface cannot implement another interface or a class.
9. You may modify your methods using the keyword abstract if you like, but it will have no
effect on compilation. Methods in an interface are already abstract, and the Java Language
Specification says that its use in interfaces is obsolete.
10. Likewise, the interface itself is already abstract. So you can do this if you want: public
abstract interface Chompable {}. But there's no point; it's redundant.
11. Interfaces have default access by default (!). So this is legal: interface Chompable { }. But if
you want your interface to have public access, use that modifier in the interface declaration.
12. You cannot declare an interface as having private access. It doesn't make any sense. No one
could implement it. So private interface Chompable { } gets you a compiler error for your
trouble.
13. public, static, and final are implicit on all field declarations in an interface.
There are some weird things to keep in mind.
Interfaces can be declared private or protected if they are declared nested inside another class or
interface. The following will compile, though its usefulness is dubious at best. public class interface
test {
private interface myinterface{ }}
Only an inner class of the class of which the interface is declared can implement the interface.
Java Notes 4

Encapsulation

is a language construct that facilitates the bundling of data with the methods operating on that data.
Encapsulation rule 1: Place data and the operations that perform on that data in the same class
Encapsulation rule 2: Use responsibility-driven design to determine the grouping of data and
operations into classes
Encapsulation can be described as a protective barrier that prevents the code and data being
randomly accessed by other code defined outside the class. Access to the data and code is tightly
controlled by an interface.
The main benefit of encapsulation is the ability to modify our implemented code without breaking
the code of others who use our code. With this feature Encapsulation gives maintainability,
flexibility and extensibility to our code.
Encapsulation is the technique of making the fields in a class private and providing access to the
fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the
class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as
data hiding.

Abstraction
An abstract class is one that cannot be instantiated. All other functionality of the class still exists,
and its fields, methods, and constructors are all accessed in the same manner. You just cannot create
an instance of the abstract class.If a class is abstract and cannot be instantiated, the class does not
have much use unless it is subclassed

Design Patterns
Repeatable solution to a commonly occurring problem in software design. A design pattern isn't a
finished design that can be transformed directly into code. It is a description or template for how to
solve a problem that can be used in many different situations.

Uses of Design Patterns


Design patterns can speed up the development process by providing tested, proven development
paradigms
Can solve major design problems
Improve code readability
Types
• Creational Design pattern
In software engineering, creational design patterns are design patterns that deal with object creation
mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object
creation could result in design problems or added complexity to the design. Creational design
patterns solve this problem by somehow controlling this object creation
◦ Abstract Factory - Provides a way to encapsulate a group of individual factories that
have a common theme. Creates an instance of several families of classes
Java Notes 5

◦ Builder - Separate the construction of a complex object from its representation so that
the same construction process can create different representations. Separates object
construction from its representation
◦ Factory Method - Defines a separate method for creating the objects, which subclasses
can then override to specify the derived type of product that will be created. Creates an
instance of several derived classes
◦ Object Pool - Avoid expensive acquisition and release of resources by recycling objects
that are no longer in use.
◦ Prototype - Being cloned to produce new objects.A fully initialized instance to be copied
or cloned
◦ Singleton - Restricts instantiation of a class to one object. A class of which only a single
instance can exist

• Structural Design Pattern


This design patterns is all about Class and Object composition. Structural class-creation patterns use
inheritance to compose interfaces. Structural object-patterns define ways to compose objects to
obtain new functionality.
1. Adapter
Adapts one interface for a class into one that a client expects. Match interfaces of different classes
2. Bridge
Decouples an abstraction from its implementation so that the two can vary independently.Separates
an object’s interface from its implementation
3. Composite
A tree structure of simple and composite objects. Designed as a composition of one-or-more similar
objects, all exhibiting similar functionality.
4. Decorator
Allows new/additional behavior to be added to an existing method of an object dynamically. Add
responsibilities to objects dynamically
5. Facade
Provides a simplified interface to a larger body of code.A single class that represents an entire
subsystem
6. Flyweight
When many objects must be manipulated and these cannot afford to have extraneous data, flyweight
is appropriate.A fine-grained instance used for efficient sharing
7. Private Class Data
Restricts accessor/mutator access.
8. Proxy
An object representing another object
Java Notes 6

• Behavioral Design Pattern


This design patterns is all about Class's objects communication. Behavioral patterns are those
patterns that are most specifically concerned with communication between objects.
• Chain of responsibility
A way of passing a request between a chain of objects
• Command
Encapsulate a command request as an object
• Interpreter
A way to include language elements in a program
• Iterator
Sequentially access the elements of a collection
• Mediator
Defines simplified communication between classes
• Memento
Capture and restore an object's internal state
• Null Object
Designed to act as a default value of an object
• Observer
A way of notifying change to a number of classes
• State
Alter an object's behavior when its state changes
• Strategy
Encapsulates an algorithm inside a class
• Template method
Defer the exact steps of an algorithm to a subclass
• Visitor
Defines a new operation to a class without change

Servlets
Servlets [java class in Java EE that confirms with Java Servlet API]

Java Servlet API Protocol by which the java class responds to HTTP requests latest version 3.0

Web.xml [J2EE web deployment descriptor]

Servlet Life Cycle 3 main methods init, service , distroy.

Init - The servlet is loaded into memory using the init() call
Service – For each request to the servlet,a service() method is created, which handles two
parameters ServletRequest & ServletResponse which handles incomming and outgoing data
and response.
Java Notes 7

DoGet(), doPost(),processRequest(HttpServletRequest request, HttpServletResponse


response),getServletInfo();
Destroy - Called once when the servlet is garbage collected from memory

The servlet lifecycle consists of the following steps:


• The servlet class is loaded by the Web container during start-up.
• The container calls the no-arg constructor.
• The Web container calls the init() method. This method initializes the servlet and must
be called before the servlet can service any requests. In the entire life of a servlet, the
init() method is called only once.
• After initialization, the servlet can service client requests. Each request is serviced in its own
separate thread. The Web container calls the service() method of the servlet for every
request. The service() method determines the kind of request being made and dispatches
it to an appropriate method to handle the request. The developer of the servlet must provide
an implementation for these methods. If a request for a method that is not implemented by
the servlet is made, the method of the parent class is called, typically resulting in an error
being returned to the requester.
• Finally, the Web container calls the destroy() method that takes the servlet out of
service. The destroy() method, like init(), is called only once in the lifecycle of a
servlet.
Servlets are multithreaded by default you can make it single threaded by public interface
SingleThreadModel [Ensures that servlets handle only one request at a time. This interface has no
methods , is depricated in Servlet API 2.4 itself]
Why don't we write a constructor in a servlet?
A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an
initialization code you need to run should place in the init() method, since it get called when the
servlet is first loaded. The original reason for using init() instead of constructor was ancient versions
of Java couldn’t dynamically invoke constructors with arguments. So there was no way to give the
constructor a ServletConfig. That no longer applies, but servlet containers still will only call your
no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
What is the difference between servlet context and servlet config
ServletConfig is a servlet configuration object used by a servlet container used to pass information
to a servlet during initialization. All of its initialization parameters can ONLY be set in deployment
descriptor.
The ServletContext object is contained within the ServletConfig object, which the Web server
provides the servlet when the servlet is initialized.Defines a set of methods that a servlet uses to
communicate with its servlet container
Java Notes 8

What is the difference between HttpServlet and GenericServlet?


A GenericServlet has a service() method aimed to handle requests. HttpServlet extends
GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(),
doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
Servlets must implement the interface javax.servlet.Servlet. There are two main types of servlets:

Generic servlets extend javax.servlet.GenericServlet. Generic servlets are protocol independent,


meaning that they contain no inherent support for HTTP or any other transport protocol.

HTTP servlets extend javax.servlet.HttpServlet. These servlets have built-in support for the HTTP
protocol and are much more useful in an Browser environment
Servlet Mapping : defines a mapping between URL pattern and a servlet.mappling is used to map
requests to servlets
All servlets must implements the Servlet interface

Basic Terms
Object
An object is a software bundle of related state and behavior. Software objects are often used to
model the real-world objects that you find in everyday life.Objects have states and behaviors.
Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An
object is an instance of a class.
How many ways to create an object for class
There are three steps when creating an object from a class:
• Declaration . A variable declaration with a variable name with an object type.
• Instantiation . The 'new' key word is used to create the object.
• Initialization . The 'new' keyword is followed by a call o a constructor. This call initializes
the new object.
public class MyClass{
public MyClass(String name){
System.out.println("Class name is:"+name);
}
public static void main(String[] args) {
MyClass myClass = new MyClass("My Class Name");
}
}

1.By using new operator

Integer i=new Integer();

2.Using Class

Class myclass=Class.forName(MyClassName);
myclass.newInstance();
Java Notes 9

3. Using clone()
The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();


MyObject object = anotherObject.clone();

4. Using object deserialization


Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );


MyObject object = (MyObject) inStream.readObject();
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance variable the
fully qualified path should be as follows:

class Puppy{

int puppyAge;

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public setAge( int age ){
puppyAge = age;
}

public getAge( ){
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}

Class
We say that your bicycle is an instance of the class of objects known as bicycles. A class is a
blueprint or prototype from which objects are created. A class can be defined as a template/ blue
print that describe the behaviors/states that object of its type support.
Java Notes 10

Java Variables:

We would see following type of variables in Java:


• Local Variables
• Class Variables (Static Variables)
• Instance Variables (Non static variables)
A class can contain any of the following variable types.
• Local variables . variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
• Instance variables . Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be accessed
from inside any method, constructor or blocks of that particular class.Each object has its
unique set of instant variables. An object.s state is created by the values assigned to these
instant variables.
• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap a slot for each instance variable value is
created.
• Instance variables are created when an object is created with the use of the key word 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object.s state that must be present through out the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
Normally it is recommended to make these variables private (access level).However
visibility for subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) the should be called using the fully qualified name .
ObjectReference.VariableName.

• Class variables . Class variables are variables declared with in a class, outside any method,
with the static keyword.
Class/static variables :
• Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
Java Notes 11

• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never change
from their initial value.
• Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
• Default values are same as instance variables. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during the
declaration or within the constructor. Additionally values can be assigned in special static
initializer blocks.
• Static variables can be accessed by calling with the class name . ClassName.VariableName.
• When declaring class variables as public static final, then variables names (constants) are all
in upper case. If the static variables are not public and final the naming syntax is the same as
instance and local variables.

Methods
A method is basically a behavior. A class can contain many methods. It is in methods where the
logics are written, data is manipulated and all the actions are executed.A Java method is a collection
of statements that are grouped together to perform an operation. When you call the
System.out.println method, for example, the system actually executes several statements in order to
display a message on the console.
In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}

A method definition consists of a method header and a method body. Here are all the parts of a
method:
• Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
• Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without returning a
value. In this case, the returnValueType is the keyword void.
• Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
• Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter
Java Notes 12

list refers to the type, order, and number of the parameters of a method. Parameters are
optional; that is, a method may contain no parameters.
• Method Body: The method body contains a collection of statements that define what the
method does.
method overloading that is, two methods have the same name but different parameter lists within
one class.The Java compiler determines which method is used based on the method signature.
Overloading methods can make programs clearer and more readable. Methods that perform closely
related tasks should be given the same name.
Java Enums:
Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined
values. The values in this enumerated list are called enums.
Reserved Keywords In Java
There are some words that you cannot use as object or variable names in a Java program. These
words are known as “reserved” words; they are keywords that are already used by the syntax of the
Java programming language.
For example, if you try and create a new class and name it using a reserved word:
// you can't use finally as it's a reserved word!
class finally {

public static void main(String[] args) {

//class code..

}
}

It will not compile, instead you will get the following error:
<identifier> expected

The table below lists all the words that are reserved:
abstract assert boolean break byte case
catch char class const* continue default
double do else enum extends false
final finally float for goto* if
implements import instanceof int interface long
native new null package private protected
public return short static strictfp super
switch synchronized this throw throws transient
true try void volatile while
*Even though goto and const are no longer used in the Java programming language, they still
cannot be used
Java Notes 13

Data Types in Java

There are two data types available in Java:


1. Primitive Data Types
2. Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a key word. Let us now look into detail about the eight primitive data types.
• byte
• short
• int
• long
• float
• double
• boolean
• char
Reference Data Types:
• Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy etc.
• Class objects, and various type of array variables come under reference data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the declared type or any
compatible type.
• Example : Animal animal = new Animal("giraffe");
Java Literals
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation. Literals can be assigned to any primitive type variable

Java Modifiers

Access Modifiers : default, public , protected, private


Java provides a number of access modifiers to set access levels for classes, variables, methods and
constructors. The four access levels are:
1. Visible to the package. the default. No modifiers are needed.
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method etc. A variable or method declared without any access control modifier is available
to any other class in the same package. The default modifier cannot be used for methods,
fields in an interface.
Java Notes 14

2. Visible to the class only (private).


Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself. Private access modifier is the most restrictive access level. Class and
interfaces cannot be private. Variables that are declared private can be accessed outside the
class if public getter methods are present in the class. Using the private modifier is the main
way that an object encapsulates itself and hide data from the outside world.
3. Visible to the world (public).
A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any
class belonging to the Java Universe.However if the public class we are trying to access is in
a different package, then the public class still need to be imported.Because of class
inheritance, all public methods and variables of a class are inherited by its subclasses.
4. Visible to the package and all subclasses (protected).
Variables, methods and constructors which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class. The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected. Protected access gives the subclass a chance to use
the helper method or variable, while preventing a nonrelated class from trying to use it.

Access Control and Inheritance:


The following rules for inherited methods are enforced:
• Methods declared public in a superclass also must be public in all subclasses.
• Methods declared protected in a superclass must either be protected or public in subclasses;
they cannot be private.
• Methods declared without access control (no modifier was used) can be declared more
private in subclasses.
• Methods declared private are not inherited at all, so there is no rule for them.
Non-access Modifiers : final, abstract, strictfp
• The static modifier for creating class methods and variables
• The final modifier for finalizing the implementations of classes, methods, and variables.
• The abstract modifier for creating abstract classes and methods.
• The synchronized and volatile modifiers, which are used for threads.

The static Modifier:


Static Variables:
The static key word is used to create variables that will exist independently of any instances created
for the class. Only one copy of the static variable exists regardless of the number of instances of the
class.
Static variables are also known as class variables. Local variables cannot be declared static.
Java Notes 15

Static Methods:

The static key word is used to create methods that will exist independently of any instances created
for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static
methods take all the data from parameters and compute something from those parameters, with no
reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name
of the variable or method.

The final Modifier:


final Variables:
A final variable can be explicitly initialized only once. A reference variable declared final can never
be reassigned to refer to an different object.
However the data within the object can be changed. So the state of the object can be changed but
not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
final Methods:
A final method cannot be overridden by any subclasses. As mentioned previously the final modifier
prevents a method from being modified in a subclass.
The main intention of making a method final would be that the content of the method should not be
changed by any outsider.
final Classes:
The main purpose of using a class being declared as final is to prevent the class from being
subclassed. If a class is marked as final then no class can inherit any feature from the final class.
The abstract Modifier:

abstract Class:

An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is
for the class to be extended.
A class cannot be both abstract and final. (since a final class cannot be extended). If a class contains
abstract methods then the class should be declared abstract. Otherwise a compile error will be
thrown.
An abstract class may contain both abstract methods as well normal methods.

abstract Methods:

An abstract method is a method declared with out any implementation. The methods
body(implementation) is provided by the subclass. Abstract methods can never be final or strict.

Any class that extends an abstract class must implement all the abstract methods of the super class
unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared abstract. An
abstract class does not need to contain abstract methods.

The abstract method ends with a semicolon.


Java Notes 16

The synchronized Modifier:

The synchronized key word used to indicate that a method can be accessed by only one thread at a
time. The synchronized modifier can be applied with any of the four access level modifiers.

public synchronized void showDetails(){


.......
}

The transient Modifier:

An instance variable is marked transient to indicate the JVM to skip the particular variable when
serializing the object containing it.

This modifier is included in the statement that creates the variable, preceding the class or data type
of the variable.

Example:

public transient int limit = 55; // will not persist

public int b; // will persist

The volatile Modifier:

The volatile is used to let the JVM know that a thread accessing the variable must always merge its
own private copy of the variable with the master copy in the memory.
Accessing a volatile variable synchronizes all the cached copied of the variables in the main
memory. Volatile can only be applied to instance variables which are of type object or private. A
volatile object reference can be null.

Java Basic Operators:


The Arithmetic Operators

The Relational Operators

The Bitwise Operators

The Logical Operators

The Assignment Operators

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate boolean expressions. The goal of the operator is to decide which value
should be assigned to the variable. The operator is written as :
variable x = (expression) ? value if true : value if false
Java Notes 17

instanceOf Operator:

This operator is used only for object reference variables. The operator checks whether the object is
of a particular type(class type or interface type). instanceOf operator is wriiten as:
( Object reference variable ) instanceOf (class/interface type)

StringBuffer Class

StringBuffer class is a mutable class unlike the String class which is immutable. StringBuffer can be
changed dynamically. String buffers are preferred when heavy modification of character strings is
involved (appending, inserting, deleting, modifying etc). Strings can be obtained from string
buffers. Since the StringBuffer class does not override the equals() method from the Object class,
contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in
String Buffer manipulations

public class StringBufferDemo {

public static void main(String[] args) {


// Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer("Bob");
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
System.out.println("strBuf1 : " + strBuf1);
System.out.println("strBuf2 capacity : " + strBuf2.capacity());
System.out.println("strBuf3 capacity : " + strBuf3.capacity());
}
}

StringBuffer Functions

The following program explains the usage of the some of the basic StringBuffer methods like ;
1. capacity()
Returns the current capacity of the String buffer.
2. length()
Returns the length (character count) of this string buffer.
3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by
the index argument, is returned.
4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch
5. toString()
Converts to a string representing the data in this string buffer
6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based
on the application need.
Java Notes 18

7. delete(int start, int end)


Removes the characters in a substring of this StringBuffer
8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.
9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used
based on the application need.
11. setLength(int newLength)
Sets the length of this String buffer.
Diff B/w StringBuilder and StringBuffer

StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and
StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in
single-threaded usage. Their key differences in simple term:
• StringBuffer is designed to be thread-safe and all public methods in StringBuffer are
synchronized. StringBuilder does not handle thread-safety issue and none of its methods is
synchronized.
• StringBuilder has better performance than StringBuffer under most circumstances.
• Use the new StringBuilder wherever possible.
Other than that, the two classes are remarkably similar with compatible API. It seems the author just
copied StringBuffer.java to StringBuilder.java, removing all occurrences of "synchronized". Here is
a little trace left in StringBuilder.readObject method:

Mutable Objects: When you have a reference to an instance of an object, the contents of that
instance can be altered
Immutable Objects: When you have a reference to an instance of an object, the contents of that
instance cannot be altered
To demonstrate this behaviour, we'll use java.lang.String as the immutable class and java.awt.Point as the
mutable class.
Point myPoint = new Point( 0, 0 ); /*mutable*/
System.out.println( myPoint );
myPoint.setLocation( 1.0, 0.0 );
System.out.println( myPoint );

String myString = new String( "old String" ); /*immutable */


System.out.println( myString );
myString.replaceAll( "old", "new" );
System.out.println( myString );
Java Notes 19

Constructors
Every class has a constructor. If we do not explicitly write a constructor for a class the java
compiler builds a default constructor for that class.Each time a new object is created at least one
constructor will be invoked. The main rule of constructors is that they should have the same name
as the class. A class can have more than one constructor.Constructors have no explicit return
type.You will use a constructor to give initial values to the instance variables defined by the class,
or to perform any other startup procedures required to create a fully formed object.
class Puppy{
public puppy(){
}

public puppy(String name){


// This constructor has one parameter, name.
}
}

The finalize( ) Method:


It is possible to define a method that will be called just before an object's final destruction by the
garbage collector. This method is called finalize( ), and it can be used to ensure that an object
terminates cleanly.

Inheritance
Object-oriented programming allows classes to inherit commonly used state and behavior from
other classes.Each class is allowed to have one direct superclass, and each superclass has the
potential for an unlimited number of subclasses:
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

Exceptions Handling:

A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
Java Notes 20

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by
using the throw keyword. Try to understand the different in throws and throw keywords.
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.

Exceptiosn In Java
Checked exceptions: Achecked exception is an exception that is typically a user error or a problem
that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot
be found, an exception occurs. These exceptions cannot simply be ignored at the time of
compilation.ClassNotFoundException
Unchecked ex : ArrayIndexOutOfBoundsException
Unchecked exceptions : represent defects in the program (bugs) - often invalid arguments passed to
a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and
Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect
errors in your program's logic and cannot be reasonably recovered from at run time."
* are subclasses of RuntimeException, and are usually implemented using
IllegalArgumentException, NullPointerException, or IllegalStateException
* a method is not obliged to establish a policy for the unchecked exceptions thrown by its
implementation (and they almost always do not do so)
Checked exceptions :
* represent invalid conditions in areas outside the immediate control of the program (invalid user
input, database problems, network outages, absent files)
* are subclasses of Exception
* a method is obliged to establish a policy for all checked exceptions thrown by its implementation
(either pass the checked exception further up the stack, or handle it somehow)

It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a


subclass of Exception (checked)
• Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.
• Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an error will arise. They
are also ignored at the time of compilation.
Java Notes 21

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case
of severe failures, which are not handled by the java programs. Errors are generated to indicate
errors generated by the runtime environment. Example : JVM is out of Memory. Normally
programs cannot recover from errors.
The Exception class has two main subclasses : IOException class and RuntimeException Class.

Inheritance
can be defined as the process where one object acquires the properties of another.
Extends

With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
public class Animal{
}

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}

Overriding
If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.

class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{

public void move(){


System.out.println("Dogs can walk and run");
}
}

public class TestDog{


Java Notes 22

public static void main(String args[]){


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class


}
}

Rules for method overriding:


• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
• The access level cannot be more restrictive than the overridden method's access level. For
example: if the super class method is declared public then the overridding method in the sub
class cannot be either private or public. However the access level can be less restrictive than
the overridden method's access level.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited then it cannot be overridden.
• A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared public or
protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overridden method should not
throw checked exceptions that are new or broader than the ones declared by the overridden
method. The overriding method can throw narrower or fewer exceptions than the overridden
method.
• Constructors cannot be overridden.
Super Keyoword
When invoking a superclass version of an overridden method the super keyword is used.

Polymorphism
is the ability of an object to take on many forms

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now the Deer class is considered to be polymorphic since this has multiple inheritance.
Java Notes 23

The Collection Interfaces:


A collections framework is a unified architecture for representing and manipulating collections. All
collections frameworks contain the following:
• Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.
• Implementations: These are the concrete implementations of the collection interfaces. In
essence, they are reusable data structures.
• Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface. In essence, algorithms are reusable functionality.

A collection — sometimes called a container — is simply an object that groups multiple elements
into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate
data. Typically, they represent data items that form a natural group, such as a poker hand (a
collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of
names to phone numbers).

SN Interfaces with Description


The Collection Interface
1
This enables you to work with groups of objects; it is at the top of the collections hierarchy.
The List Interface
2
This extends Collection and an instance of List stores an ordered collection of elements.
The Set
3
This extends Collection to handle sets, which must contain unique elements
The SortedSet
4
This extends Set to handle sorted sets
The Map
5
This maps unique keys to values.
The Map.Entry
6
This describes an element (a key/value pair) in a map. This is an inner class of Map.
The SortedMap
7
This extends Map so that the keys are maintained in ascending order.
The Enumeration
This is legacy interface and defines the methods by which you can enumerate (obtain one at a
8
time) the elements in a collection of objects. This legacy interface has been superceded by
Iterator.

The Collection Classes:


Java provides a set of standard collection classes that implement Collection interfaces. Some of the
classes provide full implementations that can be used as-is and others are abstract class, providing
skeletal implementations that are used as starting points for creating concrete collections.
Java Notes 24

The standard collection classes are summarized in the following table:


SN Classes with Description
AbstractCollection
1
Implements most of the Collection interface.
AbstractList
2
Extends AbstractCollection and implements most of the List interface.
AbstractSequentialList
3 Extends AbstractList for use by a collection that uses sequential rather than random access of
its elements.
LinkedList
4
Implements a linked list by extending AbstractSequentialList.
ArrayList
5
Implements a dynamic array by extending AbstractList.
AbstractSet
6
Extends AbstractCollection and implements most of the Set interface.
HashSet
7
Extends AbstractSet for use with a hash table.
LinkedHashSet
8
Extends HashSet to allow insertion-order iterations.
TreeSet
9
Implements a set stored in a tree. Extends AbstractSet.
AbstractMap
10
Implements most of the Map interface.
HashMap
11
Extends AbstractMap to use a hash table.
TreeMap
12
Extends AbstractMap to use a tree.
WeakHashMap
13
Extends AbstractMap to use a hash table with weak keys.
LinkedHashMap
14
Extends HashMap to allow insertion-order iterations.
IdentityHashMap
15
Extends AbstractMap and uses reference equality when comparing documents.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes


provide skeletal implementations of the core collection interfaces, to minimize the effort required to
implement them.
Java Notes 25

The following legacy classes defined by java.util


SN Classes with Description
Vector
1
This implements a dynamic array. It is similar to ArrayList, but with some differences.
Stack
2
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Dictionary
3 Dictionary is an abstract class that represents a key/value storage repository and operates
much like Map.
Hashtable
4
Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
Properties
5 Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is
a String and the value is also a String.
BitSet
6 A BitSet class creates a special type of array that holds bit values. This array can increase in
size as needed.

How to use an Comparator ?


Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines
precisely what sorted order means.
This interface lets us sort a given collection any number of different ways. Also this interface can be
used to sort any instances of any class.(even classes we cannot modify).
The compare Method:
int compare(Object obj1, Object obj2)

obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It
returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in
reverse order, you can create a comparator that reverses the outcome of a comparison.
The equals Method:
The equals( ) method, shown here, tests whether an object equals the invoking comparator:
boolean equals(Object obj)

obj is the object to be tested for equality. The method returns true if obj and the invoking object are
both Comparator objects and use the same ordering. Otherwise, it returns false.
Overriding equals( ) is unnecessary, and most simple comparators will not do so.
Java Notes 26

The Methods Declared by Iterator:


SN Methods with Description
boolean hasNext( )
1
Returns true if there are more elements. Otherwise, returns false.
Object next( )
2
Returns the next element. Throws NoSuchElementException if there is not a next element.
void remove( )
3 Removes the current element. Throws IllegalStateException if an attempt is made to call
remove( ) that is not preceded by a call to next( ).

The Methods Declared by ListIterator:


SN Methods with Description
void add(Object obj)
1
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
boolean hasNext( )
2
Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( )
3
Returns true if there is a previous element. Otherwise, returns false.
Object next( )
4 Returns the next element. A NoSuchElementException is thrown if there is not a next
element.
int nextIndex( )
5 Returns the index of the next element. If there is not a next element, returns the size of the
list.
Object previous( )
6 Returns the previous element. A NoSuchElementException is thrown if there is not a
previous element.
int previousIndex( )
7
Returns the index of the previous element. If there is not a previous element, returns -1.
void remove( )
8 Removes the current element from the list. An IllegalStateException is thrown if remove( ) is
called before next( ) or previous( ) is invoked.
void set(Object obj)
1 Assigns obj to the current element. This is the element last returned by a call to either next( )
or previous( ).
Java Notes 27

Serialization
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type and
the types of data stored in the object.

Multithreading

A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead
than multitasking processes.

process: A process consists of the memory space allocated by the operating system that can contain
one or more threads. A thread cannot exist on its own; it must be a part of a process. A process
remains running until all of the non-daemon threads are done executing.

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.

Above mentioned stages are explained here:


• New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
• Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Java Notes 28

• Waiting: Sometimes a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
• Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
• Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

The easiest way to create a thread is to create a class that implements the Runnable interface.

Thread synchronization.

When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchronization.
The synchronized keyword in Java creates a block of code referred to as a critical section. Every
Java object with a critical section of code gets a lock associated with the object. To enter a critical
section, a thread needs to obtain the corresponding object's lock.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a
call to a method that is a member of object occurs only after the current thread has successfully
entered object's monitor.

Interthread Communication

Consider the classic queuing problem, where one thread is producing some data and another is
consuming it. To make the problem more interesting, suppose that the producer has to wait until the
consumer is finished before it generates more data.
In a polling system, the consumer would waste many CPU cycles while it waited for the producer to
produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting
for the consumer to finish, and so on. Clearly, this situation is undesirable.
To avoid polling, Java includes an elegant interprocess communication mechanism via the
following methods:
• wait( ): This method tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
• notify( ): This method wakes up the first thread that called wait( ) on the same object.
• notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c
The highest priority thread will run first.
These methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized context.
These methods are declared within Object. Various forms of wait( ) exist that allow you to specify a
period of time to wait.
Java Notes 29

Thread Deadlock

A special type of error that you need to avoid that relates specifically to multitasking is deadlock,
which occurs when two threads have a circular dependency on a pair of synchronized objects.
For example, suppose one thread enters the monitor on object X and another thread enters the
monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as
expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread
waits forever, because to access X, it would have to release its own lock on Y so that the first thread
could complete.

Thread Control: Suspend, Stop and Resume

While the suspend( ), resume( ), and stop( ) methods defined by Thread class seem to be a perfectly
reasonable and convenient approach to managing the execution of threads, they must not be used
for new Java programs and obsolete in newer versions of Java.
The following example illustrates how the wait( ) and notify( ) methods that are inherited from
Object can be used to control the execution of a thread.
This example is similar to the program in the previous section. However, the deprecated method
calls have been removed. Let us consider the operation of this program.
The NewThread class contains a boolean instance variable named suspendFlag, which is used to
control the execution of the thread. It is initialized to false by the constructor.
The run( ) method contains a synchronized statement block that checks suspendFlag. If that variable
is true, the wait( ) method is invoked to suspend the execution of the thread. The mysuspend( )
method sets suspendFlag to true. The myresume( ) method sets suspendFlag to false and invokes
notify( ) to wake up the thread. Finally, the main( ) method has been modified to invoke the
mysuspend( ) and myresume( ) methods.

Você também pode gostar