Java Application

  • November 2019
  • PDF

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


Overview

Download & View Java Application as PDF for free.

More details

  • Words: 9,417
  • Pages: 25
JAVA: A Beginner's Guide Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end Unix workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level. The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices-television sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java's goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. It is those same goals that made Java an ideal language for distributing executable programs via the World Wide Web, and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms. This is the major reason why Java is said to be the most successful platform independent language. Java as a language has significant advantages over other languages and other programming environments that make it suitable for just about any programming task. Some of them are listed below: Applets Applets appear in a Web page much in the same way as images do, but unlike images, applets are dynamic and interactive. Applets can be used to create animations, figures, or areas that can respond to input from the reader, games, or other interactive effects on the same Web pages among the text and graphics. Java enabled browsers can successfully run applets and thus give a truly rich experience at the user end. Platform Independence Platform independence is one of the most significant advantages that Java has over other programming languages, particularly for systems that need to work on many different platforms. Java is platform-independent at both the source and the binary level. Platform-independence is a program's capability of moving easily from one computer system to another. Java binary files called byte-codes are also platform-independent and can run on multiple platforms without the need to recompile the source. Byte-codes are a set of instructions that look a lot like machine code, but are not specific to any one processor. Because of them, compilation happens just once; interpretation occurs each time the program is executed. Java byte-codes help make "write once, run anywhere" possible. Simplicity In addition to its portability and object-orientation, one of Java's initial design goals was to be small and simple, and therefore easier to write, easier to compile, easier to debug, and, best of all, easy to learn. Keeping the language small also makes it more robust because there are fewer chances for programmers to make difficult-to-find mistakes. Despite its size and simple design, however, Java still has a great deal of power and flexibility.

Better Cousin of C, C++ Java is modeled after C and C++, and much of the syntax and object-oriented structure is borrowed from the latter. If you are familiar with C++, learning Java will be particularly easy for you, because you have most of the foundation already. Although Java looks similar to C and C++, most of the more complex parts of those languages have been excluded from Java, making the language simpler without sacrificing much of its power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real objects in Java. Memory management is automatic. To an experienced programmer, these omissions may be difficult to get used to, but to beginners or programmers who have worked in other languages; they make the Java language far easier to learn. Object Oriented Programming Java is object-oriented programming (OOP) technique, which is merely a way of organizing programs for creating flexible, modular programs and reusing code. . Like most object-oriented programming languages, Java includes a set of class libraries that provide basic data types, system input and output capabilities, and other utility functions. Because these class libraries are written in Java, they are portable across platforms as all Java applications are. Applets and Applications The most common types of programs written in the Java programming language are applets and applications. If you've surfed the Web, you're probably already familiar with applets. An applet is a program that adheres to certain conventions that allow it to run within a Java-enabled browser. An application is a standalone program that runs directly on the Java platform. A special kind of application known as a server serves and supports clients on a network. Examples of servers are Web servers, proxy servers, mail servers, and print servers. Another specialized program is a servlet. A servlet can almost be thought of as an applet that runs on the server side. Java Servlets are a popular choice for building interactive web applications, replacing the use of CGI scripts. Servlets are similar to applets in that they are runtime extensions of applications. Instead of working in browsers, though, servlets run within Java Web servers, configuring or tailoring the server. Full implementation of the Java platform provides the essentials like objects, strings, threads, numbers, input and output, data structures, system properties, date and time. Both, low and high level security, including electronic signatures, public and private key management, access control, and certificates are provided by java platform. Networking management, Java Database Connectivity (JDBC), Remote Method Invocation (RMI) are some of the other features of Java. In my next article I will focus on the object oriented programming concepts. Java isn’t all that tough as the various training institutes advertise. A good written matter on Java and lots of practice on your Java Development Toolkit (JDK) is all that you need to become a Java pro.

OOPS This article is going to explain the object-oriented programming (commonly called OOPS) concepts used in languages like C++ and Java. OOP's concepts have simplified programming like never before. Basically one can write programs in two ways: One way is the process-oriented model, where the programs are written in steps of code. C language uses this approach, and as the programs become lengthy, the code gets more complex. Other way is the object-oriented programming (OOP) way. OOP organizes a program around its data (also called objects) and a set of well-defined interfaces to that data. An object-oriented program can be called as a data controlling access to code. Abstraction is an essential element for this, which manages the complexity. In a sense, when someone works on a computer, not necessary that he should know the working of each and every part of the computer. Even without the hardware knowledge, he can email, type or do other jobs on the computer. Thus people do not think of a computer as a unit made up of hundreds of cards and chips, but as a well-defined object with its own unique behavior. This is the advantage of abstraction. Object-oriented programming is modeled on how, in the real world, objects are often made up of many kinds of smaller objects. This capability of combining objects, however, is only one very general aspect of object-oriented programming. The Three Oops Concepts: 1) Encapsulation: It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data. In Java, the basis of encapsulation is the class. A class defines the structure and behavior (data and code) that will be shared by a set of objects. Each object of a given class contains the structure and behavior defined by the class, as if it were stamped out of a mold in the shape of a class. A class is a logical construct, an object has physical reality. When you create a class, you will specify the code and data that will constitute that class. Collectively, these elements are called the members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods, which define the use of the member variables. Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be marked public or private. The private methods and data can only be accessed by the code, that is a member of the class. The public method has all details

essential for external users. 2) Inheritance: It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors. 3) Polymorphism: It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation. In general polymorphism means "one interface, multiple methods", This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation. On the lighter side, extending this analogy to a dog, its sense of smell is polymorphic. If the dog smells a cat, it will bark and run around it. If the dog smells its food, it will salivate and run to its bowl. Note that the same sense of smell is at work in both the cases. The difference is what is being smelled, that is, the type of data being operated upon by the dog's nose! – Deepak Chandrasekaran April 9, 2001

Objects and Classes This time I will focus on one of the most important basics of JAVA. Object and classes are the bricks and mortar used to build JAVA. Object-oriented programming is modeled on how, in the real world, objects are often made up of many kinds of smaller objects. This capability of combining objects, however, is only one very general aspect of objectoriented programming. Object-oriented programming provides several other concepts and features to make creating and using objects easier and more flexible, and the most important of these features is that of classes. A class is a template for multiple objects with similar features. Classes embody all the features of a particular set of objects. When you write a program in an object-oriented language, you don't define actual objects. You define classes of objects. For example, you might have a Tree class that describes the features of all trees (has leaves and roots, grows, creates chlorophyll). The Tree class serves as an abstract model for the concept of a tree-to reach out and grab, or interact with, or cut down a tree you have to have a concrete instance of that tree. Of course, once you have a tree class,

you can create lots of different instances of that tree, and each different tree instance can have different features (short, tall, bushy, drops leaves in Autumn), while still behaving like and being immediately recognizable as a tree. An instance of a class is another word for an actual object. If class is the general representation of an object, an instance is its concrete representation. So what, precisely, is the difference between an instance and an object? Nothing, really. Object is the more general term, but both instances and objects are the concrete representation of a class. In fact, the terms instance and object are often used interchangeably in OOP language. An instance of a tree and a tree object are both the same thing. In an example closer to the sort of things you might want to do in Java programming, you might create a class for the user interface element called a button. The Button class defines the features of a button (its label, its size, its appearance) and how it behaves (does it need a single click or a double click to activate it, does it change color when it's clicked, what does it do when it's activated?). Once you define the Button class, you can then easily create instances of that button-that is, button objects-that all take on the basic features of the button as defined by the class, but may have different appearances and behavior based on what you want that particular button to do. By creating a Button class, you don't have to keep rewriting the code for each individual button you want to use in your program, and you can reuse the Button class to create different kinds of buttons as you need them in this program and in other programs. Tip: If you're used to programming in C, you can think of a class as sort of creating a new composite data type by using struct and typedef. Classes, however, can provide much more than just a collection of data, as you'll discover in the rest of today's lesson. When you write a Java program, you design and construct a set of classes. Then, when your program runs, instances of those classes are created and discarded as needed. Your task, as a Java programmer, is to create the right set of classes to accomplish what your program needs to accomplish. Fortunately, you don't have to start from the very beginning: the Java environment comes with a library of classes that implement a lot of the basic behavior you need-not only for basic programming tasks (classes to provide basic math functions, arrays, strings, and so on), but also for graphics and networking behavior. In many cases, the Java class libraries may be enough so that all you have to do in your Java program is create a single class that uses the standard class libraries. For complicated Java programs, you may have to create a whole set of classes with defined interactions between them. Class library is a set of classes. Behavior and Attributes Every class you write in Java is generally made up of two components: attributes and behavior. In this section, you'll learn about each one as it applies to a theoretical class called car . Attributes

Attributes are the individual things that differentiate one object from another and determine the appearance, state, or other qualities of that object. Let's create a theoretical class called car. The attributes of a car might include the following: Color: red, green, silver, brown Style: E-class, family purpose, utility vehicle Make: Honda, BMW, HYUNDAI Attributes of an object can also include information about its state; for example, you could have features for engine condition (off or on) or current gear selected. Attributes are defined by variables; in fact, you can consider them analogous to "global" variables for the entire object. Because each instance of a class can have different values for its variables, each variable is called an instance variable. Instance variables define the attributes of an object. The class defines the type of the attribute, and each instance stores its own value for that attribute. Each attribute, as the term is used here, has a single corresponding instance variable; changing the value of a variable changes the attribute of that object. Instance variables may be set when an object is created and stay constant throughout the life of the object, or they may be able to change at will as the program runs. In addition to instance variables, there are also class variables, which apply to the class itself and to all its instances. Unlike instance variables, whose values are stored in the instance, class variables' values are stored in the class itself. Behavior A class's behavior determines what instances of that class do to change their internal state changes or when that instance is asked to do something by another class or object. Behavior is the only way objects can do anything to themselves or have anything done to them. For example, to go back to the theoretical car class, here are some behaviors that the car class might have: Start the engine Stop the engine Speed up Change gear Stall To define an object's behavior, you create methods, which look and behave just like functions in other languages, but are defined inside a class. Java does not have functions defined outside classes (as C++ does). Methods are functions defined inside classes that operate on instances of those classes. Methods don't always affect only a single object; objects communicate with each other using methods as well. A class or object can call methods in another class or object to communicate changes in the environment or to ask that object to change its state.

Just as there are instance and class variables, there are also instance and class methods. Instance methods (which are so common they're usually just called methods) apply and operate on an instance of a class; class methods apply and operate on the class itself. You'll learn more about class methods later on in my forthcoming articles.

First Java Application So if you are a keen follower of this section of mine, u might now be well versatile with Object Oriented Programming Concepts and Objects and Classes in Java. This week is going to be more interactive for you. This is because you are going to create your own JAVA application. Java programs fall into two main groups: Applets and Applications. Applets, as you may have experienced, are Java programs that are downloaded over the World Wide Web and executed by a Web browser on the reader's machine. Applets depend on a Java-capable browser in order to run (although they can also be viewed using a tool called the applet viewer) Java applications are more general programs written in the Java language. Java applications don't require a browser to run, and in fact, Java can be used to create all the kinds of applications that you would normally use a more conventional programming language to create. HotJava itself is a Java application. A single Java program can be an applet or an application or both, depending on how you write that program and the capabilities that program uses. Throughout this article, you'll be writing mostly applications; then you'll apply what you've learned to write applets in the later articles. If you're eager to get started with applets, be patient. Everything that you learn while you're creating simple Java applications will apply to creating applets, and it's easier to start with the basics before moving onto the hard stuff. Creating a Java Application Let's start by creating a simple Java application. As with all programming languages, your Java source files are created in a plain text editor, or in an editor that can save files in plain ASCII without any formatting characters. On Unix, emacs, pico, or vi will work; on Windows, Notepad or DOS Edit are both text editors. Fire up your editor of choice, and enter the Java program shown in List a. Type this program, as shown, in your text editor. Be careful that all the parentheses, braces, and quotes are there. List a) Your first Java application:

1) /* 2) This is a simple Java program 3) Call this file "Demo.java". 4) */ 5) class Example{ 6) //Your program begins with a call to main( ). 7) Public static void main (String args [ ] ) { 8) System.out.println ( "This is a simple Java program."); 9) } 10) } Warning: The numbers before each line are part of the listing and not part of the program; they're there so I can refer to specific line numbers when I explain what's going on in the program. Do not include them in your own file. Entering the Program: In Java, unlike other programming languages, the name of the source file should be followed by the .java (dot java) extension. In Java the source of a file is officially called a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that a source file use the .java filename extension. Compiling the program: To compile the example program, execute the compiler, javac, specifying the name of the source file on the command line as, shown below: C:\>javac Example.java The javac compiler creates a file called Example.class that contains the bytecode version of the program. To actually run the program, you must use the java interpreter, called java. It is as shown below: C:\>java Example When the program is run, the following output is displayed:

This is a simple Java program. CLOSER EXAMINATION OF THE PROGRAM:

1. LINES1) to 4): This is a comment and the compiler ignores the contents of the comment. It is a multi-line type of comment.

2. LINE5): This line uses the keyword class to declare that a new class is being defined. Example is an identifier that is the name of the class. Entire class definition including all of its members will be enclosed in the curly brackets.

3. LINE 6): It is a single line comment supported by java. 4. LINE7): This line begins the main ( ) method. This is the line at which the program will begin executing. All java applications begin execution by calling main ( ).The public keyword is an access specifier, which allows the programmer to control the visibility of the class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. The keyword static allows main( ) to be called without having to initiate a particular instance of the class. The keyword void simply tells the compiler that main( ) does not return a value. String args [ ] declares a parameter named args which is an array of instances of the class string. Objects of type strings store character strings.

5. LINE8): This line outputs the string " This is a simple Java program." Followed by a new line on the screen. In this case, println prints the string which is passed to it. Note that the println statement ends with a semicolon. All statements in Java end with a semicolon. The reason that the other lines in the program do not end in a semicolon is that they are not, technically, statements.

6. LINE 9): It ends main. 7. LINE 10): It ends the Example class definition. In the forthcoming articles we will have a look at some of the applets in JAVA.

Your First Java Applet In the last session we saw how an application is made. Lets now check out how to make an applet. Applet make your experience more alive than an application. This is because applets can easily be downloaded onto your browser in a short time and execution time is quiet less. Creating applets is different from creating a simple application, because Java applets run and are displayed inside a Web page with other page elements and as such have special rules for how they behave. Because of these special rules for applets in many

cases (particularly the simple ones), creating an applet may be more complex than creating an application. For example, to do a simple applet, instead of merely being able to print a message, you have to create an applet to make space for your message and then use graphics operations to paint the message to the screen. Note: If you run the last sessions simple java application as an applet, the "This is a simple Java program" message prints to a special window or to a log file, depending on how the browser has screen messages set up. It will not appear on the screen unless you write your applet to put it there. In the following example, you create that simple "This is a simple Java program" Applet , place it inside a Web page, and view the result. First, you set up an environment so that your Java-capable browser can find your HTML files and your applets. Much of the time, you'll keep your HTML files and your applet code in the same directory. Although this isn't required, it makes it easier to keep track of each element. In this example, you use a directory called HTML that contains all the files you'll need. mkdir HTML Now, open up that text editor and enter Listing b) Listing b) The Simple Java Program applet. 1: import java.awt.Graphics; 2: 3: public class SimpleJavaApplet extends java.applet.Applet { 4: 5: public void paint(Graphics g) { 6: g.drawString("This is a simple java applet!", 5, 25); 7: } 8:} Save that file inside your HTML directory. Just like with Java applications, give your file a name that has the same name as the class. In this case, the filename would be SimpleJavaApplet.java.

Now I believe the first question to hit your mind would be what should be the essential features to note about applets? There are a couple I'd like to point out: The import line at the top of the file is somewhat analogous to an #include statement in C; it enables this applet to get access to the JDK classes for creating applets and for drawing graphics on the screen. The paint() method displays the content of the applet onto the screen. Here, the string Simple Java gets drawn. Applets use several standard methods to take the place of main(), which include init() to initialize the applet, start() to start it running, and paint() to display it to the screen. You'll learn about all of these in the future. Now, compile the applet just as you did the application, using javac, the Java compiler. javac SimpleJavaApplet.java Again, just as for applications, you should now have a file called SimpleJava.class in your HTML directory. To include an applet in a Web page, you refer to that applet in the HTML code for that Web page. Here, you create a very simple HTML file in the HTML directory (see Listing c). Listing c) The HTML with the applet in it. 1: 2: 3: <TITLE>Hello to Everyone! 4: 5:

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


Related Documents