# How to write Bresenham’s line algorithm in Java Applet

In this post we will learn how to draw Bresenham’s line drawing algorithm in Java Applet.

Let’s see why we use Bresenham’s when we already have DDA line algorithm:-

**Advantages of bresenham’s line drawing algorithm:-**

The Bresenham line algorithm has the following advantages:

– An fast incremental algorithm

– Uses only integer calculations

The Bresenham algorithm is another incremental scan conversion algorithm

Here is the code for the Bresenham Line Drawing Algorithm-

## Program: Bresenham’s Line Drawing Algorithm in Java Applet

The rest of the explanation of the code is the same as I explained in DDA Line drawing algorithm article. Moreover, feel free to write comments if you have any problems understanding the code or the algorithm or if any correction is required.

package computergraphics; import java.io.*; import java.awt.*; import java.applet.*; import java.util.*; import java.awt.image.*; public class Bresenham extends Applet { BufferedImage image = new BufferedImage(800, 800, BufferedImage.TYPE_INT_ARGB); WritableRaster raster = image.getRaster(); int array[] = {255, 0, 0, 255}; public void init() { setSize(300, 200); repaint(); } public void paint(Graphics g) { int dx, dy, x, y, k; int x1 = 50, y1 = 50, x2 = 200, y2 = 180; dx = x2 - x1; dy = y2 - y1; int p0 = 2 * dy - dx, p1; x = x1; y = y1; raster.setPixel(x, y, array); System.out.println("k = 0 : " + x + " " + y); for(k = 1; k <= dx; k++) { if(p0 < 0) { p1 = p0 + (2 * dy); x++; } else { p1 = p0 + (2 * dy) - (2 * dx); x++; y++; } raster.setPixel(x, y, array); System.out.println("k = " + k + " : " + x + " " + y); } g.drawImage(image, 0, 0, null); } }

Output: The output will be an applet viewer with a line drawn between the co-ordinates given in the code. Use Shift+F6 in NetBeans to easily run the above code. Do change the package name with yours.

There is no main method in this program.