Вы находитесь на странице: 1из 12


Advanced Java Programming



Classes are templates that you use to create actual objects. Every program in Java involves classes, since the code for a program can only appear within a class definition. Classes specify the objects you use in object-oriented programming. There are just two kinds of elements that you can include in a class definition: variables and method.


Java provides you with several libraries of classes which are called packages. A package is a named collection of classes. The purpose of grouping classes in a package is to make it easy to add the classes in a package into your program code. You can use any of the classes in these packages by importing them into your application. Additionally, you may wish to package related classes you create so they can be reused in other applications.


The variables in a class definition can be of any of the basic types, or they can be objects of any class, including the one that you are defining. Two kinds of variables can be included in classes, instance variables and class variables:

Instance Variables ( Non-static Variables)

Each object of the class will have its own copy of each of the instance variables that appear in the class definition. Each object will have its own values for each instance variable. The name 'instance variable' originates from the fact that an object is an 'instance' of a class. An instance variable is declared within the class definition in the usual way, with a type name and a variable name.

Class Variables ( Static Variables) A given class will only have one copy of each of its class variables, and these will be shared between all the objects of the class. The class variables exist even if no objects of the class have been created. They belong to the class, but they are included as part of every object of the class. If the value of a class variable is changed, the new value is available in all the objects of the class. A class variable must be declared using the keyword static preceding the type name.


Advanced Java Programming

The variables this

Every instance method has a variable with the name this, which refers to the current object for which the method is being called. The variable this allows the same instance method to work for different class objects. Each time an instance method is called, this variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific data members of the object referred to by this.


The methods in a class definition are named, self-contained blocks of code, that typically operate on the variables that appear in the class definition. The methods that you define for a class provide the actions that can be carried out using the variables in the class definition. Like variables, there are two varieties of methods, instance methods and class methods.

- You can execute class methods even when no objects of a class exist, whereas

executed in relation to a particular object, so if no

instance methods can only be

objects exist, there are no instance methods to be executed.

- Like class variables, class methods are declared using the keyword static.

- Since class methods can be executed when there are no objects in existence, they

cannot refer to instance variables.

Calling Methods

Calling a method is similar to calling or referring to an instance variable. The methods are accessed using the dot notation. The object whose method is called is on the left of the dot, while the name of the method and its arguments are on the right

Example - Obj.methodname(param1,param2);


Classes are organized into a hierarchy to allow you to easily reuse code. When you write a Java program, first determine which objects you'll need to use in your code. Then determine what variables and methods the object's class must store. When you know what instructions your classes contain, plan your hierarchy.


Comments are used to annotate the code so that a reader can understand the purpose of certain lines and blocks of code. Comments are ignored by the Java compiler.

- Multilines comments are preceded by /* and are ended with */.


Advanced Java Programming

- Single line comments are preceded by //.

- Documentation comments are preceded by /** and are ended with */.

Data Types

Every variable declared should have a name, a type and a value. Java has two kinds of types: primitive (fundamental, simple) and derived (composite).

Primitive Types

Primitive Type

Storage Used



8-bit integer

–128 to 127



16-bit integer

–32,768 to 32,767


32-bit integer

–2,147,483,648 to 2,147,483,647


64-bit integer

–2 63 to 2




32-bit floating-point

6 significant digits, (10 –46 , 10 38 )


64-bit floating-point

15 significant digits, (10 –324 , 10 308 )


Unicode character



Boolean variable

false and true


Implicit Casts











types.Casting from less precise to more precise data types


Explicit Casts

You can cast any of the basic types to any other, but you need to take care that you don't lose information when you do so. Casting from a larger integer type to a smaller has the potential for losing information, as does casting any floating point value to an integer. Some restrictions imposed on casts. For example, a boolean value such as true cannot be cast to any other type, and no nonboolean value can be cast to boolean.


Advanced Java Programming

Wrapper Classes for Primitive Types

Primitive Type

Wrapper Class

















Control Statement

if Statement

if statements consist of if followed by a test expression. The statement or block of statements after the expression is executed. They are structured as follows:

if (test expression){ statement;



if-else Statement

if statements are similar to if statements, but include a false statement

that is executed if the test expression returns a false value. They are structured as follows:


if (test expression){ true-statement;


else {



switch Statement

The switch statement evaluates an expression's value and jumps to a statement identified by the literal value of the expression. It saves coding time if there are several values in your statement. Its form is as follows:


Advanced Java Programming

switch (expression) { case value: statements case value: statements default: statements


Looping Instructions

Loops provide you with the ability to repeat certain statements until a condition is

and for. Three other

met. Java provides three types of loop statements: while, do

statements commonly used with loops are break, continue, and labels.


while loop

The while loop evaluates a condition to see if it is true, and then executes statements and checks the condition again. If the condition is still true, while executes the statements and checks again. This process continues until the condition is evaluated as false. The form is this:

while (expression) { true-statements ;





executes statements

before the condition is evaluated. When you use do loop statements are always

executed at least once. The form is this:

The do


loop is similar to while, but do



do {

statements; } while (expression)

for loop

The for loop allows you to test a range of values in your expression. Its form is generally this:

for(initializer; expression; increment){ statements ;


break, continue, and labels.

The break statement is used to exit loop and conditional statements before meeting a test condition. The continue statement directs execution back to the beginning of a loop without completing all of the loop statements. A label is used to identify a


Advanced Java Programming

statement so execution can be directed to it with a break or continue statement. A colon (:) must be appended to a label name. An example of a label is as follows:

variable declarations; Label:

while (test expression) { statement; if(test expression) { continue Label;





Arrays create slots that allow you to store a list of variables. Arrays are allocated using the new operator to create the array and assigning it to a variable with =. Arrays are declared as follows:

datatype variable [] = new datatype [number-of-slots];

datatype variable [] = {2, 3, 5, 7, 11, 13, 17};

Arrays are fixed size. Once storage for an array has been allocated, the array cannot grow or shrink in size.

Every array has a length data member that specifies the number of elements in the array. As illustrated by the following code segment:


For string processing , Java provides two standard classes String and StringBuffer. Strings are immutable but StringBuffers are not. A String variable is simply an object of the class String. You declare a String variable and initialize it with a declaration such as:

String myString = "My inaugural string";

Creating Objects

After you have a class that has variables and methods stored, you can create objects from it. You can think of an object as an area of memory that is allocated for an object's instance variables. To create an object of a class you must use the keyword new.


Advanced Java Programming

This new operator creates the object of the type specified and calls the constructor that is appropriate for the parameters passed in the parameter list.


Constructors are methods that you use when you create objects. Constructors can be overloaded. They have the same name as the class and no return value. If you don't define a constructor for a class, the compiler will supply a default constructor which does nothing. The primary purpose of a constructor is to provide you with the means of initializing the instance variables for the object being created. It is called when an object

is created without parameters.

Method Overloading

Java allows you to define several methods in a class with the same name, as long

as each method has a set of parameters that is unique. This is called method overloading.

The name of a method together with the type and sequence of the parameters form the signature of the method, and the signature of each method in a class must be distinct to allow the compiler to determine exactly which method you are calling.Note that the

return type has no effect on the signature of a method.

Method Overriding

Overriding is the creation of a method in the subclass that has the same signature, i.e., name, number and type of arguments, as a method in the super class. This new method hides the method of the super class.


Variables and methods that are stored in classes in the class hierarchy are inherited by subclasses, so you do not need to recreate them. In Java, if class A has been defined, we can subsequently declare a new class B, and specify that it extends A. Class

A is called the superclass of B. Class B is a subclass of A.The class B is automatically

inherits all the fields and method definitions of A. Further fields and methods can be added that are specific to B.In particular, for every method signature in class A, class B

will have a method with identical signature.


Encapsulation refers to hiding items of data and methods within an object by specifying them as private in the definition of the class. Being able to encapsulate members of a class in this way is important for the security and integrity of class objects. Another major advantage of encapsulation-the ability to hide the implementation of a class.


Advanced Java Programming

Abstract Classes

An abstract class is a class in which one or more methods are declared, but not defined. To define an abstract class you use the keyword abstract in front of the class name.The declaration for an abstract method ends with a semi-colon, and you specify the method with the keyword abstract to identify it as such. It doesn't matter whether you prefix the class name with public abstract or abstract public, they are equivalent. An abstract method cannot be private since a private method cannot be inherited, and therefore cannot be redefined in a sub-class. You cannot instantiate an object of an abstract class, but you can declare a variable for it.


An interface is essentially a collection of constants and abstract methods that you can implement in a class.The methods in an interface are always public and abstract. Constants in an interface are always public, static and final, so you do not need to specify the attributes for these either. An interface can contain just constants, just abstract methods, or both.


Java uses exceptions as a way of signaling problems when you execute a program. Exceptions arise in your Java programs when things go wrong. There are two types of exceptions: checked and unchecked. An exception that is checked at compile time is checked. All other exceptions are unchecked, also called runtime exceptions, because they are unchecked at compile time and detected only at runtime. Programmers may define their own exception classes.

To declare that your method can throw exceptions, you put the throws keyword after the parameter list for the method, and then add the list of classes for the exceptions that might be thrown, separated by commas. If another method calls this method, it too must take account of the exceptions this method can throw.

If you want to deal with the exceptions where they occur, there are three kinds of

code block that you can include in a method to handle them. These are the try, catch and

finally blocks:

A try block encloses code that may give rise to one or more exceptions

A catch block encloses code that is intended to handle those exceptions. It must

immediately follow the try block which contains the code that may throw that particular


The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.


Advanced Java Programming

AWT (Abstract Window Toolkit)

The base class for the visual AWT classes , is the component. It including container. Containers are special components that can contain other components. Container classes are Window , Frame , Dialog , FileDialog , Panel and Applet.

The Java event mechanism consists of three objects. They are an event source , an event object and event listeners.


Swing is a new and powerful GUL toolkit and part of the JFC. It has lightweight components , uses a variant of the Model View Controller Architecture , has Plaggable Look And Feel(PLAF) and uses Delegation Event Model.


Collections are objects created for the sole purpose of holding and organizing other objects.Classes that comprise the collections framework make up a large part of the java.util package. Interface are the key to the flexibility and uniformity of the collections framework. A collection represents a group of objects known as its elements.Some collections allow duplicate elements and others are not. Some are ordered and others are not.

JSP(Java Server Pages)

A JSP page is a web page that contains Java code along with the HTML tags. The Java code within the page is executed on the server side, producing textual data. A JSP page has a unique URL, which is used by the clients to access the page. Two architectural approaches for building applications using the JSP and servlet technology. These approaches are called the JSP Model1 and JSP Model2 architectures.

JSP Syntax Elements



Directives provide general information about the JSP page to the JSP


Example : <%@ page language=”java” %>

Declarations - Declarations declare and define variables and methods that can be used in the JSP page.



Example : <% ! int count = 0; %>

Scriptlets are Java code fragements that are embedded in the JSP page.


Advanced Java Programming

Example : <% Some Java code %>

Expressions - Expressions act as placeholders for Java language expressions. The expression is evaluated each time the page is accessed, and its value is then embedded in the output HTML.


Example : <%= ++count %>


Actions are commands given to the JSP engine.

Example : <jsp : include page=”copyright.jsp” />


A component architecture for Java. Support for customization and properties.Customization allows a user to alter the appearance and behaviour of a bean. Properties allow beans to be manipulated programmatically, as well as support for customization. Beans must have a get and set properties and must be private.

Java Servlets

A servlet is a server-side Java replacement for CGI scripts and programs. Servlets

are much faster and more efficient than CGI and they let you unleash the full power of

Java on your web server, including back-end connections to databases and object repositories through JDBC, RMI, and CORBA.

A web server uses a separate module to load and run servlets. This specialized

module , which is dedicated to the servlet management, is called a servlet container , or

servlet engine. Conceptually , a servlet container is a part of the web server.

Client sends HTTP request (method) telling server the type of action it wants performed and server sends response.The browser sends requests to the web server, if the target is an HTML file, the server handles it directly and if the target is a servlet , the server delegates the request to the servlet container , which in turn forwards it to the servlet. The servlet uses the file system and database to generate dynamic output.

JDBC ( Java Database Connectivity)

To create access to a database, a programmer had to create an intermediary program between the database manager and the Java program that would access the data. By making a standard JDBC specification, database manufacturers can produce interfaces for their database, regardless of the internal storage format, so that the standardized interface could work with any Java program.

The JDBC Interfaces


Advanced Java Programming

The JDBC defines eight interfaces that must be implemented to be JDBC-compliant:






Simplified API

Establishing a connection -

The first thing you need to do is establish a connection

with the DBMS you want to use. This involves two steps. They are Loading Drivers and

Making a Connection.

Creating Statements

the DBMS. You simply create a Stetement object and then execute it.


A statement object is what sends your SQL statement to

Result Set

instance of the class ResultSet to hold our results.


JDBC returns results in a ResultSet object, so we need to declare an


Advanced Java Programming