Java is a programming language released by Sun Microsystems.

Java is a widely used programming language expressly designed for use in the distributed environment of the internet. Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications. The Java is an object-oriented programming language.

Java Programming Language:

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.

Java is:

  • Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
  • Platform Independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
  • Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.
  • Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
  • Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.
  • Portable: Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.
  • Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.
  • Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.
  • High Performance: With the use of Just-In-Time compilers, Java enables high performance.
  • Distributed: Java is designed for the distributed environment of the internet.
  • Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

History of Java:

James Gosling initiated Java language project in June 1991 for use in one of his many settop box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java's core code free and opensource, aside from a small portion of code to which Sun did not hold the copyright.

Writing graphics applications  in Java using  Swing can be  quite a daunting experience which requires understanding of some large libraries, and fairly advanced aspects of Java. In a graphical system,  a  windowing  toolkit  is  usually  responsible  for  providing  a  framework  to  make  it relatively painless for a graphical user interface (GUI) to render the right bits to the screen at the right time. Both the AWT (abstract windowing toolkit) and Swing provide such a framework.  In this report, we designed and developed a simple painter project used to enable a user to draw any shape and any integrated graphic with  any color using FreeHand (move the  mouse using your hand to draw any shape and specify the coordinate in JPanel). Several tools such as Undo and  Redo  process,  Clear JPanel,  Set Background  Color &  set Foreground  Color, Save  paint (Panel) to  file ( *.  JPG; *. GIF;   *.* ), and  Open paint from  image file are  considered. The purpose of this blog is to give you practice with graphical user interface programming in Java. This blog implemented using the components from Java's awt and swing library in the Java programming language (NetBenas IDE7.2.1). As the final result of our project is enabling you to use FreeHand to draw as an easy way to draw the Circle, Line, Rectangle, Square, and Oval, and integrated graphics such as a car, a street, a football stadium, traffic signals and others.

Introduction :

Java  is  a  general-purpose,  concurrent,  class-based,  object-oriented  computer  programming language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java applications are typically compiled  to byte  code (class file)  that can  run on  any Java virtual machine  (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users [1][2].  Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.

Java can be used to write applications and applets. A Java application is similar to any other high-level language program: It can only be compiled and then run on the same machine. An applet is  compiled on  one machine,  stored on a  server in  binary, and  can be sent  to another machine over the Internet to be interpreted by a Java-aware browser. Java comes with a large library of ready-made classes and objects. The key difference between Java 1.0 and 1.1 was in this library. Similarly, Java 2.0 has a very much larger library for handling user interfaces (Swing by name) but only small changes to the core of the language.

The Fetch and Execute Cycle: Machine Language

A computer is a complex system consisting of many different components. But at the heart—or the brain, if you want—of the computer is a single component that does the actual computing. This is the Central Processing Unit, or CPU. In a modern desktop computer, the CPU is a single “chip” on the order of one square inch in size. The job of the CPU is to execute programs.

A program is simply a list of unambiguous instructions meant to be followed mechanically by a computer. A computer is built to carry out instructions that are written in a very simple type of language called machine language. Each type of computer has its own machine language, and the computer can directly execute a program only if the program is expressed in that language. (It can execute programs written in other languages if they are first translated into machine language.)

When the CPU executes a program, that program is stored in the computer’s main memory (also called the RAM or random access memory). In addition to the program, memory can also hold data that is being used or processed by the program. Main memory consists of a sequence of locations. These locations are numbered, and the sequence number of a location is called its address. An address provides a way of picking out one particular piece of information from among the millions stored in memory. When the CPU needs to access the program instruction or data in a particular location, it sends the address of that information as a signal to the memory; the memory responds by sending back the data contained in the specified location. The CPU can also store information in memory by specifying the information to be stored and the address of the location where it is to be stored.

On the level of machine language, the operation of the CPU is fairly straightforward (although it is very complicated in detail). The CPU executes a program that is stored as a sequence of machine language instructions in main memory. It does this by repeatedly reading, or fetching, an instruction from memory and then carrying out, or executing, that instruction. This process—fetch an instruction, execute it, fetch another instruction, execute it, and so on forever—is called the fetch-and-execute cycle. With one exception, which will be covered in the next section, this is all that the CPU ever does.

The details of the fetch-and-execute cycle are not terribly important, but there are a few basic things you should know. The CPU contains a few internal registers, which are small memory units capable of holding a single number or machine language instruction. The CPU uses one of these registers—the program counter, or PC—to keep track of where it is in the program it is executing. The PC stores the address of the next instruction that the CPU should execute. At the beginning of each fetch-and-execute cycle, the CPU checks the PC to see whic instruction it should fetch. During the course of the fetch-and-execute cycle, the number in the PC is updated to indicate the instruction that is to be executed in the next cycle. (Usually, but not always, this is just the instruction that sequentially follows the current instruction in the program.)

A computer executes machine language programs mechanically—that is without understanding them or thinking about them—simply because of the way it is physically put together. This is not an easy concept. A computer is a machine built of millions of tiny switches called transistors, which have the property that they can be wired together in such a way that an output from one switch can turn another switch on or off. As a computer computes, these switches turn each other on or off in a pattern determined both by the way they are wired together and by the program that the computer is executing.

Machine language instructions are expressed as binary numbers. A binary number is made up of just two possible digits, zero and one. So, a machine language instruction is just a sequence of zeros and ones. Each particular sequence encodes some particular instruction. The data that the computer manipulates is also encoded as binary numbers. A computer can work directly with binary numbers because switches can readily represent such numbers: Turn the switch on to represent a one; turn it off to represent a zero. Machine language instructions are stored in memory as patterns of switches turned on or off. When a machine language instruction is loaded into the CPU, all that happens is that certain switches are turned on or off in the pattern that encodes that particular instruction. The CPU is built to respond to this pattern by executing the instruction it encodes; it does this simply because of the way all the other switches in the CPU are wired together.

So, you should understand this much about how computers work: Main memory holds machine language programs and data. These are encoded as binary numbers. The CPU fetches machine language instructions from memory one after another and executes them. It does this mechanically, without thinking about or understanding what it does—and therefore the program it executes must be perfect, complete in all details, and unambiguous because the CPU can do nothing but execute it exactly as written.

Asynchronous Events: Polling Loops and Interrupts

The CPU spends almost all of its time fetching instructions from memory and executing them. However, the CPU and main memory are only two out of many components in a real computer system. A complete system contains other devices such as:

  • A hard disk for storing programs and data files. (Note that main memory holds only a comparatively small amount of information, and holds it only as long as the power is turned on. A hard disk is necessary for permanent storage of larger amounts of information, but programs have to be loaded from disk into main memory before they can actually be executed.)
  • A keyboard and mouse for user input.
  • A monitor and printer which can be used to display the computer’s output.
  • A modem that allows the computer to communicate with other computers over telephone lines.
  • A network interface that allows the computer to communicate with other computers that are connected to it on a network.
  • A scanner that converts images into coded binary numbers that can be stored and manipulated on the computer.

The list of devices is entirely open ended, and computer systems are built so that they can easily be expanded by adding new devices. Somehow the CPU has to communicate with and control all these devices. The CPU can only do this by executing machine language instructions (which is all it can do, period). The way this works is that for each device in a system, there is a device driver, which consists of software that the CPU executes when it has to deal with the device. Installing a new device on a system generally has two steps: plugging the device physically into the computer, and installing the device driver software. Without the device driver, the actual physical device would be useless, since the CPU would not be able to communicate with it.

A computer system consisting of many devices is typically organized by connecting those devices to one or more busses. A bus is a set of wires that carry various sorts of information between the devices connected to those wires. The wires carry data, addresses, and control signals. An address directs the data to a particular device and perhaps to a particular register or location within that device. Control signals can be used, for example, by one device to alert another that data is available for it on the data bus.

Now, devices such as keyboard, mouse, and network interface can produce input that needs to be processed by the CPU. How does the CPU know that the data is there? One simple idea, which turns out to be not very satisfactory, is for the CPU to keep checking for incoming data over and over. Whenever it finds data, it processes it. This method is called polling, since the CPU polls the input devices continually to see whether they have any input data to report.

Unfortunately, although polling is very simple, it is also very inefficient. The CPU can waste an awful lot of time just waiting for input. To avoid this inefficiency, interrupts are often used instead of polling. An interrupt is a signal sent by another device to the CPU. The CPU responds to an interrupt signal by putting aside whatever it is doing in order to respond to the interrupt. Once it has handled the interrupt, it returns to what it was doing before the interrupt occurred. For example, when you press a key on your computer keyboard, a keyboard interrupt is sent to the CPU. The CPU responds to this signal by interrupting what it is doing, reading the key that you pressed, processing it, and then returning to the task it was performing before you pressed the key.

Again, you should understand that this is a purely mechanical process: A device signals an interrupt simply by turning on a wire. The CPU is built so that when that wire is turned on, the CPU saves enough information about what it is currently doing so that it can return to the same state later. This information consists of the contents of important internal registers such as the program counter. Then the CPU jumps to some predetermined memory location and begins executing the instructions stored there. Those instructions make up an interrupt handler that does the processing necessary to respond to the interrupt. (This interrupt handler is part of the device driver software for the device that signalled the interrupt.) At the end of the interrupt handler is an instruction that tells the CPU to jump back to what it was doing; it does that by restoring its previously saved state.

Interrupts allow the CPU to deal with asynchronous events. In the regular fetch-andexecute cycle, things happen in a predetermined order; everything that happens is “synchronized” with everything else. Interrupts make it possible for the CPU to deal efficiently with events that happen “asynchronously,” that is, at unpredictable times. As another example of how interrupts are used, consider what happens when the CPU needs to access data that is stored on the hard disk. The CPU can access data directly only if it is in main memory. Data on the disk has to be copied into memory before it can be accessed.

Unfortunately, on the scale of speed at which the CPU operates, the disk drive is extremely slow. When the CPU needs data from the disk, it sends a signal to the disk drive telling it to locate the data and get it ready. (This signal is sent synchronously, under the control of a regular program.) Then, instead of just waiting the long and unpredictalble amount of time that the disk drive will take to do this, the CPU goes on with some other task. When the disk drive has the data ready, it sends an interrupt signal to the CPU. The interrupt handler can then read the requested data.

Now, you might have noticed that all this only makes sense if the CPU actually has several tasks to perform. If it has nothing better to do, it might as well spend its time polling for input or waiting for disk drive operations to complete. All modern computers use multitasking to perform several tasks at once. Some computers can be used by several people at once. Since the CPU is so fast, it can quickly switch its attention from one user to another, devoting a fraction of a second to each user in turn. This application of multitasking is called timesharing. But a modern personal computer with just a single user also uses multitasking. For example, the user might be typing a paper while a clock is continuously displaying the time and a file is being downloaded over the network.

  • Each of the individual tasks that the CPU is working on is called a thread. (Or a process; there are technical differences between threads and processes, but they are not important here.) At any given time, only one thread can actually be executed by a CPU. The CPU will continue running the same thread until one of several things happens:
  • The thread might voluntarily yield control, to give other threads a chance to run.
  • The thread might have to wait for some asynchronous event to occur. For example, the thread might request some data from the disk drive, or it might wait for the user to press a key. While it is waiting, the thread is said to be blocked, and other threads have a chance to run. When the event occurs, an interrupt will “wake up” the thread so that it can continue running.
  • The thread might use up its allotted slice of time and be suspended to allow other threads to run. Not all computers can “forcibly” suspend a thread in this way; those that can are said to use preemptive multitasking. To do preemptive multitasking, a computer needs a special timer device that generates an interrupt at regular intervals, such as 100 times per second.

 When a timer interrupt occurs, the CPU has a chance to switch from one thread to another, whether the thread that is currently running likes it or not. Ordinary users, and indeed ordinary programmers, have no need to deal with interrupts and interrupt handlers. They can concentrate on the different tasks or threads that they want the computer to perform; the details of how the computer manages to get all those tasks done are not important to them. In fact, most users, and many programmers, can ignore threads and multitasking altogether. However, threads have become increasingly important as computers have become more powerful and as they have begun to make more use of multitasking. Indeed, threads are built into the Java programming language as a fundamental programming concept.

Just as important in Java and in modern programming in general is the basic concept of asynchronous events. While programmers don’t actually deal with interrupts directly, they do often find themselves writing event handlers, which, like interrupt handlers, are called asynchronously when specified events occur. Such “event-driven programming” has a very different feel from the more traditional straight-through, synchronous programming. We will begin with the more traditional type of programming, which is still used for programming individual tasks, but we will return to threads and events later in the text.

By the way, the software that does all the interrupt handling and the communication with the user and with hardware devices is called the operating system. The operating system is the basic, essential software without which a computer would not be able to function. Other programs, such as word processors and World Wide Web browsers, are dependent upon the operating system. Common operating systems include Linux, DOS, Windows 2000, Windows XP, and the Macintosh OS.

The Java Virtual Machine

Machine language consists of very simple instructions that can be executed directly by the CPU of a computer. Almost all programs, though, are written in high-level programming languages such as Java, Pascal, or C++. A program written in a high-level language cannot be run directly on any computer. First, it has to be translated into machine language. This translation can be done by a program called a compiler. A compiler takes a high-level-language program and translates it into an executable machine-language program. Once the translation is done, the machine-language program can be run any number of times, but of course it can only be run on one type of computer (since each type of computer has its own individual machine language). If the program is to run on another type of computer it has to be re-translated, using a different compiler, into the appropriate machine language.

There is an alternative to compiling a high-level language program. Instead of using a compiler, which translates the program all at once, you can use an interpreter, which translates it instruction-by-instruction, as necessary. An interpreter is a program that acts much like a CPU, with a kind of fetch-and-execute cycle. In order to execute a program, the interpreter runs in a loop in which it repeatedly reads one instruction from the program, decides what is necessary to carry out that instruction, and then performs the appropriate machine-language commands to do so.

One use of interpreters is to execute high-level language programs. For example, the programming language Lisp is usually executed by an interpreter rather than a compiler. However, interpreters have another purpose: they can let you use a machine-language program meant for one type of computer on a completely different type of computer. For example, there is a program called “Virtual PC” that runs on Macintosh computers. Virtual PC is an interpreter that executes machine-language programs written for IBM-PC-clone computers. If you run Virtual PC on your Macintosh, you can run any PC program, including programs written for Windows. (Unfortunately, a PC program will run much more slowly than it would on an actual IBM clone.

The problem is that Virtual PC executes several Macintosh machine-language instructions for each PC machine-language instruction in the program it is interpreting. Compiled programs are inherently faster than interpreted programs.) The designers of Java chose to use a combination of compilation and interpretation. Programs written in Java are compiled into machine language, but it is a machine language for a computer that doesn’t really exist. This so-called “virtual” computer is known as the Java virtual machine. The machine language for the Java virtual machine is called Java bytecode. There is no reason why Java bytecode could not be used as the machine language of a real computer, rather than a virtual computer.

However, one of the main selling points of Java is that it can actually be used on any computer. All that the computer needs is an interpreter for Java bytecode. Such an interpreter simulates the Java virtual machine in the same way that Virtual PC simulates a PC computer. Of course, a different Jave bytecode interpreter is needed for each type of computer, but once a computer has a Java bytecode interpreter, it can run any Java bytecode program.

Object-oriented Programming:

Java supports object-oriented programming techniques that are based on a hierarchy of classes and well-defined and cooperating objects.

Classes: A class is a structure that defines the data and the methods to work on that data. When you write programs in Java, all program data is wrapped in a class, whether it is a class you write or a class you use from the Java API libraries. Classes in the Java API libraries define a set of objects that share a common structure and behavior.

Objects: An instance is a synonym for object. A newly created instance has data members and methods as defined by the class for that instance.

Well-Defined Boundaries and Cooperation: Class definitions must allow objects to cooperate during execution.

Inheritance and Polymorphism:  One object-oriented concept that helps objects work together is inheritance.  Inheritance defines  relationships among classes in an object-oriented  language. The relationship  is one  of parent  to child  where the  child or  extending  class inherits  all the attributes  (methods  and  data)  of  the  parent  class.  In  Java,  all  classes  descend  from java.lang.Object and inherit its methods. Figure 1 shows the class hierarchy as it descends from java.lang.Objectfor the classes in the user interface example above. The java.lang.Objectmethods are also shown  because they are  inherited and implemented by all  of its subclasses, which  is every class in the Java API libraries. java.lang.Objectdefines the core set of behaviors that all classes have in common.

The Basic GUI (graphical user interface ) Application

There are  two basic  types of GUI  program in  Java [5]:  stand-alone applications  and (online) applets.  An  applet  is a  program  that  runs in  a rectangular  area on  a Web page.  Applets  are generally small  programs, meant  to do fairly simple things, although there  is nothing to  stop them from  being very complex. A GUI program  offers a  much richer type  of user interface, where the user uses a mouse and keyboard to interact with GUI components such as windows, menus, buttons, check boxes, text input boxes, scroll bars, and so on.

JFrame  and  JPanel:  In  a  Java  GUI  program,  each  GUI  component  in  the  interface  is represented by an object in the program. One of the most fundamental types of component is the window. Windows have many behaviors. They can be opened and closed. They can be resized.

They have “titles” that are displayed in the title bar above the window. And most important, they can contain other GUI components such as buttons and  menus. Java, of course, has a built-in class to represent windows. There are actually several different types of window, but the most common type is represented by the JFrame class (which is included in the package javax.swing).

A  JFrame  is an  independent window  that  can, for  example, act  as  the  main window  of an application. One of the most important things to understand is that a JFrame object comes with many of  the behaviors of  windows already programmed  in. In particular, we  has one Jframe “InterfaceForm” that contents all the components, which enables the user to work on our system easily and draw any shape in Panel and the ability to be opened and closed.

JPanel is another  of the fundamental classes in Swing.  The basic JPanel is,  again, just  a blank  rectangle.  There  are  two  ways  to  make  a  useful  JPanel  :  The  first  is  to  add  other components to the panel; the second is to draw something in the panel. Both of these techniques are illustrated in our sample project. In fact, you will find JPanel in the program: content, display Panel, which is used as a drawing surface.
Components  and  Layout:  Another  way  of  using  a JPanel  is  as  a  container  to  hold  other components. In our project, we used NetBeans IDE 7.2.1 to create all components in JFrame and JPanel.

Events  and  Listeners:  The  structure  of  containers  and  components  sets  up  the  physical appearance of a GUI, but it doesn’t say anything about how the GUI behaves. That is, what can the user  do to  the GUI  and how  will it  respond? GUIs  are largely event-driven; that  is, the program waits for events that are generated by the user’s actions (or by some other cause). When an  event occurs,  the  program  responds by  executing  an  event-handling  method.  In order  to program the behavior  of a GUI,  you have to  write event-handling methods  to respond to the events that you are interested in. The most common technique for handling events in Java is to use event listeners. A listener is  an object that includes one or more event-handling methods. When an event is  detected by another object, such as a button or menu, the listener object is notified and it responds by running the appropriate event-handling method. An event is detected or generated by an object. Another object, the listener, has the responsibility of responding to the event. The event itself is actually represented by a third object, which carries information about the type of event, when it occurred, and so on. This division of responsibilities makes it easier to 6  organize  large  programs.  As an  example,  consider  the Undo or  Redo  button  in  our sample program. When the user clicks the button, an event is generated.

Graphics and Painting:

Everything you see on a computer screen has to be drawn there, even the text. The (online)  Java API includes a range of classes and methods that are devoted to drawing. In this section, I’ll look at some of the most basic of these that helping us to achieve our project. The physical structure of a GUI is built of components. The term component refers to a visual element in a GUI, including buttons, menus, text-input boxes, scroll bars, check boxes, and so on.

In  Java,  GUI  components  are  represented  by  objects  belonging  to  subclasses  of  the  class java.awt.Component.  In  a  graphical  system,  a  windowing  toolkit  is  usually  responsible  for providing a  framework to  make it  relatively painless  for a  graphical user  interface (GUI)  to render the right bits to the screen at the right time.  Both the AWT (abstract windowing toolkit) and Swing provide such a framework. But the APIs that implement it are not well understood by some developers -- a problem that has led to programs not performing as well as they could.

In order to use graphics in Java programs, there are a number of libraries we need to import. For the sake of what will be covered in these notes, you need the following statements:

import javax.swing.JFrame;

import javax.swing.JPanel;

import java.awt.Graphics;

import java.awt.geom.

* import java.awt.Color;

import javax.swing.JLabel;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;

import java.awt.BorderLayout;

import java.awt.event.*;

import java.awt.image.BufferedImage;

import java.awt.image.MemoryImageSource;

import java.awt.image.PixelGrabber;

import java.io.File; import java.io.IOException;

import javax.imageio.*;

Overview of the Java 2D API Concepts

The Java 2D™  API provides two-dimensional graphics, text, and imaging capabilities for Java™  programs  through  extensions  to  the  Abstract  Windowing  Toolkit  (AWT).  This comprehensive rendering package supports line art, text, and images in a flexible, full-featured framework  for  developing richer  user interfaces,  sophisticated  drawing  programs,  and image editors. Java 2D objects exist on a plane called user coordinate space, or just user space. When objects are rendered on a screen or a printer, user space coordinates are transformed to device space coordinates. The following links are useful to start learning about the Java 2D API:

  • Graphics class
  • Graphics2D class

The Java 2D API provides following capabilities:

  • A uniform rendering model for display devices and printers
  • A wide range of geometric primitives, such as curves, rectangles, and ellipses, as well as a mechanism for rendering virtually any geometric shape
  • Mechanisms for performing hit detection on shapes, text, and images 
  • A compositing model that provides control over how overlapping objects are rendered
  • Enhanced color support that facilitates color management
  • Support for printing complex documents
  • Control of the quality of the rendering through the use of rendering hints

Coordinates

The Java 2D API maintains two coordinate spaces:

  • User space – The space in which graphics primitives are specified
  • Device space – The coordinate system of an output device such as a screen, window, or a printer.

The screen of a computer is a grid of little squares called pixels. The color of each pixel can be set individually, and drawing on the screen just means setting the  colors of individual  pixels. When the default transformation from user space to device space is used, the origin of user space is the upper-left corner of the component’s drawing area. The x coordinate increases to the right and the y coordinate increases downward, as shown in the following figure. The top-left corner of a  window is  0,0. All  coordinates are  specified using  integers, which  is usually  sufficient. However, some cases require floating point or even double precision which are also supported.

A graphics context draws in a rectangle made up of pixels. A position in the rectangle is specified by  a  pair  of  integer  coordinates,  (x,y).  The  upper  left  corner  has  coordinates  (0,0).  The  x coordinate increases from left to right, and the y coordinate increases from top to bottom. The illustration shows a 16-by-10 pixel component (with very large pixels). A small line, rectangle, and oval are shown as they would be drawn by coloring individual pixels. (Note that, properly speaking, the coordinates don’t belong to the pixels but to the grid lines between them.)  For any component, you can find out the size of the rectangle that it occupies by calling the  instance methods  getWidth()  and  getHeight(),  which  return  the  number of  pixels  in  the horizontal and vertical directions, respectively.

Fundamental Building Blocks of Programs

There are two basic aspects of programming: data and instructions. To work with data, you need to understand variables and types; to work with instructions, you need to understand control structures and subroutines. You’ll spend a large part of the course becoming familiar with these concepts. A variable is just a memory location (or several locations treated as a unit) that has been given a name so that it can be easily referred to and used in a program. The programmer only has to worry about the name; it is the compiler’s responsibility to keep track of the memory location. The programmer does need to keep in mind that the name refers to a kind of “box” in memory that can hold data, even if the programmer doesn’t have to know where in memory that box is located.

In Java and most other languages, a variable has a type that indicates what sort of data it can hold. One type of variable might hold integers—whole numbers such as 3, -7, and 0— while another holds floating point numbers—numbers with decimal points such as 3.14, -2.7, or 17.0. (Yes, the computer does make a distinction between the integer 17 and the floatingpoint number 17.0; they actually look quite different inside the computer.) There could also be types for individual characters (’A’, ’;’, etc.), strings (“Hello”, “A string can include many characters”, etc.), and less common types such as dates, colors, sounds, or any other type of data that a program might need to store.

Programming languages always have commands for getting data into and out of variables and for doing computations with data. For example, the following “assignment statement,” which might appear in a Java program, tells the computer to take the number stored in the variable named “principal”, multiply that number by 0.07, and then store the result in the variable named “interest”:

interest = principal * 0.07;

There are also “input commands” for getting data from the user or from files on the computer’s disks and “output commands” for sending data in the other direction. These basic commands—for moving data from place to place and for performing computations—are the building blocks for all programs. These building blocks are combined into complex programs using control structures and subroutines.

A program is a sequence of instructions. In the ordinary “flow of control,” the computer executes the instructions in the sequence in which they appear, one after the other. However, this is obviously very limited: the computer would soon run out of instructions to execute. Control structures are special instructions that can change the flow of control. There are two basic types of control structure: loops, which allow a sequence of instructions to be repeated over and over, and branches, which allow the computer to decide between two or more different courses of action by testing conditions that occur as the program is running. For example, it might be that if the value of the variable “principal” is greater than 10000, then the “interest” should be computed by multiplying the principal by 0.05; if not, then the interest should be computed by multiplying the principal by 0.04. A program needs some way of expressing this type of decision. In Java, it could be expressed using the following “if statement”:

if (principal > 10000)

interest = principal * 0.05;

else

interest = principal * 0.04;

Loops are used when the same task has to be performed more than once. For example, if you want to print out a mailing label for each name on a mailing list, you might say, “Get the first name and address and print the label; get the second name and address and print the label; get the third name and address and print the label—” But this quickly becomes ridiculous—and might not work at all if you don’t know in advance how many names there are. What you would like to say is something like “While there are more names to process, get the next name and address, and print the label.” A loop can be used in a program to express such repetition.

Large programs are so complex that it would be almost impossible to write them if there were not some way to break them up into manageable “chunks.” Subroutines provide one way to do this. A subroutine consists of the instructions for performing some task, grouped together as a unit and given a name. That name can then be used as a substitute for the whole set of instructions. For example, suppose that one of the tasks that your program needs to perform  is to draw a house on the screen. You can take the necessary instructions, make them into a subroutine, and give that subroutine some appropriate name—say, “drawHouse()”. Then anyplace in your program where you need to draw a house, you can do so with the single command:

drawHouse();

This will have the same effect as repeating all the house-drawing instructions in each place. The advantage here is not just that you save typing. Organizing your program into subroutines also helps you organize your thinking and your program design effort. While writing the house-drawing subroutine, you can concentrate on the problem of drawing a house without worrying for the moment about the rest of the program. And once the subroutine is written, you can forget about the details of drawing houses—that problem is solved, since you have a subroutine to do it for you. A subroutine becomes just like a built-in part of the language which you can use without thinking about the details of what goes on “inside” the subroutine. Variables, types, loops, branches, and subroutines are the basis of what might be called “traditional programming.” However, as programs become larger, additional structure is needed to help deal with their complexity.

Java PDF Viewer

The Viewer available with the PDF library can be added to the Report Generator as well, giving you the ability to rasterize and display PDFs as well as create them. See the PDF Library page for more details on the viewer.

Tools You Will Need

For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended). You will also need the following softwares:

  • Linux 7.1 or Windows xp/7/8 operating system
  • Java JDK 8
  • Microsoft Notepad or any other text editor

This tutorial will provide the necessary skills to create GUI, networking, and web applications using Java.

Java - Environment Setup

You really do not need to set up your own environment to start learning Java programming language. Reason is very simple, we already have Java Programming environment setup online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.

Try the following example using Try it option available at the top right corner of the following sample code box:

public class MyFirstJavaProgram {

public static void main(String []args) {

System.out.println("Hello World");

}

}

Local Environment Setup

If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Following are the steps to set up the environment.

Java SE is freely available from the link Download Java. You can download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you installed Java on your machine, you will need to set environment variables to point to correct installation directories:

Setting Up the Path for Windows

Assuming you have installed Java in c:\Program Files\java\jdk directory:

  • Right-click on 'My Computer' and select 'Properties'.
  • Click the 'Environment variables' button under the 'Advanced' tab.
  • Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation, if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

Popular Java Editors

To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
  • Netbeans: A Java IDE that is open-source and free, which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: A Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/.

Java – Basic Syntax

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

  • Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
  • Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
  • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program

Let us look at a simple code that will print the words Hello World.

public class MyFirstJavaProgram {

/* This is my first java program.

* This will print 'Hello World' as the output

*/

public static void main(String []args) {

System.out.println("Hello World"); // prints Hello World

}

}

Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps:

  • Open notepad and add the code as above.
  • Save the file as: MyFirstJavaProgram.java.
  • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
  • Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
  • Now, type ' java MyFirstJavaProgram ' to run your program.
  • You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java

C:\> java MyFirstJavaProgram

Hello World

Basic Syntax

About Java programs, it is very important to keep in mind the following points.

  • Case Sensitivity - Java is case sensitive, which means identifier Helloand hello would have different meaning in Java.
  • Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example: class MyFirstJavaClass
  • Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example: public void myMethodName()
  • Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
  • public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program.

Java Identifiers

All Java components require names. Names used for classes, variables, and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows:

  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
  • After the first character, identifiers can have any combination of characters.
  • A key word cannot be used as an identifier.
  • Most importantly, identifiers are case sensitive.
  • Examples of legal identifiers: age, $salary, _value, __1_value.
  • Examples of illegal identifiers: 123abc, -salary.

Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:

  • Access Modifiers: default, public , protected, private
  • Non-access Modifiers: final, abstract, strictfp

Java Variables

Following are the types of variables in Java:

  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static Variables)

Java Arrays

Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap.

Java Enums

Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. With the use of enums it is possible to reduce the number of bugs in your code. For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.

class FreshJuice {

enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }

FreshJuiceSize size;

}

public class FreshJuiceTest {

public static void main(String args[]){

FreshJuice juice = new FreshJuice();

juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;

System.out.println("Size: " + juice.size);

}

}

The above example will produce the following result:

Size: MEDIUM

Comments in Java

Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.

public class MyFirstJavaProgram{

/* This is my first java program.

* This will print 'Hello World' as the output

* This is an example of multi-line comments.

*/

public static void main(String []args){

// This is an example of single line comment

/* This is also an example of single line comment. */

System.out.println("Hello World")

}

}

Using Blank Lines

A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.

Inheritance

In Java, classes can be derived from classes. Basically, if you need to create a new class  and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code. This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.

Interfaces

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

Objects in Java

Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running. If you compare the software object with a real-world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

Classes in Java

A class is a blueprint from which individual objects are created. Following is a sample of a class.

public class Dog{

String breed;

int ageC

String color;

void barking(){

}

void hungry(){

}

void sleeping(){

}

}

A class can contain any of the following variable types.

  • Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
  • Instance variables: Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • Class variables: Class variables are variables declared within a class, outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods. Following are some of the important topics that need to be discussed when looking into classes of the Java Language.

Constructors

When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor. Following is an example of a constructor:

public class Puppy{

public Puppy(){

}

public Puppy(String name){

// This constructor has one parameter, name.

}

}

Java also supports Singleton Classes where you would be able to create only one instance of a class.

How to Use Singleton Class?

The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.

For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

Implementing Singletons

Example 1

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance(). The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance −

// File Name: Singleton.java

public class Singleton {

private static Singleton singleton = new Singleton( );

/* A private Constructor prevents any other

* class from instantiating.

*/

private Singleton(){ }

/* Static 'instance' method */

public static Singleton getInstance( ) {

return singleton;

}

/* Other methods protected by singleton-ness */

protected static void demoMethod( ) {

System.out.println("demoMethod for singleton");

}

}

Here is the main program file, where we will create a singleton object:

// File Name: SingletonDemo.java

public class SingletonDemo {

public static void main(String[] args) {

Singleton tmp = Singleton.getInstance( );

tmp.demoMethod( );

}

}

This will produce the following result −

demoMethod for singleton

Example 2

Following implementation shows a classic Singleton design pattern:

public class ClassicSingleton {

private static ClassicSingleton instance = null;

private ClassicSingleton() {

// Exists only to defeat instantiation.

}

public static ClassicSingleton getInstance() {

if(instance == null) {

instance = new ClassicSingleton();

}

return instance;

} }

The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method. Here, ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.

Creating an Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects. There are three steps when creating an object from a class:

  • Declaration: A variable declaration with a variable name with an object type.
  • Instantiation: The 'new' keyword is used to create the object.
  • Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

AccessingInstance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path:

/* First create an object */

ObjectReference = new Constructor();

/* Now call a variable as follows */

ObjectReference.variableName;

/* Now you can call a class method as follows */

ObjectReference.MethodName();

Source File Declaration Rules

As the last part of this section, let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.

  • There can be only one public class per source file.
  • A source file can have multiple non-public classes.
  • The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java.
  • If the class is defined inside a package, then the package statement should be the first statement in the source file.
  • If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file.
  • Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.
  • Classes have several access levels and there are different types of classes; abstract
  • classes, final classes, etc. Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.

Pros and Cons of Java | Advantages and Disadvantages of Java

Advantages of Java

There are some major advantages of Java; let’s see them.

  • Simple: Java is straightforward to use, write, compile, debug, and learn than alternative programming languages. Java is less complicated than C++; as a result, Java uses automatic memory allocation and garbage collection.
  • Object-Oriented: It permits you to form standard programs and reusable code.
  • Platform-Independent: Java code runs on any machine that doesn’t need any special software to be installed, but the JVM needs to be present on the machine.
  • Distributed computing: Distributed computing involves several computers on a network working together. It helps in developing applications on networks that can contribute to both data and application functionality.
  • Secure: Java has no explicit pointer. Apart from this, it has a security manager that defines the access of classes.
  • Memory allocation: In Java, memory is divided into two parts one is heap and another is stack. Whenever we declare a variable JVM gives memory from either stack or heap space. It helps to keep the information and restore it easily.
  • Multithreaded: It has the potential for a program to perform many tasks at the same time.

Disadvantages of Java

Performance: Java is memory-consuming and significantly slower than natively compiled languages such as C or C++.

Look and Feel: The default look of GUI applications written in Java using the Swing toolkit is very different from native applications.

Single-Paradigm Language: Static imports were added in Java 5.0. The procedural paradigm is better accommodated than in earlier versions of Java.

Memory Management: In Java, Memory is managed through garbage collection, whenever the garbage collector runs, it affects the performance of the application. This is because all other threads in the have to be stopped to allow the garbage collector thread to work.