Tuesday, 10 June 2014

JAVA

UNIT-I

Lesson: Object-Oriented Programming Concepts
 This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language.
An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.
A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.
Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.
An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it.

A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. This section explains why this is useful, and introduces you to the Application Programming Interface (API) provided by the Java platform.


 Object Oriented Programming
Since Java is an object oriented programming language it has following features:
  • Reusability of Code
  • Emphasis on data rather than procedure
  •     Data is hidden and cannot be accessed by external functions
  • Objects can communicate with each other through functions
  • New data and functions can be easily addedJava has powerful features.The following are some of them:-

    Simple
    Reusable
    Portable (Platform Independent)
    Distributed
    Robust
    Secure
    High Performance
    Dynamic
    Threaded
    Interpreted
Object Oriented Programming is a method of implementation in which programs are organized as cooperative collection of objects, each of which represents an instance of a class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.
OOP Concepts
Four principles of Object Oriented Programming are
Abstraction
Encapsulation
Inheritance
Polymorphism
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.

Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.
Encapsulation
* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.

Java is Distributed

With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.

Java is Multithreaded

One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.

Java is Secure

Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.

Garbage collection

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.

Java Applications

Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more. This site outlines the building blocks of java by stating few java examplesalong with some java tutorials.

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 virtual Machine (JVM) on whichever platform it is being run.
Java Applets and Applications 

Java can be used to create two types of programs: applications and applets. An application is a program that runs on your computer, under the operating system of that computer. That is , an application created by java is more or less like one created using C or C++. When used to create applications, java is a not much different from any other computer language. Rather, it is java’s ability to create applets that makes it important. An applet is an application designed to be transmitted over the Internet and executed by a java-compatible Web browser. An applet is actually a tiny java program, dynamically downloaded across the network, just like an image, sound file, or video clip. The important difference is that an applet is an intelligent program, not just and animation or media file. In other words, and applet is a program that can react to user input and dynamically change not just run the same animation or sound over and over.

Security

As you are likely aware, every time that you download a “normal ” program, you are risking a viral infection. Prior to java, most users did not download executable programs frequently, and those who did scanned them for viruses prior to execution. Even so, most users still worried about the possibility of infection their systems with a virus. In addition to viruses, another type of maillicious program exists that must be guarded against. This type of program can gather private information, such as credit card numbers, bank account balances, and passwords, by searching the contents of your computer’s local file system, java answer both of these concerns by providing a “firewall” between a networked application and your computer.

Portability

Many types of computers and operating systems are in use throughout the world - and many are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. As you will soon see, the same mechanism that helps ensure security also helps create portability. Indeed, java’s solution to these two problems is both elegant and efficientJava Applets and Applications 

Java can be used to create two types of programs: applications and applets. An application is a program that runs on your computer, under the operating system of that computer. That is , an application created by java is more or less like one created using C or C++. When used to create applications, java is a not much different from any other computer language. Rather, it is java’s ability to create applets that makes it important. An applet is an application designed to be transmitted over the Internet and executed by a java-compatible Web browser. An applet is actually a tiny java program, dynamically downloaded across the network, just like an image, sound file, or video clip. The important difference is that an applet is an intelligent program, not just and animation or media file. In other words, and applet is a program that can react to user input and dynamically change not just run the same animation or sound over and over.

Java History

With Java, Sun Microsystems established the first programming language that wasn’t tied to any particular operating system or microprocessor. 

Applications written in Java will run anywhere, eliminating one of the biggest headaches for computer users: incompatibility between operating systems and versions of operating systems.

The following paragraph will give some information about the history of Java and explain how this programming platform from Sun Microsystems was created. 

Java’s core principles developed out of a desire to build software for consumer electronics. It all started out in 1990 when a team of Sun researchers developed some concepts for a new direction in high-tech, consumer-driven technology. Computers were everywhere and were the driving force behind many of the products in the home: the VCR, the microwave oven, the security system, and the stereo system. 

However, each product required its own interface. In other words, to control three devices, consumers had to have three remote controls and to understand programming for three devices. In addition to the fact that Sun was falling behind on it’s competitors, this was the background for Sun to launch a new project which would later become Java. 

A team code-named Green was formed to work on creating a simple device that controlled a variety of day-to-day electronics products. The team consisted of two programmers; Patrick Naughton and James Gosling, and engineer Mike Sheridan. Gosling realized that what they needed was a new programming language. 

As it was, existing programming languages like C++ had its emphasis on speed, not reliability. In consumer electronics, reliability is more important than speed. As it turned out, Gosling and Naughton managed to bring their work together, and create a new language which they calledOak. This happened in August 1991. A year later, the Green Team had developed a hand-held device with no keyboard, no buttons, and a tiny screen. You touched the screen to turn it on and controlled the action on the screen with a fingertip. This made it possible to program the VCR just by moving your finger along the screen. Still, this technology did not take off. Amongst others the chips were too expensive to manufacture. Ultimately the Green Team was a failure. 

However, Bill Joy, one of the co-founders of Sun, saw an opportunity for Oak in the emergence of the World Wide Web. His idea was to release Java for free over the Internet. By giving your product away for noncommercial use you can make it the standard. The name Oak had to be changed due to the fact it was too close to that of another product. Consequently, Oak was renamed Java in January 1995. 

Today, Joy’s vision of free and accessible technology is a reality. But Sun still needs to make sure that Java becomes the standard; then it needs to figure out how to make money from the product. Selling commercial licenses is one way to go. 

One big step was taken on December 7, 1995, when Microsoft signed a letter of interest with Sun for a Java-technology source license. Additionally, Microsoft agreed to give Sun Microsoft’s reference implementation of the Java virtual machine, and the apple application programming interface (API) for Windows. This deal was important. By integrating Java into its Explorer browse, Microsoft provided Java with a huge base of previously untapped Windows users. In addition, it was a major endorsement form the world’s largest software firm that Sun’s Interment technology is top-notch and goes a long way towards establishing Java as de facto open standard for programming on the Internet.


1.1.JAVA STEP BY STEP
     

January 15, 1991 

"Stealth Project" (as named by Scott McNealy) brainstorming meeting in Aspen with Bill Joy, Andy Bechtolsheim, Wayne Rosing, Mike Sheridan, James Gosling and Patrick Naughton.
February 1, 1991
Gosling, Sheridan, and Naughton begin work in earnest. Naughton focuses on "Aspen" graphics system, Gosling on programming language ideas, Sheridan on business development.
June 1991
Gosling starts working on the "Oak" interpreter, which, several years later (following a trademark search), is renamed "Java."
August 19, 1991
Green team demonstrates basic user interface ideas and graphics system to Sun co-founders Scott McNealy and Bill Joy.
Summer 1992
Massive amounts of hacking on Oak, and related components.
October 1, 1992
Wayne Rosing joins from SunLabs (which had formed in July 1990) and assumes management of the team.
March 15, 1993
The development team, now incorporated as FirstPerson, focuses on interactive television after learning about Time Warner's RFP for its interactive cable TV trial in Orlando, FL.
April, 1993
NCSA Mosaic 1.0, the first graphical browser for the Internet, is released.
June 14, 1993
Time Warner goes with SGI for its interactive cable TV trial, despite acknowledged superiority of Sun technology and assurances in mid-April that Sun won the deal.
Summer, 1993
Naughton flies 300,000 miles selling Oak to anyone involved in consumer electronics and interactive television; meanwhile, the rate at which people are gaining access to the Internet reaches breakneck speed.
August, 1993
After months of promising negotiations with 3DO to provide set-top box OS, 3DO president Trip Hawkins offers to buy the technology outright. McNealy refuses, and deal falls through.
September, 1993
Arthur Van Hoff joins team, originally to do application development environment aimed at interactive television; ends up doing mostly language design.
February 17, 1994 
Alternative FirstPerson business plan for doing CD-ROM/online multimedia platform based on Oak presented to Sun executives to very mixed reviews.
April 25, 1994
Sun Interactive created, half of FirstPerson employees leave to join it.
June, 1994
"Liveoak" project started. Designed by Bill Joy to use Oak for a big small operating system project.
July, 1994
Naughton reduces the "Liveoak" project's scope to simply retargeting Oak at the Internet after writing a throwaway implementation of a Web browser in a long weekend hack.
September 16, 1994
Jonathon Payne and Naughton start writing "WebRunner," a Mosaic-like browser later renamed "HotJava"
September 29, 1994
HotJava prototype is first demonstrated to Sun executives.
Autumn, 1994
Van Hoff implements Java compiler in Java. (Gosling had previously implemented it in C.)
May 23, 1995
Sun formally announces Java and HotJava at SunWorld '95.
May 23, 1995
Netscape announces its intention to license Java for use in Netscape browser.
September 21, 1995
Sun-sponsored Java development conference held in New York City.
September 25, 1995
Sun announces expanded alliance with Toshiba and a joint project to develop remote information retrieval products which incorporate Java.
September 26, 1995
Sunsoft announces suite of business-oriented development products incorporating Java.
October 30, 1995
Oracle announces its WebSystem suite of WWW software which includes a Java-compatible browser.
October 30, 1995
At the Internet World Conference in Boston, Lotus Development Corp., Intuit Inc., Borland International Inc., Macromedia Inc.,and Spyglass Inc. announce plans to license Java.
December 4, 1995
Sun and Netscape announce Javascript, a scripting language based on the Java language which is designed to be accessible to non-programmers.
December 4, 1995
Sun, Netscape and Silicon Graphics announce new software alliance to develop Internet interactivity tools.
December 4, 1995
Borland, Mitsubishi Electronics, Sybase and Symatec annouce plans to license Java.
December 6, 1995
IBM and Adobe announce licensing agreement with Sun for use of Java.
December 7, 1995
Microsoft announces plans to license Java during announcement of suite of new Internet products, including Visual Basic Script.

 FEATURES OF JAVA
Java has many advanced features when compared to other programming languages
 Compiled and Interpreted
 Platform-Independent and Portable
 Object-Oriented
 Robust and Secure
 Distributed
 Familiar, Simple and Small
 Multithreaded and Interactive
 High Performance
Dynamic and Extensible
Compiled and Interpreted: First, Java compiler translates source code into bytecode instructions. Bytecodes are not machine instructions and therefore, in the second stage, Java interpreter generates machine code that can be directly executed by the machine that is running the Java program. We can thus say that Java is both a compiled and an interpreted language.
Platform-Independent and Portable: Java programs can be easily moved from one computer system 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 a popular language for programming on Internet.
Object-Oriented: Java is a true object-oriented language. Almost everything in Java is an object.All program code and data reside within objects and classes. Java comes with an extensive set ofclasses, arranged in packages, that we can use in our programs by inheritance. The object model in Java is simple and easy to extend.
Robust and Secure: Java is a robust language. It provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types and errors. It provides automatic garbage-collection. Java also allows exception handling to catch runtime errors.
               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 cannot gain access to memory locations without proper authorization.
Distributed: Java is designed as a distributed language for creating applications on networks. It has the ability to share both data and programs. Java applications can open and access remote objects on Internet. This enables multiple programmers at remote locations to collaborate and work together on a single project.
Simple, Small and Familiar: Java is a small and simple language. Familiarity is another important feature of Java. To make the language look familiar to the existing programmers, it was modeled on C and C++ languages. Java uses many constructs of C and C++ and therefore, Java code "looks like a C++" code. In fact, Java is a simplified version of C++.
Multithreaded and Interactive: Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded programs; This means that we need not wait for the application to finish one task before beginning another. For example, we can listen to an audio clip while scrolling a page and at the same time download an applet from a distant computer.
High Performance: Java architecture is designed to reduce overheads during runtime. Further, the incorporation of multithreading enhances the overall execution speed of Java programs.
Dynamic and Extensible: Java is a dynamic language. Java is capable of dynamically linking in new class libraries, methods, and objects. Java programs support functions written in other languages such as C and C++. These functions are known as native methods. This facility enables the programmers to use the efficient functions available in these languages.

How the Java Language Differs from C and C++

This lesson contains several independent pages that discuss the differences between the Java language and C and C++.

C Data Types Not Supported By the Java Language

The Java language does not support three data types that are part of the C and C++ languages: struct, union, and pointer.

Operators

There are a few differences in how certain operators in the Java language work as compared to both C and C++.

Java Command Line Arguments Differ from C and C++

The command line arguments passed to a Java application are different in number and in type than those passed to a C or C++ program.

Java Strings are First-Class Objects

In C and C++, strings are simply a null-terminated array of characters. The Java language uses the String class provided in the java.lang package.

Miscellaneous Differences

There are several other minor differences between the C and C++ language and the Java language.
Java is a lot like C but the major difference between Java and C is that Java is an object-oriented language and has mechanism to define classes and objects. In an effort to build a simple and safe; language, the Java team did not include some of the C features in Java.
 Java does not include the C unique statement keywords sizeof, and typedef.
 Java does not contain the data types struct and union.
 Java does not define the type modifiers keywords auto, extern, register, signed, and unsigned,
 Java does not support an explicit pointer type.
 Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdefstatements.
 Java requires that the functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C.
 Java adds new operators such as instanceof and >>>.
 Java adds labelled break and continue statements.
 Java does not have “goto” control structure.
 Java adds many features required for object-oriented programming.

Java and Internet: Java is strongly associated with the Internet. Internet users can use Java to create applet programs and run them locally using a "Java-enabled browser" such as HotJava. They can also use a Java-enabled browser to download an applet located on a computer anywhere in the Internet and run it on his local computer. In fact, Java applets have made the Internet a true extension of the storage system of the local computer.
Internet users can also setup their websites containing java applets that could be used by other remote users of Internet. This feature made Java most popular programming language for Internet.
Java and World Wide Web: World Wide Web (WWW) is an open-ended information retrieval system designed to be used in the Internet's distributed environment. This system contains Web pages that provide both information and controls. Web system is open-ended and we can navigate to a new document in any direction. This is made possible with the help of a language calledHypertext Markup Language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide.
Java was meant to be used in distributed environments such as Internet. Since, both the Web and Java share the same philosophy, Java could be easily incorporated into the Web system. Before Java, the World Wide Web was limited to the display of still images and texts. However, the incorporation of Java into Web pages has made it capable of supporting animation, graphics, games, and a wide range of special effects.
OOP is one of the programming buzzwords today. Applications of OOP are beginning to gain importance in many areas. The most popular application of object-oriented programming, up to now, has been in the area of user interface design such as windows. There are hundreds of window-based systems developed using OOP techniques.
Real-business systems are often much more complex and contain many more objects with complicated attributes and methods. OOP is useful in this type of applications because it can simplify a complex problem. The different areas for application of OOP include:
 Real-time systems
 Simulation and modeling
 Object-oriented databases
 Hypertext, hypermedia
 AI and Expert systems
 Neural networks and parallel programming
 Decision support and office automation systems
 CIM/CAD/CAM systems

Why java is important to the Internet

The Internet helped catapult java to the forefront of programming, and java, in turn, has had a profound effect on the Internet. The reason for this is quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a network, two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you read your e-mail, you are viewing passive data. Even when you download a program, the program’s code is still only passive data. Even when you download a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is and the server yet initiates active agent on the client computer. For example, the server to display properly the data that the server is sending might provide a program.

As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Prior to java, cyberspace was effectively closed to half the entities that now live there, as you will see, java addresses those concerns and, by doing so, has opened the door to an exciting new form of program: the applet.

Simple
Java program

A Java program is a collection of one or more java classes. A Java source file can contain more than one class definition and has a .java extension. Each class definition in a source file is compiled into a separate class file. The name of this compiled file is comprised of the name of the class with .class as an extension. Before we proceed further in this section, I would recommend you to go through the ‘Basic Language Elements’.
Below is a java sample code for the traditional Hello World program. Basically, the idea behind this Hello World program is to learn how to create a program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.
public class HelloWorld {
               public static void main(String[] args) {
                               System.out.println("Hello World");
               }//End of main
}//End of HelloWorld Class

Output
Hello World
ABOUT THE PROGRAM
I created a class named “HelloWorld” containing a simple main function within it. The keyword class specifies that we are defining a class. The name of a public class is spelled exactly as the name of the file (Case Sensitive). All java programs begin execution with the method named main(). main method that gets executed has the following signature : public static void main(String args[]).Declaring this method as public means that it is accessible from outside the class so that the JVM can find it when it looks for the program to start it. It is necessary that the method is declared with return type void (i.e. no arguments are returned from the method). The main method contains a String argument array that can contain the command line arguments. The brackets { and } mark the beginning and ending of the class. The program contains a line ‘System.out.println(“Hello World”);’ that tells the computer to print out on one line of text namely ‘Hello World’. The semi-colon ‘;’ ends the line of code. The double slashes ‘//’ are used for comments that can be used to describe what a source code is doing. Everything to the right of the slashes on the same line does not get compiled, as they are simply the comments in a program.
Java Main method Declarations
class MainExample1 {public static void main(String[] args) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}
All the 3 valid main method’s shown above accepts a single String array argument. 

Compiling and Running an Application

To compile and run the program you need the JDK distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools. Download an editor like Textpad/EditPlus to type your code. You must save your source code with a .java extension. The name of the file must be the name of the public class contained in the file.
Steps for Saving, compiling and Running a Java
Step 1:Save the program With .java Extension.
Step 2:Compile the file from DOS prompt by typing javac <filename>.
Step 3:Successful Compilation, results in creation of .class containing byte code
Step 4:Execute the file by typing java <filename without extension>


Java Virtual Machine

What is the Java Virtual Machine? What  is its role?
Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called ajust-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can run on that platform.
The Java environment is composed of a number of system components. You use these components at compile time to create the Java program and at run time to execute the program. Java achieves its independence by creating programs designed to run on the Java Virtual Machine rather than any specific computer system.
  • After you write a Java program, you use a compiler that reads the statements in the program and translates them into a machine independent format called bytecode.
  • Bytecode files, which are very compact, are easily transported through a distributed system like the Internet.
  • The compiled Java code (resulting byte code) will be executed at run time.
Java programs can be written and executed in two ways:

  • Stand-alone application (A Java Swing Application)
  • Applet which runs on a web browser (Example: Internet Explorer)

No comments:

Post a Comment