This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA
My Java applet says: 6: <APPLET CODE="SimpleJavaApplet.class" WIDTH=150 HEIGHT=25><APPLET> 7: 8: You refer to an applet in your HTML files with the <APPLET> tag. You'll learn more about <APPLET> later on, but here are two things to note: • •
Use the CODE attribute to indicate the name of the class that contains your applet. Use the WIDTH and HEIGHT attributes to indicate the size of the applet. The browser uses these values to know how big a chunk of space to leave for the applet on the page. Here, a box 150 pixels wide and 25 pixels high is created.
Save the HTML file in your HTML directory, with a descriptive name (for example, you might name your HTML file the same name as your applet – SimpleJavaApplet.html). And now, you're ready for the final test – actually viewing the result of your applet. To view the applet, you need one of the following: • •
browser that supports Java applets, such as Netscape 2.0 and above. The appletviewer application, which is part of the JDK. The appletviewer is not a Web browser and won't enable you to see the entire Web page, but it's acceptable for testing to see how an applet will look and behave if there is nothing else available.
If you don't have a Web browser with Java capabilities built into it, you can use the appletviewer program to view your Java applet. To run appletviewer, just indicate the path to the HTML file on the command line: appletviewer HTML/SimpleJavaApplet.html Tip: Although you can start appletviewer from the same directory as your HTML and class files, you may not be able to reload that applet without quitting appletviewer first. If you start appletviewer from some other directory (as in the previous command line), you can modify and recompile your Java applets and then just use the Reload menu item to view the newer version. Java's strengths lie in its portability—both at the source and at the binary level, in its object-oriented design—and in its simplicity. Each of these features help make applets possible, but they also make Java an excellent language for writing more generalpurpose programs that do not require HotJava or other Java-capable browser to run. I guess from here, you now have the foundation to create more complex applications and applets.
Statements & Expressions In the last few articles, we saw how to create an applet and an application in Java. Now lets get into the basics of Java, that is the conditional statements that are used in Java. They form the core of any programming language, because the various conditional loops in a program enable it to work the way we want it to. A statement is the simplest thing you can do in Java; a statement forms a single Java operation. All the following are simple Java statements: int i = 1; import java.awt.Font; System.out.println("This car is a "+ color + " " + make); m.engineState = true; Statements sometimes return values—for example, when you multiply two numbers together or test to see whether one value is equal to another. These kind of statements
are called expressions. Always remember that a Java statement always ends with a semicolon. Forget the semicolon and your Java program won't compile. Java also has compound statements, or blocks, which can be placed wherever a single statement can. Block statements are surrounded by braces ({}). Variables and Data Types Variables are locations in memory in which values can be stored. They have a name, a type, and a value. Before you can use a variable, you have to declare it. Variables in short are just like the lockers in a bank. Each locker has a number, a size and a key. In order to use a locker to keep your valuables, you have to tell the bank, so that its officially yours and you have the privacy. Same is the case with variables. After variable is declared, you can then assign values to it. Similarly as soon as the bank assigns us a locker, we store valuables like will, agreement or jewelry in it. Java actually has three kinds of variables: • • •
instance variables, class variables, and local variables.
Instance variables are used to define attributes or the state for a particular object. Class variables are similar to instance variables, except their values apply to all that class's instances (and to the class itself) rather than having different values for each object. Local variables are declared and used inside method definitions, for example, for index counters in loops, as temporary variables, or to hold values that you need only inside the method definition itself. They can also be used inside blocks ({}) . Once the method (or block) finishes executing, the variable definition and its value cease to exist. Use local variables to store information needed by a single method and instance variables to store information needed by multiple methods in the object. Although all three kinds of variables are declared in much same ways, class and instance variables are accessed and assigned in slightly different ways from local variables. Now lets focus on variables as used within method definitions, later lets learn how to deal with instance and class variables. Unlike other languages, Java does not have global variables (like C)—that is, variables that are global to all parts of a program. Instance and class variables can be used to communicate global information between and among objects.
Remember, Java is an object-oriented language, so you should think in terms of objects and how they interact, rather than in terms of programs. In my next article i will give you a briefer insight into how to declare variables.
Declaring Variables In the last article we saw what exactly are the statements and expressions and how they are written. We also saw as to what are three kinds of variables used in Java like instance variables, class variables, and local variables. Lets now see as to how to declare a variable and what are the various variable types. To use any variable in a Java program, you must first declare it. Variable declarations consist of a type and a variable name: int myAge; String myName; boolean isTired; Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go), although they are most commonly declared at the beginning of the definition before they are used: public static void main (String args[ ] ) { int count; String title;the boolean isAsleep; ... } You can string together variable names with the same type: int x, y, z; String firstName, LastName; You can also give each variable an initial value when you declare it: int myAge, mySize, numShoes = 28;
String myName = "Laura"; boolean isTired = true; int a = 4, b = 5, c = 6; If there are multiple variables on the same line with only one initializer (as in the first of the previous examples), the initial value applies to only the last variable in a declaration. You can also group individual variables and initializers on the same line using commas, as with the last example, above. Local variables must be given values before they can be used (your Java program will not compile if you try to use an unassigned local variable). For this reason, it's a good idea always to give local variables initial values. Instance and class variable definitions do not have this restriction (their initial value depends on the type of the variable: null for instances of classes, 0 for numeric variables, '\0' for characters, and false for booleans). Points on Variable Names • • • • •
Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($). They cannot start with a number. After the first character, your variable names can include any letter or number. Symbols, such as %, *, @, and so on, are often reserved for operators in Java, so be careful when using symbols in variable names. In addition, the Java language uses the Unicode character set. Unicode is a character set definition that not only offers characters in the standard ASCII character set, but also several million other characters for representing most international alphabets.
Java language is case-sensitive, which means that uppercase letters are different from lowercase letters. This means that the variable X is different from the variable x, and a pen is not a Pen is not a PEN. Keep this in mind as you write your own Java programs and as you read Java code other people have written. By convention, Java variables have meaningful names, often made up of several words combined. The first word is lowercase, but all following words have an initial uppercase letter: Button theButton; long reallyBigNumber; boolean currentWeatherStateOfPlanetXShortVersion; Variable Types In addition to the variable name, each variable declaration must have a type, which defines what values that variable can hold. The variable type can be one of three things:
•
• •
One of the eight basic primitive data types - The eight primitive data types handle common types for integers, floating-point numbers, characters, and boolean values (true or false). They're called primitive because they're built into the system and are not actual objects, which makes them more efficient to use. Note that these data types are machine-independent, which means that you can rely on their sizes and characteristics to be consistent across your Java programs. The name of a class or interface An array
There are four Java integer types, each with a different range of values (as listed in Table A below). All are signed, which means they can hold either positive or negative numbers. Which type you choose for your variables depends on the range of values you expect that variable to hold; if a value becomes too big for the variable type, it is silently truncated. Table A Integer types. Type Size Range byte 8 bits —128 to 127 short 16 bits —32,768 to 32,767 int 32 bits —2,147,483,648 to 2,147,483,647 long 64 bits —9223372036854775808 to 9223372036854775807 Floating-point numbers are used for numbers with a decimal part. Java floating-point numbers are compliant with IEEE 754 (an international standard for defining floatingpoint numbers and arithmetic). There are two floating-point types: float (32 bits, singleprecision) and double (64 bits, double-precision). The char type is used for individual characters. Because Java uses the Unicode character set, the char type has 16 bits of precision, unsigned. Finally, the boolean type can have one of two values, true or false. Note that unlike in other C-like languages, boolean is not a number, nor can it be treated as one. All tests of boolean variables should test for true or false. In addition to the eight basic data types, variables in Java can also be declared to hold an instance of a particular class: String LastName; Font basicFont; OvalShape myOval;
Each of these variables can then hold only instances of the given class. As you create new classes, you can declare variables to hold instances of those classes (and their subclasses) as well. Remember that Java does not have a typedef statement (as in C and C++). To declare new types in Java, you declare a new class; then variables can be declared to be of that class's type. In the next article we will see as to how to assign values to variables.
Variables and Strings In the last article we saw how to assigning values to variables and their respective ranges. Lets try to learn more on variables and strings. Use of variables is a key to efficient coding in any programming language. Variable declaration , if not done properly, can lead to many debugging errors. Variable Assignment and Initialization • •
Once you have declared the type of a variable, you are free to initialize it and assign to it some value. Assignment and initialization works just as they did in Perl. You simply use variable name = some value. For example, consider the following code: int marks; marks = 66;
•
Of course you can also declare variables and assign values to them at the same time using the following syntax: int marks = 66;
Casting (Changing from one type to another) • • •
What if you want to multiply 3 x 1.5,Or say, int x double? Will the result be an int or a double or something else? Well, when in doubt, Java will convert to the less restrictive type to be safe. Thus, in the above example, the result will be a double since double is less restrictive. The following chart shows how types will be caste if possible. byte --> short --> int --> long --> float --> double
•
However, what if you are going the other way? Suppose you have two doubles and you want to make an int out of the product
•
To do this type of caste, you simply perform an assignment using the type to be casted to in parentheses before the value to be casted. Consider the following example in which we caste from a double to an int: double d = 345.456; int i = (int) d;
•
In this case, it will be assigned a value of "345".
Strings: • • •
In Java, there is no variable type called string. However, although Java does not have a built-in String type, it does provide you will a predefined class called String which you can use instead. I'll talk more about classes and using them in later articles. However, it would be nice to at least introduce the String class here so we can use it in the meantime. To instantiate a String, you simply use the same syntax that you would if it were a type: String s = "Hello Learner";
•
Strings have quite a few methods which allow you to manipulate them in every way that you could in Perl. To read about these methods, simply use the online documentation on java found on the SUN site.
In the later weeks, I will write in more about the intricacies that form an integral structure of the JAVA language. Currently I am doing a project with JAVA as the Front End and I learnt, the more you work in any programming language, the more you learn.
Arrays and Overloading in Java In the last article, we dealt with strings, variable initializations and castings. This week lets have a look at the array feature of java and also on a special feature called Operator Overloading. Arrays in Java • •
• •
Java has a built in array class which you can use to hold multiple values provided those values are of the same data type. In Java, arrays are much more restrictive. For example, you may not change the size of an array once you have created it. To add elements to an array dynamically you actually have to create a new, larger array and copy the old array into the new one using array Copy() in the java.lang.System class. For a dynamically resizable data structure, look to the Vector class in the java.utilpackage. However, for cases in which you do not need to dynamically resize your data structure, arrays work great. Java provides a zero-based array, which is defined much as variables are. You first declare what type of data will be stored in an array, give the array a name, and then define how large it is. Consider the following example:
int[] intArray = new int[40]; This array would hold 40 ints numbered from 0-39. •
Filling and extracting values from an array is the same process as it was for Perl. Consider the following example: int[] intArray = new int[40]; for (int i = 0; i < 40; i++) { intArray[i] = i; } for (int i = 0; i < 40; i++) { System.out.println("Value: " + intArray[i]); }
•
•
•
Java also allows you to define an array at time of initialization such as in the following example: int[] intArray = {0,1,2,3,4}; Operator Overloading Another cool feature of Java is that methods in Java can easily be overloaded such that the same method name can be used for several different implementations of the same action. For example printNumber(), printLetter(), printImage() are the various methods that can be used for several different implementations of the same action. The only requirement for overloading is that each version of the method takes a different set of parameters as arguments (sometimes, we say that it has a "different signature") such as in the following example: int add(int a, int b) { return (a+b); } float add(float a, float b) { return (a+b); }
•
Finally, it is worth noting that since methods belong to specific classes, it is fine for you to have the same method name with the same arguments in different classes. Thus, the Button class might have a setLabel(String s) method and a Label might have a setLabel(String s) method and neither will conflict since each method is specific to a specific class.
Java virtual machine: Sun Microsystems’s Java Virtual Machine is one of the best-known examples of application virtual machine. In this article we will discuss about Java Virtual Machine and how it works. As we know java has come up as powerful computer programming language, which has got its own benefits over conventional languages. Main advantage of java programming language is platform independence, which means any application written in java can be operated on any of the platform, instead of having to produce separate versions of the application for each computer and operating system. Now the question arises how it's possible for a Java application to run on many different machines? From the figure given below you can get the flow of java program execution.
1. Java Programmer writes Java Program 2. Java Compiler generates the byte code that corresponds to the instructions in the program 3. The JVM interprets the stream of bye code and executes the instructions. 4. The System receives instruction from JVM and displays desired output.
The key to Java's portability and security is the Java Virtual Machine on which java relies, because of this simulated machine computer programmer does not communicate with system, in turn it it directly communicates with virtual machine, in this way programmer utilizes functions that are built into the JVM and not the operating system. JVM does not have any information regarding the programming language. It knows only the binary format of the byte code. The java compiler from which you compile java program does not produce native executable code for a particular machine like C compiler would do. Instead it produces a special format called byte code, in other words byte code can be thought of as the machine language for JVM. The JVM interprets a stream of byte-codes as a sequence of instructions and then execute to produce desired output. JVM depends on operating system, it must have a possible mapping for its instruction on every operating system or machine that it is installed in order to work. Once the byte-codes are interpreted by the JVM the instructions are mapped to the instructions in the operating system or on the hardware. JVM actually uses operating system and machine instructions to carry out the instructions it has been given. It is possible that the instruction which JVM has can be carry out by one operating system and while with another it is not. This is one of the reason why Java has not achieved 100% portability. The main purpose of the Java Virtual Machine is to solve the problem with creating portable computer programs. The question which still comes to the mind does the JVM completely solved the problem and made Java 100% portable? The answer is no. It does not completely solve the problem, there is no doubt that it has provided a good solution that is most part effective but not 100% effective. Java has still achieved a relatively high degree of portability. Java has allowed people to develop many cross-platform applications and has proven to be useful and powerful interpretation of a virtual machine.
"Java" – Man, Not Again "Java" - Man! Not again … it's a little too much to take in a lifetime of that thing. You are reading this article on the web, and that makes me confident that you are aware of this word, which suddenly from being in a state of "some word" in the dictionary became the buzzword of the IT industry in the last 4-5 years. Come with me on a short ride to where it all started and what it is all about. It is not only for the tech-savvy software engineers and the "Geeks", as the common parlance is for these folks who put in everything they have to get it out in the best form: A solution for a
system that is robust, platform independent, optimized for high-performance and yet, simple with little or least maintenance. Patrick Naughton along with James Gosling and a group of engineers at Sun Microsystems, Inc. were interested in designing a small computer language that could be used for consumer devices like cable TV switchboxes. Given the lack of memory capacity and also as these devices as short on power, the language needed to be very small and generate very very tight code. To accommodate different Central Processing Units (CPUs), they knew they could not tie themselves down to any single architecture. The project got the code name "green". The requirement for small, tight code led the team to resurrect the model that a language, called UCSD Pascal, tried in the early days of PCs and that Niklaus Wirth had pioneered earlier. The idea was to design a portable language that generated intermediate code for hypothetical machine (often called virtual machines). These could then be used on any machine that had the correct interpreter. Since both the code and its interpreter could be really small, the main issue of size was solved. Sun and its people are from Unix background, hence they based their language on C++ rather than Pascal. So for common parlance, the idea was to make it object-oriented and not procedure-oriented. Gosling (presumably loving the way the Oak tree outside his window looked at Sun) named his language "Oak". For him: "All along, the language was a tool, and not the end". "*7", was the result and outcome of the efforts of the team and it came out in 1992. This was an extremely intelligent remote control. (Had the power of a SPARCstation in a box that was 6" by 4" by 4"). Unfortunately no one was interested in producing this at Sun and from here started the first battle to sell the technology out to someone. The Green Project (now christened as "First Person, Inc.") spent all of 1993 and a quite a fair amount of 1994 to look for a customer ready to buy the technology. Patrick Naughton had accumulated 300,000 miles trying to market and sell the technology. First Person was dissolved in 1994. While all of this was on at SMI, Internet was getting bigger, bigger and bigger. Suddenly the man called Marc Andreessen, an undergraduate student on a work-project at University of Illinois, working for $6.85 an hour came into worldwide existence. "Mosaic" - partially written by him, was the most commonly used web-browser. The language developers at SMI realized that they could come up with a real cool browser and so they did. Naughton and Jonathan Payne built the actual browser and it evolved into HotJava Browser. It was written in Java to show off it's capabilities and the power of what we now refer to as "applets": to do so, the browser was capable of interpreting the intermediate bytecodes. This "proof of technology" exhibited at SunWorld in 1995 (May 23, 1995), started the craze in the IT world the fan following that even Michael, Madonna or Monroe probably could not in their fields in such a short span of time. January 1996, Netscape 2.0 was released, Java enabled. And from then on everyone followed suit. Microsoft was not to be left behind, though did not follow the general consensus, like always, and came up with their own implementation.
First version of Java was released by Sun Microsystems, in 1996 followed by 1.02 just after about a couple of months. It failed on the big screen. Java 1.02 was not ready for prime time yet. It became clear in JavaOne conference that year what Sun really had in mind for Java and also came out with a clear vision for future. It took almost two years from then on to get it out to perform and deliver what they had started it out for, "write once, run anywhere". Release of Java 1.2 in 1998 JavaOne conference was the biggest news. It was amazing, though people were still skeptical, how in such a short a span of time much had been incorporated, from an early toy-like GUI and graphics toolkits it had been developed into sophisticated and scalable versions. Like it is always said: the more your brew, the better and stronger it gets. Java, had finally arrived…
Common Misconceptions About Java So, we now know how long it took and what all it took to come out in the way it is right now. Once it was out there and the frenzy growing, there was bound to be some misinterpretations, some misconceptions and some "I can't believe its". Lets take a quick look at some misconceptions: • • • • •
An extension of html Just another, "easy" programming language Actually, a universal language for all platforms Darn slow for serious applications on a specific platform Applets - oops! Security Issue
An extension of html I would often hear some three-four years ago that Java was an extension of HTML. Java and HTML are far from being anything close to each other. HTML is a scripting language, it describes the layout, structure and presentation of a web page and Java on the other hand, a programming language. The only common factor between the two is there are HTML extensions for placing Java "applets" on a web page. Just another "easy" programming language Whatever might be the general notion about computer programming, it is not an easy run-of-the-mill task. One needs a special aptitude to do it. Now, do not get me wrong, I am not saying it is rocket science: but you have to understand writing code for fun is different than serious application programming expected to perform in a particular fashion. Java is not as "easy" programming languages, as many perceive. You may not be required to know all functions and constants listed in the Java Application Programming User's Guide, yet you would need some basic ones to put it to real work.
Actually, a universal language for all platforms Could well become a reality, and most of the vendors want this to happen but for Bill Gates' pride. Many applications like word-processors, photo-editors, web browsers already are working perfectly on desktops using the advantage of the speed of the processor and the native user-interface library and well, have been ported to all of the 'important' platforms anyway. Darn slow for serious applications on a specific platform Whatever the language be, no matter what kind of application, it usually takes time to decipher and detect a mouse-click, one of the user-interface interactions. As a matter of fact, many programs spend most of their time on things like mouse-clicks. To prevent such a thing with applications written in Java, something called JIT (just in time) compiler was brought into being. On many operating systems JIT is available, and now all you need is run the bytecodes through it and boom! Most of the performance issues are gone. For computationally intensive work such as encryption, given its ability to keep up with the data rate of a network connection, Java is great for network-bound programs. It does not matter whether C++ is faster, fact is Java is easier to program (no pointers to handle) than C++ and definitely, portable. Applets - OOPS! Security Issue "Applets - Man they are such a big security issue, they are vulnerable to attacks." Where? On what? How? - Probably on one specific browser that has had its own vulnerabilities and failures. When you have a section of researchers trying just to find flaws and to defy the strength and sophistication of the applet security model, you are bound to have reports of failures in the Java security system. No doubt when something as big as Java arrives on the scene, it is got to be controversial for a while and definitely negatives are publicized. Change is the only thing constant, yet so difficult to acknowledge. Right? I, as a professional person having a first hand experience of Java and the other "widely used" technologies can assure you there never was ever even one application or system compromised. And I will not get into how many of virus attacks, literally millions, are carried out on great and widely used applications like email tools, word processors, and the most wonderful of all "macros". Do we need publicize the abuse through active-x controls that can be achieved? Matter is, it is so apparent that we don't even bother to go there. A'ight fellas, this is it for now and though there are many more myths like Java eliminates the need for CGI scripting; with Java one can replace a computer with an Internet appliance; I guess I am going to try to explain you more about what Java is and can do rather than tell you what it is not and what it cannot do. Fair enough I guess. So until next time… when we get Java-ized again…
http://www.boloji.com/computing/ccplus/index.htm