JAVA Networking

Basics of network programming

Network: More than one computer systems are connected to sent and receive the information with each other is considered as a Network. due to the networking there is a communication between the systems. So, that they are shared data as well as resources.

Internet: An interconnection of networks is considered as a internet or intranet(Local Area Network). It is the name for vast of worldwide systems, which consists of different types of networks or different servers. The computers that are connected to the Internet is considered as a Host.

Socket Overview:

Networks  sockets are used for networking the systems. A Network socket is like an electrical socket at which various plugs around the network has a standard way of delivering their payload. For transmission the data, the sockets are used some protocols.

Protocol is a standard set of rules, which is used to transfer the data from one system to another. Protocols are classified into two types as

Connection oriented protocols: Eg: TCP/IP Protocols

Connection-less  Protocols     Eg: UDP Protocols

Internet Protocol(IP) is a low-level routing  protocol that breaks data into small packets and sends them to an address across the network. It is not guarantee to deliver the packets to destination.

Transmission Control Protocol(TCP) is a higher level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably tranmit the data.

User Datagram Protocol(UDP) used directly to support fast, connectionless, unreliable transfer of packets.

Addresses:

When there are tens of millions of computers that are connected in a single network, an addressing scheme can be used to select an application that is running on any one of those multiple computers. The computers connected with in an internet have addresses called IP addresses. This address has the form

Num1.Num2.Num3.Num4

There are four numbers separated with dots and each number can have any value between 0 and 255

For  example:  192.27.168.35

Another way of designating a particular computer is through domain name address. The domain names are similar to that of IP addresses as they are written as a sequence of items that are separated by periods(dots).Domain names point to a particular machine through multiple levels. The levels on the right are more general and as they are read to the left, they become more specific.

Example.         http://www.jntu.edu.in

Port: A  Location where the clients and servers can exchange information is called a port. Ports can be designated using integer numbers. The numbers that are less than 1024 are reserved for predefined services such as file transfer, email etc. So, a user defined port can have  an integer value that is greater than 1024.

Simple client server program

program on Server side:

import java.net.*;

class server

{

public static void main(String arg[])throws Exception

{

System.out.println(“Server Activated”);

InetAddress a=InetAddress.getLocalHost();

Socket s=new Socket(a,1080);// or u can put “localhost” instead of Inetaddress ‘a’

}

}

program on client side:

import java.net.*;

import java.util.*;

class client

{

public static void main(String arg[])throws Exception

{

System.out.println(“Client Activated”);

ServerSocket ss=new ServerSocket(1080);

Socket s=ss.accept();

Date d=new Date();

System.out.println(d.toString());

}

}

//Write output & explanation in your words.

Multiple clients:

//Write above server/client program. But in case client programs u need write same client program for few times….. i.e

class client1

{

public static void main(String arg[])throws Exception

{

System.out.println(“Client1 Activated”);

ServerSocket ss=new ServerSocket(1080);

Socket s=ss.accept();

Date d=new Date();

System.out.println(“date at client 1”+d.toString());

}

}

class client2

{

public static void main(String arg[])throws Exception

{

System.out.println(“Client2 Activated”);

ServerSocket ss=new ServerSocket(1080);

Socket s=ss.accept();

Date d=new Date();

System.out.println(“date at client 2”+d.toString());

}

}

//U must write server side program too

// Refer Running notes too

  • Attempt 5 questions (Start with well-known one)
  • Maximum try to write to programs & syntaxes for each question based on marks
  • Don’t forget to write comment lines for each program(u can get max marks)
  • Use pencil for underlining important sentences or words etc… at the end of the exam for every subject
  • Minimum u need use one paper(2 pages) for 8 mark question and 2 papers(4 pages) for 16 mark question for every subject
  • don’t strike anything , try to keep wrong block in brackets or in comment lines

JAVA APPLETS AND SWINGS

An applet is a window based program. The applet class provides the necessary support for applet.All applets are subclasses of Applet class. The applet class is defined in the java.applet package. Therefore all applets must import java.applet package ,Applets must also import java.awt package(abstract window toolkit) since all applets run in a window , it is necessary to include support for that window. Applets are not executed by the console based java runtime interpreter rather they are executed by either an applet viewer or a web browser

  • It is the small aplication.
  • Generally applets are used for internet application.
  • It can be downloaded in internet by java compatiable web browser just like an vidio , audio files.
  • It is more secure,you can download it without any fear of virus attacks, because java is more secure.

Applet class hierarchy

APPLETS AND SWINGS

 

 

Two Types of Applets

The first are those based directly on the Applet class. These applets are use the abstract window toolkit(AWT) to provide the graphic user interface. This style of applet has been available since java was first created

The second type of applets are based on the swing class JApplet. Swing applets use the swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface that does the awt. Thus, swing-based applets are now the most popular

Local Applets

A local applet is one that is stored on your own computer system . When your Web page must find a local applet, it doesn’t need to retrieve information from the Internet-in fact, your browser doesn’t even need to be connected to the Internet at that time. As you can see infigure, a local applet is specified by a path name and a file name.

Local Applets

 

Remote Applets

A remote applet is one that is located on another computer system (Figure 3.2). This computer system may be located in the building next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser. No matter where the remote applet is located, it’s downloaded onto your computer via the Internet

Remote Applets

 

Differences between applet and application

  1. Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading.
  2. Applets can only be executed inside a java compatible container, such as a browser or appletviewer whereas Applications are executed at command line by java.exe or jview.exe.
  3. Applets execute under strict security limitations that disallow certain operations (sandbox model security) whereas Applications have no inherent security restrictions.
  4. Applets don’t have the main() method as in applications. Instead they operate on an entirely different mechanism where they are initialized by  init(),started by start(),stopped by stop() or destroyed by destroy().
  5. Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server
  6. Applets are not capable of reading and writing the user’s file system. This means that the applet neither can access nor place anything locally.
  7. Applets are not capable of communicating the server than one from which they are originating. 

    Lifecycle of Applet

 

ifecycle of Applet

 

When an applet begins, the following methods are called,

  • init()
  • start()
  • paint()

When an applet is terminated, the following sequence of method calls take place

  • stop()
  • destroy()

init( )

The init( ) method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet.

start( )

The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint( )

The paint( ) method is called each time your applet’s output must be redrawn. This situation can

occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required

stop( )

The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page

.destroy( )

The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).

Example Applet Program:

import java.awt.*;

import java.applet.*;

public class Ap extends Applet

{

public void paint(Graphics g)

{

Font f=new Font(“arial”,Font.BOLD,20);

g.setFont(f);

setBackground(Color.GREEN);

g.drawString(“Im your friend”,10,10);

}

}

/*<applet code=Ap width=100 height=100>

</applet>

*/

Passing Parameters to Applets

The APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and Boolean values, you will need to convert their string representations into their internal formats. Here is an example that demonstrates passing parameters:

 

Example:

import java.awt.*;

import java.applet.*;

public class ParamDemo extends Applet

{

public void paint(Graphics g) // Display parameters.

{

int x = Integer.parseInt(getParameter(“a”));

int y = Integer.parseInt(getParameter(“b”));

 

g.drawString(“sum is “+(x+y), 0, 10);

}

}

 

/*<applet code=”ParamDemo” width=300 height=80>

<param name=a value=10>

<param name=b value=14>

</applet> */

Swings

 

Swing is not an acronym. The name represents the collaborative choice of its designers when the project was kicked off in late 1996. Swing is actually part of a larger family of Java products known as the Java Foundation Classes ( JFC), which incorporate many of the features of Netscape’s Internet Foundation Classes (IFC) as well as design aspects from IBM’s Taligent division and Lighthouse Design. Swing has been in active development since the beta period of the Java Development Kit ( JDK) 1.1, circa spring of 1997.

Swing contains many more graphical components than its immediate predecessor, AWT. Many are components that were scribbled on programmer wishlists since Java first debuted including tables, trees, internal frames, and a plethora of advanced text components. In addition, Swing contains many design advances over AWT. For example, Swing introduced an Action class that makes it easier to coordinate GUI components with their functionality. You’ll also find that a much cleaner design prevails throughout Swing; this cuts down on the number of  unexpected surprises that you’re likely to face while coding

Swing Features

Swing provides many features for writing large-scale applications in Java. Here is an overview of some of the more popular features.

 Pluggable Look-and-Feels

One of the most exciting aspects of the Swing classes is the ability to dictate the L&F of each of the components, even resetting the L&F at runtime. L&Fs have become an important issue in GUI development over the past 10 years. Many users are familiar with the Motif style of user interface, which was common in Windows 3.1 and is still in wide use on Unix platforms. Microsoft created a more optimized L&F in their Windows 95/98/NT/2000 operating systems. In addition, the Macintosh computer system has its own carefully designed L&F, which most Apple

users feel comfortable with.

Lightweight Components

Most Swing components are lightweight. In the purest sense, this means that components are not dependent on native peers to render themselves. Instead, they use simplified graphics primitives to paint themselves on the screen and can even allow portions to be transparent.

Additional Features

  • Several other features distinguish Swing from the older AWT components:
  • Swing has wide variety of new components, such as tables, trees, sliders, spinners, progress bars, internal frames, and text components.
  • Swing components support the replacement of their insets with an arbitrary number of nested borders.
  • Swing components can have tooltips placed over them. A tooltip is a textual pop up that momentarily appears when the mouse cursor rests inside the component’s painting region.
  • Tooltips can be used to give more information about the component in question.
  • You can arbitrarily bind keyboard events to components, defining how they react tovarious keystrokes under given conditions.
  • There is additional debugging support for rendering your own lightweight Swing components

The Model-View-Controller Architecture

Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its components. Essentially, MVC breaks GUI components into three elements. Each of these elements plays a crucial role in how the component behaves.

Model

The model encompasses the state data for each component. There are different models for different types of components. For example, the model of a scrollbar component might contain information about the current position of its adjustable “thumb,” its minimum and maximum values, and the thumb’s width (relative to the range of values). A menu, on the other hand, may simply contain a list of the menu items the user can select from. This information remains the same no matter how the component is painted on the screen; model data is always independent of the component’s visual representation.

View

The view refers to how you see the component on the screen. For a good example of how views can differ, look at an application window on two different GUI platforms. Almost all window frames have a title bar spanning the top of the window. However, the title bar may have a close box on the left side (like the Mac OS platform), or it may have the close box on the right side (as in the Windows platform). These are examples of different types of views for the same window object.

 

Controller

The controller is the portion of the user interface that dictates how the component interacts with events. Events come in many forms — e.g., a mouse click, gaining or losing focus, a keyboard event that triggers a specific menu command, or even a directive to repaint part of the screen. The controller decides how each component reacts to the event—if it reacts at all.

Example of Swing program:

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class JBDemo extends JApplet implements ActionListener

{

JButton b1,b2;

public void init()

{

Container c=getContentPane();

c.setLayout(new FlowLayout(FlowLayout.CENTER));

b1=new JButton(“yes”);

b2=new JButton(“no”);

c.add(b1);

c.add(b2);

b1.addActionListener(this);

b2.addActionListener(this);

}

public void actionPerformed(ActionEvent e)

{

showStatus(e.getActionCommand());

}

}

/*<applet code=”JBDemo.class” width=300 height=250>*/

 

output:

Controller

JAVA EVENT HANDLING

The Delegation Event Model

The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events.

In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events than the design used by the old Java 1.0 approach.

Events 

In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed.

Event Sources

A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method.Here is the general form: public void addTypeListener(TypeListener el)  Here, Type is the name`

of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener(). The method that registers a mouse motion listener is called addMouseMotionListener().

Event Listeners:

A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.

Event Listener Interfaces

The delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument

Adapter Classes

Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.

For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ). The signatures of these empty methods are exactly as defined in the MouseMotionListener interface. If you were interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged( ). The empty implementation of mouseMoved( ) would handle the mouse motion events for you.

Anonymous Inner Classes

An anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner class can facilitate the writing of event handlers. Consider the applet shown in the following listing.

As before, its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse is pressed.

Layout Manager

a layout manager automatically arranges your controls within a window by using some type of algorithm.Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements the Layout Manager interface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used. Whenever a container is resized (or sized for the first time), the layout manager is used to position each of the components within it. The setLayout( ) method has the following general form: void setLayout(LayoutManager layoutObj)

Here, layoutObj is a reference to the desired layout manager. If you wish to disable the layout manager and position components manually, pass null for layoutObj. If you do this, you will need to determine the shape and position of each component manually,using the setBounds( ) method defined by Component. Normally, you will want to use a layout manager.Each layout manager keeps track of a list of components that are stored by their names. The layout manager is notified each time you add a component to a container. Whenever the container needs to be resized, the layout manager is consulted via its minimumLayoutSize( ) and preferredLayoutSize( ) methods. Each component that is being managed by a layout manager contains the getPreferredSize( ) and getMinimumSize( ) methods.

FLOWLAYOUT:

FlowLayout is the default layout manager. This is the layout manager that the preceding examples have used. FlowLayout implements a simple layout style, which is similar to how words flow in a text editor.Components are laid out from the upper-left corner, left to right and top to bottom. When no more components fit on a line, the next one appears on the next line. A small space is left between each component, above and below, as well as left and right. Here are the constructors for FlowLayout:

FlowLayout( )

FlowLayout(int how)

FlowLayout(int how, int horz, int vert)

BORDER LAYOUT:

The BorderLayout class implements a common layout style for top-level windows. It has four narrow,fixed-width components at the edges and one large area in the center. The four sides are referred to as north, south, east, and west. The middle area is called the center. Here are the constructors defined by BorderLayout:

BorderLayout( )

BorderLayout(int horz, int vert)

The first form creates a default border layout. The second allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. BorderLayout defines the following constants that specify the regions:

BorderLayout.CENTER

BorderLayout.SOUTH

BorderLayout.EAST

BorderLayout.WEST

BorderLayout.NORTH

 

GRID LAYOUT:

GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you define the number of rows and columns. The constructors supported by GridLayout are shown here:

GridLayout( )

GridLayout(int numRows, int numColumns )

GridLayout(int numRows, int numColumns, int horz, int vert)

The first form creates a single-column grid layout. The second form creates a grid layout with the specified number of rows and columns. The third form allows youto specify the horizontal and vertical space left between components in horz and vert, respectively. Either numRows or numColumns can be zero. Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero allows for unlimited-length rows

Eg: see the example which I was given in running notes

CARD LAYOUT:

The CardLayout class is unique among the other layout managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input. You

The Delegation Event Model

 

can prepare the other layouts and have them hidden, ready to be activated when needed.CardLayout provides these two constructors:

CardLayout( )

CardLayout(int horz, int vert)

The first form creates a default card layout. The second form allows you to specify the horizontal andvertical space left between components in horz and vert, respectively. Use of a card layout requires a bit

more work than the other layouts. The cards are typically held in an object of type Panel. This panel must have CardLayout selected as its layout manager. The cards that form the deck are also typically objects of type Panel. Thus, you must create a panel that contains the deck and a panel for each card in the deck. Next, you add to the appropriate panel the components that form each card. You then add these panels to the panel for which CardLayout is the layout manager. Finally, you add this panel to the main applet panel.

GRIDBAG LAYOUT:

Using GridBagLayout class you can specify the relative placement of components by specifying this positions within cells inside a grid. The key to GridBag is that each component can be a different size and each row in the grid can have a different number of columns this is why the layout is called a gridBag

It is a collection of small grids joined together. The location and size of each component in a gridBag are determined by a set of constraints linked to it. The constraints are contained in an object of type GridBagConstraints. Constraints include the height and width of a cell the placement of acomponent and its alignement.

PANEL:

The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements .A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border. This is why you don’t see these items when an applet is run inside a browser. When you run an applet using an applet viewer, the applet viewer provides the title and border. Other components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by component.

CONTAINER:

The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains.

WINDOW:

The Window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame.

FRAME:

Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. If you create a Frame object from within an applet, it will contain a warning message, such as “Java Applet Window,” to the user that an applet window has been created. This message warns users that the window they see was started by an applet and not by software running on their computer. (An applet that could masquerade as a host-based application could be used to obtain passwords and other sensitive information without the user’s knowledge.) When a Frame window is created by a program rather than an applet, a normal window is created.

Creating a Frame Window in an Applet

While it is possible to simply create a window by creating an instance of Frame, you will seldom do so, because you will not be able to do much with it. For example, you will not be able to receive or process events that occur within it or easily output information to it. Most of the time, you will create a subclass of Frame. Doing so lets you override Frame’s methods and event handling. Creating a new frame window from within an applet is actually quite easy. First, create a subclass of Frame. Next, override any of the standard window methods, such as init( ), start( ), stop( ), and paint( ). Finally, implement the windowClosing( ) method of the WindowListener interface, calling setVisible(false) when the window is closed

EXCEPTION HANDLING and MULTITHREADING

EXCEPTION HANDLING and  MULTITHREADING

Exception: An Exception is defined as “an abnormal error condition that arises during our  program execution”

When a Exception occurs in a program, the java interpreter creates an exception object and throws it out as java exceptions, which are implemented as objects of exception class. This class is defined in java.lang package

An Exception object contains datamembers that will store the exact information about the runtime error (Exception) that has occurred.

Exception Hierarchy:

All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy

EXCEPTION HANDLING & MULTITHREADING

 

‘Exception’ Class:

This class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called Runtime Exception. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing.

‘Error’ Class:

Which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the java run-time environment, itself. Stack overflow is an example of such an error.

Uncaught Exceptions:

This small program includes an expression that intentionally causes divide-by-zero error.

class Ex

{

public static void main(String ar[])

{

int a=0;

int b=10/a;

}

}

Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

—–Here is the output generated when this example is executed——

javja.lang.ArithemeticException:/by zero

Java uses 5 keywords in order to handle the exceptions

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

try block:

The statements that produces exception are identified in the program and the statements are placed in try block

Syntax:

try

{

//Statements that causes Exception

}

catch block

The catch block is used to process the exception raised. The catch block is placed immediately after the try block.

Syntax:

catch(ExceptionType ex_ob)

{

//Statements that handle Exception

}

finally block:

finally creates a block of code that will be executed after a try/catch block has completed. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.

Syntax:

finally

{

// statements that executed before try/catch

}

throw:

It is possible to create a program that throws an exception explicitly, using the “throw ” statement.

Syntax: throw throwable_instance;

Here throwable_instance must be an object type of Throwable class or subclass of Throwable. There are two ways to obtain a Throwable objects

  1. using parameter into a catch clause
  2. Crating one with the new operator

throws:

If  a method is capable of causing an exception that it doen’t handle, it must specify the behaviour to the callers of the method can guard themselves against that ex ce ptin. This can be don’t by throws statement in the methods declarations.

A throws lists the types of exceptions that a method might throw.

Syntax:     return_ type     method_name(parameter-list)throws exception-list

{

//method body

}

Here, exception-list is a comma-separated list of the exception that a method can throw.

UserDefined Exceptions

It is possible to create our own exception types to handle situations specific to our application. Such exceptions are called User-defined Exceptions. User defined exceptions are created by extending Exception class. The throw and throws keywords are used while implementing user-defined exceptions.

***Common Example for try , catch, throw , throws, finally and Userdefined exception:***

import java.io.*;

class MyException extends Exception

{

MyException(String msg)

{

super(msg);

}

}

Class Test

{

public static void main(String ar[])throws IOException

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println(“Enter marks”);

try

{

int marks=Integer.parseInt(br.readLine());

if(marks>100)

{

throw new MyException(“Greater than 100”);

}

System.out.println(“Marks=”+marks);

}

catch(MyException e)

{

System.out.println(e.getMessage());

}

finally

{

System.out.println(“completed”);

}

}

}

output-1:

Enter marks

99

Marks=99

completed

 

output-2:

Enter marks

101

Greater than 100

completed

Nested Try

A try block is placed inside the block of another try block is termed as Nested try block statements. If any error statement is in outer try block , it goes to the corresponding outer catch block. If any error statement is in inner try block first go to the inner catch block. If it is not the corresponding exception next goes to the outer catch, which is also not corresponding exception then terminated.

Example:

class NestedTry

{

public static void main(String ar[])

{

try

{

int a=args.length;//‘a’ stores no of command line args

int b=42/a;        //if a=0 it is Arithemetic Exception

try

{

if(a==1)

a=a/(a-a);

 

if(a==2)

{

int c[]={3};

c[20]=40;

}

}// end of inner try

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(“Array Index exceeds”);

}

}//end of outer try

catch(ArithmeticException e)

{

System.out.println(“Arithmetic Exception”);

}

}

}

Multiple Catch Statements:

Multiple catch statements handle the situation where more than one exception could be raised by a single  piece of code. In such situations specify two or more catch blocks, each specify different type of exception.

Example:

class MultiCatch

{

public static void main(String args[])

{

try

{

int a=args.length;

int b=42/a;

int c[]={3};

c[20]=40;

}

catch(ArithmeticException e)

{

System.out.println(e.getMessage());

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(e.getMessage());

}

}

}

 

Thread is a sequence of instsructions that is executed to define a unique flow of control. It is the smallest  unit of code.

Creating Threads:

Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart and soul of any thread.

public void run()

{

…………….

…………….(statements for implementing thread)

…………….

}

the run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start().

A new thread can be created in two ways.

  1. By extending Thread class: Define a class that extends Thread class and override its run() method with the code required by the thread.
  2. By implementing Runnable interface: Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.

 

Extending Thread Class

We can make our class runnable as thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly. It includes the following steps

  1. Declare the class as extending the Thread class
  2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute.
  3. Create a thread object and call the start() method to initiate the thread execution.

Example:

class A extends Thread

{

public void run()

{

for(int i=1;i<=5;i++)

{

System.out.println(“From Thread A : i ”+i);

}

}

}

 

class B extends Thread

{

public void run()

{

for(int j=1;j<=5;j++)

{

System.out.println(“From Thread B : j ”+j);

}

}

}

class ThreadTest

{

public static void main(String ar[])

{

A a=new A();

B b=new B();

a.start();

b.start();

}

}


output-1:

From Thread A : i 1

From Thread A : i 2

From Thread B : j 1

From Thread B : j 2

From Thread A : i 3

From Thread A : i 4

From Thread B : j 3

From Thread A : i 5

From Thread B : i 4

From Thread B : i 5

output-2:

From Thread A : i 1

From Thread B : j 1

From Thread B : j 2

From Thread B : j 3

From Thread A : i 2

From Thread B : j 4

From Thread B : j 5

From Thread A : i 3

From Thread A : i 4

From Thread A : i 5


 

Implementing Runnable Interface:

The Runnable interface declares the run() method that is required for implementing threads in our programs. To do this, we  must perform the steps listed below:

  1. Declare the class as implementing the Runnable interface.
  2. Implement the run() method
  3. call the thread’s start() method to run the thread.

 

Example:

class A implements Runnable

{

public void run()

{

for(int i=1;i<=5;i++)

{

System.out.println(“Thread A: i= ”+i);

}

}

}

class RunnableTest

{

public static void  main(String ar[])

{

A ob=new A();// A’s object ‘ob’

Thread t=new Thread(ob);

t.start();

}

}

output:

Thread A: i= 1

Thread A: i= 2

Thread A: i= 3

Thread A: i= 4

Thread A: i= 5

Lifecycle of a Thread

During the lifetime of a thread, there are many states it can enter. They include:

  1. NewBorn State
  2. Runnable State
  3. Running State
  4. Blocked State
  5. Dead State

A thread is always in one of these five states. It can move from one state to another via a variety of ways as shown in below figure.

Lifecycle of a Thread

 

NewBorn State:

When we create a thread object, the thread is  born and is said to be in newborn state. The thread is not yet scheduled for running. At t his state, we can do only one of the following things with it:

  • Schedule it for running using start() method
  • Kill it using stop() method

Runnable State:

The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. If we want a thread to relinquish control to another thread to equal priority before its turn comes, we can do so by using the yield()

Running State:

Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread.

Blocked State:

A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running s tate. This happens when the thread is suspended, sleping, or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

Dead State:

Every thread has a lifecycle. A running thread ends its life when it has completed executing its run() method. It is natural death. However, we can kill it by sending the stop message to it at any state thus causing a premature death to it. It is done by stop() method.

Synchronizing Threads:

Synchronization of threads ensures that if two or more threads need to access a shared resource then that resource is used by only one thread at a time. You can synchronize your code using the synchronized keyword. You can invoke only one synchronized method for an object at any given time.

Synchronization is based on the concept of monitor. A monitor, also known as a semaphore, is an object that is used as a mutually exclusive lock. All objects and classes are associated with a monitor and only one thread can won a monitor at a given time.

The monitor controls the way in which synchronized methods access an object or class. When a thread acquires a lock, it is said to have entered the monitor. The monitor ensures that only one thread has access to the resources at any given time. To enter an object’s monitor, you need to call a synchronized method.

When a thread is with in a synchronized method, all the other threads that try to call it on the same instance have to wait. During the execution of a synchronized method, the object is locked so that  no other synchronized method can be invoked. The monitor is automatically released when the method completes its execution. The monitor can also be released when the synchronized method executes the wait() method. When a thread calls the wait() method, it temporarily releases the locks that it holds.

example: See the example which I was given (u can find it in observation or in record or in notes)

The Synchronized Statement:

Synchronization among threads is achieved by using synchronized statements. The synchronized statements is used where the synchronization methods are not used in a class and you do not have access to the source code. You can synchronize the access to an object of this class by placing the calls to the methods defined by it inside a synchronized block .

syntax:

synchronized(obj)

{

// statements;

}

Inter-thread communication

Java  supports inter-thread communication using wait(), notify(), notifyAll() methods. 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.

  • wait() 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() wakes up the first thread that called wait() on the same object.
  • notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

Daemon Threads:

A daemon thread is a thread that runs in the background of a program and provides services to other threads. The daemon threads are  background service provides for other threads. For example, Garbage collector, clock handler, and    screen updater are the daemon threads. By default no thread that you create is a daemon  thread. The setDaemon() method is used to convert a thread to a daemon thread.

Eg:

Thread1.setDaemon(true);

setDaemon() method is used to determine if a thread is a daemon thread.

Boolean b=Thread1.isDaemon();

‘b’ contains true if Thread1 is daemon, otherwise stores false.

ThreadGroup

ThreadGroup creates a group of threads. It defines  these two constructors

ThreadGroup(String groupname);

ThreadGroup(ThreadGroup parentob,String groupname);

For both forms, group name specifies the name of the thread group. Thread groups offer a convenient way to manage groups of threads as a unit.

For example, imagine a program in which one set of threads is used for printing a  document, another set is used to display the document on the screen, and another set saves the document to a disk file. If printing is aborted, you will want an easy way to stop all threads related  to printing.

Thread Priorities:

Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower priority threads.

Java assigns to each thread a priority that determines how that thread should be treated with respected to the others. Thread priorities are integers that specify the relative priority of one thread to another. Thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules that determine when a context switch takes place.

  • A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. in this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given to the CPU.
  • A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted no matter what it is doing by a higher-priority thread.

In cases when two threads with the same priority are competing  for CPU cycles, the situation is a bit complicated. For operating systems such as windows, threads of equal priority are time sliced automatically in round-robin fasion.

To set a thread’s priority, use the setPriority() method, which is a member of Thread. This is its general form:

final void setPriority(int level)

here, level specifies the new priority setting for the calling thread. The value of level must be with in the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10 respectively. To return a thread to a default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as final variables within Thread.

We can obtain the current  priority setting by calling the getPriority() method of Thread

its general form -> final int getPriority();

JAVA PACKAGES AND INTERFACES

JAVA PACKAGES AND  INTERFACES

Package:

A package is a collection of classes and interfaces which provides a high level of access protection and names space management.

Defining & Creating package:

step1: simply include a package command has the first statement in java source file. Any class you declare with in that file will belong to the specified package.

syntax: package packagename;

Eg:       package mypack;

step 2: next define the class that is to be put in the package and declare it as public

step 3: now st ore the classname.java file in the directory having name same as  package name.

step 4: file is to be compiled, which creates .class file in the directory

java also  supports the package hierarchy , which allows to group related classes into a package and then group related packages into a larger package. We can achieve this by specifying multiple names in a pcakge statement, separated by dot .

i.e., package firstpackage.secondpackage;

Accessing package:

A java system package can be accessed either using a fully qualified classname or using import statement. We generally use import statement.

syntax: import pack1[.pack2][.pack3].classname;

or

import pack1. [.pack2][.pack3].*;

here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on. In this way we can have several packages in a package  hierarchy. We should specify explicit class name finally. Multiple import statements are valid. * indicates  that the compiler should search this entire package hierarchy when it encounters a class name.

Understanding CLASSPATH:

the package hierarchy is controlled by CLASSPATH. Until now we have  been storing all of our classes in the same unnamed default package. This works because the default current working directory(.) is usually in the class path environmental variable defined for the java runtime system by default. But there are so many unknown problems when packages are involved.

How does the java runtime system know where to look for packages that we create? The answer has twoparts. First, by default, the java runtime system uses the current working directory as its starting point. Thus if our packages in in the current directory, or a subdirectory of the current directory , it will be found. Second, you can specify a directory path by setting the CLASSPATH environmental variable.

eg: create a class called ‘packtest’ in package ‘test’. create a directory called ‘test’ and put  packtest.java inside the directory. Now we compile the program and the resultant .class file will be stored in the current working directory. Then execute the program as ;

java  test.packtest

Importing packages:

java includes import statement to bring certain classes or entire package into visibility. In a java source file import statement occurs immediately following the package statement and before any class definitions.

syntax: import pkg1[.pkg2].(classname / *) ;

here pkg1 is the name of the top level package.  pkg2 is the name of the subordinate package separated by (.)

finally classname/ * indicates whether the java compiler should import the entire package or a part of it.

eg:       import java.util.Date;

here  java is main package, util is subordinate package Date is the class belongs to util package

Example program(user defined package):

packEg.java

package siet;

public class packEg

{

public void display()

{

System.out.println(“WELCOME TO SWARNANDHRA INSTITUE”);

}

}

packuse.java

import siet.packEg;

class Display

{

public static void main(String ar[])

 

packEg p = new packEg();

p.display();

}

}

now we ill get output as “WELCOME TO SWARNANDHRA INSTITUE”

 Interface:

An interface is a special case of abstract class, which contains all the abstract methods (methods without their implementation). An interface specify what a class must do, but not how to do.

Using the keyword interface, we can fully abstract a class interface from its implementation. Interfaces are syntactically similar to classes, but they lack instance variable, and their methods are declared without anybody. Once it is defined, any number of classes can implement an interface. Also, once class can implement any number of interfaces.

Defining interface:

An interface is defined much like a class. This is the general form of an interface:

access interface interface_name

{

type final_varname1=value;

type final_varname2=value;

. . . .

returntype method-name1(parameter_list);

returntype method-name2(parameter_list);

. . . .

}

here , access is either public or not used. When no access specifier is included, then defult access  results, and the interface is only available to other members of the class package in which it is declared. when it is declared as public, the interface can be used by any other code. interface_name can be any valid identifier.

Methods which are declared have no bodies. they end with a semicolon after the parameter list. they are explicitly abstract methods.

variables are implicitly final and static, meaning they cannot be changed by the implementing class. They must be initialized with a constant value. All the methods and variable are implicitly public if the interface, itself is declared as public.

            Eg:

interface

{

int  pcode=999;                       // final variable

String pname=”HardDisk”;  // final variable

void show();                           // abstract method

}

Implementing interfaces:

Once an interface has been defined, one or more lases can implement that interface. To implement an interface, include the implementes clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this:

access class classname [extends superclass] [implements interface [,interface…]]

{

// class body

}

Eg:

interface product

{

int pcode=999;

String pname=”HardDisk”;

abstract void showProduct();

}

class ProductDesc implements Product

{

public void showProduct()

{

System.out.println(“Pcode=”+pcode);

System.out.println(“PName=”+pname);

}

}

class DemoInterface

{

public static void main(String ar[])

{

ProductDesc ob=new ProductDesc();

ob.showProduct();

}

}

Note:

  • At the time of overriding, the interface methods must be declared as public.
  • Interfaces are introduced to implement multiple inheritance indirectly in java

Variables in interface:

Interfaces can also be used to declare a set of constants  that can be used in different classes. The constant values will be available to any class that implements the interface. The values can be used in any method, as part of any variable declaration, or anywhere where we can use a final value.

Example:

interface A

{

int m=10, n=50;

}

class B implements A

{

void display()

{

System.out.println(“m=”+m+” , n=”+n);

}

}

Extending interfaces

Like classes, interfaces can also be extended. That is , an interface can be subinterfaced from other interfaces. The new subinterface will inherit all the members of the superinterface in the manner similar to subclasses. This is achieved using the keyword extends as shown below

interface name2 extends name1

{

body of name2;

}

interface ItemConstants

{

int code=1001;

String name=”Fan”;

}

interface Item extends ItemConstants

{

void display();

}

class display implements Item

{

public void display()

{

System.out.println(code+”:”+name);

}

}

Applying interfaces

Implementing Multiple Inheritance:

A class can extend only class  but it can implement multiple interfaces. This is one of the ways to ruse multiple inheritance in java. The class must override all the methods of all the interfaces.

eg:

interface citizen

{

String name=”Rama”;

abstract void show();

}

interface Employ

{

int eno=65, salary=20000;

abstract void showEmploy();

}

class professor implements Citizen, Employ

{

int public=100;           //publications

public void show()

{

System.out.print(“Name=”+name);

}

public void showEmploy()

{

System.out.println(“eno=”+eno+”salary=”+salary);

}

}

class DemoMultiple

{

public static void main(String ar[])

{

Professor p=new Professor();

p.showCitizen();

p.showEmploy();

p.showProfessor();

}

}

Differences between classes and interfaces

Both classes and interfaces contain methods and variables but with major difference. An interface defines only abstract methods and final fields i.e., they don’t specify any code for implementing these methods and data fields contain only constants. Using an interface we specify what a class must do, but not how to do. In contrast to interfaces, classes have instance variables and their methods have body. Once an interface is defined any number of classes can implement it. In some situations one class implements several interfaces.

since an interface defines only abstract methods, it is the responsibility of the class that implements an interface to define the code for implementation of these methods. Both classes and interfaces can be executed. Interfaces are in a different hierarchy from classes and because of this it is possible for classes which are unrelated in terms of the class hierarchy to implement the same interface.

The frequently used interfaces in different packages are as follows

package                          interface

java.lang                           Runnable, Cloneable

java.util                              Enumeration, Observer

java.io                                DataInput,      DataOutput

java.awt                               LayoutManager, MenuContainer

java.applet                           AudioClip, AppletStub

 

StringTokenizer Class :

The processing of text often consists of parsing a formatted input string. Parsing is the division of text  into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process. We can enumerate the individual tokens contained in it using StringTokenizer .

To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter for example, “, ; :” sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline etc

The StringTokenizer constructors are shown here:

StringTokenizer(String str)

StringTokenizer(String str, String delimiters)

StringTokenizer(String str, String delimiters, Boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the second and third versions, delimiters is a string that specifies the delimiters. Delimiters are not returned as tokens by the first two forms. Once you have created a StringTokenizer object, the nextToken( ) method is used to extract consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to be extracted. Since StringTokenizer implements Enumeration , the hasMoreElements( ) and nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and nextToken( ) , respectively. The StringTokenizer methods are shown in below.

Method                                                          Description  

int countTokens( )                          ::             Using the current set of delimiters, the method                                                                                        determines the number of tokens left to be parsed and                                                                          returns the result.

boolean hasMoreElements( )          ::         Returns true if one or more tokens remain in the string                                                                          and returns false if there are none.

boolean hasMoreTokens( )             ::          Returns true if one or more tokens remain in the string                                                                          and returns false if there are none.

Object nextElement( )                    ::            Returns the next token as an Object.

String nextToken( )                            ::         Returns the next token as a String.

String nextToken(String delimiters)      ::      Returns the next token as a String and sets the                                                                                          delimiters string to that specified by delimiters

INHERITANCE

Inheritance  is one of the corner stones of Object oriented programming. Because it allows hierarchical classifications. In terminology of java, a class that is inherited is called a super class. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of super class. It inherits all of the instance variables and methods defined by the super class and adds its own, unique elements.

Hierarchical abstractions

A powerful way to manage abstraction is through the use of hierarchical classification. This allows to break the complex systems into manageable pieces.

for example, a car is a single object for outside but the car consists of several subsystems such as steering, breaks, sound system, seat belts etc. Again the sound system consists of radio, DVD player etc.

Here we manage the complexity of a car system through the use of hierarchical classification. Here everything we view in this world is an object. The topmost hierarchy for every object is material object.

Base class:

suppose in the above example, car is the base class. and the sub classes are steering, breaks, engine etc

The behaviour of the child class is always an extension of the properties of the associated with the parent class.

Subclass:

Consider the relationship associated with the parent class and subclass

  • Instances of a sub class must possess all the data areas associated with the parent class.
  • Instances of a sub-class must implement through inheritance at least some or all functionalities defined for the parent class.
  • Thus an instance of a child class can mime the behaviour of the parent class and should be indistinguishable from the instance of parent class if substituted in similar situation.

This creates a problem because we use so many forms of inheritance. To solve this, we use principle of substitutability .

Substitutability :

Def: “The principle of substitutability” says that if we have two classes ‘A’ and ‘B’ such that class B is sub-class of A class, it should be possible to substitute instances of class B for instance of class A in any situation with no observable effect.

Subtype: The term subtype often refers to a subclass relationship in which the principle of substitutability is maintained.

statically typed languages (C++) place much more emphasis on principle of substitutability than dynamically typed languages (Small Talk)

The reason for this is the statically typed languages tend to characterize objects by their class and dynamically typed languages tend to characterize by behaviour.

That is the subtype us determined in statically typed languages by their class and dynamically typed languages by their behaviour.

Forms of inheritance:

Inheritance is used in variety of ways. The following list represents general abstract categories and is not intended to be exhaustive.

 

  1. Sub-classing for Specialization:

The most common use of inheritance and sub-classing is for specialization. In this the derived class is specialized form of the parent class and satisfies the specifications of the parent in all relevant aspects. This is the most ideal form of inheritance, something that a good design should strive for

eg: A class window provides general windowing operations such as moving, resizing etc. A specialized sub class text edit window inherits the window opens. and in addition provides the windows to display textual material

eg:

class Parent

{

int i=10;

void show()

{

System.out.println(“i value=”+i);

}

}

class Child extends Parent

{

// show() will  be called  by Child Object in main class

}

 

  1. Sub-classing for Specification:

In the classes maintained a certain common interface i.e, they implement the same methods the parent class can be the combination of implemented operations and the operations are differed to child class. The child merely implements behaviour describe but not implemented in the parent. In such classes the parent class is mostly known as abstract specification class.

Eg:

abstract class Parent

{

int i;

abstract void show(); // only specifications

}

class Child extends Parent

{

i=20;

void  show()

{

System.out.println(“i =”+i);

}

}

 

  1. Sub-classing for Construction:

A class can often inherit , almost all of its desired functionality from the parent class perhaps changing only the names of the methods used to interface to the class are modifying the arguments in a certain fashion. This may be true if the new class and the parent class failed to share the relationship.

eg:

class Parent

{

int i=10;

void show()

{

System.out.println(“i value=”+i);

}

}

class Child extends Parent

{

i=30;

void  display() // own implementation of child class

{

System.out.println(“i value=”+i);

}

 

}

 

  1. Sub-classing for extension.

In sub-classing for generalization modifies or extends on the existing functionality of an object. But sub-classing for extension acts totally new abilities. In the sub-classing for generalization it must override atleast one method from the parent and here we must atleast extend one method of the parent.

Eg:

class Parent

{

int i=10;

void show()

{

System.out.println(“i value=”+i);

}

}

class Child extends Parent

{

// show() will  be called  by Child Object in main class

void  display() // new method is also implemented

{

System.out.println(“This is child class”);

}

 

}

 

 

  1. Sub-classing for limitation:

Subclassing for limitation occurs when the behaviour of the sub-class is smaller or more restrictive than the behaviour of the parent class.

Eg:

class Parent

{

int i=10;

void show()

{

System.out.println(“i value=”+i);

}

void  display() // new method is also implemented

{

System.out.println(“This is Parent class”);

}

 

}

class Child extends Parent

{

// show() will  be called  by Child Object in main class

// display() may not use .i.e, all methods of Parent will not be used

}

 

  1. subclassing for Combination:

A common situation is that a sub class may represent the combination of features from two or more parent classes.

For example a class teaching assistant can be desired from both the parent classes teacher and assistant

 

 

Benefits of Inheritance:

various benefits of inheritance are

  1. S/w Reusability:

Many programmers spend much of their time in rewriting code they have written many times before. So with inheritance code once written can be reused.

  1. code sharing

Code sharing occurs at two levels. At first level many users or projects can use the same class. In the second level sharing occurs when two or more classes developed by a single programmer as part of a project which is being inherited from a single parent class. Here also code is written once and reused. This is possible through inheritance.

  1. Consistency of inheritance:

When two or more classes inherit from the same superclass we are assured that the behaviour they inherit will be the same in all cases. Thus we can guarantee that interfaces to similar objects are in fact similar.

  1. software components:

Inheritance provides programmers the ability to construct reusable s/w components. The goal behind these is to provide applications that require little or no actual coding. Already such libraries and packages are commercially available.

  1. Rapid Prototyping:

When a s/w system is constructed largely out of reusable components development can be concentrated on understanding the new and unusual portion of the system. Thus s/w system can be generated more quickly and easily leading to a style of programming known as ‘Rapid Prototyping’ or ‘exploratory programming’

  1. Polymorphism and Framework:

Generally s/w is written from the bottom up , although it may be designed from top-down. This is like building a wall where every brick must be laid on top of another brick i.e., the lower level routines are written and on top of these slightly higher abstraction are produced and at last more abstract elements are generated. polymorphism permits the programmer to generate high level reusable components.

  1. Information Hiding:

A Programmer who reuses a software need only to understand the nature of the component and its interface. There is no need to have detailed information of the component and it is information hiding.

 

Costs of Inheritance:

Although they are benefits with object oriented programming we must also consider the cost of inheritance.

  1. Execution Speed: The inherited methods which must deal with orbitary sub-classes are often slower than specialized code. Here efficiency is often misplaed. It is far better to develop a working system and monitor it.
  2. Program Size: The use of any s/w library imposes a size penalty not imposed by systems constructed for a specific project. Although the expense may be substantial and size of program becomes less important.
  3. Message passing overhead: Message passing is costly by nature a more costly operation than simple procedure invocation
  4. Program Complexity: Although object oriented programming is often touched as a solution to s/w complexity. the complexity increases when we use inheritance. But it is not considerable.

 

Inheritances in Java:

  1. Single  Inheritance
  2. Multi-level Inheritance
  3. Hierarchical   Inheritance

 

  1. Single Inheritance:

In a class hierarchy when a child has one and only one parent and parent has one only child, that inheritance is said to be single inheritance.

Single Inheritance

 

Example

Single Inheritance Example

 

class Student

{

int rollno;

void getNo(int no)

{

rollno=no;

}

void putNo()

{

System.out.println(“rollno= ”+rollno);

}

}

class Marks extends Student

{

float marks;

void getMarks(float m)

{

marks=m;

}

void putMarks()

{

System.out.println(“marks= ”+marks);

}

}

 

class Display

{

public static void main(String ar[])

{

Marks ob=new Marks();

 

ob.getNo(44);

ob.putNo();

 

ob.getMarks(66);

ob.putMarks();

}

}

 

  1. Multi-level Inheritance

In a class hierarchy, when a class is derived from already derived class then that inheritance is said to be  multi-level inheritance

Multi-level Inheritance

 

Example

Multi-level Inheritance Example

 

class Student

{

int rollno;

 

void getNo(int no)

{

rollno=no;

}

 

void putNo()

{

System.out.println(“rollno= ”+rollno);

}

}

class Marks extends Student

{

float marks;

void getMarks(float m)

{

marks=m;

}

void putMarks()

{

System.out.println(“marks= ”+marks);

}

}

 

class Sports extends Marks

{

float score;

void getScore(float scr)

{

score=scr;

}

void putScore()

{

System.out.println(“score= ”+score);

}

}

 

class Display

{

public static void main(String ar[])

{

Sports ob=new Sports();

 

ob.getNo(44);

ob.putNo();

 

ob.getMarks(55);

ob.putMarks();

 

ob.getScore(85);

ob.putScore();

}

}

  1. Hierarchical inheritance:

In a class hierarchy, when a parent class  has two or more than two child classes then, the inheritance is said to be hierarchical inheritance.

Hierarchical inheritance:

 

Example

Hierarchical inheritance Example

 

class Student

{

int rollno;

 

void getNo(int no)

{

rollno=no;

}

 

void putNo()

{

System.out.println(“rollno= ”+rollno);

}

}

class Marks extends Student

{

float marks;

void getMarks(float m)

{

marks=m;

}

void putMarks()

{

System.out.println(“marks= ”+marks);

}

}

 

class Sports extends Student

{

float score;

void getScore(float scr)

{

score=scr;

}

void putScore()

{

System.out.println(“score= ”+score);

}

}

 

class Display

{

public static void main(String ar[])

{

Marks s1=new Marks();

Sports s2=new Sports();

 

s1.getNo(44);

s1.putNo();

s1.getMarks(45);

s1.putMarks();

 

s2.getNo(44);

s2.putNo();

s2.getScore(95);

s2.putScore();

}

}

 

Polymorphism:

It is  a mechanism of having multiple forms. In other words polymorphism is a mechanism of defining an interface to represent a general class actions.

 

Method Overriding:

In a class hierarchy when a method of a subclass has the same name and type signature has that of  a method in its superclass, then the method in the subclass is said to be override the method in the superclass. When this is the case the mechanism called “method overriding” and such methods are called overridden methods.

When overridden method is using base class object the base class version is executed and if it is called by subclass, the subclass version is executed.

eg:

class A

{

void callMe()

{

System.out.println(“I am version of superclass A”);

}

}

class B extends A

{

void callMe()

{

System.out.println(“I am version of subclass B”);

}

}

 

 

class Display

{

public static void main(String ar[])

{

B ob=new B();

ob.callMe(); // B’s callMe() will be executed

// i.e, A’s callMe() overridden by B’s callMe()

}

}

Abstract Keyword:

  1. To declare abstract methods
  2. To declare abstract classes

 

  1. Abstract Method:

It is a method in which we have only method declaration but it will not have definition or body. Abstract methods aare declared with abstract keyword and terminated by semicolon (;)

Syntax: abstract return_type MethodName(parameter_list);

  • In a class hierarchy when a superclass containing an abstract method. all the subclasses of that superclass must override the base class method.
  • If the child fails to override the superclass abstract method, the child class must also be abstract.
  • Hence abstract method follows the process of method overriding.

 

  1. Abstract Classes:

A class which consists atleast one abstract method is called abstract class. The class definition must be preceded by abstract keyword.

Syntax:

            abstract class className

{

            —–

            —–

            abstract returntype MethodName(parameter_list)

            {

                        ——-

                        ——-

}

——-

——-

// it can include concrete methods also

}

 

eg:

abstract class Shape

{

abstract void callMe();

}

 

class sub extends Shape

{

void callMe()

{

System.out.println(“I am sub’s Method”)

}

}

 

class DemoAbstract

{

public static void main(String ar[])

{

sub s=new sub();

s.callMe();

}

}

 

 

 

 

final keyword:

final keyword is used for the following  purposes

  1. To define final datamembers
  2. To define final methods
  3. To define final classes
  1. final datamembers:

when a data member is declared as final, its value can’t be changed through out the  program. Hence final variables can be treated as ‘java constants’ Hence when a datamember is declared as final its value must be assigned immediately.

eg: final double pie=3.14;

  1. final methods:

when a method is declared as final its value cant be overridden at all

syntax:            final returntype MethodName(ParameterList)

{

——-

——-

}

When a base class method is declared as final no subclass of that superclass will be allowed to override the base class final method

eg:

final void show()

{

——

——

}

  1. final class:

when a class is declared as a final it cant be inherited at all. Hence we cant have subclasses for final classes.

super keyword:

  • It is used for referring the immediate superclass of the sub class
  • super keyword is used to access super class data members from its subclass.

eg:

class A

{

int x;

}

 

 

class B

{

int x;

B(int p, int q)

{

super.x=p;       // superclass variable is initialized

x=q;                 // subclass variable is initialized

}

void display()

{

System.out.println(“super class variable=”+super.x);

System.out.println(“sub class variable=”+ x);

 

}

 

}

class DemoSuper

{

public static void main(String ar[])

{

B ob=new B(10,20);

ob.display();

}

}

super uses:

1)super keyword is used to access superclass methods from its subclass

eg:  above example

2) super keyword is used to access superclass constructor from its subclass

eg:

class A

{

int x,y;

A(int m, int n)

{

x=m;

y=n;

}

}

class B

{

int z;

B(int p, int q, int r)

{

super(p,q);      // superclass variable is initialized

z=r;                  // subclass variable is initialized

}

void display()

{

System.out.println(“super class variables=”+super.x+” ”+super.y);

System.out.println(“sub class variable=”+ z);

 

}

 

}

class DemoSuper

{

public static void main(String ar[])

{

B ob=new B(10,20,30);

ob.display();

}

}

Member access rules

As java is an object-oriented programming language, data is given more importance regarding its access. Data is to be protected against unauthorized access. In order to protect data in a well built way, data is organized into three categories.

  1. Public data
  2. Private data
  3. Protected data

public, private & protected are called access specifiers. The following table illustrates the member access rules

  • The members declared as public can be accessed any where, any class and any package.
  • The members declared as private can be accessed only by the methods of same class where the private members are declared.
  • The members declared as protected cannot be accessed in non-subclasses of different packages in rest of the cases they can be accessed. If you want any member to be accessed in the subclasses of other packages they can be declared as protected. These members are being protected from the access facility of non-subclasses of other packages.
  • The members declared by nothing, like of no modifier is being placed before a member of a class then, these members can be access only up to package. This occurs by default. Different packages are not allowed to access these no modifier members.

 

Public Protected No Modifier Private
Same class Yes Yes Yes Yes
Same Package Same class Yes Yes Yes No
Same PackageNo-sub Classes Yes Yes Yes No
Different PackageSub Classes Yes Yes No No
Different PackageNon-Subclasses Yes No No No

JAVA BASICS

Java is a general purpose, object oriented programming language developed by Sun MicroSystems in 1991. Originally called OAK by  James gosling , one of the inventors of the language. But was renamed as java in 1995.

The primary motivation of java was not the internet. It was designed to be embedded in various  consumer electronic devices such as Microwave ovens, washing machines and remote controls etc.

The trouble with C and C++ is that they are designed to be compiled for specific target i.e, we require a full C++ compiler targeted for the CPU working in a specific environment. The problem is that compilers are expensive and time consuming to create.

So Gosling and his team began to work on a portable, platform independent language that could be used to produce code that would run on variety of CPUs under different environments. The effort ultimately lead to creation of ‘java

C is familiar for its syntax, C++ is familiar for its object oriented features. So java came with good features of both these languages but not the enhanced version of C or C++.

Java Magic (Byte Code)

The magic of java is the security and portability. Problems are just solved by its byte code i.e output of java compiler is byte code not executable code.

Again this byte code is executed by java runtime system, which is called JVM (Java Virtual Machine). JVM is an interpreter for byte code. Transforming the java program into byte code makes it much easier to run a program in a wide variety of environments. Although if JVM differs from platform to platform, all the machines understand the same byte code.

Java Buzzwords(Features) (S S P OR MAC HDD)

Simple: Java was designed to be easy for professional programmers to learn, if he already knows C &C++. Java includes syntaxes from C and object oriented concepts from C++. The confusing concepts in both C & C++ are leftover here. So java is easy to learn and it is simple language.

Secure: Security becomes an important issue for a language that is used for programming on internet. Threat of viruses and abuse of resources are everywhere. Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. The absence of pointers in java ensures that programs can’t gain access to memory locations without proper authorization.

Portable: The most significant contribution of java over other languages is its portability. Java programs can be easily moved from on computer to another, anywhere and anytime. Changes and upgrades in operating systems, processors and system resources will not force any changes in java programs. This is the reason why java has become popular language for programming on internet which interconnects different kinds of systems world wide.

Object Oriented: java is a true object oriented language. Almost everything in java is an object. All program code and data reside with in objects & classes. Java comes with an extensive set of classes, arranged in packages, that we can use in our programs by inheritance. The object Model in java is simple and easy to extend.

Robust:  Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and runtime checking for data types. It is designed as a garbage collected language relieving the programmers virtually all memory management problems. Java also incorporates the concept of exception handling which captures serious errors and eliminates any risk of crash the system.

Multithreaded: It means handling multiple tasks simultaneously. Java supports Multithreaded programs. This means that we need not wait for the application to finish one task before another. For eg, we can listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer. This feature greatly improves the interactive performance of graphical applications.

Architectural Neutral:  One of the problems facing by programmers was program written today will not  be run tomorrow even in the same machine or if the OS or if the processor upgrades. So java designers made it architectural neutral by implementing JVM (Java Virtual Machine)through java runtime environment. The main role of java designers to make it architecture neutral write once, run anywhere, anytime forever.

Compiled & Interpreted: Usually a computer language is either compiled or interpreted. Java combines both these approaches thus making java a two stage system. First java compiler translates source code into what is known as byte code. Byte codes are not machine instructions and therefore, in second stage java interpreter generates machine code that can be directly executed by the machine that is running the java program.  So we can say that java is both compiled and interpreted language.

High Performance: Java performance is impressive for an interpreted language, mainly due to the use of intermediate byte code. Java architecture is also designed to reduce overheads during runtime. Further, the incorporation of multithreading enhances the over all execution speed of java programs.

Dynamic: java programs carry with them substantial amount of runtime information that is used to access the objects at runtime. This makes java Dynamic.

Distributed: java is designed for the distributed environment of the internet because it handle TCP/IP protocols. Java supports two computers to support remotely through a package called Remote Method Invocation (RMI)

Data types:

Every variable in java has a datatype. Datatypes specify the size and type of values that can be stored. Java language is rich in its datatypes.

Integer types:

Java supports 4 t ypes of integers, they are byte short , int and long. Java does not support the concept of unsigned types and therefore all java values are signed ,meaning they can  be +ve or –ve

Type               Size                 Range

byte                 1 byte              -128  to 127

short                2 bytes             -215  to  215-1

int                    4 bytes             -231  to  231-1

long                 8 bytes             -263  to  263-1

byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from -128 to 127. Variables of type ‘byte’ are especially useful when you’re working with a stream of data from a n/w or file. byte variables are declared by use of ’byte’ keyword.

eg: byte b, c;

 

short: short is signed 16 b it type. It has range from -215  to  215-1. The short variables are declared  by use of  short keyword.

eg: short s;

 

int: The most commonly used integer type is int. It is a signed 32 bit type that a range from -231  to  231-1. In addition to other uses, variables of type int are commonly employed to control loop and to index arrays. ‘int’ type is most versatile & efficient type. int variables are declared by use of ‘int’ keyword.

eg: int a;

 

long: long is a signed 64 bit type and is useful for those occasions where an int type is not large enough to hold the desired values. The range of long is quite large. It has range from -263  to  263-1. long variables are declared by use of ‘long’ keyword

eg: long a;

Floating point types:

Floating point numbers are used when evaluating expressions that require fractional precision. There are two kinds of floating point types, float and double. Which represent single and double precision numbers respectively.

                       Type               Size                 Range

float                 4 bytes             1.4e-045  to  3.4e+038

short                8 bytes             4.9e-324  to  1.8e+308

float: the type float specifies a single precision value that uses 32 bits of storage. Single precision is faster on same processors and takes half as much space as double precision. float variables are declared by use of ‘float’ keyword.

eg:  float a=1.234;

 

double: double precision, as denoted by the double keyword, uses 64 bits to store a value. All transcendental math functions such as sin(), cos() and sqrt() return double values. double variables are declared by use of ‘double’ keyword.

eg: double d;

 

char: In java, the datatype used to store characters is char. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. Thus in java char is a 16bit type. The range of char is 0 to 65536. There are no negative chars. char variables are declared by use of char keyword.

eg: char c;

 

boolean: Java has a simple type called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators such as a<b. Boolean is also the type required by conditional expressions that govern the control statements such as ‘if’ and ‘for’. boolean variables are declared by use of ‘boolean’ keyword.

eg: boolean b; b=false;

 

Java Virtual Machine:

Generally all language compilers translate source code into machine code for a specific computer. In java, architectural neutral is achieved because compiler produces an intermediate code called Byte code, for a machine is called JVM

Java Virtual Machine

A virtual machine code is not machine specific. The code generated by the java interpreter  by acting as an intermediary between the virtual machine and real machine.

Java Virtual Machine

Implementing a java program:

Implementation of java application program involves a series of steps. They include

  • Creating the program
  • Compiling the program
  • Running the program

Remember that, before we begin creating the program, JDK must be properly installed on our system.

Creating the program:

We can create a program using any text editor

class Sample

{

public static void main(String arg[])

{

System.out.println(“Hi friend”);

}

}

We have to save this program with a name like prog.java

A java Application have any no of classes, but only one main class. Main class is nothing but class which contains main() method

Compiling the program:

To compile the program we must run the java compiler javac, with the name of the source file on command line as shown below

C:\>    javac prog.java

If everything is OK, java compiler(javac) creates a file called Sample.class (<classname.class>) containing the bytecodes of the program prog.java

Running the program:

We need to use the java interpreter to run stand alone applications. At the command prompt, type…

C:\> java Sample

Now, the interpreter looks for the main method in the program and begins execution from there. When executed our program displays the following

o/p:      Hi friend

Java PROGRAM STRUCTURE:

A java program may contain many classes of which only one class defines a main method. Classes contain datamembers and methods that operate on the data members of the class.

Java program may contain one or more sections as shown below.

JAVA BASICS

 

 

Documentation section:

This section comprises of a set of comment lines giving the name of program, the author & other details, which the programmer would like to refer at later stage. It is suggested one.

Package statement:

The first statement allowed in java is a ‘package’ statement.

This statement declares a package name and informs the compiler that the classes defined here belong to this package.

Eg: package student;

It is optional section.

Import statement:

This is similar to the #include statement in C

Eg:       import java.io.*;

It is optional section.

Interface statement:

An interface is like a class but includes a group of method declarations. It is also optional section and is used only when we wish to implement the multiple inheritance feature in jprogram.

Class Definitions:

A java program may contain multiple class definitions. Classes are the primary & essential elements of a java program.

Main Method Class:

Since every java stand alone program requires a main method as its starting point, this class is the essential part of a java program.The main method creates objects of various classes and establishes communications between them. On reaching the end of main, the program terminates and the control passes back to the operating system.

COMMAND LINE ARGUMENTS:

Sometimes we will need to supply data into a java program when it runs. This type of data will be supplied in the form of command line arguments. The command line arguments will immediately follow the program  name on the command line. These command line arguments will be collected into an array of string which is supplied as a parameter to main methods.

Later these command line arguments must be processed and then accessed. The following program takes command line argument and prints them.

Eg: class Display

{

public static void main(String args[])

{

for(i=0;i<args.length();i++)

System.out.println(args[i]);

}

}

c:\> javac file.java

c:\> java Display hi this is ur friend

o/p->                 hi

this

is

ur

friend

 

 

 

VARIABLES:

A variable is an identifier that denotes a storage location used to store a data value. All variables have a scope, w hich defines their visibility and a lifetime.

Declaring variable:

All variables must be declared before they can be used. The basic form of a variable declaration is ,                type identifier[=value][, identifier [=value]… ];

Eg:  int  value;

float avg;

in the above example, ‘value’ is an integer type variable , where as ‘avg’ is float type variable.

To declare more than one variable of the specified type, use a comma-separated list.

int  a,b,c;         // declares three integer variables    a, b, and c

int d=3,e,f=5;  // declares 3 integer variables initializing d and f

Unlike in C, variable can be declared any where in the program, where ever they are needed.

 

Dynamic Initialization:

Although the preceding examples have used only  constants  as initializers, java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

For example,

Class   DynInit

{

Public static void main(String arg[])

{

double a=3.0, b=4.0;

double c=Math.sqrt(a*a+b*b);                       //   c is dynamically initialized

System.out.println(“Hypotenuse is  ”+c);

}

}

Here, three local variables a, b, c are declared. The two a and b are initialized by constants. However c is initialized dynamically.

 

Classification of variables:

Java variables are actually classified into three kinds:

  • Instance variables
  • Class variables
  • Local variables

Instance variables are created when the objects are instantiated and therefore they are associated with  the objects.They take different values for each object.

Class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable.

  • Instance and class variables are declared inside a class.

Local variables are declared and used inside methods and program blocks(defined between opening brace { and a closing brace} ). These variables are visible to the program only from the beginning of its program block to the end of the program block.

Scope and lifetime of variables:

Scope of variables:  Scope is defined as an area of the program where the variable is accessible. As a general rule, variables declared insid a scope are not visible to code that is defined outside that scope.

Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope.This means that objects declared in the outer scope will be visible to code within the inner scope. However the reverse is not true. Objects declared with in the inner scope will not be visible outside it.

// program to demostarte block scope

class scope

{

public static void main(String ar[])

{

Int  x; // known to all code with in main

x=10;

if(x==10)

{

Int  y =20;  // known only to this block

System.out.println(“x and y: ”+x+” ”+y);

x=y*2;

}

y = 100; // Error! y not known here

System.out.println(“x is ”+x);                 // x is still known here

}

}

 

As the comments indicate, the variable x is declared at the start of main()’s scope and is accessible to all subsequent code within main(). y is only visible to the code in  if  block .

Lifetime of variables:

Varaibles are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not  hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values between calls to that method. Also a variable declared within a block will lose its values when the block is left. Thus, the lifetime of a variable is confined to its scope.

 

class Lifetime

{

public static void main(String ar[])

{

int x;

for(x=0; x<3; x++)

{

int y=-1;                      // y is initialized each time block is entered

System.out.println(“y is : ”+y);                     // this always prints -1

Y=100;

System.out.println(“y is now : ”+y);

}

}

}

The output of above program is :

y is : -1

y is now:  100

y is : -1

y is now:  100

y is : -1

y is now:  100

 

Arrays

An array is a collection of homogeneous data items that share a common name. Arrays of anytype can be created and may have one or more dimensions. A specific element in an array is accessed by its index.

One-Dimensional Arrays:

general form of a one-dimensional array declaration is

type  var-name[];

eg:       int marks[];

and we must use new operator to allocate memory. So the general form of new as it applies to one-dimensional arrays appears as follows.

type var-name[]=new type[size];

eg:       int marks[] = new int[20];

 

//Demonstrate a one-dimensional array

class Array

{

public static void main(String ar[])

{

int month_days[]=new int[12];

month_days[0] = 31;

month_days[1] = 28;

month_days[2] = 31;

month_days[3] = 30;

month_days[4] = 31;

month_days[5] = 30;

month_days[6] = 31;

month_days[7] = 31;

month_days[8] = 30;

month_days[9] = 31;

month_days[10] = 30;

month_days[11]= 31;

System.out.println(“October has  ”+month_days[9]);

}

}

 

We can also write above program as below…

class Array

{

public static void main(String ar[])

{

int month_days[]={31,28,31,30,31,30,31,31,30,31,30,31};

System.out.println(“October has  ”+month_days[9]+” days”);

}

 

            }

}

 

 

Two (Multi)-Dimensional Arrays:

In java,  multidimensional arrays are actually arrays of arrays.

example:

int  twoD[][] = new int[4][5];

eg program:

class Matrix

{

public static void main(String ar[])

{

int mat[][]=new int[3][4];

for(int i=0;i<3;i++)

{

for(int j=0;j<4;j++)

{

mat[i][j]=i;

System.out.print(mat[i][j]+” ”);

}

System.out.println();

}

}

}

the above program inserts values into a matrix ‘mat’ of order 3×4 and prints

Manually allocate differing size second dimensions

 

// Manually allocate differing size second dimensions

class Traingle

{

public static void main(String ar[])

{

int t[][] = new int[4][];

t[0] = new int[1];

t[1] = new int[2];

t[2] = new int[3];

t[3] = new int[4];

for(int i=0;i<4;i++)

{

for(int j=0;j<i+1;j++)

{

t[i][j]=i;

System.out.print(t[i][j]+” ”);

}

System.out.println();

}

}

}

 

Operators

Java supports a rich set of operators. Operators are used in programs to manipulate data and variables. Java operators can be classified into a number of related categories as below:

  1. Arithmetic operators
  2. Increment & Decrement operators
  3. Relational operators
  4. Bitwise operators
  5. Logical operators
  6. Assignment Operator
  7. Conditional Operator

 

1)Arithmetic operators:

These are used in mathematical expressions in the same way that they are used in algebra. The following are the list of arithmetic operators:

Operator                                Meaning

+                                         Addition

–                                          Subtraction

*                                          Multiplication

/                                          Division

%                                         Modulo division (Remainder)

+=                                       Addition assignment

-=                                        Subtraction assignment

*=                                        Multiplication assignment

/=                                        Division assignment

%=                                       Modulus assignment

 

Arithmetic operators are used as shown  below:

a-b                   a+b

a*b                   a/b

a%b                 -a*b

  • here a and b are operands

 

2)Increment & Decrement operators:

The ++ and the – are java’s increment and decrement operators. The increment operator increases its operand by one. The decrement operator decreases its operand by one.

for example,

x=x+1;  can be written like x++;  using increment operator

similarly,

x=x-1;  can be written like x–;  using decrement operator

 

3)Relational operators:

The relational operators determine the relationship that one operand has to the other. The outcome of these operators is a boolean value. The relational operational operators are most frequently used in the expressions that control the if statement and the various loop statements. The following are the list of Relational operators:

Operator                                Meaning

= =                                        Equal to

! =                                         Not equal to

>                                           Greater than

<                                           Less than

> =                                        Greater than or equal to

< =                                        Less than or equal to

As stated, the result produced by a relational operator is a Boolean value. For example,

int a=4;

int b=1;

boolean c=a>b;

  • in this case, the result of a<b(which is true) is stored in c

 

if(a>b)

{

}

  • in this case, a>b results true, so if statement will be executed

 

Bitwise operators:

Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. The following are the list of Bitwise operators:

 

Operator                                Meaning

    &                                         bitwise AND

!                                           bitwise OR

^                                          bitwise XOR

~                                          bitwise unary NOT

< <                                                       shift left

> >                                                       shift right

> > >                                                    shift right with zero fill

 

Logical operators:

Logical operators are also called as Boolean Logical operators. They operate on boolean operands. All of the binary logical operators combine two boolean values to form a resultant  boolean value.

Operator                                Meaning

    &&                                      logical AND

||                                        logical OR

^                                         logical XOR

       !                                         logical NOT

The logical operators && and || are used when we want to form compound conditions by combining two or more relations.

for example,

if( a>b && x ==10) { }

A             B             A&&B                 A||B                     A^B                       !A

true     true     true                 true                 false                 false

true     false     false                 true                 true                 false

false     true     false                 true                 true                 true

false     false     false                 false                 false                 true

 

Assignment Operator (=):

The assignment operator is the single equal sign, = . It has general form:

var =expression;

Here, the type of var must be compatible with the type of expression.

the assignment operator allows to create a chain of assignments.

For example,

int  x, y, z;

x = y = z = 100;  // set x, y and z to 100

 

Conditional Operator( ?:)

The character pair ?: is a ternary operator available in Java. This operator is used to construct conditional expressions of the form

                        exp1 ? exp2 : exp3

exp1 is evaluated firt. It it is nonzero (true), then the exp2 is evaluated and becomes the value of the conditional expression. if exp1 is false, exp3 is  evaluated and its value becomes the value of the conditional expression.

For example,

a=10 , b=20;

x = ( a > b )? a : b ;

x will  be assigned the value of b. This can be achieved using the if…else statement as follows:

if(a > b)

x = a;

else

x = b;

Expressions

When operands and operators are combined, an expression is formed. The execution of an expression will produce a value.

Arithmetic expression:

If we use arithmetic operators in an expression, that is treated as an Arithmetic expression.     Eg:    a+b-c;

 

Increment or Decrement Expression.

If we use Increment or Decrement operators in an expression, that is treated as Increment or Decrement expression.      Eg:       a++;     b- -;

 

Relational expression:

If we use Relational operators in an expression, that is treated as a Relational expression:         Eg:       a>b;

Logical expression:

If we use Boolean logical operators in an expression, that is treated as a logical expression:       Eg:             a&&b;

 

Conditional expression:

If we use arithmetic operators in an expression, that is treated as an Conditional expression.   Eg:   a>b? a: b;

… like this, we have some other expressions.

Control Statements

A Control statement is a statement that controls the flow of execution of the program. Java’s program control statements are divided into 3 categories

  • Selection Statements
  • Iteration Statements
  • Jump Statements

1)Selection Statements:

Selection statement controls the flow of the program depending on the result of the conditional expression or the state of a variable. There are two selection statements : if and switch

  • if statement:

‘if’ is a selection statement that is used to choose two choices in a program.

Syntax:

if(condition)

statement1;

else

statement2;

‘condition’ is any expression that returns a Boolean value (i.e., true/false). Statement is a single or multiple statements.

If the condition is true then the control goes to the statement1 and it is executed. Otherwise, the  statement2 is executed.

  • Nested if statement:

It means an if statement under another if statement.

Syntax:

if(condition)

{

if(condition)

statement;

 

}

  • if-else-if ladder:

if-else-if statement is a sequence of if-else statements.

Syntax:

if(condition)

statement1;

else if(condition)

statement2;

else if(condition)

statement3;

.

.

else         statement2;

In if-else-if ladder if a condition is not met then the control flows from top to  bottom until the last if statement.

  • switch statement:

It provides more than one choice to choose. It’s a better alternative to if-else-if ladder.

Syntax:

switch(expression)

{

case value1:  statement1;

break;

case value2:  statement2;

break;

case value3:  statement3;

break;

.

.

.

case valueN:  statementN;

break;

default :          statement;

}

here, the expression may be of type byte, short, int or char only. the case values must be of type expression and each value should be unique. when control comes to the switch statement then the value of the expression is compared with the case values, if a match is found then the statement(s) corresponding to that case is executed. If none of the case is matched then the default statement is executed.

2)Iteration Statements:

These statements allows the part of the program to repeat one or more times until some condition becomes true. There are 3 iteration statements: while, do-while and for

  • while statement:

‘while’ is an iteration statement, that repeats a statement or block of statements until some condition is true.

Syntax:

while(condition)

{

// body of the loop

}

where the condition may be any boolean expression. The body of the loop will be executed as long as the condition is true. Once the condition becomes false, the control passes to the statement immediately after the while loop.

 

  • do-while statement:

‘do-while’ statement is very much similar to while statement with little difference. In while statement, if the condition is initially false then the body of loop will not be executed at all. Where as in do-while statement, body of the loop will be executed at least once since the condition of do-while is at the bottom of the loop.

Syntax:

do

{

// body of the loop

} while(condition);

Each iteration of do-while executes the body of loop first and evaluates the condition later. If condition is true, the loop repeats. Otherwise, the loop terminates.

 

 

 

  • for statement:

‘for’ statement also repeats the execution of statements while its condition is true.

Syntax:

for(initialization; condition; iteration)

{

// body of the loop

}

where initialization portion of the loop sets the value of the variable that acts as a counter. This portion is executed first when the loop starts. And it is executed only once. when the control goes to condition, condition is evaluated. If condition is true, the body of loop is executes. Otherwise the loop terminates.Next iteration portion is executed. This helps to increment or decrement the control variable.

The loop then iterates evaluating condition, then executing the body and then executing the iteration portion each time it iterates.

 

2) Jump Statements:

Jump statements allows the control to jump to a particular position. There are 3 types of jump statements.

  • break statement:

in java, there are 3 uses of break statement.

  • It helps to terminate a statement sequence in switch
  • It can be used to exit or terminate the loop
  • It can be used as another form of goto

Eg:

class A

{

public static void main(String arg[])

{

for(int i=0; i<100; i++)

{

if(i==10)

break; // terminates loop if i is 10

System.out.println(“i :”+i);

}

}

}

  • continue statement:

The continue statement starts the next iteration of the immediately enclosing iteration statements(while, do-while or for). When the control goes to continue statement, then it skips the remaining statements and starts the next iteration of enclosing structure.

Eg:

class A

{

public static void main(String arg[])

{

for(int i=0; i<100; i++)

{

System.out.println(“i :”+i);

if(i%2==0)

continue;

System.out.println(“  “);

}

}

}

 

  • return statement:

This is used to return from a method. When the control reaches to return statement, it causes the program control to transfer back to the caller of the method.

Eg:

class A

{

public static void main(String arg[])

{

boolean t=true;

if(t)

return;

System.out.println(“Hi”); // This won’t execute

}

}

In this example, return statement returns to the java run time system, since the caller of main() is runtime system.

 

Type Conversion & Costing

We can assign a value of a variable of one type to a variable of another type. This process is known as casting. If two types are compatible with each other, then the type conversion is done implicitly by Java. This is known as automatic (implicit) type conversion.

Eg:

int a=10;

double b=a;

As shown in above example, it is always possible to assign the value of int variable ‘a’ to double variable ‘b’. This is done implicitly by the system as both variable’s datatypes are compatible

conversion of larger datatype to smaller datatype is known as Narrowing

conversion of smaller datatype to larger datatype is known as Widening.

Automatic Type conversion:

The system performs automatic type conversion when one type of data is assigned to another type of variable only if following rules are satisfied.

  • The types are compatible
  • The destination type is larger than the source type.

A widening conversion took place when these 2 rules are satisfied. Example, widening conversion takes place between int and byte as int is larger than byte to hold its all valid values.

Casting incompatible types:

What if we want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is called narrowing conversion. To create a conversion between two incompatible types, we must use a cast. A cast is simply an explicit type conversion. It has this general form:

                                    (target-type) value

Here, target-type specifies the desired type to convert the specified value to.

The following program demonstrates some type conversions that require casts:

class conversion

{

public static void main(String arg[])

{

byte b;

int i= 257;

double d=323.142;

 

System.out.println(”Conversion of int to byte”);

b=(byte) i;

System.out.println(“i and b ”+i+” ”+b);

 

System.out.println(”Conversion of double to int”);

i=(int) d;

System.out.println(“i and b ”+i+” ”+b);

 

System.out.println(”Conversion of double to byte”);

b=(byte) d;

System.out.println(“i and b ”+i+” ”+b);

 

}

}

 

this program generates the following result

Conversion of int to byte

i and b 257  1

Conversion of double to int

d and i  323.142  323

Conversion of double to byte

d and b 323.142  67

In above eg, When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256(range of byte), which is 1 in this case. When the d is  converted to an int, its fractional component is lost. When d is converted to a byte, its fractional component is lost, and the value is reduces modulo 256, which in this case is 67.

 

Classes & objects:

Concept of Classes

A class is defined as an encapsulation of data and methods that operate on the data. When we are creating a class we are actually creating a new datatype. This new datatype is also called ADT.

–diagram-

When we define a class we can easily create a no of instances of that class

Creating class in java:

In java, a class can be defined through the use of class keyword. The general definition of a class is given below:

class classname

{

type instance_variable1;

type instance_variable1;

.

.

.

returntype method name(parameter list)

{

// body of method

}

.

.

.

}

 

Here,

  • class is a keyword used to define class
  • class name is the identifier that specifies the name of the class
  • type specifies the datatype of the variable
  • instance_variable1, . . . are the variable defined in the class
  • method name is the method defined in the class that can operate on the variables in the class

Example:

class sample

{

int x, y;

setXY()

{

x=10; y=20;

}

}

The variables defined in the class are called member variables/data members

The functions defined in the class are called member functions/member methods.

Both data members and member methods together called members of class.

 

Concept of Objects

Objects are instances of a class. Objects are created and th is process is called “Instantiation”. In java objects are created through the use of new operator. The new operator creates an object and allocates memory to that object. Since objects are created at runtime, they are called runtime entities.

In java object creation is a two step process.

Step1: create a reference variable of the class

Eg: Sample s;

When this declaration is made a reference variable is created in memory and initialized with null.

Step2: create the object using the new operator and assign the address of the object to the reference variable created in step1.

            Eg: Sample s=new Sample();

The step2 creates the object physically and stores the address of the object in the reference variable.

Accessing members of an object:

Once an object of a class is created we can access the members of the class through the use of object name and ‘.‘ (dot) operator.

Syntax:  objectname. member;

Example:

class sample

{

int x, y;

setXY()

{

x=10; y=20;

}

printXY()

{

System.out.print(“=”+x);

System.out.print(“=”+y);

 

}

}

class Demo

{

public static void main(String ar[])

{

Sample s;

s=new String();

s.setXY();

s.printXY();

}

}

 

Constructors

A constructor is a special kind of method that has the same name as that of class in which it is defined. It is used to automaticallyl initialize an object when the object is created. Constructor gets executed automatically at the time of creating the object. A constructor doesn’t have any return type.

Example:

// program to demonstrate constructor

class Student

{

int number;

String name;

Student()         // default constructor

{

number=569;

name=”satyam”;

}

Student(int no, String s)        // parameterized  constructor

 

{

number=no;

name=s;

}

void showStudent()

{

System.out.println(“number =”+number);

System.out.println(“name =”+name);

}

}

 

class Demo

{

public static void main(String ar[])

{

Student s1=new Student();

Student s2=new Student(72,”raju”);

s1.showStudent();

s1.showStudent();

}

}

 

output:number= 569

name= satyam

number= 72

name= raju

 

// and explain about above program

this’ keyword

‘this’ keyword refers to the current object. sometimes a member method of a class needs to refer to the object in which it was invoked. In order to serve this purpose java introduces “this keyword”.

By using ‘this’ keyword we can remove name space conflict.

Name Space Conflict:

When the parameters of a member method have the same name as that of instance variables of the class, local variables take the priority over the instance variable. This leads to conflict called ‘name space conflict’. It can  be resolved through use of “this”

eg:

class Student

{

int number;

String name;

void setStudent(int number,  String name)

{

this.number=number;

this.name=name;

}

void showStudent()

{

System.out.println(“number=”+number);

System.out.println(“name=”+name);

}

}

class Display

{

public static void main(String ar[])

{

Student s=new Student(); // object creation for class Student

s.setStudent(1,”Rama”);

s.showStudent();

}

}

 

Understanding static keyword:

In java , static keyword can be used for the following purposes.

  1. To create static data members
  2. To define static methods
  3. To define static blocks

Static variables:

When a datamember of a class, is declared static only one copy of it is created in memory and is used by all the objects of the class. Hence static variables are essentially global variables.

When a modification is performed on a static variable the change will be reflected in all objects of the class for which the static variable is a member.

 

Static Methods:

  • A static method can call other static methods only
  • A static method can access static variables only
  • Static methods cant have access to this/ super keyword.

 

Static Blocks:

Just like static variables and static methods we can also create a static block . this static block is used to initialize the static variables.

Example program:

class UseStatic

{

static int a=3;

static int b;

static void meth(int x)

{

System.out.println(“x=” + x);

System.out.println(“a=” + a);

System.out.println(“b=” + b);

 

}

static

{

System.out.println(“static block initialized”);

}

 

public static void main(String args[])

{

meth(69);

}

}

 

output:

static block initialized

x = 69

a = 3

b = 12

 

// and explain about program

 

Access Control:

Java’s access specifiers are public, private and protected. Java also defines a default access level. protected applies only when inheritance is involved.

When a member of a class is specified as public, then that member can be accessed by anyother code.

When a member of class is specified as private, then that member can only be accessed by other members of its class, but not anyother class members.

Garbage Collection

Objects are dynamically allocated using the ‘new’ operator and their memory  must be released after reallocation. In C++, they are manually released by the use of delete operator. Java deallocates memory automatically and it is called “Garbage Collection”. When no references to an object exist the object is assumed to be no longer needed and the memory occupied by the object can be reclaimed and t his is how “garbage collection” is done.

Finalize() Method :

In some situations an object will lead to perform some action when it is destroyed. Suppose for example an object is holding some non-java resource such as file-handling. We must  have to free the resources after the object is destroyed.

To handle these situations java provides finalization using finalize() method

Syntax:            protected void finalize()

{

// finalization code here

}

protected prevents to access finalize method  by code defined outside the class.

void is used because it doesn’t return anything.

Overloading methods

In java, it is possible for a class, to contain two or more methods with the same name as long as the method signatures are different. That is the method should have different number of parameters or different type of parameters when this is the case the methods are said to be overloaded and the mechanism is called method overloading.

Example:

class Student

{

int  no ,marks;

String name;

void setStudent()

{

no=1;

marks=89;

name=”rama”;

}

 

void setStudent(int  no, int marks, String name)

{

this.no=no;

this.marks=marks;

this.name=name;

}

void showStudent()

{

System.out.println(“number=”+no);

System.out.println(“marks=”+marks);

System.out.println(“name”+name);

}

}

class MethodOverload

{

public static void main(String ar[])

{

Student s=new Student();

s.setStudent();

s.showStudent();

 

s.setStudent(69,81,”ramu”);

s.showStudent();

}

}

output:

number=1

marks=89

name=rama

 

number=69

marks=81

name=ramu

 

 

Overloading Constructors

Just like member methods constructors can also be overloaded. the following example demonstrates this,

class Student

{

int no;

String name;

Student()

{

no=70;

name=”ram”;

}

Student(int n, String s)

{

no=n;

name=s;

}

void show()

{

System.out.println(“Number=”+no);

System.out.println(“Name=”+name);

}

}

class Display

{

public static void main(String ar[])

{

Student s1= new Student();

Student s2= new Student(69,”satya”);

s1.show();

s2.show();

}

}

output:

number=70

name=ram

number=69

name=satya

 

Parameter passing

There are two ways that a computer language can pass an argument to a subroutine (method).

  1. call by value
  2. call by reference

In the first way, the change made to the parameter of the subroutine have no effect on the argument.

In the second way, the changes made to the parameter will effect the argument used to call the subroutine.

In java when you pass a primitive type it is pass by value. when you  pass an object(reference) to a method, it is done through pass by reference

Example:

// call by value

class Test

{

void meth(int i , int j)

{

i+=2;

j*=2;

}

}

class CallByValue

{

public static void main(String arg[])

{

Test ob= new Test();

int a=10 , b=20;

System.out.println(“a and b before call: ”+a+” ”+b);

ob.meth(a,b);

System.out.println(“a and b after  call: ”+a+” ”+b);

 

}

}

output:

a and b before call: 10 20

a and b after  call: 10 20

 

Recursion

Java supports recursion. It is the process of defining something interms of itself. It is the attribute that allows a method to call itself. The method that calls itself is said to be recursive method.

The classic example of recursion is the computation of the factorial of a number.

class Factorial

{

int fact(int n)

{

if(n==1) return 1;

return (fact(n-1)*n);

}

}

class Recursion

{

public static void main(String ar[])

{

Factorial f=new Factorial();

System.out.println(“Factorial of 5 is”+ f.fact(5));

}

}

output above program:

Factorial of 5 is 120

 

Nested & inner classes:

It is possible to define a class with in another class. Such classes are known as nested classes. The scope of nested class is bounded by the scope of its enclosing class. Thus, if class B is defined with in class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class.

There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it can not refer to members of its enclosing class directly.

The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variable and methods of its outer class and may refer to them directly.

Example:

class  Outer

{

int outer_x=10;

void outerMethod()

{

System.out.println(“In Outerclass Method”);

Inner in=new Inner();

In.innerMethod();

}

class Inner

{

void innerMethod()

{

System.out.println(“In Innerclass Method”);

System.out.println(“outer class variable:”+outer_x);

}

}

}

 

class Display

{

public static void main(String ar[])

{

Outer out=new Outer();

Out.outerMethod();

}

}

output:

In Outerclass Method

In Innerclass Method

outer class variable: 10

 

String Handling

A String is a sequence of characters. In java , Strings are class objects and implemented using two classes, namely, String and StringBuffer. A java string is an instantiated object of the String class.A java String is not a character array and is not NULL terminated. Strings may be declared and created as follows:

String stringname= new String(“string”);

String name=new String(“kanth”);  is same as

String name=”kanth”;

like arrays, it is possible to get the length of string using the length method of the String class.

int len = name.length();

Java string can be concatenated using the + operator.

eg:       String firstname = ”sri”;

String lastname = ”kanth”;

String name = firstname+lastname;

( or )

String name = ”sri”+”kanth”;

 

String Arrays:

we can also create an use arrays that contain strings. The statement,

String names[]=new String[3];

will create an names array of size 3 to hold three string constants.

 

String Methods: (Methods of String class)

The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks.

 

Method                                                          Task

s2=s1.toLowerCase()                                        converts the String s1 to all lowecase

s2=s1.toUpperCase()                                        converts the String s1 to all Uppercase

s2=s1.replace(‘x’,’y’);                                       Replace all appearances of x with y

s2=s1.trim();                                                        Remove white spaces at the beginning and end of String s1

s1.equals(s2);                                                      Returns ‘true’ if s1 is equal to s2

s1.equalsIgnoreCase(s2)                                 Returns ‘true’ if s1=s2, ignoring the case of characters

s1.length()                                                            Gives the length of s1

s1.CharAt(n)                                                       Gives nth character of s1

s1.compareTo(s2)                                              Returns –ve if s1<s2, positive if s1>s2, and zero if s1 is equal s2

s1.concat(s2)                                                       Concatenates s1 and s2

s1.indexOf(‘x’)                                                   Gives the position of the first occurrence of ‘x’ in string s1

s1.indexOf(‘x’,n)                                                Gives the position of ‘x’ that occurs after nth position in the- string s1

 

//Alphabetical ordering of strings

class StringOrdering

{

public static void  main(String args[])

{

String names[]={“india”,”usa”,”australia”,”africa”,”japan”};

int size=names.length;

String temp;

for(int i=0;i<size;i++)

{

for(int j=i+1;j<size;j++)

{

if(names[j].compareTo(names[i])<0)

{

temp=names[i];

names[i]=name[j];

names[j]=temp;

}

}

}

for(int i=0;i<size;i++)

System.out.println(names[i]);

}

}

above program produces the following result

africa

australia

india

japan

usa

 

String Buffer Class :

StringBuffer is a peer class of String. While String creates string of fixed length, StringBuffer creates strings of flexible length that can be modified in terms of  both length and content. We can insert characters and substrings in the middle of a string, or append another string to the end.

Below, there are some of methods that are frequently used in string manipulations.

 

Method                                              Task

s1.setCharAt(n,’x’)                                            Modifies the nth character to x

s1.append(s2)                                                     Appends the string s2 to s1 at the end

s1.insert(n,s2)                                                     Inserts the string s2 at the position n of the string s1

s1.setLength(n)                                                  sets the length of the string s1 to n. if n<s1.length() s1 is

truncated .if n>s1.length() zeros are added to s1

 

Important questions in this unit:

1a) With an example, explain scope and lifetime of variables. [10M]

  1. b) Describe the methods to modifying a string. [10M]

 

2.a) Briefly describe the type conversion mechanisms.[10M]

  1. b) Explain with a java program about reference variables? [10M]

 

3)a) Describe java garbage collection mechanism? [8M]

  1. b) What is a constructor? Describe its special properties.[12M]

 

4 a)What is the difference between public member and private member of a class[5M]

b)Explain about static keyword[15M]

 

5 a)Explain about Constructor overloading?[10M]

b)Explain about Method Overriding[10M]

 

6 a) Explain about Command line arguments[10M]

  1. b) Briefly explain about classes and objects[10M]
JAVA Object Oriented Thinking

Object Oriented Thinking

When computers were first invented, programming was done manually by toggling in a binary machine instructions by use of front panel.

As programs began to grow, high level languages were introduced that gives the programmer more tools to handle complexity.

The first widespread high level language is FORTRAN. Which gave birth to structured programming in 1960’s. The Main problem with the high level language was they have no specific structure and programs becomes larger, the problem of complexity also increases.

So C became the popular structured oriented language to solve all the above problems.

However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new way of programming was invented and it was OOP. OOP is a programming methodology that helps to organize complex programs through the use of inheritance, encapsulation & polymorphism.

OOP is a Revolutionary idea totally unlike anything that has came  before in programming

OOP is an evolutionary step following naturally on the heels of earlier programming abstractions.

A way of viewing world:

It means how we handle the real world situations through OOP and how we could make the computer closely model the techniques.

Eg: Raju wished to send some flowers to his friend for his birthday & he was living some miles away. He went to local florist and said the kind of flowers. He want to send to his friend’s address. And florist assured those flowers will be sent automatically.

Agents:

The  Structure of OOP is similar to that of a community, that consists of agents interacting with each other. These agents are also called as objects. An agent or an object plays a role of providing a service or performing an action, and other members of this community can access these services or actions.

Consider an eg, raju and ravi are good friends who live in two different cities far from each other. If Raju wants to send flowers to ravi, he can request his local florist ‘hari’ to send flowers to ravi by giving all the information along with the address.

Hari works as an agent (or object) who performs the task of satisfying raju’s request. Hari then performs a set of operations or methods to satisfy the request which is actually hidden from ravi, Hari forwards a message to ravi’s local florist. Then local florist asks a delivery person to deliver those flowers to ravi. The objects or agents helping raju in solving the problem of sending flowers to his friend ravi can be shown in figure.

java

Responsibilities:

A fundamental concept in OOP is to describe behavior in terms of responsibilities. A Request to perform an action denotes the desired result. An object can use any technique that  helps in obtaining the desired result and this process will not have any interference from other object. The abstraction level will be increased when a  problem is evaluated in terms of responsibilities. The objects will thus become independent from each other which will help in solving complex problems. An Object has a collection of responsibilities related with it which is termed as ‘protocol’

The Operation of a traditional program depends on how it acts on data structures. Where as an OOP operates by requesting data structure to perform a service.

Messages & Methods:

When a message is passed to an agent (or object) that is capable of performing an action, then that action will be initiated in OOP. An object which receives the message sent is called ‘receiver’. When a receiver accepts a message, it means that the receiver has accepted the responsibility of processing the requested action. It then performs a method as a response to the message in order to fulfill the request.

Classes & Instances:

A Receiver’s class determines which method is to be invoked by the object in response to a message. When similar messages are requested then all the objects of a class will invoke the same method.

All objects are said to be the instances of a class.

For e.g.,  If ‘flower’ is a class then Rose is its instance

Class Hierarchies (Inheritance):

It is possible to organize classes in the form of a structure that corresponds to  hierarchical inheritance. All the child classes can inherit the properties of their parent classes. A parent class that does not have any direct instances is called an abstract class. It is used in the creation of subclasses.

Object Oriented Thinking

Object Oriented Thinking

Let ‘Hari’ be a florist, but florist more specific form of shot keeper. Additionally, a shop keeper is a human and a human is definitely a mammal. But a mammal is an animal & animal is material object.

All these categories along with their relationships can be represented using a graphical technique shown in figure. Each category is regarded as a class. The classes at the top of the tree are said to be more abstract classes and the classes at the bottom of the tree are said to be more specific classes.

Inheritance is a principle, according to which knowledge of a category (or class) which is more general can also be applied to a category which is more specific.

Method Binding:

When the method is super class have same name that of the method in sub class, then the subclass method overridden the super-class method. The program will find out a class to which the reference is actually pointing and that class method will be binded.

E.g.

class parent

{               void print()

{      System.out.println(“From Parent”);

}

}

class  child extends parent

{

void print()

{  System.out.println(“From Child”);

}

}

class  Bind

{

Public static void main(String arg[])

{     child ob=new child();

ob.print();

}

}

o/p:       From Child

The child’s object ‘ob’ will point to child class print() method thus that method will be binded.

Overriding:

When the name and type of the method in a subclass is same as that of a method in its super class. Then it is said that the method present in subclass overrides the method present in super class. Calling an overridden method from a subclass will always point to the type of that method as defined by the subclass, where as the type of method defined by super class is hidden.

E.g. (above ’method binding’ example)

Exceptions:

Exception is a error condition that occurs in the program execution. There is an object called ‘Exception’ object that holds error information. This information includes the type and state of the program when the error occurred.

E.g. Stack overflow, Memory error etc

Summary of OOP concepts (proposed by Alan kay):

  1. Everything is an
  2. Computation is performed by objects communicating with each other, requesting that other objects perform actions. Objects communicate by sending & receiving messages. A message is a request for an action bundled with whatever arguments may be necessary to complete the task.
  3. Each object has its own memory, which consists of other objects.
  4. Every Object is an instance of class. A class simply represents a grouping of similar objects, such as integers or lists.
  5. The class is the repository for behavior associated with an object. That is all objects that are instances of same class can perform the same actions.
  6. Classes are organized into a singly rooted tree structure, called inheritance hierarchy.

Copyng with complexity:

When programs are larger then complex is more programmers found it difficult to remember all the information they needed to know in order to develop or debug their software.

Non-Linear behavior of  complexity:

When projects become larger, a task that can be solved  by a  programmer in 2 months can’t be accomplished by 2 programmers working for one month. The reason for this non-linear behavior is complexity. The inter connections between the software components is complicated. The OOP designers illustrated this with a memorable phrase “The bearing of a child takes nine months, no matter how many women are assigned to the task”

Abstraction Mechanisms:

In general to reduce the complexities in OOP we use abstraction mechanism. Abstraction is the ability to encapsulate, isolate design and execution the information. Object oriented techniques can be seen as a natural  outcome of a long historical progression from procedures, to modules, to abstract datatypes and finally to objects.

Procedures are the functions that allowed tasks to be executed repeatedly. The procedure gave the first possibility for information hiding.

Modules are the independent parts of program. A module provides the ability to divide the program into two parts. The public part is accessible outside the module. The private part is accessible only with in the module.

An abstract data type is a programmer defined datatype that can be manipulated like the system defined datatypes. Objects are instances of a class. Object oriented programming adds several important new ideas. Among them, message passing, inheritance and polymorphism are important. Message passing is the idea that the interpretation of a message can vary with different objects. Inheritance allows different datatypes to share same code, and increase the functionality. Polymorphism allows this shared code to be tailored to fit t he specific circumstances of individual datatypes.