Visitors

Sunday, December 14, 2008

Variables in java



Visit for java

http://javaforhelp.blogspot.com

Variables

The next example prints a part of the Fibonacci sequence, an infinite sequence whose first few terms are

1
1
2
3
5
8
13
21
34

The Fibonacci sequence starts with the terms 1 and 1, and each successive term is the sum of the previous two terms. A Fibonacci printing program is simple, and it demonstrates how to declare variables, write a simple loop, and perform basic arithmetic. Here is the Fibonacci program:

class Fibonacci {
/** Print out the Fibonacci sequence for values < lo =" 1;" hi =" 1;" hi =" lo" lo =" hi">

This example declares a Fibonacci class that, like HelloWorld, has a main method. The first two lines of main are statements declaring two local variables: lo and hi. In this program hi is the current term in the series and lo is the previous term. Local variables are declared within a block of code, such as a method body, in contrast to fields that are declared as members of a class. Every variable must have a type that precedes its name when the variable is declared. The variables lo and hi are of type int, 32-bit signed integers with values in the range 231 through 2311.

The Java programming language has built-in "primitive" data types to support integer, floating-point, boolean, and character values. These primitive types hold numeric data that is understood directly, as opposed to object types defined by programmers. The type of every variable must be defined explicitly. The primitive data types are:

boolean

either TRue or false

char

16-bit Unicode UTF-16 character (unsigned)

byte

8-bit integer (signed)

short

16-bit integer (signed)

int

32-bit integer (signed)

long

64-bit integer (signed)

float

32-bit floating-point (IEEE 754)

double

64-bit floating-point (IEEE 754)


For each primitive type there is also a corresponding object type, generally termed a "wrapper" class. For example, the class Integer is the wrapper class for int. In most contexts, the language automatically converts between primitive types and objects of the wrapper class if one type is used where the other is expected.

In the Fibonacci program, we declared hi and lo with initial values of 1. The initial values are set by initialization expressions, using the = operator, when the variables are declared. The = operator (also called the assignment operator), sets the variable named on the left-hand side to the value of the expression on the right-hand side.

Local variables are undefined prior to initialization. You don't have to initialize them at the point at which you declare them, but if you try to use local variables before assigning a value, the compiler will refuse to compile your program until you fix the problem.

As both lo and hi are of the same type, we could have used a short-hand form for declaring them. We can declare more than one variable of a given type by separating the variable names (with their initialization expressions) by commas. We could replace the first two lines of main with the single equivalent line

int lo = 1, hi = 1;

or the much more readable

int lo = 1,
hi = 1;
http://javaforhelp.blogspot.com

Notice that the presence of line breaks makes no difference to the meaning of the statementline breaks, spaces, tabs, and other whitespace are purely for the programmer's convenience.

The while statement in the example demonstrates one way of looping. The expression inside the while is evaluatedif the expression is true, the loop's body is executed and the expression is tested again. The while is repeated until the expression becomes false. If it never becomes false, the loop will run forever unless something intervenes to break out of the loop, such as a break statement or an exception.

The body of the while consists of a single statement. That could be a simple statement (such as a method invocation), another control-flow statement, or a blockzero or more individual statements enclosed in curly braces.

The expression that while tests is a boolean expression that has the value true or false. Boolean expressions can be formed with the comparison operators (<, <=, >, >=) to compare the relative magnitudes of two values or with the == operator or != operator to test for equality or inequality, respectively. The boolean expression hi< 50 in the example tests whether the current high value of the sequence is less than 50. If the high value is less than 50, its value is printed and the next value is calculated. If the high value equals or exceeds 50, control passes to the first line of code following the body of the while loop. That is the end of the main method in this example, so the program is finished.

To calculate the next value in the sequence we perform some simple arithmetic and again use the = operator to assign the value of the arithmetic expression on the right to the variable on the left. As you would expect, the + operator calculates the sum of its operands, and the - operator calculates the difference. The language defines a number of arithmetic operators for the primitive integer and floating-point types including addition (+), subtraction (-), multiplication (*), and division (/), as well as some other operators we talk about later.

Notice that the println method accepts an integer argument in the Fibonacci example, whereas it accepted a string argument in the HelloWorld example. The println method is one of many methods that are overloaded so that they can accept arguments of different types. The runtime system decides which method to actually invoke based on the number and types of arguments you pass to it. This is a very powerful tool.



Example for java

An Example Program

Example 1-1 shows a Java program to compute factorials.Note that the numbers at the beginning of each line are not part of the program; they are there for ease of reference when we dissect the program line-by-line.

The factorial of an integer is the product of the number and all positive integers less than the number. So, for example, the factorial of 4, which is also written 4!, is 4 times 3 times 2 times 1, or 24. By definition, 0! is 1.

Example 1-1. Factorial.java: a program to compute factorials
 1 /**
2 * This program computes the factorial of a number
3 */
4 public class Factorial { // Define a class
5 public static void main(String[] args) { // The program starts here
6 int input = Integer.parseInt(args[0]); // Get the user's input
7 double result = factorial(input); // Compute the factorial
8 System.out.println(result); // Print out the result
9 } // The main() method ends here
10
11 public static double factorial(int x) { // This method computes x!
12 if (x < fact =" 1.0;"> 1) { // Loop until x equals 1
16 fact = fact * x; // Multiply by x each time
17 x = x - 1; // And then decrement x
18 } // Jump back to start of loop
19 return fact; // Return the result
20 } // factorial() ends here
21 } // The class ends here

1.3.1. Compiling and Running the Program

Before we look at how the program works, we must first discuss how to run it. In order to compile and run the program, you need a Java development kit (JDK) of some sort. Sun Microsystems created the Java language and ships a free JDK for its Solaris operating system and also for Linux and Microsoft Windows platforms. At the time of this writing, the current version of Sun's JDK is available for download from http://java.sun.com. Be sure to get the JDK and not the Java Runtime Environment. The JRE enables you to run existing Java programs, but not to write and compile your own.

[4] Other companies, such as Apple, have licensed and ported the JDK to their operating systems. In Apple's case, this arrangement leads to a delay in the latest JDK being available on that platform.

The Sun JDK is not the only Java programming environment you can use. gcj, for example, is a Java compiler released under the GNU general public license. A number of companies sell Java IDEs (integrated development environments), and high-quality open-source IDEs are also available. This book assumes that you are using Sun's JDK and its accompanying command-line tools. If you are using a product from some other vendor, be sure to read that vendor's documentation to learn how to compile and run a simple program, like that shown in Example 1-1.

Once you have a Java programming environment installed, the first step towards running our program is to type it in. Using your favorite text editor, enter the program as it is shown in Example 1-1.[5] Omit the line numbers, which are just for reference. Note that Java is a case-sensitive language, so you must type lowercase letters in lowercase and uppercase letters in uppercase. You'll notice that many of the lines of this program end with semicolons. It is a common mistake to forget these characters, but the program won't work without them, so be careful! You can omit everything from // to the end of a line: those are comments that are there for your benefit and are ignored by Java.


When writing Java programs, you should use a text editor that saves files in plain-text format, not a word processor that supports fonts and formatting and saves files in a proprietary format. My favorite text editor on Unix systems is Emacs. If you use a Windows system, you might use Notepad or WordPad, if you don't have a more specialized programmer's editor (versions of GNU Emacs, for example, are available for Windows). If you are using an IDE, it should include an appropriate text editor; read the documentation that came with the product. When you are done entering the program, save it in a file named Factorial.java. This is important; the program will not work if you save it by any other name.

After writing a program like this one, the next step is to compile it. With Sun's JDK, the Java compiler is known as javac. javac is a command-line tool, so you can only use it from a terminal window, such as an MS-DOS window on a Windows system or an xterm window on a Unix system. Compile the program by typing the following command:

C:\> javac Factorial.java

If this command prints any error messages, you probably got something wrong when you typed in the program. If it does not print any error messages, however, the compilation has succeeded, and javac creates a file called Factorial.class. This is the compiled version of the program.

Once you have compiled a Java program, you must still run it. Java programs are not compiled into native machine language, so they cannot be executed directly by the system. Instead, they are run by another program known as the Java interpreter. In Sun's JDK, the interpreter is a command-line program named, appropriately enough, java. To run the factorial program, type:

C:\> java Factorial 4

java is the command to run the Java interpreter, Factorial is the name of the Java program we want the interpreter to run, and 4 is the input datathe number we want the interpreter to compute the factorial of. The program prints a single line of output, telling us that the factorial of 4 is 24:

C:\> java Factorial 4
24.0

Congratulations! You've just written, compiled, and run your first Java program. Try running it again to compute the factorials of some other numbers.

1.3.2. Analyzing the Program

Now that you have run the factorial program, let's analyze it line by line to see what makes a Java program tick.

1.3.2.1 Comments

The first three lines of the program are a comment. Java ignores them, but they tell a human programmer what the program does. A comment begins with the characters /* and ends with the characters */. Any amount of text, including multiple lines of text, may appear between these characters. Java also supports another type of comment, which you can see in lines 4 through 21. If the characters // appear in a Java program, Java ignores those characters and any other text that appears between those characters and the end of the line.

1.3.2.2 Defining a class

Line 4 is the first line of Java code. It says that we are defining a class named Factorial. This explains why the program had to be stored in a file named Factorial.java. That filename indicates that the file contains Java source code for a class named Factorial. The word public is a modifier; it says that the class is publicly available and that anyone may use it. The open curly-brace character ({) marks the beginning of the body of the class, which extends all the way to line 21, where we find the matching close curly-brace character (}). The program contains a number of pairs of curly braces; the lines are indented to show the nesting within these braces.

A class is the fundamental unit of program structure in Java, so it is not surprising that the first line of our program declares a class. All Java programs are classes, although some programs use many classes instead of just one. Java is an object-oriented programming language, and classes are a fundamental part of the object-oriented paradigm. Each class defines a unique kind of object. Example 1-1 is not really an object-oriented program, however, so I'm not going to go into detail about classes and objects here. That is the topic of Chapter 3. For now, all you need to understand is that a class defines a set of interacting members. Those members may be fields, methods, or other classes. The Factorial class contains two members, both of which are methods. They are described in upcoming sections.

1.3.2.3 Defining a method

Line 5 begins the definition of a method of our Factorial class. A method is a named chunk of Java code. A Java program can call, or invoke, a method to execute the code in it. If you have programmed in other languages, you have probably seen methods before, but they may have been called functions, procedures, or subroutines. The interesting thing about methods is that they have parameters and return values. When you call a method, you pass it some data you want it to operate on, and it returns a result to you. A method is like an algebraic function:

y = f(x)

Here, the mathematical function f performs some computation on the value represented by x and returns a value, which we represent by y.

To return to line 5, the public and static keywords are modifiers. public means the method is publicly accessible; anyone can use it. The meaning of the static modifier is not important here; it is explained in Chapter 3. The void keyword specifies the return value of the method. In this case, it specifies that this method does not have a return value.

The word main is the name of the method. main is a special name.[6] When you run the Java interpreter, it reads in the class you specify, then looks for a method named main().[7] When the interpreter finds this method, it starts running the program at that method. When the main() method finishes, the program is done, and the Java interpreter exits. In other words, the main() method is the main entry point into a Java program. It is not actually sufficient for a method to be named main( ), however. The method must be declared public static void exactly as shown in line 5. In fact, the only part of line 5 you can change is the word args, which you can replace with any word you want. You'll be using this line in all of your Java programs, so go ahead and commit it to memory now!

[6] All Java programs that are run directly by the Java interpreter must have a main() method. Programs of this sort are often called applications. It is possible to write programs that are not run directly by the interpreter, but are dynamically loaded into some other already running Java program. Examples are applets, which are programs run by a web browser, and servlets, which are programs run by a web server. Applets are discussed in Java Foundation Classes while servlets are discussed in Java . In this book, we consider only applications.

[7] By convention, when this book refers to a method, it follows the name of the method by a pair of parentheses. As you'll see, parentheses are an important part of method syntax, and they serve here to keep method names distinct from the names of classes, fields, variables, and so on.

Following the name of the main() method is a list of method parameters in parentheses. This main( ) method has only a single parameter. String[] specifies the type of the parameter, which is an array of strings (i.e., a numbered list of strings of text). args specifies the name of the parameter. In the algebraic equation f(x), x is simply a way of referring to an unknown value. args serves the same purpose for the main() method. As we'll see, the name args is used in the body of the method to refer to the unknown value that is passed to the method.

As I've just explained, the main() method is a special one that is called by the Java interpreter when it starts running a Java class (program). When you invoke the Java interpreter like this:

C:\> java Factorial 4

the string "4" is passed to the main( ) method as the value of the parameter named args. More precisely, an array of strings containing only one entry, 4, is passed to main(). If we invoke the program like this:

C:\> java Factorial 4 3 2 1

then an array of four strings, 4, 3, 2, and 1, is passed to the main( ) method as the value of the parameter named args. Our program looks only at the first string in the array, so the other strings are ignored.

Finally, the last thing on line 5 is an open curly brace. This marks the beginning of the body of the main() method, which continues until the matching close curly brace on line 9. Methods are composed of statements, which the Java interpreter executes in sequential order. In this case, lines 6, 7, and 8 are three statements that compose the body of the main() method. Each statement ends with a semicolon to separate it from the next. This is an important part of Java syntax; beginning programmers often forget the semicolons.

1.3.2.4 Declaring a variable and parsing input

The first statement of the main() method, line 6, declares a variable and assigns a value to it. In any programming language, a variable is simply a symbolic name for a value. We've already seen that, in this program, the name args refers to the parameter value passed to the main() method. Method parameters are one type of variable. It is also possible for methods to declare additional "local" variables. Methods can use local variables to store and reference the intermediate values they use while performing their computations.

This is exactly what we are doing on line 6. That line begins with the words int input, which declare a variable named input and specify that the variable has the type int; that is, it is an integer. Java can work with several different types of values, including integers, real or floating-point numbers, characters (e.g., letters and digits), and strings of text. Java is a strongly typed language, which means that all variables must have a type specified and can refer only to values of that type. Our input variable always refers to an integer, so it cannot refer to a floating-point number or a string. Method parameters are also typed. Recall that the args parameter had a type of String[ ].

Continuing with line 6, the variable declaration int input is followed by the = character. This is the assignment operator in Java; it sets the value of a variable. When reading Java code, don't read = as "equals," but instead read it as "is assigned the value." As we'll see in Chapter 2, there is a different operator for "equals."

The value assigned to our input variable is Integer.parseInt(args[0]). This is a method invocation. This first statement of the main( ) method invokes another method whose name is Integer.parseInt( ). As you might guess, this method "parses" an integer; that is, it converts a string representation of an integer, such as 4, to the integer itself. The Integer.parseInt() method is not part of the Java language, but it is a core part of the Java API or Application Programming Interface. Every Java program can use the powerful set of classes and methods defined by this core API. The second half of this book is a quick reference that documents that core API.

When you call a method, you pass values (called arguments) that are assigned to the corresponding parameters defined by the method, and the method returns a value. The argument passed to Integer.parseInt() is args[0]. Recall that args is the name of the parameter for main(); it specifies an array (or list) of strings. The elements of an array are numbered sequentially, and the first one is always numbered 0. We care about only the first string in the args array, so we use the expression args[0] to refer to that string. When we invoke the program as shown earlier, line 6 takes the first string specified after the name of the class, 4, and passes it to the method named Integer.parseInt(). This method converts the string to the corresponding integer and returns the integer as its return value. Finally, this returned integer is assigned to the variable named input.

1.3.2.5 Computing the result

The statement on line 7 is a lot like the statement on line 6. It declares a variable and assigns a value to it. The value assigned to the variable is computed by invoking a method. The variable is named result, and it has a type of double. double means a double-precision floating-point number. The variable is assigned a value that is computed by the factorial( ) method. The factorial() method, however, is not part of the standard Java API. Instead, it is defined as part of our program by lines 11 through 19. The argument passed to factorial( ) is the value referred to by the input variable that was computed on line 6. We'll consider the body of the factorial() method shortly, but you can surmise from its name that this method takes an input value, computes the factorial of that value, and returns the result.

1.3.2.6 Displaying output

Line 8 simply calls a method named System.out.println( ). This commonly used method is part of the core Java API; it causes the Java interpreter to print out a value. In this case, the value that it prints is the value referred to by the variable named result. This is the result of our factorial computation. If the input variable holds the value 4, the result variable holds the value 24, and this line prints out that value.

The System.out.println( ) method does not have a return value. There is no variable declaration or = assignment operator in this statement since there is no value to assign to anything. Another way to say this is that, like the main( ) method of line 5, System.out.println( ) is declared void.

1.3.2.7 The end of a method

Line 9 contains only a single character, }. This marks the end of the method. When the Java interpreter gets here, it is through executing the main( ) method, so it stops running. The end of the main( ) method is also the end of the variable scope for the input and result variables declared within main( ) and for the args parameter of main( ). These variable and parameter names have meaning only within the main( ) method and cannot be used elsewhere in the program unless other parts of the program declare different variables or parameters that happen to have the same name.

1.3.2.8 Blank lines

Line 10 is a blank line. You can insert blank lines and spaces anywhere in a program, and you should use them liberally to make the program readable. A blank line appears here to separate the main( ) method from the factorial() method that begins on line 11. You'll notice that the program also uses whitespace to indent the various lines of code. This kind of indentation is optional; it emphasizes the structure of the program and greatly enhances the readability of the code.

1.3.2.9 Another method

Line 11 begins the definition of the factorial() method that was used by the main( ) method. Compare this line to line 5 to note its similarities and differences. The factorial( ) method has the same public and static modifiers. It takes a single integer parameter, which we call x. Unlike the main( ) method, which had no return value (void), factorial( ) returns a value of type double. The open curly brace marks the beginning of the method body, which continues past the nested braces on lines 15 and 18 to line 20, where the matching close curly brace is found. The body of the factorial( ) method, like the body of the main() method, is composed of statements, which are found on lines 12 through 19.

1.3.2.10 Checking for valid input

In the main() method, we saw variable declarations, assignments, and method invocations. The statement on line 12 is different. It is an if statement, which executes another statement conditionally. We saw earlier that the Java interpreter executes the three statements of the main() method one after another. It always executes them in exactly that way, in exactly that order. An if statement is a flow-control statement; it can affect the way the interpreter runs a program.

The if keyword is followed by a parenthesized expression and a statement. The Java interpreter first evaluates the expression. If it is true, the interpreter executes the statement. If the expression is false, however, the interpreter skips the statement and goes to the next one. The condition for the if statement on line 12 is x <>. It checks whether the value passed to the factorial() method is less than zero. If it is, this expression is true, and the statement on line 13 is executed. Line 12 does not end with a semicolon because the statement on line 13 is part of the if statement. Semicolons are required only at the end of a statement.

Line 13 is a return statement. It says that the return value of the factorial( ) method is 0.0. return is also a flow-control statement. When the Java interpreter sees a return, it stops executing the current method and returns the specified value immediately. A return statement can stand alone, but in this case, the return statement is part of the if statement on line 12. The indentation of line 13 helps emphasize this fact. (Java ignores this indentation, but it is very helpful for humans who read Java code!) Line 13 is executed only if the expression on line 12 is true.

Before we move on, we should pull back a bit and talk about why lines 12 and 13 are necessary in the first place. It is an error to try to compute a factorial for a negative number, so these lines make sure that the input value x is valid. If it is not valid, they cause factorial( ) to return a consistent invalid result, 0.0.

1.3.2.11 An important variable

Line 14 is another variable declaration; it declares a variable named fact of type double and assigns it an initial value of 1.0. This variable holds the value of the factorial as we compute it in the statements that follow. In Java, variables can be declared anywhere; they are not restricted to the beginning of a method or block of code.

1.3.2.12 Looping and computing the factorial

Line 15 introduces another type of statement: the while loop. Like an if statement, a while statement consists of a parenthesized expression and a statement. When the Java interpreter sees a while statement, it evaluates the associated expression. If that expression is TRue, the interpreter executes the statement. The interpreter repeats this process, evaluating the expression and executing the statement if the expression is true, until the expression evaluates to false. The expression on line 15 is x > 1, so the while statement loops while the parameter x holds a value that is greater than 1. Another way to say this is that the loop continues until x holds a value less than or equal to 1. We can assume from this expression that if the loop is ever going to terminate, the value of x must somehow be modified by the statement that the loop executes.

The major difference between the if statement on lines 12-13 and the while loop on lines 15-18 is that the statement associated with the while loop is a compound statement. A compound statement is zero or more statements grouped between curly braces. The while keyword on line 15 is followed by an expression in parentheses and then by an open curly brace. This means that the body of the loop consists of all statements between that opening brace and the closing brace on line 18. Earlier in the chapter, I said that all Java statements end with semicolons. This rule does not apply to compound statements, however, as you can see by the lack of a semicolon at the end of line 18. The statements inside the compound statement (lines 16 and 17) do end with semicolons, of course.

The body of the while loop consists of the statements on line 16 and 17. Line 16 multiplies the value of fact by the value of x and stores the result back into fact. Line 17 is similar. It subtracts 1 from the value of x and stores the result back into x. The * character on line 16 is important: it is the multiplication operator. And, as you can probably guess, the - on line 17 is the subtraction operator. An operator is a key part of Java syntax: it performs a computation on one or two operands to produce a new value. Operands and operators combine to form expressions, such as fact * x or x - 1. We've seen other operators in the program. Line 15, for example, uses the greater-than operator (>) in the expression x > 1, which compares the value of the variable x to 1. The value of this expression is a boolean truth valueeither TRue or false, depending on the result of the comparison.

To understand this while loop, it is helpful to think like the Java interpreter. Suppose we are trying to compute the factorial of 4. Before the loop starts, fact is 1.0, and x is 4. After the body of the loop has been executed onceafter the first iterationfact is 4.0, and x is 3. After the second iteration, fact is 12.0, and x is 2. After the third iteration, fact is 24.0, and x is 1. When the interpreter tests the loop condition after the third iteration, it finds that x > 1 is no longer true, so it stops running the loop, and the program resumes at line 19.

1.3.2.13 Returning the result

Line 19 is another return statement, like the one we saw on line 13. This one does not return a constant value like 0.0, but instead returns the value of the fact variable. If the value of x passed into the factorial() function is 4, then, as we saw earlier, the value of fact is 24.0, so this is the value returned. Recall that the factorial() method was invoked on line 7 of the program. When this return statement is executed, control returns to line 7, where the return value is assigned to the variable named result.

1.3.3. Exceptions

If you've made it all the way through the line-by-line analysis of Example 1-1, you are well on your way to understanding the basics of the Java language.[8] It is a simple but nontrivial program that illustrates many of the features of Java. There is one more important feature of Java programming I want to introduce, but it is one that does not appear in the program listing itself. Recall that the program computes the factorial of the number you specify on the command line. What happens if you run the program without specifying a number?

[8] If you didn't understand all the details of this factorial program, don't worry. We'll cover the details of the Java language a lot more thoroughly in subsequent chapters. However, if you feel like you didn't understand any of the line-by-line analysis, you may also find that the upcoming chapters are over your head. In that case, you should probably go elsewhere to learn the basics of the Java language and return to this book to solidify your understanding, and, of course, to use as a reference. One resource you may find useful in learning the language is Sun's online Java tutorial, available at http://java.sun.com/docs/books/tutorial.

C:\> java Factorial
java.lang.ArrayIndexOutOfBoundsException: 0
at Factorial.main(Factorial.java:6)
C:\>

And what happens if you specify a value that is not a number?

C:\> java Factorial ten
java.lang.NumberFormatException: ten
at java.lang.Integer.parseInt(Integer.java)
at java.lang.Integer.parseInt(Integer.java)
at Factorial.main(Factorial.java:6)
C:\>

In both cases, an error occurs or, in Java terminology, an exception is thrown. When an exception is thrown, the Java interpreter prints a message that explains what type of exception it was and where it occurred (both exceptions above occurred on line 6). In the first case, the exception is thrown because there are no strings in the args list, meaning we asked for a nonexistent string with args[0]. In the second case, the exception is thrown because Integer.parseInt( ) cannot convert the string "ten" to a number. We'll see more about exceptions in Chapter 2 and learn how to handle them gracefully as they occur.

Introduction Java(Part1)

Chapter 1. Introduction

Welcome to Java. This chapter begins by explaining what Java is and describing some of the features that distinguish it from other programming languages. Next, it outlines the structure of this book, with special emphasis on what is new in Java 5.0. Finally, as a quick tutorial introduction to the language, it walks you through a simple Java program you can type, compile, and run.


http://javaforhelp.blogspot.com

Chapter 2. Java Syntax from the Ground Up

This chapter is a terse but comprehensive introduction to Java syntax. It is written primarily for readers who are new to the language but have at least some previous programming experience. Determined novices with no prior programming experience may also find it useful. If you already know Java, you should find it a useful language reference. The chapter includes comparisons of Java to C and C++ for the benefit of programmers coming from those languages.

This chapter documents the syntax of Java programs by starting at the very lowest level of Java syntax and building from there, covering increasingly higher orders of structure. It covers:

  • The characters used to write Java programs and the encoding of those characters.

  • Literal values, identifiers, and other tokens that comprise a Java program.

  • The data types that Java can manipulate.

  • The operators used in Java to group individual tokens into larger expressions.

  • Statements, which group expressions and other statements to form logical chunks of Java code.

  • Methods (also called functions, procedures, or subroutines), which are named collections of Java statements that can be invoked by other Java code.

  • Classes, which are collections of methods and fields. Classes are the central program element in Java and form the basis for object-oriented programming. Chapter 3 is devoted entirely to a discussion of classes and objects.

  • Packages, which are collections of related classes.

  • Java programs, which consist of one or more interacting classes that may be drawn from one or more packages.

The syntax of most programming languages is complex, and Java is no exception. In general, it is not possible to document all elements of a language without referring to other elements that have not yet been discussed. For example, it is not really possible to explain in a meaningful way the operators and statements supported by Java without referring to objects. But it is also not possible to document objects thoroughly without referring to the operators and statements of the language. The process of learning Java, or any language, is therefore an iterative one. If you are new to Java (or a Java-style programming language), you may find that you benefit greatly from working through this chapter and the next twice, so that you can grasp the interrelated concepts.

http://javaforhelp.blogspot.com

Chapter 3. Object-Oriented Programming in Java

Now that we've covered fundamental Java syntax, we are ready to begin object-oriented programming in Java. All Java programs use objects, and the type of an object is defined by its class or interface. Every Java program is defined as a class, and nontrivial programs usually include a number of classes and interface definitions. This chapter explains how to define new classes and interfaces and how to do object-oriented programming with them.[1]

[1] If you do not have object-oriented (OO) programming background, don't worry; this chapter does not assume any prior experience. If you do have experience with OO programming, however, be careful. The term "object-oriented" has different meanings in different languages. Don't assume that Java works the same way as your favorite OO language. This is particularly true for C++ programmers. Although Java and C++ borrow much syntax from C, the similarities between the two languages do not go far beyond the level of syntax. Don't let your experience with C++ lull you into a false familiarity with Java.

This is a relatively long and detailed chapter, so we begin with an overview and some definitions. A class is a collection of fields that hold values and methods that operate on those values. Classes are the most fundamental structural element of all Java programs. You cannot write Java code without defining a class. All Java statements appear within methods, and all methods are implemented within classes.

A class defines a new reference type, such as the Point type defined in Chapter 2. An object is an instance of a class. The Point class defines a type that is the set of all possible two-dimensional points. A Point object is a value of that type: it represents a single two-dimensional point.

Objects are usually created by instantiating a class with the new keyword and a constructor invocation, as shown here:

Point p = new Point(1.0, 2.0);

Constructors are covered in Section 3.3 later in this chapter.

A class definition consists of a signature and a body. The class signature defines the name of the class and may also specify other important information. The body of a class is a set of members enclosed in curly braces. The members of a class may include fields and methods, constructors and initializers, and nested types.

Members can be static or nonstatic. A static member belongs to the class itself while a nonstatic member is associated with the instances of a class (see Section 3.2 later in this chapter).

The signature of a class may declare that the class extends another class. The extended class is known as the superclass and the extension is known as the subclass. A subclass inherits the members of its superclass and may declare new members or override inherited methods with new implementations.

The signature of a class may also declare that the class implements one or more interfaces. An interface is a reference type that defines method signatures but does not include method bodies to implement the methods. A class that implements an interface is required to provide bodies for the interface's methods. Instances of such a class are also instances of the interface type that it implements.

The members of a class may have access modifiers public , protected, or private, which specify their visibility and accessibility to clients and to subclasses. This allows classes to hide members that are not part of their public API. When applied to fields, this ability to hide members enables an object-oriented design technique known as data encapsulation .

Classes and interfaces are the most important of the five fundamental reference types defined by Java. Arrays, enumerated types (or "enums") and annotation types are the other three. Arrays are covered in Chapter 2. Enumerated types and annotation types were introduced in Java 5.0 (see Chapter 4). Enums are a specialized kind of class and annotation types are a specialized kind of interface.



http://javaforhelp.blogspot.com

Chapter 4. Java 5.0 Language Features

This chapter covers the three most important new language features of Java 5.0. Generics add type-safety and expressiveness to Java programs by allowing types to be parameterized with other types. A List that contains String objects, for example, can be written as List. Using parameterized types makes Java code clearer and allows us to remove most casts from our programs.

Enumerated types, or enums, are a new category of reference type, like classes and interfaces. An enumerated type defines a finite ("enumerated") set of values, and, importantly, provides type-safety: a variable of enumerated type can hold only values of that enumerated type or null. Here is a simple enumerated type definition:

public enum Seasons { WINTER, SPRING, SUMMER, AUTUMN }

The third Java 5.0 feature discussed in this chapter is program annotations and the annotation types that define them. An annotation associates arbitrary data (or metadata) with a program element such as a class, method, field, or even a method parameter or local variable. The type of data held in an annotation is defined by its annotation type, which, like enumerated types, is another new category of reference type. The Java 5.0 platform includes three standard annotation types used to provide additional information to the Java compiler. Annotations will probably find their greatest use with code generation tools in Java enterprise programming.

Java 5.0 also introduces a number of other important new language features that don't require a special chapter to explain. Coverage of these changes is found in sections throughout Chapter 2. They include:

  • Autoboxing and unboxing conversions

  • The for/in looping statement, sometimes called "foreach"

  • Methods with variable-length argument lists, also known as varargs methods

  • The ability to narrow the return type of a method when overriding, known as a " covariant return"

  • The import static directive, which imports the static members of a type into the name space



Chapter 4. Java 5.0 Language Features

This chapter covers the three most important new language features of Java 5.0. Generics add type-safety and expressiveness to Java programs by allowing types to be parameterized with other types. A List that contains String objects, for example, can be written as List. Using parameterized types makes Java code clearer and allows us to remove most casts from our programs.

Enumerated types, or enums, are a new category of reference type, like classes and interfaces. An enumerated type defines a finite ("enumerated") set of values, and, importantly, provides type-safety: a variable of enumerated type can hold only values of that enumerated type or null. Here is a simple enumerated type definition:

public enum Seasons { WINTER, SPRING, SUMMER, AUTUMN }

The third Java 5.0 feature discussed in this chapter is program annotations and the annotation types that define them. An annotation associates arbitrary data (or metadata) with a program element such as a class, method, field, or even a method parameter or local variable. The type of data held in an annotation is defined by its annotation type, which, like enumerated types, is another new category of reference type. The Java 5.0 platform includes three standard annotation types used to provide additional information to the Java compiler. Annotations will probably find their greatest use with code generation tools in Java enterprise programming.

Java 5.0 also introduces a number of other important new language features that don't require a special chapter to explain. Coverage of these changes is found in sections throughout Chapter 2. They include:

  • Autoboxing and unboxing conversions

  • The for/in looping statement, sometimes called "foreach"

  • Methods with variable-length argument lists, also known as varargs methods

  • The ability to narrow the return type of a method when overriding, known as a " covariant return"

  • The import static directive, which imports the static members of a type into the namespace



Chapter 5. The Java Platform

Chapters Chapter 2, Chapter 3, and Chapter 4 documented the Java programming language. This chapter switches gears and covers the Java platforma vast collection of predefined classes available to every Java program, regardless of the underlying host system on which it is running. The classes of the Java platform are collected into related groups, known as packages. This chapter begins with an overview of the packages of the Java platform that are documented in this book. It then moves on to demonstrate, in the form of short examples, the most useful classes in these packages. Most of the examples are code snippets only, not full programs you can compile and run. For fully fleshed-out, real-world examples,




Chapter 6. Java Security

Java programs can dynamically load Java classes from a variety of sources, including untrusted sources, such as web sites reached across an insecure network. The ability to create and work with such mobile code is one of the great strengths and features of Java. To make it work successfully, however, Java puts great emphasis on a security architecture that allows untrusted code to run safely, without fear of damage to the host system.

The need for a security system in Java is most acutely demonstrated by appletsminiature Java applications designed to be embedded in web pages.[1] When a user visits a web page (with a Java-enabled web browser) that contains an applet, the web browser downloads the Java class files that define that applet and runs them. In the absence of a security system, an applet could wreak havoc on the user's system by deleting files, installing a virus, stealing confidential information, and so on. Somewhat more subtly, an applet could take advantage of the user's system to forge email, generate spam, or launch hacking attempts on other systems.


Java's main line of defense against such malicious code is access control: untrusted code is simply not given access to certain sensitive portions of the core Java API. For example, an untrusted applet is not typically allowed to read, write, or delete files on the host system or connect over the network to any computer other than the web server from which it was downloaded. This chapter describes the Java access control architecture and a few other facets of the Java security system.



Chapter 7. Programming and Documentation Conventions

This chapter explains a number of important and useful Java programming and documentation conventions. It covers:

  • General naming and capitalization conventions

  • Portability tips and conventions

  • Javadoc documentation comment syntax and conventions

  • JavaBeans conventions

None of the conventions described here are mandatory. Following them, however, will make your code easier to read and maintain, portable, and self-documenting.



Chapter 8. Java Development Tools

Sun's implementation of Java includes a number of tools for Java developers. Chief among these are the Java interpreter and the Java compiler, of course, but there are a number of others as well. This chapter documents most tools shipped with the JDK. Notable omissions are the RMI and IDL tools that are specific to enterprise programming and which are documented in Java

The tools documented here are part of Sun's development kit; they are implementation details and not part of the Java specification itself. If you are using a Java development environment other than Sun's JDK, you should consult your vendor's tool documentation.

Some examples in this chapter use Unix conventions for file and path separators. If Windows is your development platform, change forward slashes in filenames to backward slashes, and colons in path specifications to semicolons.


http://javaforhelp.blogspot.com

Friday, August 8, 2008

C Programming Section B

C++ Programming Section B

C++ Programming


C++ Programming


//vowels.cpp
#include"iostream.h"
#include"conio.h"
#include"string.h"
int vo=0,cc=0;
class vowel
{
private:
char str[' '];

public:
void display();
void getdata()
{
int n;
cout<<"Enter the string for find the num of vowels and costraint\n";
cin.getline(str,80);
//cin>>str;
}

void findvowel()
{

strupr(str);
for(int i=0;str[i]!='\0';i++)
{
if(str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
{
vo++;
}
else
if(str[i]!=' ')
{
cc++;
}
}
display();
}
};

void vowel::display()
{
cout<<"Num of vowels are "<<vo<<"\n";
cout<<"Num of costraint are "<<cc<<"\n";
}
void main()
{
clrscr();
vowel v;
v.getdata();
v.findvowel();
getch();
}


//zerosmaller.cpp
//Create a function to find the smallest of two numbers
# include<iostream.h>
# include <conio.h>
void main()
{
int a,b,c,d;
void zero_smaller(int &,int &);
clrscr();
cout<<"\nEnter any two numbers\n";
cin>>a>>b;
c=a;
d=b;
zero_smaller(a,b);
if(a==0)
cout<<"\n"<<c<<" is the smallest number";
else
if(b==0)
cout<<"\n"<<d<<" is the smallest number";
else
cout<<"\nBoth the numbers are same";
getch();
}
void zero_smaller(int &x,int &y)
{
if(x<y)
x=0;
else
if(y<x)
y=0;
}





//array.cpp
#include"iostream.h"
#include"conio.h"
#include"stdio.h"

class student
{
private:
char name[80];
int age;
float mark;

public:
void read()
{
cout<<"\n\nEnter name : ";
gets(name);
cout<<"\n\nEnter age and mark : ";
cin>>age>>mark;
}

void display()
{
cout<<"\n"<<"Name is "<<name;
cout<<"\n"<<"Age is "<<age;
cout<<endl<<"Mark is "<<mark;
}


};


void main()
{
student s[' '];
int n,i;
clrscr();
cout<<"Enter the num of object : ";
cin>>n;
for(i=0;i<n;i++)
s[i].read();
clrscr();
for(i=0;i<n;i++)
{
cout<<"\n\n\n\nstudent "<
<i+1<<" details : \n\n";
s[i].display();
}
getch();
}


//thispointer.cpp
#include <iostream.h>
#include <conio.h>

class student
{
private:
char na[10];
int age;
public:
void get_data()
{
cout<<"\nEnter Student Name := "; cin>>na;
cout<<"Enter Student Age := "; cin>>age;
}
void put_data()
{
cout<<na<<" age is = "<<age;
}
student grater(student);
};
student student::grater(student s)
{
if(age>=s.age)
return *this;
else
return s;
}
void main()
{
// clrscr();
student s1,s2;
cout<<"\nDemonstrate this Pointer.\n";
s1.get_data();
s2.get_data();

student s = s1.grater(s2);
cout<<"\n\nEldest Student ";
s.put_data();

getch();
}


//pointersort.cpp
#include <iostream.h>
#include <conio.h>
#include <string.h>
class sort
{
char na[10];
public:
void read()
{
cin>>na;
}
void write()
{
cout<<na;
}
char* ret()
{
return na;
}
};
void main()
{
// clrscr();
sort s[10];
sort *ps[10],*temp;
char ch;
int n=0;

cout<<"Pointer Sort.\n";
cout<<"\nEnter Names :\n";
do
{
s[n].read();
ps[n]=&s[n];
cout<<"Do you want continue [y/n] :- ";
cin>>ch;
n++;
}while(ch=='y');

for(int i=0;i<n;i++)
for(int j=1;j<n-i;j++)
if(strcmpi(ps[j-1]->ret(),ps[j]->ret())>0)
{
temp = ps[j-1];
ps[j-1] = ps[j];
ps[j] = temp;
}

cout<<"\nSorted Names are :\n";
for(i=0;i<n;i++)
{
ps[i]->write();
cout<<'\n';
}
getch();
}


//staticFunction.cpp
#include <iostream.h>
#include <conio.h>

class Number
{
private:
static int count;
int no;
public:
void Assign_no()
{
no = ++count;
}
void Display_no()
{
cout<<"\n\nObject Number = "<<no;
}
static void Display_count();
/* {
cout<<"\nNo of Objects Created = "<<count;
} */
};

void Number::Display_count()
{
cout<<"\nNo of Objects Created = "<<count;
}

int Number::count;

void main()
{
// clrscr();
cout<<"\t\tDemonstration of Static Function\n";
Number obj1;
obj1.Assign_no();
Number::Display_count();

Number obj2,obj3;
obj2.Assign_no();
obj3.Assign_no();
Number::Display_count();

obj1.Display_no();
obj2.Display_no();
obj3.Display_no();

getch();
}