Thursday, November 24, 2011

Java Training

Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/ http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.



Objects and Reference Variables

There are two types of variables in Java – primitive type variables and reference variables. 

Primitive type variables directly store data into their memory space.  For instance, consider the following statements:

            int x;
            x = 45;

The variable x can store an int value in its memory space. The second statement stores 45 in x.



Reference variables are variables that store the address of a memory space.  For instance, consider the following statements:

String str = new String("Java Programming");

The variable str cannot directly store data in its memory space.  The variable str stores the memory location, that is, the address of the memory space where the actual data is stored.

In Java, new is an operator. It causes the system to allocate memory space of a specific type, store specific data in that memory space, and return the address of that memory space. The assignment operator stores the address of that memory space into the variable str.  Consequently, str is a reference variable.

The memory space where the string "Java Programming" is stored is called a String object. String objects are called instances of the class String.  Using the operator new to create a class object is called an instantiation of that class

String objects can be instantiated without using the new operator.

To change the value of an object, you must look at the object’s class and see if it provides a method that allows you to change the value of the (existing) object.  If there is not, the object is called immutable, and cannot be changed once it is created. 

String objects are immutable. 

To change the value of an immutable object, you can re-instantiate it.  For instance, for the str object, you could change the value from "Java Programming" to "Hello there!" with the statement:

            str = "Hello there!";

This statement would cause the system to allocate memory space to store the string "Hello there!" and the address of the allocated memory space would be stored in str. However, the address of the allocated memory space will be different than the address for the string "Java Programming".



The memory space storing "Java Programming" still exists, but no String variable refers to it.  If no other String variable refers to it, then sometimes during program execution, the Java system reclaims this memory space for later use. This is called garbage collection. If you do not want to depend on the system for garbage collection, then you can include the statement

System.gc();

in your program to instruct the computer to run the garbage collector.


Using Predefined Classes and Methods in a Program

A method is a set of instructions. When a method executes, it accomplishes something.

Java comes with a wealth of classes called predefined classes. In addition, every predefined class contains many useful predefined methods, which accomplish very useful results.

Predefined classes are organized as a collection of packages, called class libraries. A particular package can contain several classes and each class can contain several methods.

There are two types of methods in a class: static and non-static. A static method can be used, that is, called, using the name of the class containing the method.

A method must be called in order to be executed.  A method may require that certain information is given to it in order to execute.  In order to perform a method call, you need to know the number and type of arguments (or parameters) for the method.

In general, to use a predefined method in a program:

  1. You need to know the name of the class containing the method.

  1. You need to know the name of the package containing the class, and import this class from the package in the program.

  1. You need to know the name of the method. In addition, you need to know the number of parameters the method takes and the type of each parameter. You must also be aware of what the return type of the method is or, loosely speaking, what the method does.


Dot Between Class (Object) Name and Class Member: A Precaution

In Java, the dot (.) is an operator called the member access operator.  In order to make a method call, you often need to specify the name of the class that contains the method, and the name of the method, separated by a dot (.).  For instance, consider the following statement:

            int x = Math.pow(2,3);

Math is the name of a predefined class which contains a number of predefined methods.  One of these methods is the method pow, which calculates the result of raising one number to the power of another number.  That is, Math.pow(x, y) = xy.

In dot notation, the dot separates the class variable name, that is, the object name from the member, or method, name. It is also worth noting that methods are distinguished from (reference) variables by the presence of parentheses, and that methods that have no parameters must have empty parentheses


The class String

The class String provides various methods that allow us to manipulate strings in various ways.   Because the Java system automatically makes the class String available, you do not need to import this class. Therefore, in order to use a String method you need to know its name, parameters, and what the method does.

The index (position) of the first character in a String is 0, the index of the second character is 1, and so on. The length of a string is the number of characters in it.

The method substring determines a substring from within a String.  The general statement to use the method substring is:

StringVariable.substring(startIndex, endIndex)

This statement determines the substring in the string specified by StringVariable starting at the position indicated by startIndex until endIndex-1.

Beyond the substring method, the class String contains other methods to manipulate a string. The methods associated with the class String are called the members of the class String.


The general expression to use a String method on a String variable is:

StringVariable.StringMethodName(parameters)

Input/Output

A program performs three basic operations: it gets data, manipulates the data, and outputs the results. Writing programs for input/output (I/O) is quite complex. Java offers extensive support for I/O operations by providing a substantial number of I/O classes such as the class Scanner.


Formatting Output with printf

The methods print and println, discussed in chapter 2, cannot directly format certain outputs in a specific manner. To format the output in a specific manner, you use the method printf.

The syntax to use the method printf to produce the output on the standard output device is:

System.out.printf(formatString);

or:

System.out.printf(formatString, argumentList);

where formatString is a string specifying the format of the output and argumentList is a list of arguments. If argumentList has more than one argument, then the arguments are separated with commas. 


For instance:

System.out.printf("There are %.2f inches in %d centimeters.%n",
centimeters / 2.54, centimeters);

Notice that the format string consists of the two expressions, %.2f and %d; these are called format specifiers. By default, format specifiers and the arguments in argumentList have a one-to-one correspondence.

A format specifier for general, character, and numeric types has the following syntax:

%[argument_index$][flags][width][.precision]conversion

The optional argument_index is a (decimal) integer indicating the position of the argument in the argument list.

The optional flags is a set of characters that modifies the output format.

The optional width is a (decimal) integer indicating the minimum number of characters to be written to the output.

The optional precision is a (decimal) integer usually used to restrict the number of characters.

The required conversion is a character indicating how the argument should be formatted. 

Table 3-2 in the text summarizes some of the supported conversions.

In a format specifier, if the number of columns in the option width is less than the number of columns required to output the value of the expression, the output is expanded to the required number of columns. 

If the precision specified is greater than the argument’s precision, extra zeros are added to the end of the argument’s value.

Parsing Numeric Strings

Input to a program using input dialog boxes is in string format. Even numeric data is input as strings. Therefore, it is necessary to convert numeric strings into numeric form.

A string consisting of only an integer or a decimal number is called a numeric string. Java provides special methods to convert numeric strings into their equivalent numeric form.

To convert a string consisting of an integer to a value of the type int, we use the following expression:

Integer.parseInt(strExpression)

To convert a string consisting of a decimal number to a value of the type float, we use the following expression:

Float.parseFloat(strExpression)

To convert a string consisting of a decimal number to a value of the type double, we use the following expression:

Double.parseDouble(strExpression)

Note that Integer, Float, and Double are classes that contain methods to convert a numeric string into a number. These classes are called wrapper classes. Moreover, parseInt is a method of the class Integer, which converts a numeric integer string into a value of the type int. Similarly, parseFloat is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float, and the method parseDouble is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double.


Using Dialog Boxes for Input/Output

Another way to gather input and output results is to use a graphical user interface (GUI). Java provides the class JOptionPane, which allows the programmer to use GUI components for I/O. This class is contained in the package javax.swing and has two methods that we use here—showInputDialog and showMessageDialog.  To use this class in a program, the program must import it from the package javax.swing.



The method showInputDialog allows the user to input a string from the keyboard. The syntax to use the method showInputDialog is:

str = JOptionPane.showInputDialog(stringExpression);

where str is a String variable and stringExpression is an expression evaluating to a string. When this statement executes, a dialog box containing stringExpression appears on the screen prompting the user to enter the data. The data entered is returned as a string and assigned to the variable str.

The method showMessageDialog is used to display results.  The syntax for this method is:

str = JOptionPane.showMessageDialog(parentComponent,
messageStringExpression, boxTitleString, messageType);

Table 3-3 in the text describes each of the parameters for the showMessageDialog method.  Table 3-4 in the text describe the various possible values for the messageType parameter.

Statement System.exit

In order to use the input/output dialog box and properly terminate program execution, the program must include the statement:

System.exit(0);

This statement is needed only for programs that have GUI components such as input/output dialog boxes.


Formatting the Output Using the String Method format

The method printf cannot be used with output dialog boxes. One way to format the output in an output dialog box is to use the String method format. An expression to use the String method format is:

String.format(formatString, argumentList)

The meaning of the parameters formatString and argumentList is the same as with the method printf. The value of the expression is a formatted string. This method can also be used as an argument to the methods print, println, or printf.

File Input/Output

By using a file as a source of input data, you can prepare the data before running a program, and the program can access the data each time it runs. Saving output to a file allows the output to be saved and distributed to others, and the output produced by one program can be used as input to other programs.

A file is an area in secondary storage used to hold information.   To input data from a file, you use the class FileReader in conjunction with a Scanner object.  For instance:

            Scanner inFile = new Scanner(new FileReader("a:\\prog.dat"));

To output to a file, you use the classes FileWriter and PrintWriter.  These classes contain methods to read data from a file and send the output of a program to a file. 

The Java file I/O process consists of the following steps:

  1. Import the necessary classes from the packages java.util and java.io into the program.

  1. Create and associate the appropriate objects with the input/output sources.

  1. Use the appropriate methods associated with the variables created in Step 2 to input/output the data.

  1. Close the files.


Storing (Writing) Output to a File

To store the output of a program in a file, you use the class PrintWriter. You declare a PrintWriter variable and associate this variable with the file where the output will be stored.  For instance:

PrintWriter outFile = new PrintWriter("a:\\prog.out");

The methods print, println, printf, and flush can be used with outFile, the same way that they are used with System.out.



Once the output is completed, Step 4 requires closing the file. You close the input and output files by using the method close.  For instance:

            outfile.close();

Closing the output file ensures that the entire output generated by the program will be sent to the output file.

Step 3 requires that you create appropriate objects for file I/O. For an input file, the file must exist before the program executes. If the input file does not exist, then the statement to associate the object with the input file fails and it throws a FileNotFoundException exception.

An output file does not have to exist before it is opened.  If the designated output file already exists, by default the old contents are erased when the file is opened.  If the program is not able to create or access the output file, it throws a FileNotFoundException.


Do you want to know the secrets of Java Programming and use it for the advancement of your career in IT? Do you have problems in your Java course? Here is an instant solution for your problem. Avail the Java training package of Prof Erwin Globio and get free tips about Java Programming Secrets. For more free information about Java and Java Training visit the following sites: http://erwinglobio.sulit.com.ph/ http://erwinglobio.multiply.com/ http://erwinglobio.wordpress.com/. You may contact the Java Trainer at 09393741359 or 09323956678. Call now and be one of the Java Experts.